Fix more compiler warnings.
[org-mode.git] / lisp / org.el
blob7d4c5448dd251ba6d96621b9abf19011bf11fb28
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 If this variable is set, `org-log-state-notes-insert-after-drawers'
2504 will be ignored.
2506 You can set the property LOG_INTO_DRAWER to overrule this setting for
2507 a subtree."
2508 :group 'org-todo
2509 :group 'org-progress
2510 :type '(choice
2511 (const :tag "Not into a drawer" nil)
2512 (const :tag "LOGBOOK" t)
2513 (string :tag "Other")))
2515 (if (fboundp 'defvaralias)
2516 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2518 (defun org-log-into-drawer ()
2519 "Return the value of `org-log-into-drawer', but let properties overrule.
2520 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2521 used instead of the default value."
2522 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2523 (cond
2524 ((not p) org-log-into-drawer)
2525 ((equal p "nil") nil)
2526 ((equal p "t") "LOGBOOK")
2527 (t p))))
2529 (defcustom org-log-state-notes-insert-after-drawers nil
2530 "Non-nil means insert state change notes after any drawers in entry.
2531 Only the drawers that *immediately* follow the headline and the
2532 deadline/scheduled line are skipped.
2533 When nil, insert notes right after the heading and perhaps the line
2534 with deadline/scheduling if present.
2536 This variable will have no effect if `org-log-into-drawer' is
2537 set."
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-states-order-reversed t
2543 "Non-nil means the latest state note will be directly after heading.
2544 When nil, the state change notes will be ordered according to time."
2545 :group 'org-todo
2546 :group 'org-progress
2547 :type 'boolean)
2549 (defcustom org-todo-repeat-to-state nil
2550 "The TODO state to which a repeater should return the repeating task.
2551 By default this is the first task in a TODO sequence, or the previous state
2552 in a TODO_TYP set. But you can specify another task here.
2553 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2554 :group 'org-todo
2555 :version "24.1"
2556 :type '(choice (const :tag "Head of sequence" nil)
2557 (string :tag "Specific state")))
2559 (defcustom org-log-repeat 'time
2560 "Non-nil means record moving through the DONE state when triggering repeat.
2561 An auto-repeating task is immediately switched back to TODO when
2562 marked DONE. If you are not logging state changes (by adding \"@\"
2563 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2564 record a closing note, there will be no record of the task moving
2565 through DONE. This variable forces taking a note anyway.
2567 nil Don't force a record
2568 time Record a time stamp
2569 note Prompt for a note and add it with template `org-log-note-headings'
2571 This option can also be set with on a per-file-basis with
2573 #+STARTUP: nologrepeat
2574 #+STARTUP: logrepeat
2575 #+STARTUP: lognoterepeat
2577 You can have local logging settings for a subtree by setting the LOGGING
2578 property to one or more of these keywords."
2579 :group 'org-todo
2580 :group 'org-progress
2581 :type '(choice
2582 (const :tag "Don't force a record" nil)
2583 (const :tag "Force recording the DONE state" time)
2584 (const :tag "Force recording a note with the DONE state" note)))
2587 (defgroup org-priorities nil
2588 "Priorities in Org-mode."
2589 :tag "Org Priorities"
2590 :group 'org-todo)
2592 (defcustom org-enable-priority-commands t
2593 "Non-nil means priority commands are active.
2594 When nil, these commands will be disabled, so that you never accidentally
2595 set a priority."
2596 :group 'org-priorities
2597 :type 'boolean)
2599 (defcustom org-highest-priority ?A
2600 "The highest priority of TODO items. A character like ?A, ?B etc.
2601 Must have a smaller ASCII number than `org-lowest-priority'."
2602 :group 'org-priorities
2603 :type 'character)
2605 (defcustom org-lowest-priority ?C
2606 "The lowest priority of TODO items. A character like ?A, ?B etc.
2607 Must have a larger ASCII number than `org-highest-priority'."
2608 :group 'org-priorities
2609 :type 'character)
2611 (defcustom org-default-priority ?B
2612 "The default priority of TODO items.
2613 This is the priority an item gets if no explicit priority is given.
2614 When starting to cycle on an empty priority the first step in the cycle
2615 depends on `org-priority-start-cycle-with-default'. The resulting first
2616 step priority must not exceed the range from `org-highest-priority' to
2617 `org-lowest-priority' which means that `org-default-priority' has to be
2618 in this range exclusive or inclusive the range boundaries. Else the
2619 first step refuses to set the default and the second will fall back
2620 to (depending on the command used) the highest or lowest priority."
2621 :group 'org-priorities
2622 :type 'character)
2624 (defcustom org-priority-start-cycle-with-default t
2625 "Non-nil means start with default priority when starting to cycle.
2626 When this is nil, the first step in the cycle will be (depending on the
2627 command used) one higher or lower than the default priority.
2628 See also `org-default-priority'."
2629 :group 'org-priorities
2630 :type 'boolean)
2632 (defcustom org-get-priority-function nil
2633 "Function to extract the priority from a string.
2634 The string is normally the headline. If this is nil Org computes the
2635 priority from the priority cookie like [#A] in the headline. It returns
2636 an integer, increasing by 1000 for each priority level.
2637 The user can set a different function here, which should take a string
2638 as an argument and return the numeric priority."
2639 :group 'org-priorities
2640 :version "24.1"
2641 :type 'function)
2643 (defgroup org-time nil
2644 "Options concerning time stamps and deadlines in Org-mode."
2645 :tag "Org Time"
2646 :group 'org)
2648 (defcustom org-insert-labeled-timestamps-at-point nil
2649 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2650 When nil, these labeled time stamps are forces into the second line of an
2651 entry, just after the headline. When scheduling from the global TODO list,
2652 the time stamp will always be forced into the second line."
2653 :group 'org-time
2654 :type 'boolean)
2656 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2657 "Formats for `format-time-string' which are used for time stamps.
2658 It is not recommended to change this constant.")
2660 (defcustom org-time-stamp-rounding-minutes '(0 5)
2661 "Number of minutes to round time stamps to.
2662 These are two values, the first applies when first creating a time stamp.
2663 The second applies when changing it with the commands `S-up' and `S-down'.
2664 When changing the time stamp, this means that it will change in steps
2665 of N minutes, as given by the second value.
2667 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2668 numbers should be factors of 60, so for example 5, 10, 15.
2670 When this is larger than 1, you can still force an exact time stamp by using
2671 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2672 and by using a prefix arg to `S-up/down' to specify the exact number
2673 of minutes to shift."
2674 :group 'org-time
2675 :get #'(lambda (var) ; Make sure both elements are there
2676 (if (integerp (default-value var))
2677 (list (default-value var) 5)
2678 (default-value var)))
2679 :type '(list
2680 (integer :tag "when inserting times")
2681 (integer :tag "when modifying times")))
2683 ;; Normalize old customizations of this variable.
2684 (when (integerp org-time-stamp-rounding-minutes)
2685 (setq org-time-stamp-rounding-minutes
2686 (list org-time-stamp-rounding-minutes
2687 org-time-stamp-rounding-minutes)))
2689 (defcustom org-display-custom-times nil
2690 "Non-nil means overlay custom formats over all time stamps.
2691 The formats are defined through the variable `org-time-stamp-custom-formats'.
2692 To turn this on on a per-file basis, insert anywhere in the file:
2693 #+STARTUP: customtime"
2694 :group 'org-time
2695 :set 'set-default
2696 :type 'sexp)
2697 (make-variable-buffer-local 'org-display-custom-times)
2699 (defcustom org-time-stamp-custom-formats
2700 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2701 "Custom formats for time stamps. See `format-time-string' for the syntax.
2702 These are overlaid over the default ISO format if the variable
2703 `org-display-custom-times' is set. Time like %H:%M should be at the
2704 end of the second format. The custom formats are also honored by export
2705 commands, if custom time display is turned on at the time of export."
2706 :group 'org-time
2707 :type 'sexp)
2709 (defun org-time-stamp-format (&optional long inactive)
2710 "Get the right format for a time string."
2711 (let ((f (if long (cdr org-time-stamp-formats)
2712 (car org-time-stamp-formats))))
2713 (if inactive
2714 (concat "[" (substring f 1 -1) "]")
2715 f)))
2717 (defcustom org-time-clocksum-format
2718 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2719 "The format string used when creating CLOCKSUM lines.
2720 This is also used when Org mode generates a time duration.
2722 The value can be a single format string containing two
2723 %-sequences, which will be filled with the number of hours and
2724 minutes in that order.
2726 Alternatively, the value can be a plist associating any of the
2727 keys :years, :months, :weeks, :days, :hours or :minutes with
2728 format strings. The time duration is formatted using only the
2729 time components that are needed and concatenating the results.
2730 If a time unit in absent, it falls back to the next smallest
2731 unit.
2733 The keys :require-years, :require-months, :require-days,
2734 :require-weeks, :require-hours, :require-minutes are also
2735 meaningful. A non-nil value for these keys indicates that the
2736 corresponding time component should always be included, even if
2737 its value is 0.
2740 For example,
2742 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2743 :require-minutes t)
2745 means durations longer than a day will be expressed in days,
2746 hours and minutes, and durations less than a day will always be
2747 expressed in hours and minutes (even for durations less than an
2748 hour).
2750 The value
2752 \(:days \"%dd\" :minutes \"%dm\")
2754 means durations longer than a day will be expressed in days and
2755 minutes, and durations less than a day will be expressed entirely
2756 in minutes (even for durations longer than an hour)."
2757 :group 'org-time
2758 :type '(choice (string :tag "Format string")
2759 (set :tag "Plist"
2760 (group :inline t (const :tag "Years" :years)
2761 (string :tag "Format string"))
2762 (group :inline t
2763 (const :tag "Always show years" :require-years)
2764 (const t))
2765 (group :inline t (const :tag "Months" :months)
2766 (string :tag "Format string"))
2767 (group :inline t
2768 (const :tag "Always show months" :require-months)
2769 (const t))
2770 (group :inline t (const :tag "Weeks" :weeks)
2771 (string :tag "Format string"))
2772 (group :inline t
2773 (const :tag "Always show weeks" :require-weeks)
2774 (const t))
2775 (group :inline t (const :tag "Days" :days)
2776 (string :tag "Format string"))
2777 (group :inline t
2778 (const :tag "Always show days" :require-days)
2779 (const t))
2780 (group :inline t (const :tag "Hours" :hours)
2781 (string :tag "Format string"))
2782 (group :inline t
2783 (const :tag "Always show hours" :require-hours)
2784 (const t))
2785 (group :inline t (const :tag "Minutes" :minutes)
2786 (string :tag "Format string"))
2787 (group :inline t
2788 (const :tag "Always show minutes" :require-minutes)
2789 (const t)))))
2791 (defcustom org-time-clocksum-use-fractional nil
2792 "If non-nil, \\[org-clock-display] uses fractional times.
2793 org-mode generates a time duration."
2794 :group 'org-time
2795 :type 'boolean)
2797 (defcustom org-time-clocksum-fractional-format "%.2f"
2798 "The format string used when creating CLOCKSUM lines,
2799 or when Org mode generates a time duration, if
2800 `org-time-clocksum-use-fractional' is enabled.
2802 The value can be a single format string containing one
2803 %-sequence, which will be filled with the number of hours as
2804 a float.
2806 Alternatively, the value can be a plist associating any of the
2807 keys :years, :months, :weeks, :days, :hours or :minutes with
2808 a format string. The time duration is formatted using the
2809 largest time unit which gives a non-zero integer part. If all
2810 specified formats have zero integer part, the smallest time unit
2811 is used."
2812 :group 'org-time
2813 :type '(choice (string :tag "Format string")
2814 (set (group :inline t (const :tag "Years" :years)
2815 (string :tag "Format string"))
2816 (group :inline t (const :tag "Months" :months)
2817 (string :tag "Format string"))
2818 (group :inline t (const :tag "Weeks" :weeks)
2819 (string :tag "Format string"))
2820 (group :inline t (const :tag "Days" :days)
2821 (string :tag "Format string"))
2822 (group :inline t (const :tag "Hours" :hours)
2823 (string :tag "Format string"))
2824 (group :inline t (const :tag "Minutes" :minutes)
2825 (string :tag "Format string")))))
2827 (defcustom org-deadline-warning-days 14
2828 "No. of days before expiration during which a deadline becomes active.
2829 This variable governs the display in sparse trees and in the agenda.
2830 When 0 or negative, it means use this number (the absolute value of it)
2831 even if a deadline has a different individual lead time specified.
2833 Custom commands can set this variable in the options section."
2834 :group 'org-time
2835 :group 'org-agenda-daily/weekly
2836 :type 'integer)
2838 (defcustom org-read-date-prefer-future t
2839 "Non-nil means assume future for incomplete date input from user.
2840 This affects the following situations:
2841 1. The user gives a month but not a year.
2842 For example, if it is April and you enter \"feb 2\", this will be read
2843 as Feb 2, *next* year. \"May 5\", however, will be this year.
2844 2. The user gives a day, but no month.
2845 For example, if today is the 15th, and you enter \"3\", Org-mode will
2846 read this as the third of *next* month. However, if you enter \"17\",
2847 it will be considered as *this* month.
2849 If you set this variable to the symbol `time', then also the following
2850 will work:
2852 3. If the user gives a time.
2853 If the time is before now, it will be interpreted as tomorrow.
2855 Currently none of this works for ISO week specifications.
2857 When this option is nil, the current day, month and year will always be
2858 used as defaults.
2860 See also `org-agenda-jump-prefer-future'."
2861 :group 'org-time
2862 :type '(choice
2863 (const :tag "Never" nil)
2864 (const :tag "Check month and day" t)
2865 (const :tag "Check month, day, and time" time)))
2867 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2868 "Should the agenda jump command prefer the future for incomplete dates?
2869 The default is to do the same as configured in `org-read-date-prefer-future'.
2870 But you can also set a deviating value here.
2871 This may t or nil, or the symbol `org-read-date-prefer-future'."
2872 :group 'org-agenda
2873 :group 'org-time
2874 :version "24.1"
2875 :type '(choice
2876 (const :tag "Use org-read-date-prefer-future"
2877 org-read-date-prefer-future)
2878 (const :tag "Never" nil)
2879 (const :tag "Always" t)))
2881 (defcustom org-read-date-force-compatible-dates t
2882 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2884 Depending on the system Emacs is running on, certain dates cannot
2885 be represented with the type used internally to represent time.
2886 Dates between 1970-1-1 and 2038-1-1 can always be represented
2887 correctly. Some systems allow for earlier dates, some for later,
2888 some for both. One way to find out it to insert any date into an
2889 Org buffer, putting the cursor on the year and hitting S-up and
2890 S-down to test the range.
2892 When this variable is set to t, the date/time prompt will not let
2893 you specify dates outside the 1970-2037 range, so it is certain that
2894 these dates will work in whatever version of Emacs you are
2895 running, and also that you can move a file from one Emacs implementation
2896 to another. WHenever Org is forcing the year for you, it will display
2897 a message and beep.
2899 When this variable is nil, Org will check if the date is
2900 representable in the specific Emacs implementation you are using.
2901 If not, it will force a year, usually the current year, and beep
2902 to remind you. Currently this setting is not recommended because
2903 the likelihood that you will open your Org files in an Emacs that
2904 has limited date range is not negligible.
2906 A workaround for this problem is to use diary sexp dates for time
2907 stamps outside of this range."
2908 :group 'org-time
2909 :version "24.1"
2910 :type 'boolean)
2912 (defcustom org-read-date-display-live t
2913 "Non-nil means display current interpretation of date prompt live.
2914 This display will be in an overlay, in the minibuffer."
2915 :group 'org-time
2916 :type 'boolean)
2918 (defcustom org-read-date-popup-calendar t
2919 "Non-nil means pop up a calendar when prompting for a date.
2920 In the calendar, the date can be selected with mouse-1. However, the
2921 minibuffer will also be active, and you can simply enter the date as well.
2922 When nil, only the minibuffer will be available."
2923 :group 'org-time
2924 :type 'boolean)
2925 (if (fboundp 'defvaralias)
2926 (defvaralias 'org-popup-calendar-for-date-prompt
2927 'org-read-date-popup-calendar))
2929 (defcustom org-read-date-minibuffer-setup-hook nil
2930 "Hook to be used to set up keys for the date/time interface.
2931 Add key definitions to `minibuffer-local-map', which will be a temporary
2932 copy."
2933 :group 'org-time
2934 :type 'hook)
2936 (defcustom org-extend-today-until 0
2937 "The hour when your day really ends. Must be an integer.
2938 This has influence for the following applications:
2939 - When switching the agenda to \"today\". It it is still earlier than
2940 the time given here, the day recognized as TODAY is actually yesterday.
2941 - When a date is read from the user and it is still before the time given
2942 here, the current date and time will be assumed to be yesterday, 23:59.
2943 Also, timestamps inserted in capture templates follow this rule.
2945 IMPORTANT: This is a feature whose implementation is and likely will
2946 remain incomplete. Really, it is only here because past midnight seems to
2947 be the favorite working time of John Wiegley :-)"
2948 :group 'org-time
2949 :type 'integer)
2951 (defcustom org-use-effective-time nil
2952 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2953 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2954 \"effective time\" of any timestamps between midnight and 8am will be
2955 23:59 of the previous day."
2956 :group 'org-time
2957 :version "24.1"
2958 :type 'boolean)
2960 (defcustom org-use-last-clock-out-time-as-effective-time nil
2961 "When non-nil, use the last clock out time for `org-todo'.
2962 Note that this option has precedence over the combined use of
2963 `org-use-effective-time' and `org-extend-today-until'."
2964 :group 'org-time
2965 ;; :version "24.3"
2966 :type 'boolean)
2968 (defcustom org-edit-timestamp-down-means-later nil
2969 "Non-nil means S-down will increase the time in a time stamp.
2970 When nil, S-up will increase."
2971 :group 'org-time
2972 :type 'boolean)
2974 (defcustom org-calendar-follow-timestamp-change t
2975 "Non-nil means make the calendar window follow timestamp changes.
2976 When a timestamp is modified and the calendar window is visible, it will be
2977 moved to the new date."
2978 :group 'org-time
2979 :type 'boolean)
2981 (defgroup org-tags nil
2982 "Options concerning tags in Org-mode."
2983 :tag "Org Tags"
2984 :group 'org)
2986 (defcustom org-tag-alist nil
2987 "List of tags allowed in Org-mode files.
2988 When this list is nil, Org-mode will base TAG input on what is already in the
2989 buffer.
2990 The value of this variable is an alist, the car of each entry must be a
2991 keyword as a string, the cdr may be a character that is used to select
2992 that tag through the fast-tag-selection interface.
2993 See the manual for details."
2994 :group 'org-tags
2995 :type '(repeat
2996 (choice
2997 (cons (string :tag "Tag name")
2998 (character :tag "Access char"))
2999 (list :tag "Start radio group"
3000 (const :startgroup)
3001 (option (string :tag "Group description")))
3002 (list :tag "End radio group"
3003 (const :endgroup)
3004 (option (string :tag "Group description")))
3005 (const :tag "New line" (:newline)))))
3007 (defcustom org-tag-persistent-alist nil
3008 "List of tags that will always appear in all Org-mode files.
3009 This is in addition to any in buffer settings or customizations
3010 of `org-tag-alist'.
3011 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3012 The value of this variable is an alist, the car of each entry must be a
3013 keyword as a string, the cdr may be a character that is used to select
3014 that tag through the fast-tag-selection interface.
3015 See the manual for details.
3016 To disable these tags on a per-file basis, insert anywhere in the file:
3017 #+STARTUP: noptag"
3018 :group 'org-tags
3019 :type '(repeat
3020 (choice
3021 (cons (string :tag "Tag name")
3022 (character :tag "Access char"))
3023 (const :tag "Start radio group" (:startgroup))
3024 (const :tag "End radio group" (:endgroup))
3025 (const :tag "New line" (:newline)))))
3027 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3028 "If non-nil, always offer completion for all tags of all agenda files.
3029 Instead of customizing this variable directly, you might want to
3030 set it locally for capture buffers, because there no list of
3031 tags in that file can be created dynamically (there are none).
3033 (add-hook 'org-capture-mode-hook
3034 (lambda ()
3035 (set (make-local-variable
3036 'org-complete-tags-always-offer-all-agenda-tags)
3037 t)))"
3038 :group 'org-tags
3039 :version "24.1"
3040 :type 'boolean)
3042 (defvar org-file-tags nil
3043 "List of tags that can be inherited by all entries in the file.
3044 The tags will be inherited if the variable `org-use-tag-inheritance'
3045 says they should be.
3046 This variable is populated from #+FILETAGS lines.")
3048 (defcustom org-use-fast-tag-selection 'auto
3049 "Non-nil means use fast tag selection scheme.
3050 This is a special interface to select and deselect tags with single keys.
3051 When nil, fast selection is never used.
3052 When the symbol `auto', fast selection is used if and only if selection
3053 characters for tags have been configured, either through the variable
3054 `org-tag-alist' or through a #+TAGS line in the buffer.
3055 When t, fast selection is always used and selection keys are assigned
3056 automatically if necessary."
3057 :group 'org-tags
3058 :type '(choice
3059 (const :tag "Always" t)
3060 (const :tag "Never" nil)
3061 (const :tag "When selection characters are configured" 'auto)))
3063 (defcustom org-fast-tag-selection-single-key nil
3064 "Non-nil means fast tag selection exits after first change.
3065 When nil, you have to press RET to exit it.
3066 During fast tag selection, you can toggle this flag with `C-c'.
3067 This variable can also have the value `expert'. In this case, the window
3068 displaying the tags menu is not even shown, until you press C-c again."
3069 :group 'org-tags
3070 :type '(choice
3071 (const :tag "No" nil)
3072 (const :tag "Yes" t)
3073 (const :tag "Expert" expert)))
3075 (defvar org-fast-tag-selection-include-todo nil
3076 "Non-nil means fast tags selection interface will also offer TODO states.
3077 This is an undocumented feature, you should not rely on it.")
3079 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3080 "The column to which tags should be indented in a headline.
3081 If this number is positive, it specifies the column. If it is negative,
3082 it means that the tags should be flushright to that column. For example,
3083 -80 works well for a normal 80 character screen.
3084 When 0, place tags directly after headline text, with only one space in
3085 between."
3086 :group 'org-tags
3087 :type 'integer)
3089 (defcustom org-auto-align-tags t
3090 "Non-nil keeps tags aligned when modifying headlines.
3091 Some operations (i.e. demoting) change the length of a headline and
3092 therefore shift the tags around. With this option turned on, after
3093 each such operation the tags are again aligned to `org-tags-column'."
3094 :group 'org-tags
3095 :type 'boolean)
3097 (defcustom org-use-tag-inheritance t
3098 "Non-nil means tags in levels apply also for sublevels.
3099 When nil, only the tags directly given in a specific line apply there.
3100 This may also be a list of tags that should be inherited, or a regexp that
3101 matches tags that should be inherited. Additional control is possible
3102 with the variable `org-tags-exclude-from-inheritance' which gives an
3103 explicit list of tags to be excluded from inheritance., even if the value of
3104 `org-use-tag-inheritance' would select it for inheritance.
3106 If this option is t, a match early-on in a tree can lead to a large
3107 number of matches in the subtree when constructing the agenda or creating
3108 a sparse tree. If you only want to see the first match in a tree during
3109 a search, check out the variable `org-tags-match-list-sublevels'."
3110 :group 'org-tags
3111 :type '(choice
3112 (const :tag "Not" nil)
3113 (const :tag "Always" t)
3114 (repeat :tag "Specific tags" (string :tag "Tag"))
3115 (regexp :tag "Tags matched by regexp")))
3117 (defcustom org-tags-exclude-from-inheritance nil
3118 "List of tags that should never be inherited.
3119 This is a way to exclude a few tags from inheritance. For way to do
3120 the opposite, to actively allow inheritance for selected tags,
3121 see the variable `org-use-tag-inheritance'."
3122 :group 'org-tags
3123 :type '(repeat (string :tag "Tag")))
3125 (defun org-tag-inherit-p (tag)
3126 "Check if TAG is one that should be inherited."
3127 (cond
3128 ((member tag org-tags-exclude-from-inheritance) nil)
3129 ((eq org-use-tag-inheritance t) t)
3130 ((not org-use-tag-inheritance) nil)
3131 ((stringp org-use-tag-inheritance)
3132 (string-match org-use-tag-inheritance tag))
3133 ((listp org-use-tag-inheritance)
3134 (member tag org-use-tag-inheritance))
3135 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3137 (defcustom org-tags-match-list-sublevels t
3138 "Non-nil means list also sublevels of headlines matching a search.
3139 This variable applies to tags/property searches, and also to stuck
3140 projects because this search is based on a tags match as well.
3142 When set to the symbol `indented', sublevels are indented with
3143 leading dots.
3145 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3146 the sublevels of a headline matching a tag search often also match
3147 the same search. Listing all of them can create very long lists.
3148 Setting this variable to nil causes subtrees of a match to be skipped.
3150 This variable is semi-obsolete and probably should always be true. It
3151 is better to limit inheritance to certain tags using the variables
3152 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3153 :group 'org-tags
3154 :type '(choice
3155 (const :tag "No, don't list them" nil)
3156 (const :tag "Yes, do list them" t)
3157 (const :tag "List them, indented with leading dots" indented)))
3159 (defcustom org-tags-sort-function nil
3160 "When set, tags are sorted using this function as a comparator."
3161 :group 'org-tags
3162 :type '(choice
3163 (const :tag "No sorting" nil)
3164 (const :tag "Alphabetical" string<)
3165 (const :tag "Reverse alphabetical" string>)
3166 (function :tag "Custom function" nil)))
3168 (defvar org-tags-history nil
3169 "History of minibuffer reads for tags.")
3170 (defvar org-last-tags-completion-table nil
3171 "The last used completion table for tags.")
3172 (defvar org-after-tags-change-hook nil
3173 "Hook that is run after the tags in a line have changed.")
3175 (defgroup org-properties nil
3176 "Options concerning properties in Org-mode."
3177 :tag "Org Properties"
3178 :group 'org)
3180 (defcustom org-property-format "%-10s %s"
3181 "How property key/value pairs should be formatted by `indent-line'.
3182 When `indent-line' hits a property definition, it will format the line
3183 according to this format, mainly to make sure that the values are
3184 lined-up with respect to each other."
3185 :group 'org-properties
3186 :type 'string)
3188 (defcustom org-properties-postprocess-alist nil
3189 "Alist of properties and functions to adjust inserted values.
3190 Elements of this alist must be of the form
3192 ([string] [function])
3194 where [string] must be a property name and [function] must be a
3195 lambda expression: this lambda expression must take one argument,
3196 the value to adjust, and return the new value as a string.
3198 For example, this element will allow the property \"Remaining\"
3199 to be updated wrt the relation between the \"Effort\" property
3200 and the clock summary:
3202 ((\"Remaining\" (lambda(value)
3203 (let ((clocksum (org-clock-sum-current-item))
3204 (effort (org-duration-string-to-minutes
3205 (org-entry-get (point) \"Effort\"))))
3206 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3207 :group 'org-properties
3208 :version "24.1"
3209 :type '(alist :key-type (string :tag "Property")
3210 :value-type (function :tag "Function")))
3212 (defcustom org-use-property-inheritance nil
3213 "Non-nil means properties apply also for sublevels.
3215 This setting is chiefly used during property searches. Turning it on can
3216 cause significant overhead when doing a search, which is why it is not
3217 on by default.
3219 When nil, only the properties directly given in the current entry count.
3220 When t, every property is inherited. The value may also be a list of
3221 properties that should have inheritance, or a regular expression matching
3222 properties that should be inherited.
3224 However, note that some special properties use inheritance under special
3225 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3226 and the properties ending in \"_ALL\" when they are used as descriptor
3227 for valid values of a property.
3229 Note for programmers:
3230 When querying an entry with `org-entry-get', you can control if inheritance
3231 should be used. By default, `org-entry-get' looks only at the local
3232 properties. You can request inheritance by setting the inherit argument
3233 to t (to force inheritance) or to `selective' (to respect the setting
3234 in this variable)."
3235 :group 'org-properties
3236 :type '(choice
3237 (const :tag "Not" nil)
3238 (const :tag "Always" t)
3239 (repeat :tag "Specific properties" (string :tag "Property"))
3240 (regexp :tag "Properties matched by regexp")))
3242 (defun org-property-inherit-p (property)
3243 "Check if PROPERTY is one that should be inherited."
3244 (cond
3245 ((eq org-use-property-inheritance t) t)
3246 ((not org-use-property-inheritance) nil)
3247 ((stringp org-use-property-inheritance)
3248 (string-match org-use-property-inheritance property))
3249 ((listp org-use-property-inheritance)
3250 (member property org-use-property-inheritance))
3251 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3253 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3254 "The default column format, if no other format has been defined.
3255 This variable can be set on the per-file basis by inserting a line
3257 #+COLUMNS: %25ITEM ....."
3258 :group 'org-properties
3259 :type 'string)
3261 (defcustom org-columns-ellipses ".."
3262 "The ellipses to be used when a field in column view is truncated.
3263 When this is the empty string, as many characters as possible are shown,
3264 but then there will be no visual indication that the field has been truncated.
3265 When this is a string of length N, the last N characters of a truncated
3266 field are replaced by this string. If the column is narrower than the
3267 ellipses string, only part of the ellipses string will be shown."
3268 :group 'org-properties
3269 :type 'string)
3271 (defcustom org-columns-modify-value-for-display-function nil
3272 "Function that modifies values for display in column view.
3273 For example, it can be used to cut out a certain part from a time stamp.
3274 The function must take 2 arguments:
3276 column-title The title of the column (*not* the property name)
3277 value The value that should be modified.
3279 The function should return the value that should be displayed,
3280 or nil if the normal value should be used."
3281 :group 'org-properties
3282 :type 'function)
3284 (defcustom org-effort-property "Effort"
3285 "The property that is being used to keep track of effort estimates.
3286 Effort estimates given in this property need to have the format H:MM."
3287 :group 'org-properties
3288 :group 'org-progress
3289 :type '(string :tag "Property"))
3291 (defconst org-global-properties-fixed
3292 '(("VISIBILITY_ALL" . "folded children content all")
3293 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3294 "List of property/value pairs that can be inherited by any entry.
3296 These are fixed values, for the preset properties. The user variable
3297 that can be used to add to this list is `org-global-properties'.
3299 The entries in this list are cons cells where the car is a property
3300 name and cdr is a string with the value. If the value represents
3301 multiple items like an \"_ALL\" property, separate the items by
3302 spaces.")
3304 (defcustom org-global-properties nil
3305 "List of property/value pairs that can be inherited by any entry.
3307 This list will be combined with the constant `org-global-properties-fixed'.
3309 The entries in this list are cons cells where the car is a property
3310 name and cdr is a string with the value.
3312 You can set buffer-local values for the same purpose in the variable
3313 `org-file-properties' this by adding lines like
3315 #+PROPERTY: NAME VALUE"
3316 :group 'org-properties
3317 :type '(repeat
3318 (cons (string :tag "Property")
3319 (string :tag "Value"))))
3321 (defvar org-file-properties nil
3322 "List of property/value pairs that can be inherited by any entry.
3323 Valid for the current buffer.
3324 This variable is populated from #+PROPERTY lines.")
3325 (make-variable-buffer-local 'org-file-properties)
3327 (defgroup org-agenda nil
3328 "Options concerning agenda views in Org-mode."
3329 :tag "Org Agenda"
3330 :group 'org)
3332 (defvar org-category nil
3333 "Variable used by org files to set a category for agenda display.
3334 Such files should use a file variable to set it, for example
3336 # -*- mode: org; org-category: \"ELisp\"
3338 or contain a special line
3340 #+CATEGORY: ELisp
3342 If the file does not specify a category, then file's base name
3343 is used instead.")
3344 (make-variable-buffer-local 'org-category)
3345 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3347 (defcustom org-agenda-files nil
3348 "The files to be used for agenda display.
3349 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3350 \\[org-remove-file]. You can also use customize to edit the list.
3352 If an entry is a directory, all files in that directory that are matched by
3353 `org-agenda-file-regexp' will be part of the file list.
3355 If the value of the variable is not a list but a single file name, then
3356 the list of agenda files is actually stored and maintained in that file, one
3357 agenda file per line. In this file paths can be given relative to
3358 `org-directory'. Tilde expansion and environment variable substitution
3359 are also made."
3360 :group 'org-agenda
3361 :type '(choice
3362 (repeat :tag "List of files and directories" file)
3363 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3365 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3366 "Regular expression to match files for `org-agenda-files'.
3367 If any element in the list in that variable contains a directory instead
3368 of a normal file, all files in that directory that are matched by this
3369 regular expression will be included."
3370 :group 'org-agenda
3371 :type 'regexp)
3373 (defcustom org-agenda-text-search-extra-files nil
3374 "List of extra files to be searched by text search commands.
3375 These files will be search in addition to the agenda files by the
3376 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3377 Note that these files will only be searched for text search commands,
3378 not for the other agenda views like todo lists, tag searches or the weekly
3379 agenda. This variable is intended to list notes and possibly archive files
3380 that should also be searched by these two commands.
3381 In fact, if the first element in the list is the symbol `agenda-archives',
3382 than all archive files of all agenda files will be added to the search
3383 scope."
3384 :group 'org-agenda
3385 :type '(set :greedy t
3386 (const :tag "Agenda Archives" agenda-archives)
3387 (repeat :inline t (file))))
3389 (if (fboundp 'defvaralias)
3390 (defvaralias 'org-agenda-multi-occur-extra-files
3391 'org-agenda-text-search-extra-files))
3393 (defcustom org-agenda-skip-unavailable-files nil
3394 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3395 A nil value means to remove them, after a query, from the list."
3396 :group 'org-agenda
3397 :type 'boolean)
3399 (defcustom org-calendar-to-agenda-key [?c]
3400 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3401 The command `org-calendar-goto-agenda' will be bound to this key. The
3402 default is the character `c' because then `c' can be used to switch back and
3403 forth between agenda and calendar."
3404 :group 'org-agenda
3405 :type 'sexp)
3407 (defcustom org-calendar-insert-diary-entry-key [?i]
3408 "The key to be installed in `calendar-mode-map' for adding diary entries.
3409 This option is irrelevant until `org-agenda-diary-file' has been configured
3410 to point to an Org-mode file. When that is the case, the command
3411 `org-agenda-diary-entry' will be bound to the key given here, by default
3412 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3413 if you want to continue doing this, you need to change this to a different
3414 key."
3415 :group 'org-agenda
3416 :type 'sexp)
3418 (defcustom org-agenda-diary-file 'diary-file
3419 "File to which to add new entries with the `i' key in agenda and calendar.
3420 When this is the symbol `diary-file', the functionality in the Emacs
3421 calendar will be used to add entries to the `diary-file'. But when this
3422 points to a file, `org-agenda-diary-entry' will be used instead."
3423 :group 'org-agenda
3424 :type '(choice
3425 (const :tag "The standard Emacs diary file" diary-file)
3426 (file :tag "Special Org file diary entries")))
3428 (eval-after-load "calendar"
3429 '(progn
3430 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3431 'org-calendar-goto-agenda)
3432 (add-hook 'calendar-mode-hook
3433 (lambda ()
3434 (unless (eq org-agenda-diary-file 'diary-file)
3435 (define-key calendar-mode-map
3436 org-calendar-insert-diary-entry-key
3437 'org-agenda-diary-entry))))))
3439 (defgroup org-latex nil
3440 "Options for embedding LaTeX code into Org-mode."
3441 :tag "Org LaTeX"
3442 :group 'org)
3444 (defcustom org-format-latex-options
3445 '(:foreground default :background default :scale 1.0
3446 :html-foreground "Black" :html-background "Transparent"
3447 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3448 "Options for creating images from LaTeX fragments.
3449 This is a property list with the following properties:
3450 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3451 `default' means use the foreground of the default face.
3452 `auto' means use the foreground from the text face.
3453 :background the background color, or \"Transparent\".
3454 `default' means use the background of the default face.
3455 `auto' means use the background from the text face.
3456 :scale a scaling factor for the size of the images, to get more pixels
3457 :html-foreground, :html-background, :html-scale
3458 the same numbers for HTML export.
3459 :matchers a list indicating which matchers should be used to
3460 find LaTeX fragments. Valid members of this list are:
3461 \"begin\" find environments
3462 \"$1\" find single characters surrounded by $.$
3463 \"$\" find math expressions surrounded by $...$
3464 \"$$\" find math expressions surrounded by $$....$$
3465 \"\\(\" find math expressions surrounded by \\(...\\)
3466 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3467 :group 'org-latex
3468 :type 'plist)
3470 (defcustom org-format-latex-signal-error t
3471 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3472 When nil, just push out a message."
3473 :group 'org-latex
3474 :version "24.1"
3475 :type 'boolean)
3477 (defcustom org-latex-to-mathml-jar-file nil
3478 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3479 Use this to specify additional executable file say a jar file.
3481 When using MathToWeb as the converter, specify the full-path to
3482 your mathtoweb.jar file."
3483 :group 'org-latex
3484 :version "24.1"
3485 :type '(choice
3486 (const :tag "None" nil)
3487 (file :tag "JAR file" :must-match t)))
3489 (defcustom org-latex-to-mathml-convert-command nil
3490 "Command to convert LaTeX fragments to MathML.
3491 Replace format-specifiers in the command as noted below and use
3492 `shell-command' to convert LaTeX to MathML.
3493 %j: Executable file in fully expanded form as specified by
3494 `org-latex-to-mathml-jar-file'.
3495 %I: Input LaTeX file in fully expanded form
3496 %o: Output MathML file
3497 This command is used by `org-create-math-formula'.
3499 When using MathToWeb as the converter, set this to
3500 \"java -jar %j -unicode -force -df %o %I\"."
3501 :group 'org-latex
3502 :version "24.1"
3503 :type '(choice
3504 (const :tag "None" nil)
3505 (string :tag "\nShell command")))
3507 (defcustom org-latex-create-formula-image-program 'dvipng
3508 "Program to convert LaTeX fragments with.
3510 dvipng Process the LaTeX fragments to dvi file, then convert
3511 dvi files to png files using dvipng.
3512 This will also include processing of non-math environments.
3513 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3514 to convert pdf files to png files"
3515 :group 'org-latex
3516 :version "24.1"
3517 :type '(choice
3518 (const :tag "dvipng" dvipng)
3519 (const :tag "imagemagick" imagemagick)))
3521 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3522 "Path to store latex preview images.
3523 A relative path here creates many directories relative to the
3524 processed org files paths. An absolute path puts all preview
3525 images at the same place."
3526 :group 'org-latex
3527 :version "24.3"
3528 :type 'string)
3530 (defun org-format-latex-mathml-available-p ()
3531 "Return t if `org-latex-to-mathml-convert-command' is usable."
3532 (save-match-data
3533 (when (and (boundp 'org-latex-to-mathml-convert-command)
3534 org-latex-to-mathml-convert-command)
3535 (let ((executable (car (split-string
3536 org-latex-to-mathml-convert-command))))
3537 (when (executable-find executable)
3538 (if (string-match
3539 "%j" org-latex-to-mathml-convert-command)
3540 (file-readable-p org-latex-to-mathml-jar-file)
3541 t))))))
3543 (defcustom org-format-latex-header "\\documentclass{article}
3544 \\usepackage[usenames]{color}
3545 \\usepackage{amsmath}
3546 \\usepackage[mathscr]{eucal}
3547 \\pagestyle{empty} % do not remove
3548 \[PACKAGES]
3549 \[DEFAULT-PACKAGES]
3550 % The settings below are copied from fullpage.sty
3551 \\setlength{\\textwidth}{\\paperwidth}
3552 \\addtolength{\\textwidth}{-3cm}
3553 \\setlength{\\oddsidemargin}{1.5cm}
3554 \\addtolength{\\oddsidemargin}{-2.54cm}
3555 \\setlength{\\evensidemargin}{\\oddsidemargin}
3556 \\setlength{\\textheight}{\\paperheight}
3557 \\addtolength{\\textheight}{-\\headheight}
3558 \\addtolength{\\textheight}{-\\headsep}
3559 \\addtolength{\\textheight}{-\\footskip}
3560 \\addtolength{\\textheight}{-3cm}
3561 \\setlength{\\topmargin}{1.5cm}
3562 \\addtolength{\\topmargin}{-2.54cm}"
3563 "The document header used for processing LaTeX fragments.
3564 It is imperative that this header make sure that no page number
3565 appears on the page. The package defined in the variables
3566 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3567 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3568 will be appended."
3569 :group 'org-latex
3570 :type 'string)
3572 (defvar org-format-latex-header-extra nil)
3574 (defun org-set-packages-alist (var val)
3575 "Set the packages alist and make sure it has 3 elements per entry."
3576 (set var (mapcar (lambda (x)
3577 (if (and (consp x) (= (length x) 2))
3578 (list (car x) (nth 1 x) t)
3580 val)))
3582 (defun org-get-packages-alist (var)
3584 "Get the packages alist and make sure it has 3 elements per entry."
3585 (mapcar (lambda (x)
3586 (if (and (consp x) (= (length x) 2))
3587 (list (car x) (nth 1 x) t)
3589 (default-value var)))
3591 ;; The following variables are defined here because is it also used
3592 ;; when formatting latex fragments. Originally it was part of the
3593 ;; LaTeX exporter, which is why the name includes "export".
3594 (defcustom org-export-latex-default-packages-alist
3595 '(("AUTO" "inputenc" t)
3596 ("T1" "fontenc" t)
3597 ("" "fixltx2e" nil)
3598 ("" "graphicx" t)
3599 ("" "longtable" nil)
3600 ("" "float" nil)
3601 ("" "wrapfig" nil)
3602 ("" "soul" t)
3603 ("" "textcomp" t)
3604 ("" "marvosym" t)
3605 ("" "wasysym" t)
3606 ("" "latexsym" t)
3607 ("" "amssymb" t)
3608 ("" "hyperref" nil)
3609 "\\tolerance=1000"
3611 "Alist of default packages to be inserted in the header.
3612 Change this only if one of the packages here causes an incompatibility
3613 with another package you are using.
3614 The packages in this list are needed by one part or another of Org-mode
3615 to function properly.
3617 - inputenc, fontenc: for basic font and character selection
3618 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3619 for interpreting the entities in `org-entities'. You can skip some of these
3620 packages if you don't use any of the symbols in it.
3621 - graphicx: for including images
3622 - float, wrapfig: for figure placement
3623 - longtable: for long tables
3624 - hyperref: for cross references
3626 Therefore you should not modify this variable unless you know what you
3627 are doing. The one reason to change it anyway is that you might be loading
3628 some other package that conflicts with one of the default packages.
3629 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3630 If SNIPPET-FLAG is t, the package also needs to be included when
3631 compiling LaTeX snippets into images for inclusion into HTML."
3632 :group 'org-export-latex
3633 :set 'org-set-packages-alist
3634 :get 'org-get-packages-alist
3635 :version "24.1"
3636 :type '(repeat
3637 (choice
3638 (list :tag "options/package pair"
3639 (string :tag "options")
3640 (string :tag "package")
3641 (boolean :tag "Snippet"))
3642 (string :tag "A line of LaTeX"))))
3644 (defcustom org-export-latex-packages-alist nil
3645 "Alist of packages to be inserted in every LaTeX header.
3646 These will be inserted after `org-export-latex-default-packages-alist'.
3647 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3648 SNIPPET-FLAG, when t, indicates that this package is also needed when
3649 turning LaTeX snippets into images for inclusion into HTML.
3650 Make sure that you only list packages here which:
3651 - you want in every file
3652 - do not conflict with the default packages in
3653 `org-export-latex-default-packages-alist'
3654 - do not conflict with the setup in `org-format-latex-header'."
3655 :group 'org-export-latex
3656 :set 'org-set-packages-alist
3657 :get 'org-get-packages-alist
3658 :type '(repeat
3659 (choice
3660 (list :tag "options/package pair"
3661 (string :tag "options")
3662 (string :tag "package")
3663 (boolean :tag "Snippet"))
3664 (string :tag "A line of LaTeX"))))
3667 (defgroup org-appearance nil
3668 "Settings for Org-mode appearance."
3669 :tag "Org Appearance"
3670 :group 'org)
3672 (defcustom org-level-color-stars-only nil
3673 "Non-nil means fontify only the stars in each headline.
3674 When nil, the entire headline is fontified.
3675 Changing it requires restart of `font-lock-mode' to become effective
3676 also in regions already fontified."
3677 :group 'org-appearance
3678 :type 'boolean)
3680 (defcustom org-hide-leading-stars nil
3681 "Non-nil means hide the first N-1 stars in a headline.
3682 This works by using the face `org-hide' for these stars. This
3683 face is white for a light background, and black for a dark
3684 background. You may have to customize the face `org-hide' to
3685 make this work.
3686 Changing it requires restart of `font-lock-mode' to become effective
3687 also in regions already fontified.
3688 You may also set this on a per-file basis by adding one of the following
3689 lines to the buffer:
3691 #+STARTUP: hidestars
3692 #+STARTUP: showstars"
3693 :group 'org-appearance
3694 :type 'boolean)
3696 (defcustom org-hidden-keywords nil
3697 "List of symbols corresponding to keywords to be hidden the org buffer.
3698 For example, a value '(title) for this list will make the document's title
3699 appear in the buffer without the initial #+TITLE: keyword."
3700 :group 'org-appearance
3701 :version "24.1"
3702 :type '(set (const :tag "#+AUTHOR" author)
3703 (const :tag "#+DATE" date)
3704 (const :tag "#+EMAIL" email)
3705 (const :tag "#+TITLE" title)))
3707 (defcustom org-custom-properties nil
3708 "List of properties (as strings) with a special meaning.
3709 The default use of these custom properties is to let the user
3710 hide them with `org-toggle-custom-properties-visibility'."
3711 :group 'org-properties
3712 :group 'org-appearance
3713 :version "24.3"
3714 :type '(repeat (string :tag "Property Name")))
3716 (defcustom org-fontify-done-headline nil
3717 "Non-nil means change the face of a headline if it is marked DONE.
3718 Normally, only the TODO/DONE keyword indicates the state of a headline.
3719 When this is non-nil, the headline after the keyword is set to the
3720 `org-headline-done' as an additional indication."
3721 :group 'org-appearance
3722 :type 'boolean)
3724 (defcustom org-fontify-emphasized-text t
3725 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3726 Changing this variable requires a restart of Emacs to take effect."
3727 :group 'org-appearance
3728 :type 'boolean)
3730 (defcustom org-fontify-whole-heading-line nil
3731 "Non-nil means fontify the whole line for headings.
3732 This is useful when setting a background color for the
3733 org-level-* faces."
3734 :group 'org-appearance
3735 :type 'boolean)
3737 (defcustom org-highlight-latex-fragments-and-specials nil
3738 "Non-nil means fontify what is treated specially by the exporters."
3739 :group 'org-appearance
3740 :type 'boolean)
3742 (defcustom org-hide-emphasis-markers nil
3743 "Non-nil mean font-lock should hide the emphasis marker characters."
3744 :group 'org-appearance
3745 :type 'boolean)
3747 (defcustom org-pretty-entities nil
3748 "Non-nil means show entities as UTF8 characters.
3749 When nil, the \\name form remains in the buffer."
3750 :group 'org-appearance
3751 :version "24.1"
3752 :type 'boolean)
3754 (defcustom org-pretty-entities-include-sub-superscripts t
3755 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3756 :group 'org-appearance
3757 :version "24.1"
3758 :type 'boolean)
3760 (defvar org-emph-re nil
3761 "Regular expression for matching emphasis.
3762 After a match, the match groups contain these elements:
3763 0 The match of the full regular expression, including the characters
3764 before and after the proper match
3765 1 The character before the proper match, or empty at beginning of line
3766 2 The proper match, including the leading and trailing markers
3767 3 The leading marker like * or /, indicating the type of highlighting
3768 4 The text between the emphasis markers, not including the markers
3769 5 The character after the match, empty at the end of a line")
3770 (defvar org-verbatim-re nil
3771 "Regular expression for matching verbatim text.")
3772 (defvar org-emphasis-regexp-components) ; defined just below
3773 (defvar org-emphasis-alist) ; defined just below
3774 (defun org-set-emph-re (var val)
3775 "Set variable and compute the emphasis regular expression."
3776 (set var val)
3777 (when (and (boundp 'org-emphasis-alist)
3778 (boundp 'org-emphasis-regexp-components)
3779 org-emphasis-alist org-emphasis-regexp-components)
3780 (let* ((e org-emphasis-regexp-components)
3781 (pre (car e))
3782 (post (nth 1 e))
3783 (border (nth 2 e))
3784 (body (nth 3 e))
3785 (nl (nth 4 e))
3786 (body1 (concat body "*?"))
3787 (markers (mapconcat 'car org-emphasis-alist ""))
3788 (vmarkers (mapconcat
3789 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3790 org-emphasis-alist "")))
3791 ;; make sure special characters appear at the right position in the class
3792 (if (string-match "\\^" markers)
3793 (setq markers (concat (replace-match "" t t markers) "^")))
3794 (if (string-match "-" markers)
3795 (setq markers (concat (replace-match "" t t markers) "-")))
3796 (if (string-match "\\^" vmarkers)
3797 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3798 (if (string-match "-" vmarkers)
3799 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3800 (if (> nl 0)
3801 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3802 (int-to-string nl) "\\}")))
3803 ;; Make the regexp
3804 (setq org-emph-re
3805 (concat "\\([" pre "]\\|^\\)"
3806 "\\("
3807 "\\([" markers "]\\)"
3808 "\\("
3809 "[^" border "]\\|"
3810 "[^" border "]"
3811 body1
3812 "[^" border "]"
3813 "\\)"
3814 "\\3\\)"
3815 "\\([" post "]\\|$\\)"))
3816 (setq org-verbatim-re
3817 (concat "\\([" pre "]\\|^\\)"
3818 "\\("
3819 "\\([" vmarkers "]\\)"
3820 "\\("
3821 "[^" border "]\\|"
3822 "[^" border "]"
3823 body1
3824 "[^" border "]"
3825 "\\)"
3826 "\\3\\)"
3827 "\\([" post "]\\|$\\)")))))
3829 (defcustom org-emphasis-regexp-components
3830 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3831 "Components used to build the regular expression for emphasis.
3832 This is a list with five entries. Terminology: In an emphasis string
3833 like \" *strong word* \", we call the initial space PREMATCH, the final
3834 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3835 and \"trong wor\" is the body. The different components in this variable
3836 specify what is allowed/forbidden in each part:
3838 pre Chars allowed as prematch. Beginning of line will be allowed too.
3839 post Chars allowed as postmatch. End of line will be allowed too.
3840 border The chars *forbidden* as border characters.
3841 body-regexp A regexp like \".\" to match a body character. Don't use
3842 non-shy groups here, and don't allow newline here.
3843 newline The maximum number of newlines allowed in an emphasis exp.
3845 Use customize to modify this, or restart Emacs after changing it."
3846 :group 'org-appearance
3847 :set 'org-set-emph-re
3848 :type '(list
3849 (sexp :tag "Allowed chars in pre ")
3850 (sexp :tag "Allowed chars in post ")
3851 (sexp :tag "Forbidden chars in border ")
3852 (sexp :tag "Regexp for body ")
3853 (integer :tag "number of newlines allowed")
3854 (option (boolean :tag "Please ignore this button"))))
3856 (defcustom org-emphasis-alist
3857 `(("*" bold "<b>" "</b>")
3858 ("/" italic "<i>" "</i>")
3859 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3860 ("=" org-code "<code>" "</code>" verbatim)
3861 ("~" org-verbatim "<code>" "</code>" verbatim)
3862 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3863 "<del>" "</del>")
3865 "Special syntax for emphasized text.
3866 Text starting and ending with a special character will be emphasized, for
3867 example *bold*, _underlined_ and /italic/. This variable sets the marker
3868 characters, the face to be used by font-lock for highlighting in Org-mode
3869 Emacs buffers, and the HTML tags to be used for this.
3870 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3871 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3872 Use customize to modify this, or restart Emacs after changing it."
3873 :group 'org-appearance
3874 :set 'org-set-emph-re
3875 :type '(repeat
3876 (list
3877 (string :tag "Marker character")
3878 (choice
3879 (face :tag "Font-lock-face")
3880 (plist :tag "Face property list"))
3881 (string :tag "HTML start tag")
3882 (string :tag "HTML end tag")
3883 (option (const verbatim)))))
3885 (defvar org-protecting-blocks
3886 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3887 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3888 This is needed for font-lock setup.")
3890 ;;; Miscellaneous options
3892 (defgroup org-completion nil
3893 "Completion in Org-mode."
3894 :tag "Org Completion"
3895 :group 'org)
3897 (defcustom org-completion-use-ido nil
3898 "Non-nil means use ido completion wherever possible.
3899 Note that `ido-mode' must be active for this variable to be relevant.
3900 If you decide to turn this variable on, you might well want to turn off
3901 `org-outline-path-complete-in-steps'.
3902 See also `org-completion-use-iswitchb'."
3903 :group 'org-completion
3904 :type 'boolean)
3906 (defcustom org-completion-use-iswitchb nil
3907 "Non-nil means use iswitchb completion wherever possible.
3908 Note that `iswitchb-mode' must be active for this variable to be relevant.
3909 If you decide to turn this variable on, you might well want to turn off
3910 `org-outline-path-complete-in-steps'.
3911 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3912 :group 'org-completion
3913 :type 'boolean)
3915 (defcustom org-completion-fallback-command 'hippie-expand
3916 "The expansion command called by \\[pcomplete] in normal context.
3917 Normal means, no org-mode-specific context."
3918 :group 'org-completion
3919 :type 'function)
3921 ;;; Functions and variables from their packages
3922 ;; Declared here to avoid compiler warnings
3924 ;; XEmacs only
3925 (defvar outline-mode-menu-heading)
3926 (defvar outline-mode-menu-show)
3927 (defvar outline-mode-menu-hide)
3928 (defvar zmacs-regions) ; XEmacs regions
3930 ;; Emacs only
3931 (defvar mark-active)
3933 ;; Various packages
3934 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3935 (declare-function calendar-forward-day "cal-move" (arg))
3936 (declare-function calendar-goto-date "cal-move" (date))
3937 (declare-function calendar-goto-today "cal-move" ())
3938 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3939 (defvar calc-embedded-close-formula)
3940 (defvar calc-embedded-open-formula)
3941 (declare-function cdlatex-tab "ext:cdlatex" ())
3942 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3943 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3944 (defvar font-lock-unfontify-region-function)
3945 (declare-function iswitchb-read-buffer "iswitchb"
3946 (prompt &optional default require-match start matches-set))
3947 (defvar iswitchb-temp-buflist)
3948 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3949 (defvar org-agenda-tags-todo-honor-ignore-options)
3950 (declare-function org-agenda-skip "org-agenda" ())
3951 (declare-function
3952 org-agenda-format-item "org-agenda"
3953 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3954 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3955 (declare-function org-agenda-change-all-lines "org-agenda"
3956 (newhead hdmarker &optional fixface just-this))
3957 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3958 (declare-function org-agenda-maybe-redo "org-agenda" ())
3959 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3960 (beg end))
3961 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3962 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3963 "org-agenda" (&optional end))
3964 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3965 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3966 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3967 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3968 (declare-function org-indent-mode "org-indent" (&optional arg))
3969 (declare-function parse-time-string "parse-time" (string))
3970 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3971 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3972 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3973 (defvar remember-data-file)
3974 (defvar texmathp-why)
3975 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3976 (declare-function table--at-cell-p "table" (position &optional object at-column))
3978 (defvar w3m-current-url)
3979 (defvar w3m-current-title)
3981 (defvar org-latex-regexps)
3983 ;;; Autoload and prepare some org modules
3985 ;; Some table stuff that needs to be defined here, because it is used
3986 ;; by the functions setting up org-mode or checking for table context.
3988 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3989 "Detect an org-type or table-type table.")
3990 (defconst org-table-line-regexp "^[ \t]*|"
3991 "Detect an org-type table line.")
3992 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3993 "Detect an org-type table line.")
3994 (defconst org-table-hline-regexp "^[ \t]*|-"
3995 "Detect an org-type table hline.")
3996 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3997 "Detect a table-type table hline.")
3998 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3999 "Detect the first line outside a table when searching from within it.
4000 This works for both table types.")
4002 ;; Autoload the functions in org-table.el that are needed by functions here.
4004 (eval-and-compile
4005 (org-autoload "org-table"
4006 '(org-table-begin org-table-blank-field org-table-end)))
4008 ;;;###autoload
4009 (defun turn-on-orgtbl ()
4010 "Unconditionally turn on `orgtbl-mode'."
4011 (require 'org-table)
4012 (orgtbl-mode 1))
4014 (defun org-at-table-p (&optional table-type)
4015 "Return t if the cursor is inside an org-type table.
4016 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4017 (if org-enable-table-editor
4018 (save-excursion
4019 (beginning-of-line 1)
4020 (looking-at (if table-type org-table-any-line-regexp
4021 org-table-line-regexp)))
4022 nil))
4023 (defsubst org-table-p () (org-at-table-p))
4025 (defun org-at-table.el-p ()
4026 "Return t if and only if we are at a table.el table."
4027 (and (org-at-table-p 'any)
4028 (save-excursion
4029 (goto-char (org-table-begin 'any))
4030 (looking-at org-table1-hline-regexp))))
4031 (defun org-table-recognize-table.el ()
4032 "If there is a table.el table nearby, recognize it and move into it."
4033 (if org-table-tab-recognizes-table.el
4034 (if (org-at-table.el-p)
4035 (progn
4036 (beginning-of-line 1)
4037 (if (looking-at org-table-dataline-regexp)
4039 (if (looking-at org-table1-hline-regexp)
4040 (progn
4041 (beginning-of-line 2)
4042 (if (looking-at org-table-any-border-regexp)
4043 (beginning-of-line -1)))))
4044 (if (re-search-forward "|" (org-table-end t) t)
4045 (progn
4046 (require 'table)
4047 (if (table--at-cell-p (point))
4049 (message "recognizing table.el table...")
4050 (table-recognize-table)
4051 (message "recognizing table.el table...done")))
4052 (error "This should not happen"))
4054 nil)
4055 nil))
4057 (defun org-at-table-hline-p ()
4058 "Return t if the cursor is inside a hline in a table."
4059 (if org-enable-table-editor
4060 (save-excursion
4061 (beginning-of-line 1)
4062 (looking-at org-table-hline-regexp))
4063 nil))
4065 (defvar org-table-clean-did-remove-column nil)
4067 (defun org-table-map-tables (function &optional quietly)
4068 "Apply FUNCTION to the start of all tables in the buffer."
4069 (save-excursion
4070 (save-restriction
4071 (widen)
4072 (goto-char (point-min))
4073 (while (re-search-forward org-table-any-line-regexp nil t)
4074 (unless quietly
4075 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4076 (beginning-of-line 1)
4077 (when (and (looking-at org-table-line-regexp)
4078 ;; Exclude tables in src/example/verbatim/clocktable blocks
4079 (not (org-in-block-p '("src" "example"))))
4080 (save-excursion (funcall function))
4081 (or (looking-at org-table-line-regexp)
4082 (forward-char 1)))
4083 (re-search-forward org-table-any-border-regexp nil 1))))
4084 (unless quietly (message "Mapping tables: done")))
4086 ;; Declare and autoload functions from org-exp.el & Co
4088 (declare-function org-default-export-plist "org-exp")
4089 (declare-function org-infile-export-plist "org-exp")
4090 (declare-function org-get-current-options "org-exp")
4092 ;; Declare and autoload functions from org-agenda.el
4094 (eval-and-compile
4095 (org-autoload "org-agenda"
4096 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4098 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4099 (declare-function org-clock-update-mode-line "org-clock" ())
4100 (declare-function org-resolve-clocks "org-clock"
4101 (&optional also-non-dangling-p prompt last-valid))
4102 (defvar org-clock-start-time)
4103 (defvar org-clock-marker (make-marker)
4104 "Marker recording the last clock-in.")
4105 (defvar org-clock-hd-marker (make-marker)
4106 "Marker recording the last clock-in, but the headline position.")
4107 (defvar org-clock-heading ""
4108 "The heading of the current clock entry.")
4109 (defun org-clock-is-active ()
4110 "Return non-nil if clock is currently running.
4111 The return value is actually the clock marker."
4112 (marker-buffer org-clock-marker))
4114 (eval-and-compile
4115 (org-autoload "org-clock" '(org-clock-remove-overlays
4116 org-clock-update-time-maybe
4117 org-clocktable-shift)))
4119 (defun org-check-running-clock ()
4120 "Check if the current buffer contains the running clock.
4121 If yes, offer to stop it and to save the buffer with the changes."
4122 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4123 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4124 (buffer-name))))
4125 (org-clock-out)
4126 (when (y-or-n-p "Save changed buffer?")
4127 (save-buffer))))
4129 (defun org-clocktable-try-shift (dir n)
4130 "Check if this line starts a clock table, if yes, shift the time block."
4131 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4132 (org-clocktable-shift dir n)))
4134 ;;;###autoload
4135 (defun org-clock-persistence-insinuate ()
4136 "Set up hooks for clock persistence."
4137 (require 'org-clock)
4138 (add-hook 'org-mode-hook 'org-clock-load)
4139 (add-hook 'kill-emacs-hook 'org-clock-save))
4141 ;; Define the variable already here, to make sure we have it.
4142 (defvar org-indent-mode nil
4143 "Non-nil if Org-Indent mode is enabled.
4144 Use the command `org-indent-mode' to change this variable.")
4146 ;; Autoload archiving code
4147 ;; The stuff that is needed for cycling and tags has to be defined here.
4149 (defgroup org-archive nil
4150 "Options concerning archiving in Org-mode."
4151 :tag "Org Archive"
4152 :group 'org-structure)
4154 (defcustom org-archive-location "%s_archive::"
4155 "The location where subtrees should be archived.
4157 The value of this variable is a string, consisting of two parts,
4158 separated by a double-colon. The first part is a filename and
4159 the second part is a headline.
4161 When the filename is omitted, archiving happens in the same file.
4162 %s in the filename will be replaced by the current file
4163 name (without the directory part). Archiving to a different file
4164 is useful to keep archived entries from contributing to the
4165 Org-mode Agenda.
4167 The archived entries will be filed as subtrees of the specified
4168 headline. When the headline is omitted, the subtrees are simply
4169 filed away at the end of the file, as top-level entries. Also in
4170 the heading you can use %s to represent the file name, this can be
4171 useful when using the same archive for a number of different files.
4173 Here are a few examples:
4174 \"%s_archive::\"
4175 If the current file is Projects.org, archive in file
4176 Projects.org_archive, as top-level trees. This is the default.
4178 \"::* Archived Tasks\"
4179 Archive in the current file, under the top-level headline
4180 \"* Archived Tasks\".
4182 \"~/org/archive.org::\"
4183 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4185 \"~/org/archive.org::* From %s\"
4186 Archive in file ~/org/archive.org (absolute path), under headlines
4187 \"From FILENAME\" where file name is the current file name.
4189 \"~/org/datetree.org::datetree/* Finished Tasks\"
4190 The \"datetree/\" string is special, signifying to archive
4191 items to the datetree. Items are placed in either the CLOSED
4192 date of the item, or the current date if there is no CLOSED date.
4193 The heading will be a subentry to the current date. There doesn't
4194 need to be a heading, but there always needs to be a slash after
4195 datetree. For example, to store archived items directly in the
4196 datetree, use \"~/org/datetree.org::datetree/\".
4198 \"basement::** Finished Tasks\"
4199 Archive in file ./basement (relative path), as level 3 trees
4200 below the level 2 heading \"** Finished Tasks\".
4202 You may set this option on a per-file basis by adding to the buffer a
4203 line like
4205 #+ARCHIVE: basement::** Finished Tasks
4207 You may also define it locally for a subtree by setting an ARCHIVE property
4208 in the entry. If such a property is found in an entry, or anywhere up
4209 the hierarchy, it will be used."
4210 :group 'org-archive
4211 :type 'string)
4213 (defcustom org-archive-tag "ARCHIVE"
4214 "The tag that marks a subtree as archived.
4215 An archived subtree does not open during visibility cycling, and does
4216 not contribute to the agenda listings.
4217 After changing this, font-lock must be restarted in the relevant buffers to
4218 get the proper fontification."
4219 :group 'org-archive
4220 :group 'org-keywords
4221 :type 'string)
4223 (defcustom org-agenda-skip-archived-trees t
4224 "Non-nil means the agenda will skip any items located in archived trees.
4225 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4226 variable is no longer recommended, you should leave it at the value t.
4227 Instead, use the key `v' to cycle the archives-mode in the agenda."
4228 :group 'org-archive
4229 :group 'org-agenda-skip
4230 :type 'boolean)
4232 (defcustom org-columns-skip-archived-trees t
4233 "Non-nil means ignore archived trees when creating column view."
4234 :group 'org-archive
4235 :group 'org-properties
4236 :type 'boolean)
4238 (defcustom org-cycle-open-archived-trees nil
4239 "Non-nil means `org-cycle' will open archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE.
4241 When nil, archived trees will stay folded. You can still open them with
4242 normal outline commands like `show-all', but not with the cycling commands."
4243 :group 'org-archive
4244 :group 'org-cycle
4245 :type 'boolean)
4247 (defcustom org-sparse-tree-open-archived-trees nil
4248 "Non-nil means sparse tree construction shows matches in archived trees.
4249 When nil, matches in these trees are highlighted, but the trees are kept in
4250 collapsed state."
4251 :group 'org-archive
4252 :group 'org-sparse-trees
4253 :type 'boolean)
4255 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4256 "The default date type when building a sparse tree.
4257 When this is nil, a date is a scheduled or a deadline timestamp.
4258 Otherwise, these types are allowed:
4260 all: all timestamps
4261 active: only active timestamps (<...>)
4262 inactive: only inactive timestamps (<...)
4263 scheduled: only scheduled timestamps
4264 deadline: only deadline timestamps"
4265 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4266 (const :tag "All timestamps" all)
4267 (const :tag "Only active timestamps" active)
4268 (const :tag "Only inactive timestamps" inactive)
4269 (const :tag "Only scheduled timestamps" scheduled)
4270 (const :tag "Only deadline timestamps" deadline))
4271 :version "24.3"
4272 :group 'org-sparse-trees)
4274 (defun org-cycle-hide-archived-subtrees (state)
4275 "Re-hide all archived subtrees after a visibility state change."
4276 (when (and (not org-cycle-open-archived-trees)
4277 (not (memq state '(overview folded))))
4278 (save-excursion
4279 (let* ((globalp (memq state '(contents all)))
4280 (beg (if globalp (point-min) (point)))
4281 (end (if globalp (point-max) (org-end-of-subtree t))))
4282 (org-hide-archived-subtrees beg end)
4283 (goto-char beg)
4284 (if (looking-at (concat ".*:" org-archive-tag ":"))
4285 (message "%s" (substitute-command-keys
4286 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4288 (defun org-force-cycle-archived ()
4289 "Cycle subtree even if it is archived."
4290 (interactive)
4291 (setq this-command 'org-cycle)
4292 (let ((org-cycle-open-archived-trees t))
4293 (call-interactively 'org-cycle)))
4295 (defun org-hide-archived-subtrees (beg end)
4296 "Re-hide all archived subtrees after a visibility state change."
4297 (save-excursion
4298 (let* ((re (concat ":" org-archive-tag ":")))
4299 (goto-char beg)
4300 (while (re-search-forward re end t)
4301 (when (org-at-heading-p)
4302 (org-flag-subtree t)
4303 (org-end-of-subtree t))))))
4305 (declare-function outline-end-of-heading "outline" ())
4306 (declare-function outline-flag-region "outline" (from to flag))
4307 (defun org-flag-subtree (flag)
4308 (save-excursion
4309 (org-back-to-heading t)
4310 (outline-end-of-heading)
4311 (outline-flag-region (point)
4312 (progn (org-end-of-subtree t) (point))
4313 flag)))
4315 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4317 (eval-and-compile
4318 (org-autoload "org-archive"
4319 '(org-add-archive-files)))
4321 ;; Autoload Column View Code
4323 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4324 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4325 (declare-function org-columns-compute "org-colview" (property))
4327 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4328 '(org-columns-number-to-string
4329 org-columns-get-format-and-top-level
4330 org-columns-compute
4331 org-columns-remove-overlays))
4333 ;; Autoload ID code
4335 (declare-function org-id-store-link "org-id")
4336 (declare-function org-id-locations-load "org-id")
4337 (declare-function org-id-locations-save "org-id")
4338 (defvar org-id-track-globally)
4339 (org-autoload "org-id"
4340 '(org-id-new
4341 org-id-copy
4342 org-id-get-with-outline-path-completion
4343 org-id-get-with-outline-drilling))
4345 ;;; Variables for pre-computed regular expressions, all buffer local
4347 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4348 "Matches first line of a hidden block.")
4349 (make-variable-buffer-local 'org-drawer-regexp)
4350 (defvar org-todo-regexp nil
4351 "Matches any of the TODO state keywords.")
4352 (make-variable-buffer-local 'org-todo-regexp)
4353 (defvar org-not-done-regexp nil
4354 "Matches any of the TODO state keywords except the last one.")
4355 (make-variable-buffer-local 'org-not-done-regexp)
4356 (defvar org-not-done-heading-regexp nil
4357 "Matches a TODO headline that is not done.")
4358 (make-variable-buffer-local 'org-not-done-regexp)
4359 (defvar org-todo-line-regexp nil
4360 "Matches a headline and puts TODO state into group 2 if present.")
4361 (make-variable-buffer-local 'org-todo-line-regexp)
4362 (defvar org-complex-heading-regexp nil
4363 "Matches a headline and puts everything into groups:
4364 group 1: the stars
4365 group 2: The todo keyword, maybe
4366 group 3: Priority cookie
4367 group 4: True headline
4368 group 5: Tags")
4369 (make-variable-buffer-local 'org-complex-heading-regexp)
4370 (defvar org-complex-heading-regexp-format nil
4371 "Printf format to make regexp to match an exact headline.
4372 This regexp will match the headline of any node which has the
4373 exact headline text that is put into the format, but may have any
4374 TODO state, priority and tags.")
4375 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4376 (defvar org-todo-line-tags-regexp nil
4377 "Matches a headline and puts TODO state into group 2 if present.
4378 Also put tags into group 4 if tags are present.")
4379 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4380 (defvar org-ds-keyword-length 12
4381 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4382 (make-variable-buffer-local 'org-ds-keyword-length)
4383 (defvar org-deadline-regexp nil
4384 "Matches the DEADLINE keyword.")
4385 (make-variable-buffer-local 'org-deadline-regexp)
4386 (defvar org-deadline-time-regexp nil
4387 "Matches the DEADLINE keyword together with a time stamp.")
4388 (make-variable-buffer-local 'org-deadline-time-regexp)
4389 (defvar org-deadline-line-regexp nil
4390 "Matches the DEADLINE keyword and the rest of the line.")
4391 (make-variable-buffer-local 'org-deadline-line-regexp)
4392 (defvar org-scheduled-regexp nil
4393 "Matches the SCHEDULED keyword.")
4394 (make-variable-buffer-local 'org-scheduled-regexp)
4395 (defvar org-scheduled-time-regexp nil
4396 "Matches the SCHEDULED keyword together with a time stamp.")
4397 (make-variable-buffer-local 'org-scheduled-time-regexp)
4398 (defvar org-closed-time-regexp nil
4399 "Matches the CLOSED keyword together with a time stamp.")
4400 (make-variable-buffer-local 'org-closed-time-regexp)
4402 (defvar org-keyword-time-regexp nil
4403 "Matches any of the 4 keywords, together with the time stamp.")
4404 (make-variable-buffer-local 'org-keyword-time-regexp)
4405 (defvar org-keyword-time-not-clock-regexp nil
4406 "Matches any of the 3 keywords, together with the time stamp.")
4407 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4408 (defvar org-maybe-keyword-time-regexp nil
4409 "Matches a timestamp, possibly preceded by a keyword.")
4410 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4411 (defvar org-all-time-keywords nil
4412 "List of time keywords.")
4413 (make-variable-buffer-local 'org-all-time-keywords)
4415 (defconst org-plain-time-of-day-regexp
4416 (concat
4417 "\\(\\<[012]?[0-9]"
4418 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4419 "\\(--?"
4420 "\\(\\<[012]?[0-9]"
4421 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4422 "\\)?")
4423 "Regular expression to match a plain time or time range.
4424 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4425 groups carry important information:
4426 0 the full match
4427 1 the first time, range or not
4428 8 the second time, if it is a range.")
4430 (defconst org-plain-time-extension-regexp
4431 (concat
4432 "\\(\\<[012]?[0-9]"
4433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4434 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4435 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4436 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4437 groups carry important information:
4438 0 the full match
4439 7 hours of duration
4440 9 minutes of duration")
4442 (defconst org-stamp-time-of-day-regexp
4443 (concat
4444 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4445 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4446 "\\(--?"
4447 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4448 "Regular expression to match a timestamp time or time range.
4449 After a match, the following groups carry important information:
4450 0 the full match
4451 1 date plus weekday, for back referencing to make sure both times are on the same day
4452 2 the first time, range or not
4453 4 the second time, if it is a range.")
4455 (defconst org-startup-options
4456 '(("fold" org-startup-folded t)
4457 ("overview" org-startup-folded t)
4458 ("nofold" org-startup-folded nil)
4459 ("showall" org-startup-folded nil)
4460 ("showeverything" org-startup-folded showeverything)
4461 ("content" org-startup-folded content)
4462 ("indent" org-startup-indented t)
4463 ("noindent" org-startup-indented nil)
4464 ("hidestars" org-hide-leading-stars t)
4465 ("showstars" org-hide-leading-stars nil)
4466 ("odd" org-odd-levels-only t)
4467 ("oddeven" org-odd-levels-only nil)
4468 ("align" org-startup-align-all-tables t)
4469 ("noalign" org-startup-align-all-tables nil)
4470 ("inlineimages" org-startup-with-inline-images t)
4471 ("noinlineimages" org-startup-with-inline-images nil)
4472 ("customtime" org-display-custom-times t)
4473 ("logdone" org-log-done time)
4474 ("lognotedone" org-log-done note)
4475 ("nologdone" org-log-done nil)
4476 ("lognoteclock-out" org-log-note-clock-out t)
4477 ("nolognoteclock-out" org-log-note-clock-out nil)
4478 ("logrepeat" org-log-repeat state)
4479 ("lognoterepeat" org-log-repeat note)
4480 ("nologrepeat" org-log-repeat nil)
4481 ("logreschedule" org-log-reschedule time)
4482 ("lognotereschedule" org-log-reschedule note)
4483 ("nologreschedule" org-log-reschedule nil)
4484 ("logredeadline" org-log-redeadline time)
4485 ("lognoteredeadline" org-log-redeadline note)
4486 ("nologredeadline" org-log-redeadline nil)
4487 ("logrefile" org-log-refile time)
4488 ("lognoterefile" org-log-refile note)
4489 ("nologrefile" org-log-refile nil)
4490 ("fninline" org-footnote-define-inline t)
4491 ("nofninline" org-footnote-define-inline nil)
4492 ("fnlocal" org-footnote-section nil)
4493 ("fnauto" org-footnote-auto-label t)
4494 ("fnprompt" org-footnote-auto-label nil)
4495 ("fnconfirm" org-footnote-auto-label confirm)
4496 ("fnplain" org-footnote-auto-label plain)
4497 ("fnadjust" org-footnote-auto-adjust t)
4498 ("nofnadjust" org-footnote-auto-adjust nil)
4499 ("constcgs" constants-unit-system cgs)
4500 ("constSI" constants-unit-system SI)
4501 ("noptag" org-tag-persistent-alist nil)
4502 ("hideblocks" org-hide-block-startup t)
4503 ("nohideblocks" org-hide-block-startup nil)
4504 ("beamer" org-startup-with-beamer-mode t)
4505 ("entitiespretty" org-pretty-entities t)
4506 ("entitiesplain" org-pretty-entities nil))
4507 "Variable associated with STARTUP options for org-mode.
4508 Each element is a list of three items: the startup options (as written
4509 in the #+STARTUP line), the corresponding variable, and the value to set
4510 this variable to if the option is found. An optional forth element PUSH
4511 means to push this value onto the list in the variable.")
4513 (defun org-update-property-plist (key val props)
4514 "Update PROPS with KEY and VAL."
4515 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4516 (key (if appending (substring key 0 (- (length key) 1)) key))
4517 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4518 (previous (cdr (assoc key props))))
4519 (if appending
4520 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4521 (cons (cons key val) remainder))))
4523 (defconst org-block-regexp
4524 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4525 "Regular expression for hiding blocks.")
4526 (defconst org-heading-keyword-regexp-format
4527 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4528 "Printf format for a regexp matching an headline with some keyword.
4529 This regexp will match the headline of any node which has the
4530 exact keyword that is put into the format. The keyword isn't in
4531 any group by default, but the stars and the body are.")
4532 (defconst org-heading-keyword-maybe-regexp-format
4533 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4534 "Printf format for a regexp matching an headline, possibly with some keyword.
4535 This regexp can match any headline with the specified keyword, or
4536 without a keyword. The keyword isn't in any group by default,
4537 but the stars and the body are.")
4539 (defun org-set-regexps-and-options ()
4540 "Precompute regular expressions for current buffer."
4541 (when (derived-mode-p 'org-mode)
4542 (org-set-local 'org-todo-kwd-alist nil)
4543 (org-set-local 'org-todo-key-alist nil)
4544 (org-set-local 'org-todo-key-trigger nil)
4545 (org-set-local 'org-todo-keywords-1 nil)
4546 (org-set-local 'org-done-keywords nil)
4547 (org-set-local 'org-todo-heads nil)
4548 (org-set-local 'org-todo-sets nil)
4549 (org-set-local 'org-todo-log-states nil)
4550 (org-set-local 'org-file-properties nil)
4551 (org-set-local 'org-file-tags nil)
4552 (let ((re (org-make-options-regexp
4553 '("CATEGORY" "TODO" "COLUMNS"
4554 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4555 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4556 "OPTIONS")
4557 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4558 (splitre "[ \t]+")
4559 (scripts org-use-sub-superscripts)
4560 kwds kws0 kwsa key log value cat arch tags const links hw dws
4561 tail sep kws1 prio props ftags drawers beamer-p
4562 ext-setup-or-nil setup-contents (start 0))
4563 (save-excursion
4564 (save-restriction
4565 (widen)
4566 (goto-char (point-min))
4567 (while (or (and ext-setup-or-nil
4568 (string-match re ext-setup-or-nil start)
4569 (setq start (match-end 0)))
4570 (and (setq ext-setup-or-nil nil start 0)
4571 (re-search-forward re nil t)))
4572 (setq key (upcase (match-string 1 ext-setup-or-nil))
4573 value (org-match-string-no-properties 2 ext-setup-or-nil))
4574 (if (stringp value) (setq value (org-trim value)))
4575 (cond
4576 ((equal key "CATEGORY")
4577 (setq cat value))
4578 ((member key '("SEQ_TODO" "TODO"))
4579 (push (cons 'sequence (org-split-string value splitre)) kwds))
4580 ((equal key "TYP_TODO")
4581 (push (cons 'type (org-split-string value splitre)) kwds))
4582 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4583 ;; general TODO-like setup
4584 (push (cons (intern (downcase (match-string 1 key)))
4585 (org-split-string value splitre)) kwds))
4586 ((equal key "TAGS")
4587 (setq tags (append tags (if tags '("\\n") nil)
4588 (org-split-string value splitre))))
4589 ((equal key "COLUMNS")
4590 (org-set-local 'org-columns-default-format value))
4591 ((equal key "LINK")
4592 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4593 (push (cons (match-string 1 value)
4594 (org-trim (match-string 2 value)))
4595 links)))
4596 ((equal key "PRIORITIES")
4597 (setq prio (org-split-string value " +")))
4598 ((equal key "PROPERTY")
4599 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4600 (setq props (org-update-property-plist (match-string 1 value)
4601 (match-string 2 value)
4602 props))))
4603 ((equal key "FILETAGS")
4604 (when (string-match "\\S-" value)
4605 (setq ftags
4606 (append
4607 ftags
4608 (apply 'append
4609 (mapcar (lambda (x) (org-split-string x ":"))
4610 (org-split-string value)))))))
4611 ((equal key "DRAWERS")
4612 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4613 ((equal key "CONSTANTS")
4614 (setq const (append const (org-split-string value splitre))))
4615 ((equal key "STARTUP")
4616 (let ((opts (org-split-string value splitre))
4617 l var val)
4618 (while (setq l (pop opts))
4619 (when (setq l (assoc l org-startup-options))
4620 (setq var (nth 1 l) val (nth 2 l))
4621 (if (not (nth 3 l))
4622 (set (make-local-variable var) val)
4623 (if (not (listp (symbol-value var)))
4624 (set (make-local-variable var) nil))
4625 (set (make-local-variable var) (symbol-value var))
4626 (add-to-list var val))))))
4627 ((equal key "ARCHIVE")
4628 (setq arch value)
4629 (remove-text-properties 0 (length arch)
4630 '(face t fontified t) arch))
4631 ((equal key "LATEX_CLASS")
4632 (setq beamer-p (equal value "beamer")))
4633 ((equal key "OPTIONS")
4634 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4635 (setq scripts (read (match-string 2 value)))))
4636 ((equal key "SETUPFILE")
4637 (setq setup-contents (org-file-contents
4638 (expand-file-name
4639 (org-remove-double-quotes value))
4640 'noerror))
4641 (if (not ext-setup-or-nil)
4642 (setq ext-setup-or-nil setup-contents start 0)
4643 (setq ext-setup-or-nil
4644 (concat (substring ext-setup-or-nil 0 start)
4645 "\n" setup-contents "\n"
4646 (substring ext-setup-or-nil start)))))))
4647 ;; search for property blocks
4648 (goto-char (point-min))
4649 (while (re-search-forward org-block-regexp nil t)
4650 (when (equal "PROPERTY" (upcase (match-string 1)))
4651 (setq value (replace-regexp-in-string
4652 "[\n\r]" " " (match-string 4)))
4653 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4654 (setq props (org-update-property-plist (match-string 1 value)
4655 (match-string 2 value)
4656 props)))))))
4657 (org-set-local 'org-use-sub-superscripts scripts)
4658 (when cat
4659 (org-set-local 'org-category (intern cat))
4660 (push (cons "CATEGORY" cat) props))
4661 (when prio
4662 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4663 (setq prio (mapcar 'string-to-char prio))
4664 (org-set-local 'org-highest-priority (nth 0 prio))
4665 (org-set-local 'org-lowest-priority (nth 1 prio))
4666 (org-set-local 'org-default-priority (nth 2 prio)))
4667 (and props (org-set-local 'org-file-properties (nreverse props)))
4668 (and ftags (org-set-local 'org-file-tags
4669 (mapcar 'org-add-prop-inherited ftags)))
4670 (and drawers (org-set-local 'org-drawers drawers))
4671 (and arch (org-set-local 'org-archive-location arch))
4672 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4673 ;; Process the TODO keywords
4674 (unless kwds
4675 ;; Use the global values as if they had been given locally.
4676 (setq kwds (default-value 'org-todo-keywords))
4677 (if (stringp (car kwds))
4678 (setq kwds (list (cons org-todo-interpretation
4679 (default-value 'org-todo-keywords)))))
4680 (setq kwds (reverse kwds)))
4681 (setq kwds (nreverse kwds))
4682 (let (inter kws kw)
4683 (while (setq kws (pop kwds))
4684 (let ((kws (or
4685 (run-hook-with-args-until-success
4686 'org-todo-setup-filter-hook kws)
4687 kws)))
4688 (setq inter (pop kws) sep (member "|" kws)
4689 kws0 (delete "|" (copy-sequence kws))
4690 kwsa nil
4691 kws1 (mapcar
4692 (lambda (x)
4693 ;; 1 2
4694 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4695 (progn
4696 (setq kw (match-string 1 x)
4697 key (and (match-end 2) (match-string 2 x))
4698 log (org-extract-log-state-settings x))
4699 (push (cons kw (and key (string-to-char key))) kwsa)
4700 (and log (push log org-todo-log-states))
4702 (error "Invalid TODO keyword %s" x)))
4703 kws0)
4704 kwsa (if kwsa (append '((:startgroup))
4705 (nreverse kwsa)
4706 '((:endgroup))))
4707 hw (car kws1)
4708 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4709 tail (list inter hw (car dws) (org-last dws))))
4710 (add-to-list 'org-todo-heads hw 'append)
4711 (push kws1 org-todo-sets)
4712 (setq org-done-keywords (append org-done-keywords dws nil))
4713 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4714 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4715 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4716 (setq org-todo-sets (nreverse org-todo-sets)
4717 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4718 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4719 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4720 ;; Process the constants
4721 (when const
4722 (let (e cst)
4723 (while (setq e (pop const))
4724 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4725 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4726 (setq org-table-formula-constants-local cst)))
4728 ;; Process the tags.
4729 (when tags
4730 (let (e tgs)
4731 (while (setq e (pop tags))
4732 (cond
4733 ((equal e "{") (push '(:startgroup) tgs))
4734 ((equal e "}") (push '(:endgroup) tgs))
4735 ((equal e "\\n") (push '(:newline) tgs))
4736 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4737 (push (cons (match-string 1 e)
4738 (string-to-char (match-string 2 e)))
4739 tgs))
4740 (t (push (list e) tgs))))
4741 (org-set-local 'org-tag-alist nil)
4742 (while (setq e (pop tgs))
4743 (or (and (stringp (car e))
4744 (assoc (car e) org-tag-alist))
4745 (push e org-tag-alist)))))
4747 ;; Compute the regular expressions and other local variables.
4748 ;; Using `org-outline-regexp-bol' would complicate them much,
4749 ;; because of the fixed white space at the end of that string.
4750 (if (not org-done-keywords)
4751 (setq org-done-keywords (and org-todo-keywords-1
4752 (list (org-last org-todo-keywords-1)))))
4753 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4754 (length org-scheduled-string)
4755 (length org-clock-string)
4756 (length org-closed-string)))
4757 org-drawer-regexp
4758 (concat "^[ \t]*:\\("
4759 (mapconcat 'regexp-quote org-drawers "\\|")
4760 "\\):[ \t]*$")
4761 org-not-done-keywords
4762 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4763 org-todo-regexp
4764 (concat "\\("
4765 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4766 "\\)")
4767 org-not-done-regexp
4768 (concat "\\("
4769 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4770 "\\)")
4771 org-not-done-heading-regexp
4772 (format org-heading-keyword-regexp-format org-not-done-regexp)
4773 org-todo-line-regexp
4774 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4775 org-complex-heading-regexp
4776 (concat "^\\(\\*+\\)"
4777 "\\(?: +" org-todo-regexp "\\)?"
4778 "\\(?: +\\(\\[#.\\]\\)\\)?"
4779 "\\(?: +\\(.*?\\)\\)??"
4780 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4781 "[ \t]*$")
4782 org-complex-heading-regexp-format
4783 (concat "^\\(\\*+\\)"
4784 "\\(?: +" org-todo-regexp "\\)?"
4785 "\\(?: +\\(\\[#.\\]\\)\\)?"
4786 "\\(?: +"
4787 ;; Stats cookies can be stuck to body.
4788 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4789 "\\(%s\\)"
4790 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4791 "\\)"
4792 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4793 "[ \t]*$")
4794 org-todo-line-tags-regexp
4795 (concat "^\\(\\*+\\)"
4796 "\\(?: +" org-todo-regexp "\\)?"
4797 "\\(?: +\\(.*?\\)\\)??"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-deadline-regexp (concat "\\<" org-deadline-string)
4801 org-deadline-time-regexp
4802 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4803 org-deadline-line-regexp
4804 (concat "\\<\\(" org-deadline-string "\\).*")
4805 org-scheduled-regexp
4806 (concat "\\<" org-scheduled-string)
4807 org-scheduled-time-regexp
4808 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4809 org-closed-time-regexp
4810 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4811 org-keyword-time-regexp
4812 (concat "\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\|" org-clock-string "\\)"
4816 " *[[<]\\([^]>]+\\)[]>]")
4817 org-keyword-time-not-clock-regexp
4818 (concat "\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\)"
4822 " *[[<]\\([^]>]+\\)[]>]")
4823 org-maybe-keyword-time-regexp
4824 (concat "\\(\\<\\(" org-scheduled-string
4825 "\\|" org-deadline-string
4826 "\\|" org-closed-string
4827 "\\|" org-clock-string "\\)\\)?"
4828 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4829 org-all-time-keywords
4830 (mapcar (lambda (w) (substring w 0 -1))
4831 (list org-scheduled-string org-deadline-string
4832 org-clock-string org-closed-string))
4834 (org-compute-latex-and-specials-regexp)
4835 (org-set-font-lock-defaults))))
4837 (defun org-file-contents (file &optional noerror)
4838 "Return the contents of FILE, as a string."
4839 (if (or (not file)
4840 (not (file-readable-p file)))
4841 (if noerror
4842 (progn
4843 (message "Cannot read file \"%s\"" file)
4844 (ding) (sit-for 2)
4846 (error "Cannot read file \"%s\"" file))
4847 (with-temp-buffer
4848 (insert-file-contents file)
4849 (buffer-string))))
4851 (defun org-extract-log-state-settings (x)
4852 "Extract the log state setting from a TODO keyword string.
4853 This will extract info from a string like \"WAIT(w@/!)\"."
4854 (let (kw key log1 log2)
4855 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4856 (setq kw (match-string 1 x)
4857 key (and (match-end 2) (match-string 2 x))
4858 log1 (and (match-end 3) (match-string 3 x))
4859 log2 (and (match-end 4) (match-string 4 x)))
4860 (and (or log1 log2)
4861 (list kw
4862 (and log1 (if (equal log1 "!") 'time 'note))
4863 (and log2 (if (equal log2 "!") 'time 'note)))))))
4865 (defun org-remove-keyword-keys (list)
4866 "Remove a pair of parenthesis at the end of each string in LIST."
4867 (mapcar (lambda (x)
4868 (if (string-match "(.*)$" x)
4869 (substring x 0 (match-beginning 0))
4871 list))
4873 (defun org-assign-fast-keys (alist)
4874 "Assign fast keys to a keyword-key alist.
4875 Respect keys that are already there."
4876 (let (new e (alt ?0))
4877 (while (setq e (pop alist))
4878 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4879 (cdr e)) ;; Key already assigned.
4880 (push e new)
4881 (let ((clist (string-to-list (downcase (car e))))
4882 (used (append new alist)))
4883 (when (= (car clist) ?@)
4884 (pop clist))
4885 (while (and clist (rassoc (car clist) used))
4886 (pop clist))
4887 (unless clist
4888 (while (rassoc alt used)
4889 (incf alt)))
4890 (push (cons (car e) (or (car clist) alt)) new))))
4891 (nreverse new)))
4893 ;;; Some variables used in various places
4895 (defvar org-window-configuration nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-selected-window nil
4898 "Used in various places to store a window configuration.")
4899 (defvar org-finish-function nil
4900 "Function to be called when `C-c C-c' is used.
4901 This is for getting out of special buffers like capture.")
4904 ;; FIXME: Occasionally check by commenting these, to make sure
4905 ;; no other functions uses these, forgetting to let-bind them.
4906 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4907 (defvar org-last-state)
4908 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4910 ;; Defined somewhere in this file, but used before definition.
4911 (defvar org-entities) ;; defined in org-entities.el
4912 (defvar org-struct-menu)
4913 (defvar org-org-menu)
4914 (defvar org-tbl-menu)
4916 ;;;; Define the Org-mode
4918 ;; We use a before-change function to check if a table might need
4919 ;; an update.
4920 (defvar org-table-may-need-update t
4921 "Indicates that a table might need an update.
4922 This variable is set by `org-before-change-function'.
4923 `org-table-align' sets it back to nil.")
4924 (defun org-before-change-function (beg end)
4925 "Every change indicates that a table might need an update."
4926 (setq org-table-may-need-update t))
4927 (defvar org-mode-map)
4928 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4929 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4930 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4931 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4932 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4933 (defvar org-table-buffer-is-an nil)
4935 (defvar bidi-paragraph-direction)
4936 (defvar buffer-face-mode-face)
4938 (require 'outline)
4939 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4940 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4941 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4943 ;; Other stuff we need.
4944 (require 'time-date)
4945 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4946 (require 'easymenu)
4947 (require 'overlay)
4949 (require 'org-macs)
4950 (require 'org-entities)
4951 ;; (require 'org-compat) moved higher up in the file before it is first used
4952 (require 'org-faces)
4953 (require 'org-list)
4954 (require 'org-pcomplete)
4955 (require 'org-src)
4956 (require 'org-footnote)
4958 ;; babel
4959 (require 'ob)
4961 ;;;###autoload
4962 (define-derived-mode org-mode outline-mode "Org"
4963 "Outline-based notes management and organizer, alias
4964 \"Carsten's outline-mode for keeping track of everything.\"
4966 Org-mode develops organizational tasks around a NOTES file which
4967 contains information about projects as plain text. Org-mode is
4968 implemented on top of outline-mode, which is ideal to keep the content
4969 of large files well structured. It supports ToDo items, deadlines and
4970 time stamps, which magically appear in the diary listing of the Emacs
4971 calendar. Tables are easily created with a built-in table editor.
4972 Plain text URL-like links connect to websites, emails (VM), Usenet
4973 messages (Gnus), BBDB entries, and any files related to the project.
4974 For printing and sharing of notes, an Org-mode file (or a part of it)
4975 can be exported as a structured ASCII or HTML file.
4977 The following commands are available:
4979 \\{org-mode-map}"
4981 ;; Get rid of Outline menus, they are not needed
4982 ;; Need to do this here because define-derived-mode sets up
4983 ;; the keymap so late. Still, it is a waste to call this each time
4984 ;; we switch another buffer into org-mode.
4985 (if (featurep 'xemacs)
4986 (when (boundp 'outline-mode-menu-heading)
4987 ;; Assume this is Greg's port, it uses easymenu
4988 (easy-menu-remove outline-mode-menu-heading)
4989 (easy-menu-remove outline-mode-menu-show)
4990 (easy-menu-remove outline-mode-menu-hide))
4991 (define-key org-mode-map [menu-bar headings] 'undefined)
4992 (define-key org-mode-map [menu-bar hide] 'undefined)
4993 (define-key org-mode-map [menu-bar show] 'undefined))
4995 (org-load-modules-maybe)
4996 (easy-menu-add org-org-menu)
4997 (easy-menu-add org-tbl-menu)
4998 (org-install-agenda-files-menu)
4999 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5000 (add-to-invisibility-spec '(org-cwidth))
5001 (add-to-invisibility-spec '(org-hide-block . t))
5002 (when (featurep 'xemacs)
5003 (org-set-local 'line-move-ignore-invisible t))
5004 (org-set-local 'outline-regexp org-outline-regexp)
5005 (org-set-local 'outline-level 'org-outline-level)
5006 (setq bidi-paragraph-direction 'left-to-right)
5007 (when (and org-ellipsis
5008 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5009 (fboundp 'make-glyph-code))
5010 (unless org-display-table
5011 (setq org-display-table (make-display-table)))
5012 (set-display-table-slot
5013 org-display-table 4
5014 (vconcat (mapcar
5015 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5016 org-ellipsis)))
5017 (if (stringp org-ellipsis) org-ellipsis "..."))))
5018 (setq buffer-display-table org-display-table))
5019 (org-set-regexps-and-options)
5020 (when (and org-tag-faces (not org-tags-special-faces-re))
5021 ;; tag faces set outside customize.... force initialization.
5022 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5023 ;; Calc embedded
5024 (org-set-local 'calc-embedded-open-mode "# ")
5025 (modify-syntax-entry ?@ "w")
5026 (modify-syntax-entry ?\" "\"")
5027 (if org-startup-truncated (setq truncate-lines t))
5028 (org-set-local 'font-lock-unfontify-region-function
5029 'org-unfontify-region)
5030 ;; Activate before-change-function
5031 (org-set-local 'org-table-may-need-update t)
5032 (org-add-hook 'before-change-functions 'org-before-change-function nil
5033 'local)
5034 ;; Check for running clock before killing a buffer
5035 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5036 ;; Initialize macros templates.
5037 (org-macro-initialize-templates)
5038 ;; Initialize radio targets.
5039 (org-update-radio-target-regexp)
5040 ;; Indentation.
5041 (org-set-local 'indent-line-function 'org-indent-line)
5042 (org-set-local 'indent-region-function 'org-indent-region)
5043 ;; Filling and auto-filling.
5044 (org-setup-filling)
5045 ;; Comments.
5046 (org-setup-comments-handling)
5047 ;; Beginning/end of defun
5048 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5049 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5050 ;; Next error for sparse trees
5051 (org-set-local 'next-error-function 'org-occur-next-match)
5052 ;; Make sure dependence stuff works reliably, even for users who set it
5053 ;; too late :-(
5054 (if org-enforce-todo-dependencies
5055 (add-hook 'org-blocker-hook
5056 'org-block-todo-from-children-or-siblings-or-parent)
5057 (remove-hook 'org-blocker-hook
5058 'org-block-todo-from-children-or-siblings-or-parent))
5059 (if org-enforce-todo-checkbox-dependencies
5060 (add-hook 'org-blocker-hook
5061 'org-block-todo-from-checkboxes)
5062 (remove-hook 'org-blocker-hook
5063 'org-block-todo-from-checkboxes))
5065 ;; Align options lines
5066 (org-set-local
5067 'align-mode-rules-list
5068 '((org-in-buffer-settings
5069 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5070 (modes . '(org-mode)))))
5072 ;; Imenu
5073 (org-set-local 'imenu-create-index-function
5074 'org-imenu-get-tree)
5076 ;; Make isearch reveal context
5077 (if (or (featurep 'xemacs)
5078 (not (boundp 'outline-isearch-open-invisible-function)))
5079 ;; Emacs 21 and XEmacs make use of the hook
5080 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5081 ;; Emacs 22 deals with this through a special variable
5082 (org-set-local 'outline-isearch-open-invisible-function
5083 (lambda (&rest ignore) (org-show-context 'isearch))))
5085 ;; Turn on org-beamer-mode?
5086 (and org-startup-with-beamer-mode (org-beamer-mode))
5088 ;; Setup the pcomplete hooks
5089 (set (make-local-variable 'pcomplete-command-completion-function)
5090 'org-pcomplete-initial)
5091 (set (make-local-variable 'pcomplete-command-name-function)
5092 'org-command-at-point)
5093 (set (make-local-variable 'pcomplete-default-completion-function)
5094 'ignore)
5095 (set (make-local-variable 'pcomplete-parse-arguments-function)
5096 'org-parse-arguments)
5097 (set (make-local-variable 'pcomplete-termination-string) "")
5098 (when (>= emacs-major-version 23)
5099 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5101 ;; If empty file that did not turn on org-mode automatically, make it to.
5102 (if (and org-insert-mode-line-in-empty-file
5103 (org-called-interactively-p 'any)
5104 (= (point-min) (point-max)))
5105 (insert "# -*- mode: org -*-\n\n"))
5106 (unless org-inhibit-startup
5107 (when org-startup-align-all-tables
5108 (let ((bmp (buffer-modified-p)))
5109 (org-table-map-tables 'org-table-align 'quietly)
5110 (set-buffer-modified-p bmp)))
5111 (when org-startup-with-inline-images
5112 (org-display-inline-images))
5113 (when org-startup-indented
5114 (require 'org-indent)
5115 (org-indent-mode 1))
5116 (unless org-inhibit-startup-visibility-stuff
5117 (org-set-startup-visibility)))
5118 ;; Try to set org-hide correctly
5119 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5121 (when (fboundp 'abbrev-table-put)
5122 (abbrev-table-put org-mode-abbrev-table
5123 :parents (list text-mode-abbrev-table)))
5125 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5128 (defun org-find-invisible-foreground ()
5129 (let ((candidates (remove
5130 "unspecified-bg"
5131 (nconc
5132 (list (face-background 'default)
5133 (face-background 'org-default))
5134 (mapcar
5135 (lambda (alist)
5136 (when (boundp alist)
5137 (cdr (assoc 'background-color (symbol-value alist)))))
5138 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5139 (list (face-foreground 'org-hide))))))
5140 (car (remove nil candidates))))
5142 (defun org-current-time ()
5143 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5144 (if (> (car org-time-stamp-rounding-minutes) 1)
5145 (let ((r (car org-time-stamp-rounding-minutes))
5146 (time (decode-time)))
5147 (apply 'encode-time
5148 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5149 (nthcdr 2 time))))
5150 (current-time)))
5152 (defun org-today ()
5153 "Return today date, considering `org-extend-today-until'."
5154 (time-to-days
5155 (time-subtract (current-time)
5156 (list 0 (* 3600 org-extend-today-until) 0))))
5158 ;;;; Font-Lock stuff, including the activators
5160 (defvar org-mouse-map (make-sparse-keymap))
5161 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5162 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5163 (when org-mouse-1-follows-link
5164 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5165 (when org-tab-follows-link
5166 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5167 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5169 (require 'font-lock)
5171 (defconst org-non-link-chars "]\t\n\r<>")
5172 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5173 "shell" "elisp" "doi" "message"))
5174 (defvar org-link-types-re nil
5175 "Matches a link that has a url-like prefix like \"http:\"")
5176 (defvar org-link-re-with-space nil
5177 "Matches a link with spaces, optional angular brackets around it.")
5178 (defvar org-link-re-with-space2 nil
5179 "Matches a link with spaces, optional angular brackets around it.")
5180 (defvar org-link-re-with-space3 nil
5181 "Matches a link with spaces, only for internal part in bracket links.")
5182 (defvar org-angle-link-re nil
5183 "Matches link with angular brackets, spaces are allowed.")
5184 (defvar org-plain-link-re nil
5185 "Matches plain link, without spaces.")
5186 (defvar org-bracket-link-regexp nil
5187 "Matches a link in double brackets.")
5188 (defvar org-bracket-link-analytic-regexp nil
5189 "Regular expression used to analyze links.
5190 Here is what the match groups contain after a match:
5191 1: http:
5192 2: http
5193 3: path
5194 4: [desc]
5195 5: desc")
5196 (defvar org-bracket-link-analytic-regexp++ nil
5197 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5198 (defvar org-any-link-re nil
5199 "Regular expression matching any link.")
5201 (defcustom org-match-sexp-depth 3
5202 "Number of stacked braces for sub/superscript matching.
5203 This has to be set before loading org.el to be effective."
5204 :group 'org-export-translation ; ??????????????????????????/
5205 :type 'integer)
5207 (defun org-create-multibrace-regexp (left right n)
5208 "Create a regular expression which will match a balanced sexp.
5209 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5210 as single character strings.
5211 The regexp returned will match the entire expression including the
5212 delimiters. It will also define a single group which contains the
5213 match except for the outermost delimiters. The maximum depth of
5214 stacked delimiters is N. Escaping delimiters is not possible."
5215 (let* ((nothing (concat "[^" left right "]*?"))
5216 (or "\\|")
5217 (re nothing)
5218 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5219 (while (> n 1)
5220 (setq n (1- n)
5221 re (concat re or next)
5222 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5223 (concat left "\\(" re "\\)" right)))
5225 (defvar org-match-substring-regexp
5226 (concat
5227 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5228 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5229 "\\|"
5230 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5231 "\\|"
5232 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5233 "The regular expression matching a sub- or superscript.")
5235 (defvar org-match-substring-with-braces-regexp
5236 (concat
5237 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5238 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5239 "\\)")
5240 "The regular expression matching a sub- or superscript, forcing braces.")
5242 (defun org-make-link-regexps ()
5243 "Update the link regular expressions.
5244 This should be called after the variable `org-link-types' has changed."
5245 (setq org-link-types-re
5246 (concat
5247 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5248 org-link-re-with-space
5249 (concat
5250 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5251 "\\([^" org-non-link-chars " ]"
5252 "[^" org-non-link-chars "]*"
5253 "[^" org-non-link-chars " ]\\)>?")
5254 org-link-re-with-space2
5255 (concat
5256 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5257 "\\([^" org-non-link-chars " ]"
5258 "[^\t\n\r]*"
5259 "[^" org-non-link-chars " ]\\)>?")
5260 org-link-re-with-space3
5261 (concat
5262 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5263 "\\([^" org-non-link-chars " ]"
5264 "[^\t\n\r]*\\)")
5265 org-angle-link-re
5266 (concat
5267 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5268 "\\([^" org-non-link-chars " ]"
5269 "[^" org-non-link-chars "]*"
5270 "\\)>")
5271 org-plain-link-re
5272 (concat
5273 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5274 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5275 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5276 org-bracket-link-regexp
5277 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5278 org-bracket-link-analytic-regexp
5279 (concat
5280 "\\[\\["
5281 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5282 "\\([^]]+\\)"
5283 "\\]"
5284 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5285 "\\]")
5286 org-bracket-link-analytic-regexp++
5287 (concat
5288 "\\[\\["
5289 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5290 "\\([^]]+\\)"
5291 "\\]"
5292 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5293 "\\]")
5294 org-any-link-re
5295 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5296 org-angle-link-re "\\)\\|\\("
5297 org-plain-link-re "\\)")))
5299 (org-make-link-regexps)
5301 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5302 "Regular expression for fast time stamp matching.")
5303 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5304 "Regular expression for fast time stamp matching.")
5305 (defconst org-ts-regexp0
5306 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5307 "Regular expression matching time strings for analysis.
5308 This one does not require the space after the date, so it can be used
5309 on a string that terminates immediately after the date.")
5310 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5311 "Regular expression matching time strings for analysis.")
5312 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5313 "Regular expression matching time stamps, with groups.")
5314 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5315 "Regular expression matching time stamps (also [..]), with groups.")
5316 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5317 "Regular expression matching a time stamp range.")
5318 (defconst org-tr-regexp-both
5319 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5320 "Regular expression matching a time stamp range.")
5321 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5322 org-ts-regexp "\\)?")
5323 "Regular expression matching a time stamp or time stamp range.")
5324 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5325 org-ts-regexp-both "\\)?")
5326 "Regular expression matching a time stamp or time stamp range.
5327 The time stamps may be either active or inactive.")
5329 (defvar org-emph-face nil)
5331 (defun org-do-emphasis-faces (limit)
5332 "Run through the buffer and add overlays to emphasized strings."
5333 (let (rtn a)
5334 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5335 (if (not (= (char-after (match-beginning 3))
5336 (char-after (match-beginning 4))))
5337 (progn
5338 (setq rtn t)
5339 (setq a (assoc (match-string 3) org-emphasis-alist))
5340 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5341 'face
5342 (nth 1 a))
5343 (and (nth 4 a)
5344 (org-remove-flyspell-overlays-in
5345 (match-beginning 0) (match-end 0)))
5346 (add-text-properties (match-beginning 2) (match-end 2)
5347 '(font-lock-multiline t org-emphasis t))
5348 (when org-hide-emphasis-markers
5349 (add-text-properties (match-end 4) (match-beginning 5)
5350 '(invisible org-link))
5351 (add-text-properties (match-beginning 3) (match-end 3)
5352 '(invisible org-link)))))
5353 (backward-char 1))
5354 rtn))
5356 (defun org-emphasize (&optional char)
5357 "Insert or change an emphasis, i.e. a font like bold or italic.
5358 If there is an active region, change that region to a new emphasis.
5359 If there is no region, just insert the marker characters and position
5360 the cursor between them.
5361 CHAR should be either the marker character, or the first character of the
5362 HTML tag associated with that emphasis. If CHAR is a space, the means
5363 to remove the emphasis of the selected region.
5364 If char is not given (for example in an interactive call) it
5365 will be prompted for."
5366 (interactive)
5367 (let ((eal org-emphasis-alist) e det
5368 (erc org-emphasis-regexp-components)
5369 (prompt "")
5370 (string "") beg end move tag c s)
5371 (if (org-region-active-p)
5372 (setq beg (region-beginning) end (region-end)
5373 string (buffer-substring beg end))
5374 (setq move t))
5376 (while (setq e (pop eal))
5377 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5378 c (aref tag 0))
5379 (push (cons c (string-to-char (car e))) det)
5380 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5381 (substring tag 1)))))
5382 (setq det (nreverse det))
5383 (unless char
5384 (message "%s" (concat "Emphasis marker or tag:" prompt))
5385 (setq char (read-char-exclusive)))
5386 (setq char (or (cdr (assoc char det)) char))
5387 (if (equal char ?\ )
5388 (setq s "" move nil)
5389 (unless (assoc (char-to-string char) org-emphasis-alist)
5390 (error "No such emphasis marker: \"%c\"" char))
5391 (setq s (char-to-string char)))
5392 (while (and (> (length string) 1)
5393 (equal (substring string 0 1) (substring string -1))
5394 (assoc (substring string 0 1) org-emphasis-alist))
5395 (setq string (substring string 1 -1)))
5396 (setq string (concat s string s))
5397 (if beg (delete-region beg end))
5398 (unless (or (bolp)
5399 (string-match (concat "[" (nth 0 erc) "\n]")
5400 (char-to-string (char-before (point)))))
5401 (insert " "))
5402 (unless (or (eobp)
5403 (string-match (concat "[" (nth 1 erc) "\n]")
5404 (char-to-string (char-after (point)))))
5405 (insert " ") (backward-char 1))
5406 (insert string)
5407 (and move (backward-char 1))))
5409 (defconst org-nonsticky-props
5410 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5412 (defsubst org-rear-nonsticky-at (pos)
5413 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5415 (defun org-activate-plain-links (limit)
5416 "Run through the buffer and add overlays to links."
5417 (catch 'exit
5418 (let (f hl)
5419 (when (re-search-forward (concat org-plain-link-re) limit t)
5420 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5421 (setq f (get-text-property (match-beginning 0) 'face))
5422 (setq hl (org-match-string-no-properties 0))
5423 (if (or (eq f 'org-tag)
5424 (and (listp f) (memq 'org-tag f)))
5426 (add-text-properties (match-beginning 0) (match-end 0)
5427 (list 'mouse-face 'highlight
5428 'face 'org-link
5429 'htmlize-link `(:uri ,hl)
5430 'keymap org-mouse-map))
5431 (org-rear-nonsticky-at (match-end 0)))
5432 t))))
5434 (defun org-activate-code (limit)
5435 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5436 (progn
5437 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5438 (remove-text-properties (match-beginning 0) (match-end 0)
5439 '(display t invisible t intangible t))
5440 t)))
5442 (defcustom org-src-fontify-natively nil
5443 "When non-nil, fontify code in code blocks."
5444 :type 'boolean
5445 :version "24.1"
5446 :group 'org-appearance
5447 :group 'org-babel)
5449 (defcustom org-allow-promoting-top-level-subtree nil
5450 "When non-nil, allow promoting a top level subtree.
5451 The leading star of the top level headline will be replaced
5452 by a #."
5453 :type 'boolean
5454 :version "24.1"
5455 :group 'org-appearance)
5457 (defun org-fontify-meta-lines-and-blocks (limit)
5458 (condition-case nil
5459 (org-fontify-meta-lines-and-blocks-1 limit)
5460 (error (message "org-mode fontification error"))))
5462 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5463 "Fontify #+ lines and blocks, in the correct ways."
5464 (let ((case-fold-search t))
5465 (if (re-search-forward
5466 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5467 limit t)
5468 (let ((beg (match-beginning 0))
5469 (block-start (match-end 0))
5470 (block-end nil)
5471 (lang (match-string 7))
5472 (beg1 (line-beginning-position 2))
5473 (dc1 (downcase (match-string 2)))
5474 (dc3 (downcase (match-string 3)))
5475 end end1 quoting block-type ovl)
5476 (cond
5477 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5478 ;; a single line of backend-specific content
5479 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5480 (remove-text-properties (match-beginning 0) (match-end 0)
5481 '(display t invisible t intangible t))
5482 (add-text-properties (match-beginning 1) (match-end 3)
5483 '(font-lock-fontified t face org-meta-line))
5484 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5485 '(font-lock-fontified t face org-block))
5486 ; for backend-specific code
5488 ((and (match-end 4) (equal dc3 "+begin"))
5489 ;; Truly a block
5490 (setq block-type (downcase (match-string 5))
5491 quoting (member block-type org-protecting-blocks))
5492 (when (re-search-forward
5493 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5494 nil t) ;; on purpose, we look further than LIMIT
5495 (setq end (min (point-max) (match-end 0))
5496 end1 (min (point-max) (1- (match-beginning 0))))
5497 (setq block-end (match-beginning 0))
5498 (when quoting
5499 (remove-text-properties beg end
5500 '(display t invisible t intangible t)))
5501 (add-text-properties
5502 beg end
5503 '(font-lock-fontified t font-lock-multiline t))
5504 (add-text-properties beg beg1 '(face org-meta-line))
5505 (add-text-properties end1 (min (point-max) (1+ end))
5506 '(face org-meta-line)) ; for end_src
5507 (cond
5508 ((and lang (not (string= lang "")) org-src-fontify-natively)
5509 (org-src-font-lock-fontify-block lang block-start block-end)
5510 ;; remove old background overlays
5511 (mapc (lambda (ov)
5512 (if (eq (overlay-get ov 'face) 'org-block-background)
5513 (delete-overlay ov)))
5514 (overlays-at (/ (+ beg1 block-end) 2)))
5515 ;; add a background overlay
5516 (setq ovl (make-overlay beg1 block-end))
5517 (overlay-put ovl 'face 'org-block-background)
5518 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5519 (quoting
5520 (add-text-properties beg1 (min (point-max) (1+ end1))
5521 '(face org-block))) ; end of source block
5522 ((not org-fontify-quote-and-verse-blocks))
5523 ((string= block-type "quote")
5524 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5525 ((string= block-type "verse")
5526 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5527 (add-text-properties beg beg1 '(face org-block-begin-line))
5528 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5529 '(face org-block-end-line))
5531 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5532 (add-text-properties
5533 beg (match-end 3)
5534 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5535 '(font-lock-fontified t invisible t)
5536 '(font-lock-fontified t face org-document-info-keyword)))
5537 (add-text-properties
5538 (match-beginning 6) (match-end 6)
5539 (if (string-equal dc1 "+title:")
5540 '(font-lock-fontified t face org-document-title)
5541 '(font-lock-fontified t face org-document-info))))
5542 ((or (equal dc1 "+results")
5543 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5544 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5545 "+call:" "+header:" "+headers:" "+name:"))
5546 (and (match-end 4) (equal dc3 "+attr")))
5547 (add-text-properties
5548 beg (match-end 0)
5549 '(font-lock-fontified t face org-meta-line))
5551 ((member dc3 '(" " ""))
5552 (add-text-properties
5553 beg (match-end 0)
5554 '(font-lock-fontified t face font-lock-comment-face)))
5555 ((not (member (char-after beg) '(?\ ?\t)))
5556 ;; just any other in-buffer setting, but not indented
5557 (add-text-properties
5558 beg (match-end 0)
5559 '(font-lock-fontified t face org-meta-line))
5561 (t nil))))))
5563 (defun org-activate-angle-links (limit)
5564 "Run through the buffer and add overlays to links."
5565 (if (re-search-forward org-angle-link-re limit t)
5566 (progn
5567 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5568 (add-text-properties (match-beginning 0) (match-end 0)
5569 (list 'mouse-face 'highlight
5570 'keymap org-mouse-map))
5571 (org-rear-nonsticky-at (match-end 0))
5572 t)))
5574 (defun org-activate-footnote-links (limit)
5575 "Run through the buffer and add overlays to footnotes."
5576 (let ((fn (org-footnote-next-reference-or-definition limit)))
5577 (when fn
5578 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5579 (org-remove-flyspell-overlays-in beg end)
5580 (add-text-properties beg end
5581 (list 'mouse-face 'highlight
5582 'keymap org-mouse-map
5583 'help-echo
5584 (if (= (point-at-bol) beg)
5585 "Footnote definition"
5586 "Footnote reference")
5587 'font-lock-fontified t
5588 'font-lock-multiline t
5589 'face 'org-footnote))))))
5591 (defun org-activate-bracket-links (limit)
5592 "Run through the buffer and add overlays to bracketed links."
5593 (if (re-search-forward org-bracket-link-regexp limit t)
5594 (let* ((hl (org-match-string-no-properties 1))
5595 (help (concat "LINK: " hl))
5596 ;; FIXME: Above we should remove the escapes. But that
5597 ;; requires another match, protecting match data, a lot
5598 ;; of overhead for font-lock.
5599 (ip (org-maybe-intangible
5600 (list 'invisible 'org-link
5601 'keymap org-mouse-map 'mouse-face 'highlight
5602 'font-lock-multiline t 'help-echo help
5603 'htmlize-link `(:uri ,hl))))
5604 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5605 'font-lock-multiline t 'help-echo help
5606 'htmlize-link `(:uri ,hl))))
5607 ;; We need to remove the invisible property here. Table narrowing
5608 ;; may have made some of this invisible.
5609 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5610 (remove-text-properties (match-beginning 0) (match-end 0)
5611 '(invisible nil))
5612 (if (match-end 3)
5613 (progn
5614 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5615 (org-rear-nonsticky-at (match-beginning 3))
5616 (add-text-properties (match-beginning 3) (match-end 3) vp)
5617 (org-rear-nonsticky-at (match-end 3))
5618 (add-text-properties (match-end 3) (match-end 0) ip)
5619 (org-rear-nonsticky-at (match-end 0)))
5620 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5621 (org-rear-nonsticky-at (match-beginning 1))
5622 (add-text-properties (match-beginning 1) (match-end 1) vp)
5623 (org-rear-nonsticky-at (match-end 1))
5624 (add-text-properties (match-end 1) (match-end 0) ip)
5625 (org-rear-nonsticky-at (match-end 0)))
5626 t)))
5628 (defun org-activate-dates (limit)
5629 "Run through the buffer and add overlays to dates."
5630 (if (re-search-forward org-tsr-regexp-both limit t)
5631 (progn
5632 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5633 (add-text-properties (match-beginning 0) (match-end 0)
5634 (list 'mouse-face 'highlight
5635 'keymap org-mouse-map))
5636 (org-rear-nonsticky-at (match-end 0))
5637 (when org-display-custom-times
5638 (if (match-end 3)
5639 (org-display-custom-time (match-beginning 3) (match-end 3)))
5640 (org-display-custom-time (match-beginning 1) (match-end 1)))
5641 t)))
5643 (defvar org-target-link-regexp nil
5644 "Regular expression matching radio targets in plain text.")
5645 (make-variable-buffer-local 'org-target-link-regexp)
5646 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5647 "Regular expression matching a link target.")
5648 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5649 "Regular expression matching a radio target.")
5650 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5651 "Regular expression matching any target.")
5653 (defun org-activate-target-links (limit)
5654 "Run through the buffer and add overlays to target matches."
5655 (when org-target-link-regexp
5656 (let ((case-fold-search t))
5657 (if (re-search-forward org-target-link-regexp limit t)
5658 (progn
5659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5660 (add-text-properties (match-beginning 0) (match-end 0)
5661 (list 'mouse-face 'highlight
5662 'keymap org-mouse-map
5663 'help-echo "Radio target link"
5664 'org-linked-text t))
5665 (org-rear-nonsticky-at (match-end 0))
5666 t)))))
5668 (defun org-update-radio-target-regexp ()
5669 "Find all radio targets in this file and update the regular expression."
5670 (interactive)
5671 (when (memq 'radio org-activate-links)
5672 (setq org-target-link-regexp
5673 (org-make-target-link-regexp (org-all-targets 'radio)))
5674 (org-restart-font-lock)))
5676 (defun org-hide-wide-columns (limit)
5677 (let (s e)
5678 (setq s (text-property-any (point) (or limit (point-max))
5679 'org-cwidth t))
5680 (when s
5681 (setq e (next-single-property-change s 'org-cwidth))
5682 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5683 (goto-char e)
5684 t)))
5686 (defvar org-latex-and-specials-regexp nil
5687 "Regular expression for highlighting export special stuff.")
5688 (defvar org-match-substring-regexp)
5689 (defvar org-match-substring-with-braces-regexp)
5691 ;; This should be with the exporter code, but we also use if for font-locking
5692 (defconst org-export-html-special-string-regexps
5693 '(("\\\\-" . "&shy;")
5694 ("---\\([^-]\\)" . "&mdash;\\1")
5695 ("--\\([^-]\\)" . "&ndash;\\1")
5696 ("\\.\\.\\." . "&hellip;"))
5697 "Regular expressions for special string conversion.")
5700 (defun org-compute-latex-and-specials-regexp ()
5701 "Compute regular expression for stuff treated specially by exporters."
5702 (if (not org-highlight-latex-fragments-and-specials)
5703 (org-set-local 'org-latex-and-specials-regexp nil)
5704 (require 'org-exp)
5705 (let*
5706 ((matchers (plist-get org-format-latex-options :matchers))
5707 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5708 org-latex-regexps)))
5709 (org-export-allow-BIND nil)
5710 (options (org-combine-plists (org-default-export-plist)
5711 (org-infile-export-plist)))
5712 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5713 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5714 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5715 (org-export-html-expand (plist-get options :expand-quoted-html))
5716 (org-export-with-special-strings (plist-get options :special-strings))
5717 (re-sub
5718 (cond
5719 ((equal org-export-with-sub-superscripts '{})
5720 (list org-match-substring-with-braces-regexp))
5721 (org-export-with-sub-superscripts
5722 (list org-match-substring-regexp))))
5723 (re-latex
5724 (if org-export-with-LaTeX-fragments
5725 (mapcar (lambda (x) (nth 1 x)) latexs)))
5726 (re-macros
5727 (if org-export-with-TeX-macros
5728 (list (concat "\\\\"
5729 (regexp-opt
5730 (append
5732 (delq nil
5733 (mapcar 'car-safe
5734 (append org-entities-user
5735 org-entities)))
5736 (if (boundp 'org-latex-entities)
5737 (mapcar (lambda (x)
5738 (or (car-safe x) x))
5739 org-latex-entities)
5740 nil))
5741 'words))) ; FIXME
5743 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5744 (re-special (if org-export-with-special-strings
5745 (mapcar (lambda (x) (car x))
5746 org-export-html-special-string-regexps)))
5747 (re-rest
5748 (delq nil
5749 (list
5750 (if org-export-html-expand "@<[^>\n]+>")
5751 ))))
5752 (org-set-local
5753 'org-latex-and-specials-regexp
5754 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5755 re-rest) "\\|")))))
5757 (defun org-do-latex-and-special-faces (limit)
5758 "Run through the buffer and add overlays to links."
5759 (when org-latex-and-specials-regexp
5760 (let (rtn d)
5761 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5762 limit t))
5763 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5764 'face))
5765 '(org-code org-verbatim underline)))
5766 (progn
5767 (setq rtn t
5768 d (cond ((member (char-after (1+ (match-beginning 0)))
5769 '(?_ ?^)) 1)
5770 (t 0)))
5771 (font-lock-prepend-text-property
5772 (+ d (match-beginning 0)) (match-end 0)
5773 'face 'org-latex-and-export-specials)
5774 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5775 '(font-lock-multiline t)))))
5776 rtn)))
5778 (defun org-restart-font-lock ()
5779 "Restart `font-lock-mode', to force refontification."
5780 (when (and (boundp 'font-lock-mode) font-lock-mode)
5781 (font-lock-mode -1)
5782 (font-lock-mode 1)))
5784 (defun org-all-targets (&optional radio)
5785 "Return a list of all targets in this file.
5786 When optional argument RADIO is non-nil, only find radio
5787 targets."
5788 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5789 (save-excursion
5790 (goto-char (point-min))
5791 (while (re-search-forward re nil t)
5792 ;; Make sure point is really within the object.
5793 (backward-char)
5794 (let ((obj (org-element-context)))
5795 (when (memq (org-element-type obj) '(radio-target target))
5796 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5797 rtn)))
5799 (defun org-make-target-link-regexp (targets)
5800 "Make regular expression matching all strings in TARGETS.
5801 The regular expression finds the targets also if there is a line break
5802 between words."
5803 (and targets
5804 (concat
5805 "\\<\\("
5806 (mapconcat
5807 (lambda (x)
5808 (setq x (regexp-quote x))
5809 (while (string-match " +" x)
5810 (setq x (replace-match "\\s-+" t t x)))
5812 targets
5813 "\\|")
5814 "\\)\\>")))
5816 (defun org-activate-tags (limit)
5817 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5818 (progn
5819 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5820 (add-text-properties (match-beginning 1) (match-end 1)
5821 (list 'mouse-face 'highlight
5822 'keymap org-mouse-map))
5823 (org-rear-nonsticky-at (match-end 1))
5824 t)))
5826 (defun org-outline-level ()
5827 "Compute the outline level of the heading at point.
5828 If this is called at a normal headline, the level is the number of stars.
5829 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5830 (save-excursion
5831 (if (not (condition-case nil
5832 (org-back-to-heading t)
5833 (error nil)))
5835 (looking-at org-outline-regexp)
5836 (1- (- (match-end 0) (match-beginning 0))))))
5838 (defvar org-font-lock-keywords nil)
5840 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5841 "Regular expression matching a property line.")
5843 (defvar org-font-lock-hook nil
5844 "Functions to be called for special font lock stuff.")
5846 (defvar org-font-lock-set-keywords-hook nil
5847 "Functions that can manipulate `org-font-lock-extra-keywords'.
5848 This is called after `org-font-lock-extra-keywords' is defined, but before
5849 it is installed to be used by font lock. This can be useful if something
5850 needs to be inserted at a specific position in the font-lock sequence.")
5852 (defun org-font-lock-hook (limit)
5853 "Run `org-font-lock-hook' within LIMIT."
5854 (run-hook-with-args 'org-font-lock-hook limit))
5856 (defun org-set-font-lock-defaults ()
5857 "Set font lock defaults for the current buffer."
5858 (let* ((em org-fontify-emphasized-text)
5859 (lk org-activate-links)
5860 (org-font-lock-extra-keywords
5861 (list
5862 ;; Call the hook
5863 '(org-font-lock-hook)
5864 ;; Headlines
5865 `(,(if org-fontify-whole-heading-line
5866 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5867 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5868 (1 (org-get-level-face 1))
5869 (2 (org-get-level-face 2))
5870 (3 (org-get-level-face 3)))
5871 ;; Table lines
5872 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5873 (1 'org-table t))
5874 ;; Table internals
5875 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5876 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5877 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5878 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5879 ;; Drawers
5880 (list org-drawer-regexp '(0 'org-special-keyword t))
5881 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5882 ;; Properties
5883 (list org-property-re
5884 '(1 'org-special-keyword t)
5885 '(3 'org-property-value t))
5886 ;; Links
5887 (if (memq 'footnote lk) '(org-activate-footnote-links))
5888 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5889 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5890 (if (memq 'plain lk) '(org-activate-plain-links))
5891 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5892 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5893 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5894 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5895 '(org-hide-wide-columns (0 nil append))
5896 ;; TODO keyword
5897 (list (format org-heading-keyword-regexp-format
5898 org-todo-regexp)
5899 '(2 (org-get-todo-face 2) t))
5900 ;; DONE
5901 (if org-fontify-done-headline
5902 (list (format org-heading-keyword-regexp-format
5903 (concat
5904 "\\(?:"
5905 (mapconcat 'regexp-quote org-done-keywords "\\|")
5906 "\\)"))
5907 '(2 'org-headline-done t))
5908 nil)
5909 ;; Priorities
5910 '(org-font-lock-add-priority-faces)
5911 ;; Tags
5912 '(org-font-lock-add-tag-faces)
5913 ;; Special keywords
5914 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5915 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5916 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5917 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5918 ;; Emphasis
5919 (if em
5920 (if (featurep 'xemacs)
5921 '(org-do-emphasis-faces (0 nil append))
5922 '(org-do-emphasis-faces)))
5923 ;; Checkboxes
5924 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5925 1 'org-checkbox prepend)
5926 (if (cdr (assq 'checkbox org-list-automatic-rules))
5927 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5928 (0 (org-get-checkbox-statistics-face) t)))
5929 ;; Description list items
5930 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5931 1 'org-list-dt prepend)
5932 ;; ARCHIVEd headings
5933 (list (concat
5934 org-outline-regexp-bol
5935 "\\(.*:" org-archive-tag ":.*\\)")
5936 '(1 'org-archived prepend))
5937 ;; Specials
5938 '(org-do-latex-and-special-faces)
5939 '(org-fontify-entities)
5940 '(org-raise-scripts)
5941 ;; Code
5942 '(org-activate-code (1 'org-code t))
5943 ;; COMMENT
5944 (list (format org-heading-keyword-regexp-format
5945 (concat "\\("
5946 org-comment-string "\\|" org-quote-string
5947 "\\)"))
5948 '(2 'org-special-keyword t))
5949 ;; Blocks and meta lines
5950 '(org-fontify-meta-lines-and-blocks)
5952 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5953 (run-hooks 'org-font-lock-set-keywords-hook)
5954 ;; Now set the full font-lock-keywords
5955 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5956 (org-set-local 'font-lock-defaults
5957 '(org-font-lock-keywords t nil nil backward-paragraph))
5958 (kill-local-variable 'font-lock-keywords) nil))
5960 (defun org-toggle-pretty-entities ()
5961 "Toggle the composition display of entities as UTF8 characters."
5962 (interactive)
5963 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5964 (org-restart-font-lock)
5965 (if org-pretty-entities
5966 (message "Entities are displayed as UTF8 characters")
5967 (save-restriction
5968 (widen)
5969 (org-decompose-region (point-min) (point-max))
5970 (message "Entities are displayed plain"))))
5972 (defvar org-custom-properties-overlays nil
5973 "List of overlays used for custom properties.")
5974 (make-variable-buffer-local 'org-custom-properties-overlays)
5976 (defun org-toggle-custom-properties-visibility ()
5977 "Display or hide properties in `org-custom-properties'."
5978 (interactive)
5979 (if org-custom-properties-overlays
5980 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5981 (setq org-custom-properties-overlays nil))
5982 (unless (not org-custom-properties)
5983 (save-excursion
5984 (save-restriction
5985 (widen)
5986 (goto-char (point-min))
5987 (while (re-search-forward org-property-re nil t)
5988 (mapc (lambda(p)
5989 (when (equal p (substring (match-string 1) 1 -1))
5990 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5991 (overlay-put o 'invisible t)
5992 (overlay-put o 'org-custom-property t)
5993 (push o org-custom-properties-overlays))))
5994 org-custom-properties)))))))
5996 (defun org-fontify-entities (limit)
5997 "Find an entity to fontify."
5998 (let (ee)
5999 (when org-pretty-entities
6000 (catch 'match
6001 (while (re-search-forward
6002 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6003 limit t)
6004 (if (and (not (org-in-indented-comment-line))
6005 (setq ee (org-entity-get (match-string 1)))
6006 (= (length (nth 6 ee)) 1))
6007 (let*
6008 ((end (if (equal (match-string 2) "{}")
6009 (match-end 2)
6010 (match-end 1))))
6011 (add-text-properties
6012 (match-beginning 0) end
6013 (list 'font-lock-fontified t))
6014 (compose-region (match-beginning 0) end
6015 (nth 6 ee) nil)
6016 (backward-char 1)
6017 (throw 'match t))))
6018 nil))))
6020 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6021 "Fontify string S like in Org-mode."
6022 (with-temp-buffer
6023 (insert s)
6024 (let ((org-odd-levels-only odd-levels))
6025 (org-mode)
6026 (font-lock-fontify-buffer)
6027 (buffer-string))))
6029 (defvar org-m nil)
6030 (defvar org-l nil)
6031 (defvar org-f nil)
6032 (defun org-get-level-face (n)
6033 "Get the right face for match N in font-lock matching of headlines."
6034 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6035 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6036 (if org-cycle-level-faces
6037 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6038 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6039 (cond
6040 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6041 ((eq n 2) org-f)
6042 (t (if org-level-color-stars-only nil org-f))))
6045 (defun org-get-todo-face (kwd)
6046 "Get the right face for a TODO keyword KWD.
6047 If KWD is a number, get the corresponding match group."
6048 (if (numberp kwd) (setq kwd (match-string kwd)))
6049 (or (org-face-from-face-or-color
6050 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6051 (and (member kwd org-done-keywords) 'org-done)
6052 'org-todo))
6054 (defun org-face-from-face-or-color (context inherit face-or-color)
6055 "Create a face list that inherits INHERIT, but sets the foreground color.
6056 When FACE-OR-COLOR is not a string, just return it."
6057 (if (stringp face-or-color)
6058 (list :inherit inherit
6059 (cdr (assoc context org-faces-easy-properties))
6060 face-or-color)
6061 face-or-color))
6063 (defun org-font-lock-add-tag-faces (limit)
6064 "Add the special tag faces."
6065 (when (and org-tag-faces org-tags-special-faces-re)
6066 (while (re-search-forward org-tags-special-faces-re limit t)
6067 (add-text-properties (match-beginning 1) (match-end 1)
6068 (list 'face (org-get-tag-face 1)
6069 'font-lock-fontified t))
6070 (backward-char 1))))
6072 (defun org-font-lock-add-priority-faces (limit)
6073 "Add the special priority faces."
6074 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6075 (when (save-match-data (org-at-heading-p))
6076 (add-text-properties
6077 (match-beginning 0) (match-end 0)
6078 (list 'face (or (org-face-from-face-or-color
6079 'priority 'org-special-keyword
6080 (cdr (assoc (char-after (match-beginning 1))
6081 org-priority-faces)))
6082 'org-special-keyword)
6083 'font-lock-fontified t)))))
6085 (defun org-get-tag-face (kwd)
6086 "Get the right face for a TODO keyword KWD.
6087 If KWD is a number, get the corresponding match group."
6088 (if (numberp kwd) (setq kwd (match-string kwd)))
6089 (or (org-face-from-face-or-color
6090 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6091 'org-tag))
6093 (defun org-unfontify-region (beg end &optional maybe_loudly)
6094 "Remove fontification and activation overlays from links."
6095 (font-lock-default-unfontify-region beg end)
6096 (let* ((buffer-undo-list t)
6097 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6098 (inhibit-modification-hooks t)
6099 deactivate-mark buffer-file-name buffer-file-truename)
6100 (org-decompose-region beg end)
6101 (remove-text-properties beg end
6102 '(mouse-face t keymap t org-linked-text t
6103 invisible t intangible t
6104 org-no-flyspell t org-emphasis t))
6105 (org-remove-font-lock-display-properties beg end)))
6107 (defconst org-script-display '(((raise -0.3) (height 0.7))
6108 ((raise 0.3) (height 0.7))
6109 ((raise -0.5))
6110 ((raise 0.5)))
6111 "Display properties for showing superscripts and subscripts.")
6113 (defun org-remove-font-lock-display-properties (beg end)
6114 "Remove specific display properties that have been added by font lock.
6115 The will remove the raise properties that are used to show superscripts
6116 and subscripts."
6117 (let (next prop)
6118 (while (< beg end)
6119 (setq next (next-single-property-change beg 'display nil end)
6120 prop (get-text-property beg 'display))
6121 (if (member prop org-script-display)
6122 (put-text-property beg next 'display nil))
6123 (setq beg next))))
6125 (defun org-raise-scripts (limit)
6126 "Add raise properties to sub/superscripts."
6127 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6128 (if (re-search-forward
6129 (if (eq org-use-sub-superscripts t)
6130 org-match-substring-regexp
6131 org-match-substring-with-braces-regexp)
6132 limit t)
6133 (let* ((pos (point)) table-p comment-p
6134 (mpos (match-beginning 3))
6135 (emph-p (get-text-property mpos 'org-emphasis))
6136 (link-p (get-text-property mpos 'mouse-face))
6137 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6138 (goto-char (point-at-bol))
6139 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6140 comment-p (org-looking-at-p "[ \t]*#"))
6141 (goto-char pos)
6142 ;; FIXME: Should we go back one character here, for a_b^c
6143 ;; (goto-char (1- pos)) ;????????????????????
6144 (if (or comment-p emph-p link-p keyw-p)
6146 (put-text-property (match-beginning 3) (match-end 0)
6147 'display
6148 (if (equal (char-after (match-beginning 2)) ?^)
6149 (nth (if table-p 3 1) org-script-display)
6150 (nth (if table-p 2 0) org-script-display)))
6151 (add-text-properties (match-beginning 2) (match-end 2)
6152 (list 'invisible t
6153 'org-dwidth t 'org-dwidth-n 1))
6154 (if (and (eq (char-after (match-beginning 3)) ?{)
6155 (eq (char-before (match-end 3)) ?}))
6156 (progn
6157 (add-text-properties
6158 (match-beginning 3) (1+ (match-beginning 3))
6159 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6160 (add-text-properties
6161 (1- (match-end 3)) (match-end 3)
6162 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6163 t)))))
6165 ;;;; Visibility cycling, including org-goto and indirect buffer
6167 ;;; Cycling
6169 (defvar org-cycle-global-status nil)
6170 (make-variable-buffer-local 'org-cycle-global-status)
6171 (defvar org-cycle-subtree-status nil)
6172 (make-variable-buffer-local 'org-cycle-subtree-status)
6174 (defvar org-inlinetask-min-level)
6176 ;;;###autoload
6177 (defun org-cycle (&optional arg)
6178 "TAB-action and visibility cycling for Org-mode.
6180 This is the command invoked in Org-mode by the TAB key. Its main purpose
6181 is outline visibility cycling, but it also invokes other actions
6182 in special contexts.
6184 - When this function is called with a prefix argument, rotate the entire
6185 buffer through 3 states (global cycling)
6186 1. OVERVIEW: Show only top-level headlines.
6187 2. CONTENTS: Show all headlines of all levels, but no body text.
6188 3. SHOW ALL: Show everything.
6189 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6190 determined by the variable `org-startup-folded', and by any VISIBILITY
6191 properties in the buffer.
6192 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6193 including any drawers.
6195 - When inside a table, re-align the table and move to the next field.
6197 - When point is at the beginning of a headline, rotate the subtree started
6198 by this line through 3 different states (local cycling)
6199 1. FOLDED: Only the main headline is shown.
6200 2. CHILDREN: The main headline and the direct children are shown.
6201 From this state, you can move to one of the children
6202 and zoom in further.
6203 3. SUBTREE: Show the entire subtree, including body text.
6204 If there is no subtree, switch directly from CHILDREN to FOLDED.
6206 - When point is at the beginning of an empty headline and the variable
6207 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6208 of the headline by demoting and promoting it to likely levels. This
6209 speeds up creation document structure by pressing TAB once or several
6210 times right after creating a new headline.
6212 - When there is a numeric prefix, go up to a heading with level ARG, do
6213 a `show-subtree' and return to the previous cursor position. If ARG
6214 is negative, go up that many levels.
6216 - When point is not at the beginning of a headline, execute the global
6217 binding for TAB, which is re-indenting the line. See the option
6218 `org-cycle-emulate-tab' for details.
6220 - Special case: if point is at the beginning of the buffer and there is
6221 no headline in line 1, this function will act as if called with prefix arg
6222 (C-u TAB, same as S-TAB) also when called without prefix arg.
6223 But only if also the variable `org-cycle-global-at-bob' is t."
6224 (interactive "P")
6225 (org-load-modules-maybe)
6226 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6227 (and org-cycle-level-after-item/entry-creation
6228 (or (org-cycle-level)
6229 (org-cycle-item-indentation))))
6230 (let* ((limit-level
6231 (or org-cycle-max-level
6232 (and (boundp 'org-inlinetask-min-level)
6233 org-inlinetask-min-level
6234 (1- org-inlinetask-min-level))))
6235 (nstars (and limit-level
6236 (if org-odd-levels-only
6237 (and limit-level (1- (* limit-level 2)))
6238 limit-level)))
6239 (org-outline-regexp
6240 (if (not (derived-mode-p 'org-mode))
6241 outline-regexp
6242 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6243 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6244 (not (looking-at org-outline-regexp))))
6245 (org-cycle-hook
6246 (if bob-special
6247 (delq 'org-optimize-window-after-visibility-change
6248 (copy-sequence org-cycle-hook))
6249 org-cycle-hook))
6250 (pos (point)))
6252 (if (or bob-special (equal arg '(4)))
6253 ;; special case: use global cycling
6254 (setq arg t))
6256 (cond
6258 ((equal arg '(16))
6259 (setq last-command 'dummy)
6260 (org-set-startup-visibility)
6261 (message "Startup visibility, plus VISIBILITY properties"))
6263 ((equal arg '(64))
6264 (show-all)
6265 (message "Entire buffer visible, including drawers"))
6267 ;; Table: enter it or move to the next field.
6268 ((org-at-table-p 'any)
6269 (if (org-at-table.el-p)
6270 (message "Use C-c ' to edit table.el tables")
6271 (if arg (org-table-edit-field t)
6272 (org-table-justify-field-maybe)
6273 (call-interactively 'org-table-next-field))))
6275 ((run-hook-with-args-until-success
6276 'org-tab-after-check-for-table-hook))
6278 ;; Global cycling: delegate to `org-cycle-internal-global'.
6279 ((eq arg t) (org-cycle-internal-global))
6281 ;; Drawers: delegate to `org-flag-drawer'.
6282 ((and org-drawers org-drawer-regexp
6283 (save-excursion
6284 (beginning-of-line 1)
6285 (looking-at org-drawer-regexp)))
6286 (org-flag-drawer ; toggle block visibility
6287 (not (get-char-property (match-end 0) 'invisible))))
6289 ;; Show-subtree, ARG levels up from here.
6290 ((integerp arg)
6291 (save-excursion
6292 (org-back-to-heading)
6293 (outline-up-heading (if (< arg 0) (- arg)
6294 (- (funcall outline-level) arg)))
6295 (org-show-subtree)))
6297 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6298 ((and (featurep 'org-inlinetask)
6299 (org-inlinetask-at-task-p)
6300 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6301 (org-inlinetask-toggle-visibility))
6303 ((org-try-cdlatex-tab))
6305 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6306 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6307 (save-excursion (beginning-of-line 1)
6308 (looking-at org-outline-regexp)))
6309 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6310 (org-cycle-internal-local))
6312 ;; From there: TAB emulation and template completion.
6313 (buffer-read-only (org-back-to-heading))
6315 ((run-hook-with-args-until-success
6316 'org-tab-after-check-for-cycling-hook))
6318 ((org-try-structure-completion))
6320 ((run-hook-with-args-until-success
6321 'org-tab-before-tab-emulation-hook))
6323 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6324 (or (not (bolp))
6325 (not (looking-at org-outline-regexp))))
6326 (call-interactively (global-key-binding "\t")))
6328 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6329 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6330 (or (and (eq org-cycle-emulate-tab 'white)
6331 (= (match-end 0) (point-at-eol)))
6332 (and (eq org-cycle-emulate-tab 'whitestart)
6333 (>= (match-end 0) pos))))
6335 (eq org-cycle-emulate-tab t))
6336 (call-interactively (global-key-binding "\t")))
6338 (t (save-excursion
6339 (org-back-to-heading)
6340 (org-cycle)))))))
6342 (defun org-cycle-internal-global ()
6343 "Do the global cycling action."
6344 ;; Hack to avoid display of messages for .org attachments in Gnus
6345 (let ((ga (string-match "\\*fontification" (buffer-name))))
6346 (cond
6347 ((and (eq last-command this-command)
6348 (eq org-cycle-global-status 'overview))
6349 ;; We just created the overview - now do table of contents
6350 ;; This can be slow in very large buffers, so indicate action
6351 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6352 (unless ga (message "CONTENTS..."))
6353 (org-content)
6354 (unless ga (message "CONTENTS...done"))
6355 (setq org-cycle-global-status 'contents)
6356 (run-hook-with-args 'org-cycle-hook 'contents))
6358 ((and (eq last-command this-command)
6359 (eq org-cycle-global-status 'contents))
6360 ;; We just showed the table of contents - now show everything
6361 (run-hook-with-args 'org-pre-cycle-hook 'all)
6362 (show-all)
6363 (unless ga (message "SHOW ALL"))
6364 (setq org-cycle-global-status 'all)
6365 (run-hook-with-args 'org-cycle-hook 'all))
6368 ;; Default action: go to overview
6369 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6370 (org-overview)
6371 (unless ga (message "OVERVIEW"))
6372 (setq org-cycle-global-status 'overview)
6373 (run-hook-with-args 'org-cycle-hook 'overview)))))
6375 (defun org-cycle-internal-local ()
6376 "Do the local cycling action."
6377 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6378 ;; First, determine end of headline (EOH), end of subtree or item
6379 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6380 (save-excursion
6381 (if (org-at-item-p)
6382 (progn
6383 (beginning-of-line)
6384 (setq struct (org-list-struct))
6385 (setq eoh (point-at-eol))
6386 (setq eos (org-list-get-item-end-before-blank (point) struct))
6387 (setq has-children (org-list-has-child-p (point) struct)))
6388 (org-back-to-heading)
6389 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6390 (setq eos (save-excursion
6391 (org-end-of-subtree t)
6392 (unless (eobp)
6393 (skip-chars-forward " \t\n"))
6394 (if (eobp) (point) (1- (point)))))
6395 (setq has-children
6396 (or (save-excursion
6397 (let ((level (funcall outline-level)))
6398 (outline-next-heading)
6399 (and (org-at-heading-p t)
6400 (> (funcall outline-level) level))))
6401 (save-excursion
6402 (org-list-search-forward (org-item-beginning-re) eos t)))))
6403 ;; Determine end invisible part of buffer (EOL)
6404 (beginning-of-line 2)
6405 ;; XEmacs doesn't have `next-single-char-property-change'
6406 (if (featurep 'xemacs)
6407 (while (and (not (eobp)) ;; this is like `next-line'
6408 (get-char-property (1- (point)) 'invisible))
6409 (beginning-of-line 2))
6410 (while (and (not (eobp)) ;; this is like `next-line'
6411 (get-char-property (1- (point)) 'invisible))
6412 (goto-char (next-single-char-property-change (point) 'invisible))
6413 (and (eolp) (beginning-of-line 2))))
6414 (setq eol (point)))
6415 ;; Find out what to do next and set `this-command'
6416 (cond
6417 ((= eos eoh)
6418 ;; Nothing is hidden behind this heading
6419 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6420 (message "EMPTY ENTRY")
6421 (setq org-cycle-subtree-status nil)
6422 (save-excursion
6423 (goto-char eos)
6424 (outline-next-heading)
6425 (if (outline-invisible-p) (org-flag-heading nil))))
6426 ((and (or (>= eol eos)
6427 (not (string-match "\\S-" (buffer-substring eol eos))))
6428 (or has-children
6429 (not (setq children-skipped
6430 org-cycle-skip-children-state-if-no-children))))
6431 ;; Entire subtree is hidden in one line: children view
6432 (run-hook-with-args 'org-pre-cycle-hook 'children)
6433 (if (org-at-item-p)
6434 (org-list-set-item-visibility (point-at-bol) struct 'children)
6435 (org-show-entry)
6436 (org-with-limited-levels (show-children))
6437 ;; FIXME: This slows down the func way too much.
6438 ;; How keep drawers hidden in subtree anyway?
6439 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6440 ;; (org-cycle-hide-drawers 'subtree))
6442 ;; Fold every list in subtree to top-level items.
6443 (when (eq org-cycle-include-plain-lists 'integrate)
6444 (save-excursion
6445 (org-back-to-heading)
6446 (while (org-list-search-forward (org-item-beginning-re) eos t)
6447 (beginning-of-line 1)
6448 (let* ((struct (org-list-struct))
6449 (prevs (org-list-prevs-alist struct))
6450 (end (org-list-get-bottom-point struct)))
6451 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6452 (org-list-get-all-items (point) struct prevs))
6453 (goto-char end))))))
6454 (message "CHILDREN")
6455 (save-excursion
6456 (goto-char eos)
6457 (outline-next-heading)
6458 (if (outline-invisible-p) (org-flag-heading nil)))
6459 (setq org-cycle-subtree-status 'children)
6460 (run-hook-with-args 'org-cycle-hook 'children))
6461 ((or children-skipped
6462 (and (eq last-command this-command)
6463 (eq org-cycle-subtree-status 'children)))
6464 ;; We just showed the children, or no children are there,
6465 ;; now show everything.
6466 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6467 (outline-flag-region eoh eos nil)
6468 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6469 (setq org-cycle-subtree-status 'subtree)
6470 (run-hook-with-args 'org-cycle-hook 'subtree))
6472 ;; Default action: hide the subtree.
6473 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6474 (outline-flag-region eoh eos t)
6475 (message "FOLDED")
6476 (setq org-cycle-subtree-status 'folded)
6477 (run-hook-with-args 'org-cycle-hook 'folded)))))
6479 ;;;###autoload
6480 (defun org-global-cycle (&optional arg)
6481 "Cycle the global visibility. For details see `org-cycle'.
6482 With \\[universal-argument] prefix arg, switch to startup visibility.
6483 With a numeric prefix, show all headlines up to that level."
6484 (interactive "P")
6485 (let ((org-cycle-include-plain-lists
6486 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6487 (cond
6488 ((integerp arg)
6489 (show-all)
6490 (hide-sublevels arg)
6491 (setq org-cycle-global-status 'contents))
6492 ((equal arg '(4))
6493 (org-set-startup-visibility)
6494 (message "Startup visibility, plus VISIBILITY properties."))
6496 (org-cycle '(4))))))
6498 (defun org-set-startup-visibility ()
6499 "Set the visibility required by startup options and properties."
6500 (cond
6501 ((eq org-startup-folded t)
6502 (org-cycle '(4)))
6503 ((eq org-startup-folded 'content)
6504 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6505 (org-cycle '(4)) (org-cycle '(4)))))
6506 (unless (eq org-startup-folded 'showeverything)
6507 (if org-hide-block-startup (org-hide-block-all))
6508 (org-set-visibility-according-to-property 'no-cleanup)
6509 (org-cycle-hide-archived-subtrees 'all)
6510 (org-cycle-hide-drawers 'all)
6511 (org-cycle-show-empty-lines t)))
6513 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6514 "Switch subtree visibilities according to :VISIBILITY: property."
6515 (interactive)
6516 (let (org-show-entry-below state)
6517 (save-excursion
6518 (goto-char (point-min))
6519 (while (re-search-forward
6520 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6521 nil t)
6522 (setq state (match-string 1))
6523 (save-excursion
6524 (org-back-to-heading t)
6525 (hide-subtree)
6526 (org-reveal)
6527 (cond
6528 ((equal state '("fold" "folded"))
6529 (hide-subtree))
6530 ((equal state "children")
6531 (org-show-hidden-entry)
6532 (show-children))
6533 ((equal state "content")
6534 (save-excursion
6535 (save-restriction
6536 (org-narrow-to-subtree)
6537 (org-content))))
6538 ((member state '("all" "showall"))
6539 (show-subtree)))))
6540 (unless no-cleanup
6541 (org-cycle-hide-archived-subtrees 'all)
6542 (org-cycle-hide-drawers 'all)
6543 (org-cycle-show-empty-lines 'all)))))
6545 ;; This function uses outline-regexp instead of the more fundamental
6546 ;; org-outline-regexp so that org-cycle-global works outside of Org
6547 ;; buffers, where outline-regexp is needed.
6548 (defun org-overview ()
6549 "Switch to overview mode, showing only top-level headlines.
6550 Really, this shows all headlines with level equal or greater than the level
6551 of the first headline in the buffer. This is important, because if the
6552 first headline is not level one, then (hide-sublevels 1) gives confusing
6553 results."
6554 (interactive)
6555 (let ((level (save-excursion
6556 (goto-char (point-min))
6557 (if (re-search-forward (concat "^" outline-regexp) nil t)
6558 (progn
6559 (goto-char (match-beginning 0))
6560 (funcall outline-level))))))
6561 (and level (hide-sublevels level))))
6563 (defun org-content (&optional arg)
6564 "Show all headlines in the buffer, like a table of contents.
6565 With numerical argument N, show content up to level N."
6566 (interactive "P")
6567 (save-excursion
6568 ;; Visit all headings and show their offspring
6569 (and (integerp arg) (org-overview))
6570 (goto-char (point-max))
6571 (catch 'exit
6572 (while (and (progn (condition-case nil
6573 (outline-previous-visible-heading 1)
6574 (error (goto-char (point-min))))
6576 (looking-at org-outline-regexp))
6577 (if (integerp arg)
6578 (show-children (1- arg))
6579 (show-branches))
6580 (if (bobp) (throw 'exit nil))))))
6583 (defun org-optimize-window-after-visibility-change (state)
6584 "Adjust the window after a change in outline visibility.
6585 This function is the default value of the hook `org-cycle-hook'."
6586 (when (get-buffer-window (current-buffer))
6587 (cond
6588 ((eq state 'content) nil)
6589 ((eq state 'all) nil)
6590 ((eq state 'folded) nil)
6591 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6592 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6594 (defun org-remove-empty-overlays-at (pos)
6595 "Remove outline overlays that do not contain non-white stuff."
6596 (mapc
6597 (lambda (o)
6598 (and (eq 'outline (overlay-get o 'invisible))
6599 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6600 (overlay-end o))))
6601 (delete-overlay o)))
6602 (overlays-at pos)))
6604 (defun org-clean-visibility-after-subtree-move ()
6605 "Fix visibility issues after moving a subtree."
6606 ;; First, find a reasonable region to look at:
6607 ;; Start two siblings above, end three below
6608 (let* ((beg (save-excursion
6609 (and (org-get-last-sibling)
6610 (org-get-last-sibling))
6611 (point)))
6612 (end (save-excursion
6613 (and (org-get-next-sibling)
6614 (org-get-next-sibling)
6615 (org-get-next-sibling))
6616 (if (org-at-heading-p)
6617 (point-at-eol)
6618 (point))))
6619 (level (looking-at "\\*+"))
6620 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6621 (save-excursion
6622 (save-restriction
6623 (narrow-to-region beg end)
6624 (when re
6625 ;; Properly fold already folded siblings
6626 (goto-char (point-min))
6627 (while (re-search-forward re nil t)
6628 (if (and (not (outline-invisible-p))
6629 (save-excursion
6630 (goto-char (point-at-eol)) (outline-invisible-p)))
6631 (hide-entry))))
6632 (org-cycle-show-empty-lines 'overview)
6633 (org-cycle-hide-drawers 'overview)))))
6635 (defun org-cycle-show-empty-lines (state)
6636 "Show empty lines above all visible headlines.
6637 The region to be covered depends on STATE when called through
6638 `org-cycle-hook'. Lisp program can use t for STATE to get the
6639 entire buffer covered. Note that an empty line is only shown if there
6640 are at least `org-cycle-separator-lines' empty lines before the headline."
6641 (when (not (= org-cycle-separator-lines 0))
6642 (save-excursion
6643 (let* ((n (abs org-cycle-separator-lines))
6644 (re (cond
6645 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6646 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6647 (t (let ((ns (number-to-string (- n 2))))
6648 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6649 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6650 beg end b e)
6651 (cond
6652 ((memq state '(overview contents t))
6653 (setq beg (point-min) end (point-max)))
6654 ((memq state '(children folded))
6655 (setq beg (point) end (progn (org-end-of-subtree t t)
6656 (beginning-of-line 2)
6657 (point)))))
6658 (when beg
6659 (goto-char beg)
6660 (while (re-search-forward re end t)
6661 (unless (get-char-property (match-end 1) 'invisible)
6662 (setq e (match-end 1))
6663 (if (< org-cycle-separator-lines 0)
6664 (setq b (save-excursion
6665 (goto-char (match-beginning 0))
6666 (org-back-over-empty-lines)
6667 (if (save-excursion
6668 (goto-char (max (point-min) (1- (point))))
6669 (org-at-heading-p))
6670 (1- (point))
6671 (point))))
6672 (setq b (match-beginning 1)))
6673 (outline-flag-region b e nil)))))))
6674 ;; Never hide empty lines at the end of the file.
6675 (save-excursion
6676 (goto-char (point-max))
6677 (outline-previous-heading)
6678 (outline-end-of-heading)
6679 (if (and (looking-at "[ \t\n]+")
6680 (= (match-end 0) (point-max)))
6681 (outline-flag-region (point) (match-end 0) nil))))
6683 (defun org-show-empty-lines-in-parent ()
6684 "Move to the parent and re-show empty lines before visible headlines."
6685 (save-excursion
6686 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6687 (org-cycle-show-empty-lines context))))
6689 (defun org-files-list ()
6690 "Return `org-agenda-files' list, plus all open org-mode files.
6691 This is useful for operations that need to scan all of a user's
6692 open and agenda-wise Org files."
6693 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6694 (dolist (buf (buffer-list))
6695 (with-current-buffer buf
6696 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6697 (let ((file (expand-file-name (buffer-file-name))))
6698 (unless (member file files)
6699 (push file files))))))
6700 files))
6702 (defsubst org-entry-beginning-position ()
6703 "Return the beginning position of the current entry."
6704 (save-excursion (outline-back-to-heading t) (point)))
6706 (defsubst org-entry-end-position ()
6707 "Return the end position of the current entry."
6708 (save-excursion (outline-next-heading) (point)))
6710 (defun org-cycle-hide-drawers (state)
6711 "Re-hide all drawers after a visibility state change."
6712 (when (and (derived-mode-p 'org-mode)
6713 (not (memq state '(overview folded contents))))
6714 (save-excursion
6715 (let* ((globalp (memq state '(contents all)))
6716 (beg (if globalp (point-min) (point)))
6717 (end (if globalp (point-max)
6718 (if (eq state 'children)
6719 (save-excursion (outline-next-heading) (point))
6720 (org-end-of-subtree t)))))
6721 (goto-char beg)
6722 (while (re-search-forward org-drawer-regexp end t)
6723 (org-flag-drawer t))))))
6725 (defun org-cycle-hide-inline-tasks (state)
6726 "Re-hide inline task when switching to 'contents visibility state."
6727 (when (and (eq state 'contents)
6728 (boundp 'org-inlinetask-min-level)
6729 org-inlinetask-min-level)
6730 (hide-sublevels (1- org-inlinetask-min-level))))
6732 (defun org-flag-drawer (flag)
6733 "When FLAG is non-nil, hide the drawer we are within.
6734 Otherwise make it visible."
6735 (save-excursion
6736 (beginning-of-line 1)
6737 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6738 (let ((b (match-end 0)))
6739 (if (re-search-forward
6740 "^[ \t]*:END:"
6741 (save-excursion (outline-next-heading) (point)) t)
6742 (outline-flag-region b (point-at-eol) flag)
6743 (error ":END: line missing at position %s" b))))))
6745 (defun org-subtree-end-visible-p ()
6746 "Is the end of the current subtree visible?"
6747 (pos-visible-in-window-p
6748 (save-excursion (org-end-of-subtree t) (point))))
6750 (defun org-first-headline-recenter (&optional N)
6751 "Move cursor to the first headline and recenter the headline.
6752 Optional argument N means put the headline into the Nth line of the window."
6753 (goto-char (point-min))
6754 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6755 (beginning-of-line)
6756 (recenter (prefix-numeric-value N))))
6758 ;;; Saving and restoring visibility
6760 (defun org-outline-overlay-data (&optional use-markers)
6761 "Return a list of the locations of all outline overlays.
6762 These are overlays with the `invisible' property value `outline'.
6763 The return value is a list of cons cells, with start and stop
6764 positions for each overlay.
6765 If USE-MARKERS is set, return the positions as markers."
6766 (let (beg end)
6767 (save-excursion
6768 (save-restriction
6769 (widen)
6770 (delq nil
6771 (mapcar (lambda (o)
6772 (when (eq (overlay-get o 'invisible) 'outline)
6773 (setq beg (overlay-start o)
6774 end (overlay-end o))
6775 (and beg end (> end beg)
6776 (if use-markers
6777 (cons (move-marker (make-marker) beg)
6778 (move-marker (make-marker) end))
6779 (cons beg end)))))
6780 (overlays-in (point-min) (point-max))))))))
6782 (defun org-set-outline-overlay-data (data)
6783 "Create visibility overlays for all positions in DATA.
6784 DATA should have been made by `org-outline-overlay-data'."
6785 (let (o)
6786 (save-excursion
6787 (save-restriction
6788 (widen)
6789 (show-all)
6790 (mapc (lambda (c)
6791 (outline-flag-region (car c) (cdr c) t))
6792 data)))))
6794 ;;; Folding of blocks
6796 (defvar org-hide-block-overlays nil
6797 "Overlays hiding blocks.")
6798 (make-variable-buffer-local 'org-hide-block-overlays)
6800 (defun org-block-map (function &optional start end)
6801 "Call FUNCTION at the head of all source blocks in the current buffer.
6802 Optional arguments START and END can be used to limit the range."
6803 (let ((start (or start (point-min)))
6804 (end (or end (point-max))))
6805 (save-excursion
6806 (goto-char start)
6807 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6808 (save-excursion
6809 (save-match-data
6810 (goto-char (match-beginning 0))
6811 (funcall function)))))))
6813 (defun org-hide-block-toggle-all ()
6814 "Toggle the visibility of all blocks in the current buffer."
6815 (org-block-map #'org-hide-block-toggle))
6817 (defun org-hide-block-all ()
6818 "Fold all blocks in the current buffer."
6819 (interactive)
6820 (org-show-block-all)
6821 (org-block-map #'org-hide-block-toggle-maybe))
6823 (defun org-show-block-all ()
6824 "Unfold all blocks in the current buffer."
6825 (interactive)
6826 (mapc 'delete-overlay org-hide-block-overlays)
6827 (setq org-hide-block-overlays nil))
6829 (defun org-hide-block-toggle-maybe ()
6830 "Toggle visibility of block at point."
6831 (interactive)
6832 (let ((case-fold-search t))
6833 (if (save-excursion
6834 (beginning-of-line 1)
6835 (looking-at org-block-regexp))
6836 (progn (org-hide-block-toggle)
6837 t) ;; to signal that we took action
6838 nil))) ;; to signal that we did not
6840 (defun org-hide-block-toggle (&optional force)
6841 "Toggle the visibility of the current block."
6842 (interactive)
6843 (save-excursion
6844 (beginning-of-line)
6845 (if (re-search-forward org-block-regexp nil t)
6846 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6847 (end (match-end 0)) ;; end of entire body
6849 (if (memq t (mapcar (lambda (overlay)
6850 (eq (overlay-get overlay 'invisible)
6851 'org-hide-block))
6852 (overlays-at start)))
6853 (if (or (not force) (eq force 'off))
6854 (mapc (lambda (ov)
6855 (when (member ov org-hide-block-overlays)
6856 (setq org-hide-block-overlays
6857 (delq ov org-hide-block-overlays)))
6858 (when (eq (overlay-get ov 'invisible)
6859 'org-hide-block)
6860 (delete-overlay ov)))
6861 (overlays-at start)))
6862 (setq ov (make-overlay start end))
6863 (overlay-put ov 'invisible 'org-hide-block)
6864 ;; make the block accessible to isearch
6865 (overlay-put
6866 ov 'isearch-open-invisible
6867 (lambda (ov)
6868 (when (member ov org-hide-block-overlays)
6869 (setq org-hide-block-overlays
6870 (delq ov org-hide-block-overlays)))
6871 (when (eq (overlay-get ov 'invisible)
6872 'org-hide-block)
6873 (delete-overlay ov))))
6874 (push ov org-hide-block-overlays)))
6875 (error "Not looking at a source block"))))
6877 ;; org-tab-after-check-for-cycling-hook
6878 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6879 ;; Remove overlays when changing major mode
6880 (add-hook 'org-mode-hook
6881 (lambda () (org-add-hook 'change-major-mode-hook
6882 'org-show-block-all 'append 'local)))
6884 ;;; Org-goto
6886 (defvar org-goto-window-configuration nil)
6887 (defvar org-goto-marker nil)
6888 (defvar org-goto-map
6889 (let ((map (make-sparse-keymap)))
6890 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6891 (while (setq cmd (pop cmds))
6892 (substitute-key-definition cmd cmd map global-map)))
6893 (suppress-keymap map)
6894 (org-defkey map "\C-m" 'org-goto-ret)
6895 (org-defkey map [(return)] 'org-goto-ret)
6896 (org-defkey map [(left)] 'org-goto-left)
6897 (org-defkey map [(right)] 'org-goto-right)
6898 (org-defkey map [(control ?g)] 'org-goto-quit)
6899 (org-defkey map "\C-i" 'org-cycle)
6900 (org-defkey map [(tab)] 'org-cycle)
6901 (org-defkey map [(down)] 'outline-next-visible-heading)
6902 (org-defkey map [(up)] 'outline-previous-visible-heading)
6903 (if org-goto-auto-isearch
6904 (if (fboundp 'define-key-after)
6905 (define-key-after map [t] 'org-goto-local-auto-isearch)
6906 nil)
6907 (org-defkey map "q" 'org-goto-quit)
6908 (org-defkey map "n" 'outline-next-visible-heading)
6909 (org-defkey map "p" 'outline-previous-visible-heading)
6910 (org-defkey map "f" 'outline-forward-same-level)
6911 (org-defkey map "b" 'outline-backward-same-level)
6912 (org-defkey map "u" 'outline-up-heading))
6913 (org-defkey map "/" 'org-occur)
6914 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6915 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6916 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6917 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6918 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6919 map))
6921 (defconst org-goto-help
6922 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6923 RET=jump to location [Q]uit and return to previous location
6924 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6926 (defvar org-goto-start-pos) ; dynamically scoped parameter
6928 ;; FIXME: Docstring does not mention both interfaces
6929 (defun org-goto (&optional alternative-interface)
6930 "Look up a different location in the current file, keeping current visibility.
6932 When you want look-up or go to a different location in a
6933 document, the fastest way is often to fold the entire buffer and
6934 then dive into the tree. This method has the disadvantage, that
6935 the previous location will be folded, which may not be what you
6936 want.
6938 This command works around this by showing a copy of the current
6939 buffer in an indirect buffer, in overview mode. You can dive
6940 into the tree in that copy, use org-occur and incremental search
6941 to find a location. When pressing RET or `Q', the command
6942 returns to the original buffer in which the visibility is still
6943 unchanged. After RET it will also jump to the location selected
6944 in the indirect buffer and expose the headline hierarchy above.
6946 With a prefix argument, use the alternative interface: e.g. if
6947 `org-goto-interface' is 'outline use 'outline-path-completion."
6948 (interactive "P")
6949 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6950 (org-refile-use-outline-path t)
6951 (org-refile-target-verify-function nil)
6952 (interface
6953 (if (not alternative-interface)
6954 org-goto-interface
6955 (if (eq org-goto-interface 'outline)
6956 'outline-path-completion
6957 'outline)))
6958 (org-goto-start-pos (point))
6959 (selected-point
6960 (if (eq interface 'outline)
6961 (car (org-get-location (current-buffer) org-goto-help))
6962 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6963 (org-refile-check-position pa)
6964 (nth 3 pa)))))
6965 (if selected-point
6966 (progn
6967 (org-mark-ring-push org-goto-start-pos)
6968 (goto-char selected-point)
6969 (if (or (outline-invisible-p) (org-invisible-p2))
6970 (org-show-context 'org-goto)))
6971 (message "Quit"))))
6973 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6974 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6975 (defvar org-goto-local-auto-isearch-map) ; defined below
6977 (defun org-get-location (buf help)
6978 "Let the user select a location in the Org-mode buffer BUF.
6979 This function uses a recursive edit. It returns the selected position
6980 or nil."
6981 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6982 (isearch-hide-immediately nil)
6983 (isearch-search-fun-function
6984 (lambda () 'org-goto-local-search-headings))
6985 (org-goto-selected-point org-goto-exit-command)
6986 (pop-up-frames nil)
6987 (special-display-buffer-names nil)
6988 (special-display-regexps nil)
6989 (special-display-function nil))
6990 (save-excursion
6991 (save-window-excursion
6992 (delete-other-windows)
6993 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6994 (org-pop-to-buffer-same-window
6995 (condition-case nil
6996 (make-indirect-buffer (current-buffer) "*org-goto*")
6997 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6998 (with-output-to-temp-buffer "*Help*"
6999 (princ help))
7000 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7001 (setq buffer-read-only nil)
7002 (let ((org-startup-truncated t)
7003 (org-startup-folded nil)
7004 (org-startup-align-all-tables nil))
7005 (org-mode)
7006 (org-overview))
7007 (setq buffer-read-only t)
7008 (if (and (boundp 'org-goto-start-pos)
7009 (integer-or-marker-p org-goto-start-pos))
7010 (let ((org-show-hierarchy-above t)
7011 (org-show-siblings t)
7012 (org-show-following-heading t))
7013 (goto-char org-goto-start-pos)
7014 (and (outline-invisible-p) (org-show-context)))
7015 (goto-char (point-min)))
7016 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7017 (message "Select location and press RET")
7018 (use-local-map org-goto-map)
7019 (recursive-edit)
7021 (kill-buffer "*org-goto*")
7022 (cons org-goto-selected-point org-goto-exit-command)))
7024 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7025 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7026 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7027 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7029 (defun org-goto-local-search-headings (string bound noerror)
7030 "Search and make sure that any matches are in headlines."
7031 (catch 'return
7032 (while (if isearch-forward
7033 (search-forward string bound noerror)
7034 (search-backward string bound noerror))
7035 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7036 (and (member :headline context)
7037 (not (member :tags context))))
7038 (throw 'return (point))))))
7040 (defun org-goto-local-auto-isearch ()
7041 "Start isearch."
7042 (interactive)
7043 (goto-char (point-min))
7044 (let ((keys (this-command-keys)))
7045 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7046 (isearch-mode t)
7047 (isearch-process-search-char (string-to-char keys)))))
7049 (defun org-goto-ret (&optional arg)
7050 "Finish `org-goto' by going to the new location."
7051 (interactive "P")
7052 (setq org-goto-selected-point (point)
7053 org-goto-exit-command 'return)
7054 (throw 'exit nil))
7056 (defun org-goto-left ()
7057 "Finish `org-goto' by going to the new location."
7058 (interactive)
7059 (if (org-at-heading-p)
7060 (progn
7061 (beginning-of-line 1)
7062 (setq org-goto-selected-point (point)
7063 org-goto-exit-command 'left)
7064 (throw 'exit nil))
7065 (error "Not on a heading")))
7067 (defun org-goto-right ()
7068 "Finish `org-goto' by going to the new location."
7069 (interactive)
7070 (if (org-at-heading-p)
7071 (progn
7072 (setq org-goto-selected-point (point)
7073 org-goto-exit-command 'right)
7074 (throw 'exit nil))
7075 (error "Not on a heading")))
7077 (defun org-goto-quit ()
7078 "Finish `org-goto' without cursor motion."
7079 (interactive)
7080 (setq org-goto-selected-point nil)
7081 (setq org-goto-exit-command 'quit)
7082 (throw 'exit nil))
7084 ;;; Indirect buffer display of subtrees
7086 (defvar org-indirect-dedicated-frame nil
7087 "This is the frame being used for indirect tree display.")
7088 (defvar org-last-indirect-buffer nil)
7090 (defun org-tree-to-indirect-buffer (&optional arg)
7091 "Create indirect buffer and narrow it to current subtree.
7092 With a numerical prefix ARG, go up to this level and then take that tree.
7093 If ARG is negative, go up that many levels.
7095 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7096 indirect buffer previously made with this command, to avoid proliferation of
7097 indirect buffers. However, when you call the command with a \
7098 \\[universal-argument] prefix, or
7099 when `org-indirect-buffer-display' is `new-frame', the last buffer
7100 is kept so that you can work with several indirect buffers at the same time.
7101 If `org-indirect-buffer-display' is `dedicated-frame', the \
7102 \\[universal-argument] prefix also
7103 requests that a new frame be made for the new buffer, so that the dedicated
7104 frame is not changed."
7105 (interactive "P")
7106 (let ((cbuf (current-buffer))
7107 (cwin (selected-window))
7108 (pos (point))
7109 beg end level heading ibuf)
7110 (save-excursion
7111 (org-back-to-heading t)
7112 (when (numberp arg)
7113 (setq level (org-outline-level))
7114 (if (< arg 0) (setq arg (+ level arg)))
7115 (while (> (setq level (org-outline-level)) arg)
7116 (org-up-heading-safe)))
7117 (setq beg (point)
7118 heading (org-get-heading))
7119 (org-end-of-subtree t t)
7120 (if (org-at-heading-p) (backward-char 1))
7121 (setq end (point)))
7122 (if (and (buffer-live-p org-last-indirect-buffer)
7123 (not (eq org-indirect-buffer-display 'new-frame))
7124 (not arg))
7125 (kill-buffer org-last-indirect-buffer))
7126 (setq ibuf (org-get-indirect-buffer cbuf)
7127 org-last-indirect-buffer ibuf)
7128 (cond
7129 ((or (eq org-indirect-buffer-display 'new-frame)
7130 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7131 (select-frame (make-frame))
7132 (delete-other-windows)
7133 (org-pop-to-buffer-same-window ibuf)
7134 (org-set-frame-title heading))
7135 ((eq org-indirect-buffer-display 'dedicated-frame)
7136 (raise-frame
7137 (select-frame (or (and org-indirect-dedicated-frame
7138 (frame-live-p org-indirect-dedicated-frame)
7139 org-indirect-dedicated-frame)
7140 (setq org-indirect-dedicated-frame (make-frame)))))
7141 (delete-other-windows)
7142 (org-pop-to-buffer-same-window ibuf)
7143 (org-set-frame-title (concat "Indirect: " heading)))
7144 ((eq org-indirect-buffer-display 'current-window)
7145 (org-pop-to-buffer-same-window ibuf))
7146 ((eq org-indirect-buffer-display 'other-window)
7147 (pop-to-buffer ibuf))
7148 (t (error "Invalid value")))
7149 (if (featurep 'xemacs)
7150 (save-excursion (org-mode) (turn-on-font-lock)))
7151 (narrow-to-region beg end)
7152 (show-all)
7153 (goto-char pos)
7154 (run-hook-with-args 'org-cycle-hook 'all)
7155 (and (window-live-p cwin) (select-window cwin))))
7157 (defun org-get-indirect-buffer (&optional buffer)
7158 (setq buffer (or buffer (current-buffer)))
7159 (let ((n 1) (base (buffer-name buffer)) bname)
7160 (while (buffer-live-p
7161 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7162 (setq n (1+ n)))
7163 (condition-case nil
7164 (make-indirect-buffer buffer bname 'clone)
7165 (error (make-indirect-buffer buffer bname)))))
7167 (defun org-set-frame-title (title)
7168 "Set the title of the current frame to the string TITLE."
7169 ;; FIXME: how to name a single frame in XEmacs???
7170 (unless (featurep 'xemacs)
7171 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7173 ;;;; Structure editing
7175 ;;; Inserting headlines
7177 (defun org-previous-line-empty-p ()
7178 (save-excursion
7179 (and (not (bobp))
7180 (or (beginning-of-line 0) t)
7181 (save-match-data
7182 (looking-at "[ \t]*$")))))
7184 (defun org-insert-heading (&optional force-heading invisible-ok)
7185 "Insert a new heading or item with same depth at point.
7186 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7187 If point is at the beginning of a headline, insert a sibling before the
7188 current headline. If point is not at the beginning, split the line,
7189 create the new headline with the text in the current line after point
7190 \(but see also the variable `org-M-RET-may-split-line').
7192 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7193 This is important for non-interactive uses of the command."
7194 (interactive "P")
7195 (if (or (= (buffer-size) 0)
7196 (and (not (save-excursion
7197 (and (ignore-errors (org-back-to-heading invisible-ok))
7198 (org-at-heading-p))))
7199 (or force-heading (not (org-in-item-p)))))
7200 (progn
7201 (insert "\n* ")
7202 (run-hooks 'org-insert-heading-hook))
7203 (when (or force-heading (not (org-insert-item)))
7204 (let* ((empty-line-p nil)
7205 (level nil)
7206 (on-heading (org-at-heading-p))
7207 (head (save-excursion
7208 (condition-case nil
7209 (progn
7210 (org-back-to-heading invisible-ok)
7211 (when (and (not on-heading)
7212 (featurep 'org-inlinetask)
7213 (integerp org-inlinetask-min-level)
7214 (>= (length (match-string 0))
7215 org-inlinetask-min-level))
7216 ;; Find a heading level before the inline task
7217 (while (and (setq level (org-up-heading-safe))
7218 (>= level org-inlinetask-min-level)))
7219 (if (org-at-heading-p)
7220 (org-back-to-heading invisible-ok)
7221 (error "This should not happen")))
7222 (setq empty-line-p (org-previous-line-empty-p))
7223 (match-string 0))
7224 (error "*"))))
7225 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7226 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7227 pos hide-previous previous-pos)
7228 (cond
7229 ((and (org-at-heading-p) (bolp)
7230 (or (bobp)
7231 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7232 ;; insert before the current line
7233 (open-line (if blank 2 1)))
7234 ((and (bolp)
7235 (not org-insert-heading-respect-content)
7236 (or (bobp)
7237 (save-excursion
7238 (backward-char 1) (not (outline-invisible-p)))))
7239 ;; insert right here
7240 nil)
7242 ;; somewhere in the line
7243 (save-excursion
7244 (setq previous-pos (point-at-bol))
7245 (end-of-line)
7246 (setq hide-previous (outline-invisible-p)))
7247 (and org-insert-heading-respect-content (org-show-subtree))
7248 (let ((split
7249 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7250 (save-excursion
7251 (let ((p (point)))
7252 (goto-char (point-at-bol))
7253 (and (looking-at org-complex-heading-regexp)
7254 (match-beginning 4)
7255 (> p (match-beginning 4)))))))
7256 tags pos)
7257 (cond
7258 (org-insert-heading-respect-content
7259 (org-end-of-subtree nil t)
7260 (when (featurep 'org-inlinetask)
7261 (while (and (not (eobp))
7262 (looking-at "\\(\\*+\\)[ \t]+")
7263 (>= (length (match-string 1))
7264 org-inlinetask-min-level))
7265 (org-end-of-subtree nil t)))
7266 (or (bolp) (newline))
7267 (or (org-previous-line-empty-p)
7268 (and blank (newline)))
7269 (open-line 1))
7270 ((org-at-heading-p)
7271 (when hide-previous
7272 (show-children)
7273 (org-show-entry))
7274 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7275 (setq tags (and (match-end 2) (match-string 2)))
7276 (and (match-end 1)
7277 (delete-region (match-beginning 1) (match-end 1)))
7278 (setq pos (point-at-bol))
7279 (or split (end-of-line 1))
7280 (delete-horizontal-space)
7281 (if (string-match "\\`\\*+\\'"
7282 (buffer-substring (point-at-bol) (point)))
7283 (insert " "))
7284 (newline (if blank 2 1))
7285 (when tags
7286 (save-excursion
7287 (goto-char pos)
7288 (end-of-line 1)
7289 (insert " " tags)
7290 (org-set-tags nil 'align))))
7292 (or split (end-of-line 1))
7293 (newline (if blank 2 1)))))))
7294 (insert head) (just-one-space)
7295 (setq pos (point))
7296 (end-of-line 1)
7297 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7298 (when (and org-insert-heading-respect-content hide-previous)
7299 (save-excursion
7300 (goto-char previous-pos)
7301 (hide-subtree)))
7302 (run-hooks 'org-insert-heading-hook)))))
7304 (defun org-get-heading (&optional no-tags no-todo)
7305 "Return the heading of the current entry, without the stars.
7306 When NO-TAGS is non-nil, don't include tags.
7307 When NO-TODO is non-nil, don't include TODO keywords."
7308 (save-excursion
7309 (org-back-to-heading t)
7310 (cond
7311 ((and no-tags no-todo)
7312 (looking-at org-complex-heading-regexp)
7313 (match-string 4))
7314 (no-tags
7315 (looking-at (concat org-outline-regexp
7316 "\\(.*?\\)"
7317 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7318 (match-string 1))
7319 (no-todo
7320 (looking-at org-todo-line-regexp)
7321 (match-string 3))
7322 (t (looking-at org-heading-regexp)
7323 (match-string 2)))))
7325 (defun org-heading-components ()
7326 "Return the components of the current heading.
7327 This is a list with the following elements:
7328 - the level as an integer
7329 - the reduced level, different if `org-odd-levels-only' is set.
7330 - the TODO keyword, or nil
7331 - the priority character, like ?A, or nil if no priority is given
7332 - the headline text itself, or the tags string if no headline text
7333 - the tags string, or nil."
7334 (save-excursion
7335 (org-back-to-heading t)
7336 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7337 (list (length (match-string 1))
7338 (org-reduced-level (length (match-string 1)))
7339 (org-match-string-no-properties 2)
7340 (and (match-end 3) (aref (match-string 3) 2))
7341 (org-match-string-no-properties 4)
7342 (org-match-string-no-properties 5)))))
7344 (defun org-get-entry ()
7345 "Get the entry text, after heading, entire subtree."
7346 (save-excursion
7347 (org-back-to-heading t)
7348 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7350 (defun org-insert-heading-after-current ()
7351 "Insert a new heading with same level as current, after current subtree."
7352 (interactive)
7353 (org-back-to-heading)
7354 (org-insert-heading)
7355 (org-move-subtree-down)
7356 (end-of-line 1))
7358 (defun org-insert-heading-respect-content ()
7359 (interactive)
7360 (let ((org-insert-heading-respect-content t))
7361 (org-insert-heading t)))
7363 (defun org-insert-todo-heading-respect-content (&optional force-state)
7364 (interactive "P")
7365 (let ((org-insert-heading-respect-content t))
7366 (org-insert-todo-heading force-state t)))
7368 (defun org-insert-todo-heading (arg &optional force-heading)
7369 "Insert a new heading with the same level and TODO state as current heading.
7370 If the heading has no TODO state, or if the state is DONE, use the first
7371 state (TODO by default). Also with prefix arg, force first state."
7372 (interactive "P")
7373 (when (or force-heading (not (org-insert-item 'checkbox)))
7374 (org-insert-heading force-heading)
7375 (save-excursion
7376 (org-back-to-heading)
7377 (outline-previous-heading)
7378 (looking-at org-todo-line-regexp))
7379 (let*
7380 ((new-mark-x
7381 (if (or arg
7382 (not (match-beginning 2))
7383 (member (match-string 2) org-done-keywords))
7384 (car org-todo-keywords-1)
7385 (match-string 2)))
7386 (new-mark
7388 (run-hook-with-args-until-success
7389 'org-todo-get-default-hook new-mark-x nil)
7390 new-mark-x)))
7391 (beginning-of-line 1)
7392 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7393 (if org-treat-insert-todo-heading-as-state-change
7394 (org-todo new-mark)
7395 (insert new-mark " "))))
7396 (when org-provide-todo-statistics
7397 (org-update-parent-todo-statistics))))
7399 (defun org-insert-subheading (arg)
7400 "Insert a new subheading and demote it.
7401 Works for outline headings and for plain lists alike."
7402 (interactive "P")
7403 (org-insert-heading arg)
7404 (cond
7405 ((org-at-heading-p) (org-do-demote))
7406 ((org-at-item-p) (org-indent-item))))
7408 (defun org-insert-todo-subheading (arg)
7409 "Insert a new subheading with TODO keyword or checkbox and demote it.
7410 Works for outline headings and for plain lists alike."
7411 (interactive "P")
7412 (org-insert-todo-heading arg)
7413 (cond
7414 ((org-at-heading-p) (org-do-demote))
7415 ((org-at-item-p) (org-indent-item))))
7417 ;;; Promotion and Demotion
7419 (defvar org-after-demote-entry-hook nil
7420 "Hook run after an entry has been demoted.
7421 The cursor will be at the beginning of the entry.
7422 When a subtree is being demoted, the hook will be called for each node.")
7424 (defvar org-after-promote-entry-hook nil
7425 "Hook run after an entry has been promoted.
7426 The cursor will be at the beginning of the entry.
7427 When a subtree is being promoted, the hook will be called for each node.")
7429 (defun org-promote-subtree ()
7430 "Promote the entire subtree.
7431 See also `org-promote'."
7432 (interactive)
7433 (save-excursion
7434 (org-with-limited-levels (org-map-tree 'org-promote)))
7435 (org-fix-position-after-promote))
7437 (defun org-demote-subtree ()
7438 "Demote the entire subtree. See `org-demote'.
7439 See also `org-promote'."
7440 (interactive)
7441 (save-excursion
7442 (org-with-limited-levels (org-map-tree 'org-demote)))
7443 (org-fix-position-after-promote))
7446 (defun org-do-promote ()
7447 "Promote the current heading higher up the tree.
7448 If the region is active in `transient-mark-mode', promote all headings
7449 in the region."
7450 (interactive)
7451 (save-excursion
7452 (if (org-region-active-p)
7453 (org-map-region 'org-promote (region-beginning) (region-end))
7454 (org-promote)))
7455 (org-fix-position-after-promote))
7457 (defun org-do-demote ()
7458 "Demote the current heading lower down the tree.
7459 If the region is active in `transient-mark-mode', demote all headings
7460 in the region."
7461 (interactive)
7462 (save-excursion
7463 (if (org-region-active-p)
7464 (org-map-region 'org-demote (region-beginning) (region-end))
7465 (org-demote)))
7466 (org-fix-position-after-promote))
7468 (defun org-fix-position-after-promote ()
7469 "Make sure that after pro/demotion cursor position is right."
7470 (let ((pos (point)))
7471 (when (save-excursion
7472 (beginning-of-line 1)
7473 (looking-at org-todo-line-regexp)
7474 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7475 (cond ((eobp) (insert " "))
7476 ((eolp) (insert " "))
7477 ((equal (char-after) ?\ ) (forward-char 1))))))
7479 (defun org-current-level ()
7480 "Return the level of the current entry, or nil if before the first headline.
7481 The level is the number of stars at the beginning of the headline."
7482 (save-excursion
7483 (org-with-limited-levels
7484 (if (ignore-errors (org-back-to-heading t))
7485 (funcall outline-level)))))
7487 (defun org-get-previous-line-level ()
7488 "Return the outline depth of the last headline before the current line.
7489 Returns 0 for the first headline in the buffer, and nil if before the
7490 first headline."
7491 (let ((current-level (org-current-level))
7492 (prev-level (when (> (line-number-at-pos) 1)
7493 (save-excursion
7494 (beginning-of-line 0)
7495 (org-current-level)))))
7496 (cond ((null current-level) nil) ; Before first headline
7497 ((null prev-level) 0) ; At first headline
7498 (prev-level))))
7500 (defun org-reduced-level (l)
7501 "Compute the effective level of a heading.
7502 This takes into account the setting of `org-odd-levels-only'."
7503 (cond
7504 ((zerop l) 0)
7505 (org-odd-levels-only (1+ (floor (/ l 2))))
7506 (t l)))
7508 (defun org-level-increment ()
7509 "Return the number of stars that will be added or removed at a
7510 time to headlines when structure editing, based on the value of
7511 `org-odd-levels-only'."
7512 (if org-odd-levels-only 2 1))
7514 (defun org-get-valid-level (level &optional change)
7515 "Rectify a level change under the influence of `org-odd-levels-only'
7516 LEVEL is a current level, CHANGE is by how much the level should be
7517 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7518 even level numbers will become the next higher odd number."
7519 (if org-odd-levels-only
7520 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7521 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7522 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7523 (max 1 (+ level (or change 0)))))
7525 (if (boundp 'define-obsolete-function-alias)
7526 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7527 (define-obsolete-function-alias 'org-get-legal-level
7528 'org-get-valid-level)
7529 (define-obsolete-function-alias 'org-get-legal-level
7530 'org-get-valid-level "23.1")))
7532 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7533 ;; ̀org-with-limited-levels'
7534 (defun org-promote ()
7535 "Promote the current heading higher up the tree.
7536 If the region is active in `transient-mark-mode', promote all headings
7537 in the region."
7538 (org-back-to-heading t)
7539 (let* ((level (save-match-data (funcall outline-level)))
7540 (after-change-functions (remove 'flyspell-after-change-function
7541 after-change-functions))
7542 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7543 (diff (abs (- level (length up-head) -1))))
7544 (cond ((and (= level 1) org-called-with-limited-levels
7545 org-allow-promoting-top-level-subtree)
7546 (replace-match "# " nil t))
7547 ((= level 1)
7548 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7549 (t (replace-match up-head nil t)))
7550 ;; Fixup tag positioning
7551 (unless (= level 1)
7552 (and org-auto-align-tags (org-set-tags nil t))
7553 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7554 (run-hooks 'org-after-promote-entry-hook)))
7556 (defun org-demote ()
7557 "Demote the current heading lower down the tree.
7558 If the region is active in `transient-mark-mode', demote all headings
7559 in the region."
7560 (org-back-to-heading t)
7561 (let* ((level (save-match-data (funcall outline-level)))
7562 (after-change-functions (remove 'flyspell-after-change-function
7563 after-change-functions))
7564 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7565 (diff (abs (- level (length down-head) -1))))
7566 (replace-match down-head nil t)
7567 ;; Fixup tag positioning
7568 (and org-auto-align-tags (org-set-tags nil t))
7569 (if org-adapt-indentation (org-fixup-indentation diff))
7570 (run-hooks 'org-after-demote-entry-hook)))
7572 (defun org-cycle-level ()
7573 "Cycle the level of an empty headline through possible states.
7574 This goes first to child, then to parent, level, then up the hierarchy.
7575 After top level, it switches back to sibling level."
7576 (interactive)
7577 (let ((org-adapt-indentation nil))
7578 (when (org-point-at-end-of-empty-headline)
7579 (setq this-command 'org-cycle-level) ; Only needed for caching
7580 (let ((cur-level (org-current-level))
7581 (prev-level (org-get-previous-line-level)))
7582 (cond
7583 ;; If first headline in file, promote to top-level.
7584 ((= prev-level 0)
7585 (loop repeat (/ (- cur-level 1) (org-level-increment))
7586 do (org-do-promote)))
7587 ;; If same level as prev, demote one.
7588 ((= prev-level cur-level)
7589 (org-do-demote))
7590 ;; If parent is top-level, promote to top level if not already.
7591 ((= prev-level 1)
7592 (loop repeat (/ (- cur-level 1) (org-level-increment))
7593 do (org-do-promote)))
7594 ;; If top-level, return to prev-level.
7595 ((= cur-level 1)
7596 (loop repeat (/ (- prev-level 1) (org-level-increment))
7597 do (org-do-demote)))
7598 ;; If less than prev-level, promote one.
7599 ((< cur-level prev-level)
7600 (org-do-promote))
7601 ;; If deeper than prev-level, promote until higher than
7602 ;; prev-level.
7603 ((> cur-level prev-level)
7604 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7605 do (org-do-promote))))
7606 t))))
7608 (defun org-map-tree (fun)
7609 "Call FUN for every heading underneath the current one."
7610 (org-back-to-heading)
7611 (let ((level (funcall outline-level)))
7612 (save-excursion
7613 (funcall fun)
7614 (while (and (progn
7615 (outline-next-heading)
7616 (> (funcall outline-level) level))
7617 (not (eobp)))
7618 (funcall fun)))))
7620 (defun org-map-region (fun beg end)
7621 "Call FUN for every heading between BEG and END."
7622 (let ((org-ignore-region t))
7623 (save-excursion
7624 (setq end (copy-marker end))
7625 (goto-char beg)
7626 (if (and (re-search-forward org-outline-regexp-bol nil t)
7627 (< (point) end))
7628 (funcall fun))
7629 (while (and (progn
7630 (outline-next-heading)
7631 (< (point) end))
7632 (not (eobp)))
7633 (funcall fun)))))
7635 (defvar org-property-end-re) ; silence byte-compiler
7636 (defun org-fixup-indentation (diff)
7637 "Change the indentation in the current entry by DIFF.
7638 However, if any line in the current entry has no indentation, or if it
7639 would end up with no indentation after the change, nothing at all is done."
7640 (save-excursion
7641 (let ((end (save-excursion (outline-next-heading)
7642 (point-marker)))
7643 (prohibit (if (> diff 0)
7644 "^\\S-"
7645 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7646 col)
7647 (unless (save-excursion (end-of-line 1)
7648 (re-search-forward prohibit end t))
7649 (while (and (< (point) end)
7650 (re-search-forward "^[ \t]+" end t))
7651 (goto-char (match-end 0))
7652 (setq col (current-column))
7653 (if (< diff 0) (replace-match ""))
7654 (org-indent-to-column (+ diff col))))
7655 (move-marker end nil))))
7657 (defun org-convert-to-odd-levels ()
7658 "Convert an org-mode file with all levels allowed to one with odd levels.
7659 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7660 level 5 etc."
7661 (interactive)
7662 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7663 (let ((outline-level 'org-outline-level)
7664 (org-odd-levels-only nil) n)
7665 (save-excursion
7666 (goto-char (point-min))
7667 (while (re-search-forward "^\\*\\*+ " nil t)
7668 (setq n (- (length (match-string 0)) 2))
7669 (while (>= (setq n (1- n)) 0)
7670 (org-demote))
7671 (end-of-line 1))))))
7673 (defun org-convert-to-oddeven-levels ()
7674 "Convert an org-mode file with only odd levels to one with odd/even levels.
7675 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7676 file contains a section with an even level, conversion would
7677 destroy the structure of the file. An error is signaled in this
7678 case."
7679 (interactive)
7680 (goto-char (point-min))
7681 ;; First check if there are no even levels
7682 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7683 (org-show-context t)
7684 (error "Not all levels are odd in this file. Conversion not possible"))
7685 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7686 (let ((outline-regexp org-outline-regexp)
7687 (outline-level 'org-outline-level)
7688 (org-odd-levels-only nil) n)
7689 (save-excursion
7690 (goto-char (point-min))
7691 (while (re-search-forward "^\\*\\*+ " nil t)
7692 (setq n (/ (1- (length (match-string 0))) 2))
7693 (while (>= (setq n (1- n)) 0)
7694 (org-promote))
7695 (end-of-line 1))))))
7697 (defun org-tr-level (n)
7698 "Make N odd if required."
7699 (if org-odd-levels-only (1+ (/ n 2)) n))
7701 ;;; Vertical tree motion, cutting and pasting of subtrees
7703 (defun org-move-subtree-up (&optional arg)
7704 "Move the current subtree up past ARG headlines of the same level."
7705 (interactive "p")
7706 (org-move-subtree-down (- (prefix-numeric-value arg))))
7708 (defun org-move-subtree-down (&optional arg)
7709 "Move the current subtree down past ARG headlines of the same level."
7710 (interactive "p")
7711 (setq arg (prefix-numeric-value arg))
7712 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7713 'org-get-last-sibling))
7714 (ins-point (make-marker))
7715 (cnt (abs arg))
7716 (col (current-column))
7717 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7718 ;; Select the tree
7719 (org-back-to-heading)
7720 (setq beg0 (point))
7721 (save-excursion
7722 (setq ne-beg (org-back-over-empty-lines))
7723 (setq beg (point)))
7724 (save-match-data
7725 (save-excursion (outline-end-of-heading)
7726 (setq folded (outline-invisible-p)))
7727 (outline-end-of-subtree))
7728 (outline-next-heading)
7729 (setq ne-end (org-back-over-empty-lines))
7730 (setq end (point))
7731 (goto-char beg0)
7732 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7733 ;; include less whitespace
7734 (save-excursion
7735 (goto-char beg)
7736 (forward-line (- ne-beg ne-end))
7737 (setq beg (point))))
7738 ;; Find insertion point, with error handling
7739 (while (> cnt 0)
7740 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7741 (progn (goto-char beg0)
7742 (error "Cannot move past superior level or buffer limit")))
7743 (setq cnt (1- cnt)))
7744 (if (> arg 0)
7745 ;; Moving forward - still need to move over subtree
7746 (progn (org-end-of-subtree t t)
7747 (save-excursion
7748 (org-back-over-empty-lines)
7749 (or (bolp) (newline)))))
7750 (setq ne-ins (org-back-over-empty-lines))
7751 (move-marker ins-point (point))
7752 (setq txt (buffer-substring beg end))
7753 (org-save-markers-in-region beg end)
7754 (delete-region beg end)
7755 (org-remove-empty-overlays-at beg)
7756 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7757 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7758 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7759 (let ((bbb (point)))
7760 (insert-before-markers txt)
7761 (org-reinstall-markers-in-region bbb)
7762 (move-marker ins-point bbb))
7763 (or (bolp) (insert "\n"))
7764 (setq ins-end (point))
7765 (goto-char ins-point)
7766 (org-skip-whitespace)
7767 (when (and (< arg 0)
7768 (org-first-sibling-p)
7769 (> ne-ins ne-beg))
7770 ;; Move whitespace back to beginning
7771 (save-excursion
7772 (goto-char ins-end)
7773 (let ((kill-whole-line t))
7774 (kill-line (- ne-ins ne-beg)) (point)))
7775 (insert (make-string (- ne-ins ne-beg) ?\n)))
7776 (move-marker ins-point nil)
7777 (if folded
7778 (hide-subtree)
7779 (org-show-entry)
7780 (show-children)
7781 (org-cycle-hide-drawers 'children))
7782 (org-clean-visibility-after-subtree-move)
7783 ;; move back to the initial column we were at
7784 (move-to-column col)))
7786 (defvar org-subtree-clip ""
7787 "Clipboard for cut and paste of subtrees.
7788 This is actually only a copy of the kill, because we use the normal kill
7789 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7791 (defvar org-subtree-clip-folded nil
7792 "Was the last copied subtree folded?
7793 This is used to fold the tree back after pasting.")
7795 (defun org-cut-subtree (&optional n)
7796 "Cut the current subtree into the clipboard.
7797 With prefix arg N, cut this many sequential subtrees.
7798 This is a short-hand for marking the subtree and then cutting it."
7799 (interactive "p")
7800 (org-copy-subtree n 'cut))
7802 (defun org-copy-subtree (&optional n cut force-store-markers)
7803 "Cut the current subtree into the clipboard.
7804 With prefix arg N, cut this many sequential subtrees.
7805 This is a short-hand for marking the subtree and then copying it.
7806 If CUT is non-nil, actually cut the subtree.
7807 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7808 of some markers in the region, even if CUT is non-nil. This is
7809 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7810 (interactive "p")
7811 (let (beg end folded (beg0 (point)))
7812 (if (org-called-interactively-p 'any)
7813 (org-back-to-heading nil) ; take what looks like a subtree
7814 (org-back-to-heading t)) ; take what is really there
7815 (org-back-over-empty-lines)
7816 (setq beg (point))
7817 (skip-chars-forward " \t\r\n")
7818 (save-match-data
7819 (save-excursion (outline-end-of-heading)
7820 (setq folded (outline-invisible-p)))
7821 (condition-case nil
7822 (org-forward-heading-same-level (1- n) t)
7823 (error nil))
7824 (org-end-of-subtree t t))
7825 (org-back-over-empty-lines)
7826 (setq end (point))
7827 (goto-char beg0)
7828 (when (> end beg)
7829 (setq org-subtree-clip-folded folded)
7830 (when (or cut force-store-markers)
7831 (org-save-markers-in-region beg end))
7832 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7833 (setq org-subtree-clip (current-kill 0))
7834 (message "%s: Subtree(s) with %d characters"
7835 (if cut "Cut" "Copied")
7836 (length org-subtree-clip)))))
7838 (defun org-paste-subtree (&optional level tree for-yank)
7839 "Paste the clipboard as a subtree, with modification of headline level.
7840 The entire subtree is promoted or demoted in order to match a new headline
7841 level.
7843 If the cursor is at the beginning of a headline, the same level as
7844 that headline is used to paste the tree
7846 If not, the new level is derived from the *visible* headings
7847 before and after the insertion point, and taken to be the inferior headline
7848 level of the two. So if the previous visible heading is level 3 and the
7849 next is level 4 (or vice versa), level 4 will be used for insertion.
7850 This makes sure that the subtree remains an independent subtree and does
7851 not swallow low level entries.
7853 You can also force a different level, either by using a numeric prefix
7854 argument, or by inserting the heading marker by hand. For example, if the
7855 cursor is after \"*****\", then the tree will be shifted to level 5.
7857 If optional TREE is given, use this text instead of the kill ring.
7859 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7860 move back over whitespace before inserting, and move point to the end of
7861 the inserted text when done."
7862 (interactive "P")
7863 (setq tree (or tree (and kill-ring (current-kill 0))))
7864 (unless (org-kill-is-subtree-p tree)
7865 (error "%s"
7866 (substitute-command-keys
7867 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7868 (org-with-limited-levels
7869 (let* ((visp (not (outline-invisible-p)))
7870 (txt tree)
7871 (^re_ "\\(\\*+\\)[ \t]*")
7872 (old-level (if (string-match org-outline-regexp-bol txt)
7873 (- (match-end 0) (match-beginning 0) 1)
7874 -1))
7875 (force-level (cond (level (prefix-numeric-value level))
7876 ((and (looking-at "[ \t]*$")
7877 (string-match
7878 "^\\*+$" (buffer-substring
7879 (point-at-bol) (point))))
7880 (- (match-end 1) (match-beginning 1)))
7881 ((and (bolp)
7882 (looking-at org-outline-regexp))
7883 (- (match-end 0) (point) 1))))
7884 (previous-level (save-excursion
7885 (condition-case nil
7886 (progn
7887 (outline-previous-visible-heading 1)
7888 (if (looking-at ^re_)
7889 (- (match-end 0) (match-beginning 0) 1)
7891 (error 1))))
7892 (next-level (save-excursion
7893 (condition-case nil
7894 (progn
7895 (or (looking-at org-outline-regexp)
7896 (outline-next-visible-heading 1))
7897 (if (looking-at ^re_)
7898 (- (match-end 0) (match-beginning 0) 1)
7900 (error 1))))
7901 (new-level (or force-level (max previous-level next-level)))
7902 (shift (if (or (= old-level -1)
7903 (= new-level -1)
7904 (= old-level new-level))
7906 (- new-level old-level)))
7907 (delta (if (> shift 0) -1 1))
7908 (func (if (> shift 0) 'org-demote 'org-promote))
7909 (org-odd-levels-only nil)
7910 beg end newend)
7911 ;; Remove the forced level indicator
7912 (if force-level
7913 (delete-region (point-at-bol) (point)))
7914 ;; Paste
7915 (beginning-of-line (if (bolp) 1 2))
7916 (unless for-yank (org-back-over-empty-lines))
7917 (setq beg (point))
7918 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7919 (insert-before-markers txt)
7920 (unless (string-match "\n\\'" txt) (insert "\n"))
7921 (setq newend (point))
7922 (org-reinstall-markers-in-region beg)
7923 (setq end (point))
7924 (goto-char beg)
7925 (skip-chars-forward " \t\n\r")
7926 (setq beg (point))
7927 (if (and (outline-invisible-p) visp)
7928 (save-excursion (outline-show-heading)))
7929 ;; Shift if necessary
7930 (unless (= shift 0)
7931 (save-restriction
7932 (narrow-to-region beg end)
7933 (while (not (= shift 0))
7934 (org-map-region func (point-min) (point-max))
7935 (setq shift (+ delta shift)))
7936 (goto-char (point-min))
7937 (setq newend (point-max))))
7938 (when (or (org-called-interactively-p 'interactive) for-yank)
7939 (message "Clipboard pasted as level %d subtree" new-level))
7940 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7941 kill-ring
7942 (eq org-subtree-clip (current-kill 0))
7943 org-subtree-clip-folded)
7944 ;; The tree was folded before it was killed/copied
7945 (hide-subtree))
7946 (and for-yank (goto-char newend)))))
7948 (defun org-kill-is-subtree-p (&optional txt)
7949 "Check if the current kill is an outline subtree, or a set of trees.
7950 Returns nil if kill does not start with a headline, or if the first
7951 headline level is not the largest headline level in the tree.
7952 So this will actually accept several entries of equal levels as well,
7953 which is OK for `org-paste-subtree'.
7954 If optional TXT is given, check this string instead of the current kill."
7955 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7956 (re (org-get-limited-outline-regexp))
7957 (^re (concat "^" re))
7958 (start-level (and kill
7959 (string-match
7960 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7961 kill)
7962 (- (match-end 2) (match-beginning 2) 1)))
7963 (start (1+ (or (match-beginning 2) -1))))
7964 (if (not start-level)
7965 (progn
7966 nil) ;; does not even start with a heading
7967 (catch 'exit
7968 (while (setq start (string-match ^re kill (1+ start)))
7969 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7970 (throw 'exit nil)))
7971 t))))
7973 (defvar org-markers-to-move nil
7974 "Markers that should be moved with a cut-and-paste operation.
7975 Those markers are stored together with their positions relative to
7976 the start of the region.")
7978 (defun org-save-markers-in-region (beg end)
7979 "Check markers in region.
7980 If these markers are between BEG and END, record their position relative
7981 to BEG, so that after moving the block of text, we can put the markers back
7982 into place.
7983 This function gets called just before an entry or tree gets cut from the
7984 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7985 called immediately, to move the markers with the entries."
7986 (setq org-markers-to-move nil)
7987 (when (featurep 'org-clock)
7988 (org-clock-save-markers-for-cut-and-paste beg end))
7989 (when (featurep 'org-agenda)
7990 (org-agenda-save-markers-for-cut-and-paste beg end)))
7992 (defun org-check-and-save-marker (marker beg end)
7993 "Check if MARKER is between BEG and END.
7994 If yes, remember the marker and the distance to BEG."
7995 (when (and (marker-buffer marker)
7996 (equal (marker-buffer marker) (current-buffer)))
7997 (if (and (>= marker beg) (< marker end))
7998 (push (cons marker (- marker beg)) org-markers-to-move))))
8000 (defun org-reinstall-markers-in-region (beg)
8001 "Move all remembered markers to their position relative to BEG."
8002 (mapc (lambda (x)
8003 (move-marker (car x) (+ beg (cdr x))))
8004 org-markers-to-move)
8005 (setq org-markers-to-move nil))
8007 (defun org-narrow-to-subtree ()
8008 "Narrow buffer to the current subtree."
8009 (interactive)
8010 (save-excursion
8011 (save-match-data
8012 (org-with-limited-levels
8013 (narrow-to-region
8014 (progn (org-back-to-heading t) (point))
8015 (progn (org-end-of-subtree t t)
8016 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8017 (point)))))))
8019 (defun org-narrow-to-block ()
8020 "Narrow buffer to the current block."
8021 (interactive)
8022 (let* ((case-fold-search t)
8023 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8024 "^[ \t]*#\\+end_.*")))
8025 (if blockp
8026 (narrow-to-region (car blockp) (cdr blockp))
8027 (error "Not in a block"))))
8029 (eval-when-compile
8030 (defvar org-property-drawer-re))
8032 (defvar org-property-start-re) ;; defined below
8033 (defun org-clone-subtree-with-time-shift (n &optional shift)
8034 "Clone the task (subtree) at point N times.
8035 The clones will be inserted as siblings.
8037 In interactive use, the user will be prompted for the number of
8038 clones to be produced, and for a time SHIFT, which may be a
8039 repeater as used in time stamps, for example `+3d'.
8041 When a valid repeater is given and the entry contains any time
8042 stamps, the clones will become a sequence in time, with time
8043 stamps in the subtree shifted for each clone produced. If SHIFT
8044 is nil or the empty string, time stamps will be left alone. The
8045 ID property of the original subtree is removed.
8047 If the original subtree did contain time stamps with a repeater,
8048 the following will happen:
8049 - the repeater will be removed in each clone
8050 - an additional clone will be produced, with the current, unshifted
8051 date(s) in the entry.
8052 - the original entry will be placed *after* all the clones, with
8053 repeater intact.
8054 - the start days in the repeater in the original entry will be shifted
8055 to past the last clone.
8056 In this way you can spell out a number of instances of a repeating task,
8057 and still retain the repeater to cover future instances of the task."
8058 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8059 (let (beg end template task idprop
8060 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8061 (drawer-re org-drawer-regexp))
8062 (if (not (and (integerp n) (> n 0)))
8063 (error "Invalid number of replications %s" n))
8064 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8065 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8066 shift)))
8067 (error "Invalid shift specification %s" shift))
8068 (when doshift
8069 (setq shift-n (string-to-number (match-string 1 shift))
8070 shift-what (cdr (assoc (match-string 2 shift)
8071 '(("d" . day) ("w" . week)
8072 ("m" . month) ("y" . year))))))
8073 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8074 (setq nmin 1 nmax n)
8075 (org-back-to-heading t)
8076 (setq beg (point))
8077 (setq idprop (org-entry-get nil "ID"))
8078 (org-end-of-subtree t t)
8079 (or (bolp) (insert "\n"))
8080 (setq end (point))
8081 (setq template (buffer-substring beg end))
8082 (when (and doshift
8083 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8084 (delete-region beg end)
8085 (setq end beg)
8086 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8087 (goto-char end)
8088 (loop for n from nmin to nmax do
8089 ;; prepare clone
8090 (with-temp-buffer
8091 (insert template)
8092 (org-mode)
8093 (goto-char (point-min))
8094 (org-show-subtree)
8095 (and idprop (if org-clone-delete-id
8096 (org-entry-delete nil "ID")
8097 (org-id-get-create t)))
8098 (unless (= n 0)
8099 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8100 (kill-whole-line))
8101 (goto-char (point-min))
8102 (while (re-search-forward drawer-re nil t)
8103 (mapc (lambda (d)
8104 (org-remove-empty-drawer-at d (point))) org-drawers)))
8105 (goto-char (point-min))
8106 (when doshift
8107 (while (re-search-forward org-ts-regexp-both nil t)
8108 (org-timestamp-change (* n shift-n) shift-what))
8109 (unless (= n n-no-remove)
8110 (goto-char (point-min))
8111 (while (re-search-forward org-ts-regexp nil t)
8112 (save-excursion
8113 (goto-char (match-beginning 0))
8114 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8115 (delete-region (match-beginning 1) (match-end 1)))))))
8116 (setq task (buffer-string)))
8117 (insert task))
8118 (goto-char beg)))
8120 ;;; Outline Sorting
8122 (defun org-sort (with-case)
8123 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8124 Optional argument WITH-CASE means sort case-sensitively."
8125 (interactive "P")
8126 (cond
8127 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8128 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8130 (org-call-with-arg 'org-sort-entries with-case))))
8132 (defun org-sort-remove-invisible (s)
8133 (remove-text-properties 0 (length s) org-rm-props s)
8134 (while (string-match org-bracket-link-regexp s)
8135 (setq s (replace-match (if (match-end 2)
8136 (match-string 3 s)
8137 (match-string 1 s)) t t s)))
8140 (defvar org-priority-regexp) ; defined later in the file
8142 (defvar org-after-sorting-entries-or-items-hook nil
8143 "Hook that is run after a bunch of entries or items have been sorted.
8144 When children are sorted, the cursor is in the parent line when this
8145 hook gets called. When a region or a plain list is sorted, the cursor
8146 will be in the first entry of the sorted region/list.")
8148 (defun org-sort-entries
8149 (&optional with-case sorting-type getkey-func compare-func property)
8150 "Sort entries on a certain level of an outline tree.
8151 If there is an active region, the entries in the region are sorted.
8152 Else, if the cursor is before the first entry, sort the top-level items.
8153 Else, the children of the entry at point are sorted.
8155 Sorting can be alphabetically, numerically, by date/time as given by
8156 a time stamp, by a property or by priority.
8158 The command prompts for the sorting type unless it has been given to the
8159 function through the SORTING-TYPE argument, which needs to be a character,
8160 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8161 precise meaning of each character:
8163 n Numerically, by converting the beginning of the entry/item to a number.
8164 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8165 o By order of TODO keywords.
8166 t By date/time, either the first active time stamp in the entry, or, if
8167 none exist, by the first inactive one.
8168 s By the scheduled date/time.
8169 d By deadline date/time.
8170 c By creation time, which is assumed to be the first inactive time stamp
8171 at the beginning of a line.
8172 p By priority according to the cookie.
8173 r By the value of a property.
8175 Capital letters will reverse the sort order.
8177 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8178 called with point at the beginning of the record. It must return either
8179 a string or a number that should serve as the sorting key for that record.
8181 Comparing entries ignores case by default. However, with an optional argument
8182 WITH-CASE, the sorting considers case as well."
8183 (interactive "P")
8184 (let ((case-func (if with-case 'identity 'downcase))
8185 (cmstr
8186 ;; The clock marker is lost when using `sort-subr', let's
8187 ;; store the clocking string.
8188 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8189 (save-excursion
8190 (goto-char org-clock-marker)
8191 (looking-back "^.*") (match-string-no-properties 0))))
8192 start beg end stars re re2
8193 txt what tmp)
8194 ;; Find beginning and end of region to sort
8195 (cond
8196 ((org-region-active-p)
8197 ;; we will sort the region
8198 (setq end (region-end)
8199 what "region")
8200 (goto-char (region-beginning))
8201 (if (not (org-at-heading-p)) (outline-next-heading))
8202 (setq start (point)))
8203 ((or (org-at-heading-p)
8204 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8205 ;; we will sort the children of the current headline
8206 (org-back-to-heading)
8207 (setq start (point)
8208 end (progn (org-end-of-subtree t t)
8209 (or (bolp) (insert "\n"))
8210 (org-back-over-empty-lines)
8211 (point))
8212 what "children")
8213 (goto-char start)
8214 (show-subtree)
8215 (outline-next-heading))
8217 ;; we will sort the top-level entries in this file
8218 (goto-char (point-min))
8219 (or (org-at-heading-p) (outline-next-heading))
8220 (setq start (point))
8221 (goto-char (point-max))
8222 (beginning-of-line 1)
8223 (when (looking-at ".*?\\S-")
8224 ;; File ends in a non-white line
8225 (end-of-line 1)
8226 (insert "\n"))
8227 (setq end (point-max))
8228 (setq what "top-level")
8229 (goto-char start)
8230 (show-all)))
8232 (setq beg (point))
8233 (if (>= beg end) (error "Nothing to sort"))
8235 (looking-at "\\(\\*+\\)")
8236 (setq stars (match-string 1)
8237 re (concat "^" (regexp-quote stars) " +")
8238 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8239 txt (buffer-substring beg end))
8240 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8241 (if (and (not (equal stars "*")) (string-match re2 txt))
8242 (error "Region to sort contains a level above the first entry"))
8244 (unless sorting-type
8245 (message
8246 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8247 [t]ime [s]cheduled [d]eadline [c]reated
8248 A/N/P/R/O/F/T/S/D/C means reversed:"
8249 what)
8250 (setq sorting-type (read-char-exclusive))
8252 (unless getkey-func
8253 (and (= (downcase sorting-type) ?f)
8254 (setq getkey-func
8255 (org-icompleting-read "Sort using function: "
8256 obarray 'fboundp t nil nil))
8257 (setq getkey-func (intern getkey-func))))
8259 (and (= (downcase sorting-type) ?r)
8260 (not property)
8261 (setq property
8262 (org-icompleting-read "Property: "
8263 (mapcar 'list (org-buffer-property-keys t))
8264 nil t))))
8266 (message "Sorting entries...")
8268 (save-restriction
8269 (narrow-to-region start end)
8270 (let ((dcst (downcase sorting-type))
8271 (case-fold-search nil)
8272 (now (current-time)))
8273 (sort-subr
8274 (/= dcst sorting-type)
8275 ;; This function moves to the beginning character of the "record" to
8276 ;; be sorted.
8277 (lambda nil
8278 (if (re-search-forward re nil t)
8279 (goto-char (match-beginning 0))
8280 (goto-char (point-max))))
8281 ;; This function moves to the last character of the "record" being
8282 ;; sorted.
8283 (lambda nil
8284 (save-match-data
8285 (condition-case nil
8286 (outline-forward-same-level 1)
8287 (error
8288 (goto-char (point-max))))))
8289 ;; This function returns the value that gets sorted against.
8290 (lambda nil
8291 (cond
8292 ((= dcst ?n)
8293 (if (looking-at org-complex-heading-regexp)
8294 (string-to-number (match-string 4))
8295 nil))
8296 ((= dcst ?a)
8297 (if (looking-at org-complex-heading-regexp)
8298 (funcall case-func (match-string 4))
8299 nil))
8300 ((= dcst ?t)
8301 (let ((end (save-excursion (outline-next-heading) (point))))
8302 (if (or (re-search-forward org-ts-regexp end t)
8303 (re-search-forward org-ts-regexp-both end t))
8304 (org-time-string-to-seconds (match-string 0))
8305 (org-float-time now))))
8306 ((= dcst ?c)
8307 (let ((end (save-excursion (outline-next-heading) (point))))
8308 (if (re-search-forward
8309 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8310 end t)
8311 (org-time-string-to-seconds (match-string 0))
8312 (org-float-time now))))
8313 ((= dcst ?s)
8314 (let ((end (save-excursion (outline-next-heading) (point))))
8315 (if (re-search-forward org-scheduled-time-regexp end t)
8316 (org-time-string-to-seconds (match-string 1))
8317 (org-float-time now))))
8318 ((= dcst ?d)
8319 (let ((end (save-excursion (outline-next-heading) (point))))
8320 (if (re-search-forward org-deadline-time-regexp end t)
8321 (org-time-string-to-seconds (match-string 1))
8322 (org-float-time now))))
8323 ((= dcst ?p)
8324 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8325 (string-to-char (match-string 2))
8326 org-default-priority))
8327 ((= dcst ?r)
8328 (or (org-entry-get nil property) ""))
8329 ((= dcst ?o)
8330 (if (looking-at org-complex-heading-regexp)
8331 (- 9999 (length (member (match-string 2)
8332 org-todo-keywords-1)))))
8333 ((= dcst ?f)
8334 (if getkey-func
8335 (progn
8336 (setq tmp (funcall getkey-func))
8337 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8338 tmp)
8339 (error "Invalid key function `%s'" getkey-func)))
8340 (t (error "Invalid sorting type `%c'" sorting-type))))
8342 (cond
8343 ((= dcst ?a) 'string<)
8344 ((= dcst ?f) compare-func)
8345 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8346 (run-hooks 'org-after-sorting-entries-or-items-hook)
8347 ;; Reset the clock marker if needed
8348 (when cmstr
8349 (save-excursion
8350 (goto-char start)
8351 (search-forward cmstr nil t)
8352 (move-marker org-clock-marker (point))))
8353 (message "Sorting entries...done")))
8355 (defun org-do-sort (table what &optional with-case sorting-type)
8356 "Sort TABLE of WHAT according to SORTING-TYPE.
8357 The user will be prompted for the SORTING-TYPE if the call to this
8358 function does not specify it. WHAT is only for the prompt, to indicate
8359 what is being sorted. The sorting key will be extracted from
8360 the car of the elements of the table.
8361 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8362 (unless sorting-type
8363 (message
8364 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8365 what)
8366 (setq sorting-type (read-char-exclusive)))
8367 (let ((dcst (downcase sorting-type))
8368 extractfun comparefun)
8369 ;; Define the appropriate functions
8370 (cond
8371 ((= dcst ?n)
8372 (setq extractfun 'string-to-number
8373 comparefun (if (= dcst sorting-type) '< '>)))
8374 ((= dcst ?a)
8375 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8376 (lambda(x) (downcase (org-sort-remove-invisible x))))
8377 comparefun (if (= dcst sorting-type)
8378 'string<
8379 (lambda (a b) (and (not (string< a b))
8380 (not (string= a b)))))))
8381 ((= dcst ?t)
8382 (setq extractfun
8383 (lambda (x)
8384 (if (or (string-match org-ts-regexp x)
8385 (string-match org-ts-regexp-both x))
8386 (org-float-time
8387 (org-time-string-to-time (match-string 0 x)))
8389 comparefun (if (= dcst sorting-type) '< '>)))
8390 (t (error "Invalid sorting type `%c'" sorting-type)))
8392 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8393 table)
8394 (lambda (a b) (funcall comparefun (car a) (car b))))))
8397 ;;; The orgstruct minor mode
8399 ;; Define a minor mode which can be used in other modes in order to
8400 ;; integrate the org-mode structure editing commands.
8402 ;; This is really a hack, because the org-mode structure commands use
8403 ;; keys which normally belong to the major mode. Here is how it
8404 ;; works: The minor mode defines all the keys necessary to operate the
8405 ;; structure commands, but wraps the commands into a function which
8406 ;; tests if the cursor is currently at a headline or a plain list
8407 ;; item. If that is the case, the structure command is used,
8408 ;; temporarily setting many Org-mode variables like regular
8409 ;; expressions for filling etc. However, when any of those keys is
8410 ;; used at a different location, function uses `key-binding' to look
8411 ;; up if the key has an associated command in another currently active
8412 ;; keymap (minor modes, major mode, global), and executes that
8413 ;; command. There might be problems if any of the keys is otherwise
8414 ;; used as a prefix key.
8416 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8417 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8418 ;; addresses this by checking explicitly for both bindings.
8420 (defvar orgstruct-mode-map (make-sparse-keymap)
8421 "Keymap for the minor `orgstruct-mode'.")
8423 (defvar org-local-vars nil
8424 "List of local variables, for use by `orgstruct-mode'.")
8426 ;;;###autoload
8427 (define-minor-mode orgstruct-mode
8428 "Toggle the minor mode `orgstruct-mode'.
8429 This mode is for using Org-mode structure commands in other
8430 modes. The following keys behave as if Org-mode were active, if
8431 the cursor is on a headline, or on a plain list item (both as
8432 defined by Org-mode).
8434 M-up Move entry/item up
8435 M-down Move entry/item down
8436 M-left Promote
8437 M-right Demote
8438 M-S-up Move entry/item up
8439 M-S-down Move entry/item down
8440 M-S-left Promote subtree
8441 M-S-right Demote subtree
8442 M-q Fill paragraph and items like in Org-mode
8443 C-c ^ Sort entries
8444 C-c - Cycle list bullet
8445 TAB Cycle item visibility
8446 M-RET Insert new heading/item
8447 S-M-RET Insert new TODO heading / Checkbox item
8448 C-c C-c Set tags / toggle checkbox"
8449 nil " OrgStruct" nil
8450 (org-load-modules-maybe)
8451 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8453 ;;;###autoload
8454 (defun turn-on-orgstruct ()
8455 "Unconditionally turn on `orgstruct-mode'."
8456 (orgstruct-mode 1))
8458 (defvar org-fb-vars nil)
8459 (make-variable-buffer-local 'org-fb-vars)
8460 (defun orgstruct++-mode (&optional arg)
8461 "Toggle `orgstruct-mode', the enhanced version of it.
8462 In addition to setting orgstruct-mode, this also exports all
8463 indentation and autofilling variables from org-mode into the
8464 buffer. It will also recognize item context in multiline items."
8465 (interactive "P")
8466 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8467 (if (< arg 1)
8468 (progn (orgstruct-mode -1)
8469 (mapc (lambda(v)
8470 (org-set-local (car v)
8471 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8472 org-fb-vars))
8473 (orgstruct-mode 1)
8474 (setq org-fb-vars nil)
8475 (let (var val)
8476 (mapc
8477 (lambda (x)
8478 (when (string-match
8479 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8480 (symbol-name (car x)))
8481 (setq var (car x) val (nth 1 x))
8482 (push (list var `(quote ,(eval var))) org-fb-vars)
8483 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8484 org-local-vars)
8485 (org-set-local 'orgstruct-is-++ t))))
8487 (defvar orgstruct-is-++ nil
8488 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8489 (make-variable-buffer-local 'orgstruct-is-++)
8491 ;;;###autoload
8492 (defun turn-on-orgstruct++ ()
8493 "Unconditionally turn on `orgstruct++-mode'."
8494 (orgstruct++-mode 1))
8496 (defun orgstruct-error ()
8497 "Error when there is no default binding for a structure key."
8498 (interactive)
8499 (error "This key has no function outside structure elements"))
8501 (defun orgstruct-setup ()
8502 "Setup orgstruct keymaps."
8503 (let ((nfunc 0)
8504 (bindings
8505 (list
8506 '([(meta up)] org-metaup)
8507 '([(meta down)] org-metadown)
8508 '([(meta left)] org-metaleft)
8509 '([(meta right)] org-metaright)
8510 '([(meta shift up)] org-shiftmetaup)
8511 '([(meta shift down)] org-shiftmetadown)
8512 '([(meta shift left)] org-shiftmetaleft)
8513 '([(meta shift right)] org-shiftmetaright)
8514 '([?\e (up)] org-metaup)
8515 '([?\e (down)] org-metadown)
8516 '([?\e (left)] org-metaleft)
8517 '([?\e (right)] org-metaright)
8518 '([?\e (shift up)] org-shiftmetaup)
8519 '([?\e (shift down)] org-shiftmetadown)
8520 '([?\e (shift left)] org-shiftmetaleft)
8521 '([?\e (shift right)] org-shiftmetaright)
8522 '([(shift up)] org-shiftup)
8523 '([(shift down)] org-shiftdown)
8524 '([(shift left)] org-shiftleft)
8525 '([(shift right)] org-shiftright)
8526 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8527 '("\M-q" fill-paragraph)
8528 '("\C-c^" org-sort)
8529 '("\C-c-" org-cycle-list-bullet)))
8530 elt key fun cmd)
8531 (while (setq elt (pop bindings))
8532 (setq nfunc (1+ nfunc))
8533 (setq key (org-key (car elt))
8534 fun (nth 1 elt)
8535 cmd (orgstruct-make-binding fun nfunc key))
8536 (org-defkey orgstruct-mode-map key cmd))
8538 ;; Prevent an error for users who forgot to make autoloads
8539 (require 'org-element)
8541 ;; Special treatment needed for TAB and RET
8542 (org-defkey orgstruct-mode-map [(tab)]
8543 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8544 (org-defkey orgstruct-mode-map "\C-i"
8545 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8547 (org-defkey orgstruct-mode-map "\M-\C-m"
8548 (orgstruct-make-binding 'org-insert-heading 105
8549 "\M-\C-m" [(meta return)]))
8550 (org-defkey orgstruct-mode-map [(meta return)]
8551 (orgstruct-make-binding 'org-insert-heading 106
8552 [(meta return)] "\M-\C-m"))
8554 (org-defkey orgstruct-mode-map [(shift meta return)]
8555 (orgstruct-make-binding 'org-insert-todo-heading 107
8556 [(meta return)] "\M-\C-m"))
8558 (org-defkey orgstruct-mode-map "\e\C-m"
8559 (orgstruct-make-binding 'org-insert-heading 108
8560 "\e\C-m" [?\e (return)]))
8561 (org-defkey orgstruct-mode-map [?\e (return)]
8562 (orgstruct-make-binding 'org-insert-heading 109
8563 [?\e (return)] "\e\C-m"))
8564 (org-defkey orgstruct-mode-map [?\e (shift return)]
8565 (orgstruct-make-binding 'org-insert-todo-heading 110
8566 [?\e (return)] "\e\C-m"))
8568 (unless org-local-vars
8569 (setq org-local-vars (org-get-local-variables)))
8573 (defun orgstruct-make-binding (fun n &rest keys)
8574 "Create a function for binding in the structure minor mode.
8575 FUN is the command to call inside a table. N is used to create a unique
8576 command name. KEYS are keys that should be checked in for a command
8577 to execute outside of tables."
8578 (eval
8579 (list 'defun
8580 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8581 '(arg)
8582 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8583 "Outside of structure, run the binding of `"
8584 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8585 "'.")
8586 '(interactive "p")
8587 (list 'if
8588 `(org-context-p 'headline 'item
8589 (and orgstruct-is-++
8590 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8591 'item-body))
8592 (list 'org-run-like-in-org-mode (list 'quote fun))
8593 (list 'let '(orgstruct-mode)
8594 (list 'call-interactively
8595 (append '(or)
8596 (mapcar (lambda (k)
8597 (list 'key-binding k))
8598 keys)
8599 '('orgstruct-error))))))))
8601 (defun org-contextualize-keys (alist contexts)
8602 "Return valid elements in ALIST depending on CONTEXTS.
8604 `org-agenda-custom-commands' or `org-capture-templates' are the
8605 values used for ALIST, and `org-agenda-custom-commands-contexts'
8606 or `org-capture-templates-contexts' are the associated contexts
8607 definitions."
8608 (let ((contexts
8609 ;; normalize contexts
8610 (mapcar
8611 (lambda(c) (cond ((listp (cadr c))
8612 (list (car c) (car c) (cadr c)))
8613 ((string= "" (cadr c))
8614 (list (car c) (car c) (caddr c)))
8615 (t c))) contexts))
8616 (a alist) c r s)
8617 ;; loop over all commands or templates
8618 (while (setq c (pop a))
8619 (let (vrules repl)
8620 (cond
8621 ((not (assoc (car c) contexts))
8622 (push c r))
8623 ((and (assoc (car c) contexts)
8624 (setq vrules (org-contextualize-validate-key
8625 (car c) contexts)))
8626 (mapc (lambda (vr)
8627 (when (not (equal (car vr) (cadr vr)))
8628 (setq repl vr))) vrules)
8629 (if (not repl) (push c r)
8630 (push (cadr repl) s)
8631 (push
8632 (cons (car c)
8633 (cdr (or (assoc (cadr repl) alist)
8634 (error "Undefined key `%s' as contextual replacement for `%s'"
8635 (cadr repl) (car c)))))
8636 r))))))
8637 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8638 (delq
8640 (delete-dups
8641 (mapcar (lambda (x)
8642 (let ((tpl (car x)))
8643 (when (not (delq
8645 (mapcar (lambda(y)
8646 (equal y tpl)) s))) x)))
8647 (reverse r))))))
8649 (defun org-contextualize-validate-key (key contexts)
8650 "Check CONTEXTS for agenda or capture KEY."
8651 (let (r rr res)
8652 (while (setq r (pop contexts))
8653 (mapc
8654 (lambda (rr)
8655 (when
8656 (and (equal key (car r))
8657 (if (functionp rr) (funcall rr)
8658 (or (and (eq (car rr) 'in-file)
8659 (buffer-file-name)
8660 (string-match (cdr rr) (buffer-file-name)))
8661 (and (eq (car rr) 'in-mode)
8662 (string-match (cdr rr) (symbol-name major-mode)))
8663 (when (and (eq (car rr) 'not-in-file)
8664 (buffer-file-name))
8665 (not (string-match (cdr rr) (buffer-file-name))))
8666 (when (eq (car rr) 'not-in-mode)
8667 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8668 (push r res)))
8669 (car (last r))))
8670 (delete-dups (delq nil res))))
8672 (defun org-context-p (&rest contexts)
8673 "Check if local context is any of CONTEXTS.
8674 Possible values in the list of contexts are `table', `headline', and `item'."
8675 (let ((pos (point)))
8676 (goto-char (point-at-bol))
8677 (prog1 (or (and (memq 'table contexts)
8678 (looking-at "[ \t]*|"))
8679 (and (memq 'headline contexts)
8680 (looking-at org-outline-regexp))
8681 (and (memq 'item contexts)
8682 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8683 (and (memq 'item-body contexts)
8684 (org-in-item-p)))
8685 (goto-char pos))))
8687 (defun org-get-local-variables ()
8688 "Return a list of all local variables in an Org mode buffer."
8689 (let (varlist)
8690 (with-current-buffer (get-buffer-create "*Org tmp*")
8691 (erase-buffer)
8692 (org-mode)
8693 (setq varlist (buffer-local-variables)))
8694 (kill-buffer "*Org tmp*")
8695 (delq nil
8696 (mapcar
8697 (lambda (x)
8698 (setq x
8699 (if (symbolp x)
8700 (list x)
8701 (list (car x) (list 'quote (cdr x)))))
8702 (if (string-match
8703 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8704 (symbol-name (car x)))
8705 x nil))
8706 varlist))))
8708 (defun org-clone-local-variables (from-buffer &optional regexp)
8709 "Clone local variables from FROM-BUFFER.
8710 Optional argument REGEXP selects variables to clone."
8711 (mapc
8712 (lambda (pair)
8713 (and (symbolp (car pair))
8714 (or (null regexp)
8715 (string-match regexp (symbol-name (car pair))))
8716 (set (make-local-variable (car pair))
8717 (cdr pair))))
8718 (buffer-local-variables from-buffer)))
8720 ;;;###autoload
8721 (defun org-run-like-in-org-mode (cmd)
8722 "Run a command, pretending that the current buffer is in Org-mode.
8723 This will temporarily bind local variables that are typically bound in
8724 Org-mode to the values they have in Org-mode, and then interactively
8725 call CMD."
8726 (org-load-modules-maybe)
8727 (unless org-local-vars
8728 (setq org-local-vars (org-get-local-variables)))
8729 (eval (list 'let org-local-vars
8730 (list 'call-interactively (list 'quote cmd)))))
8732 ;;;; Archiving
8734 (defun org-get-category (&optional pos force-refresh)
8735 "Get the category applying to position POS."
8736 (save-match-data
8737 (if force-refresh (org-refresh-category-properties))
8738 (let ((pos (or pos (point))))
8739 (or (get-text-property pos 'org-category)
8740 (progn (org-refresh-category-properties)
8741 (get-text-property pos 'org-category))))))
8743 (defun org-refresh-category-properties ()
8744 "Refresh category text properties in the buffer."
8745 (let ((case-fold-search t)
8746 (inhibit-read-only t)
8747 (def-cat (cond
8748 ((null org-category)
8749 (if buffer-file-name
8750 (file-name-sans-extension
8751 (file-name-nondirectory buffer-file-name))
8752 "???"))
8753 ((symbolp org-category) (symbol-name org-category))
8754 (t org-category)))
8755 beg end cat pos optionp)
8756 (org-unmodified
8757 (save-excursion
8758 (save-restriction
8759 (widen)
8760 (goto-char (point-min))
8761 (put-text-property (point) (point-max) 'org-category def-cat)
8762 (while (re-search-forward
8763 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8764 (setq pos (match-end 0)
8765 optionp (equal (char-after (match-beginning 0)) ?#)
8766 cat (org-trim (match-string 2)))
8767 (if optionp
8768 (setq beg (point-at-bol) end (point-max))
8769 (org-back-to-heading t)
8770 (setq beg (point) end (org-end-of-subtree t t)))
8771 (put-text-property beg end 'org-category cat)
8772 (put-text-property beg end 'org-category-position beg)
8773 (goto-char pos)))))))
8776 ;;;; Link Stuff
8778 ;;; Link abbreviations
8780 (defun org-link-expand-abbrev (link)
8781 "Apply replacements as defined in `org-link-abbrev-alist'."
8782 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8783 (let* ((key (match-string 1 link))
8784 (as (or (assoc key org-link-abbrev-alist-local)
8785 (assoc key org-link-abbrev-alist)))
8786 (tag (and (match-end 2) (match-string 3 link)))
8787 rpl)
8788 (if (not as)
8789 link
8790 (setq rpl (cdr as))
8791 (cond
8792 ((symbolp rpl) (funcall rpl tag))
8793 ((string-match "%(\\([^)]+\\))" rpl)
8794 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8795 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8796 ((string-match "%h" rpl)
8797 (replace-match (url-hexify-string (or tag "")) t t rpl))
8798 (t (concat rpl tag)))))
8799 link))
8801 ;;; Storing and inserting links
8803 (defvar org-insert-link-history nil
8804 "Minibuffer history for links inserted with `org-insert-link'.")
8806 (defvar org-stored-links nil
8807 "Contains the links stored with `org-store-link'.")
8809 (defvar org-store-link-plist nil
8810 "Plist with info about the most recently link created with `org-store-link'.")
8812 (defvar org-link-protocols nil
8813 "Link protocols added to Org-mode using `org-add-link-type'.")
8815 (defvar org-store-link-functions nil
8816 "List of functions that are called to create and store a link.
8817 Each function will be called in turn until one returns a non-nil
8818 value. Each function should check if it is responsible for creating
8819 this link (for example by looking at the major mode).
8820 If not, it must exit and return nil.
8821 If yes, it should return a non-nil value after a calling
8822 `org-store-link-props' with a list of properties and values.
8823 Special properties are:
8825 :type The link prefix, like \"http\". This must be given.
8826 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8827 This is obligatory as well.
8828 :description Optional default description for the second pair
8829 of brackets in an Org-mode link. The user can still change
8830 this when inserting this link into an Org-mode buffer.
8832 In addition to these, any additional properties can be specified
8833 and then used in capture templates.")
8835 (defun org-add-link-type (type &optional follow export)
8836 "Add TYPE to the list of `org-link-types'.
8837 Re-compute all regular expressions depending on `org-link-types'
8839 FOLLOW and EXPORT are two functions.
8841 FOLLOW should take the link path as the single argument and do whatever
8842 is necessary to follow the link, for example find a file or display
8843 a mail message.
8845 EXPORT should format the link path for export to one of the export formats.
8846 It should be a function accepting three arguments:
8848 path the path of the link, the text after the prefix (like \"http:\")
8849 desc the description of the link, if any, or a description added by
8850 org-export-normalize-links if there is none
8851 format the export format, a symbol like `html' or `latex' or `ascii'..
8853 The function may use the FORMAT information to return different values
8854 depending on the format. The return value will be put literally into
8855 the exported file. If the return value is nil, this means Org should
8856 do what it normally does with links which do not have EXPORT defined.
8858 Org-mode has a built-in default for exporting links. If you are happy with
8859 this default, there is no need to define an export function for the link
8860 type. For a simple example of an export function, see `org-bbdb.el'."
8861 (add-to-list 'org-link-types type t)
8862 (org-make-link-regexps)
8863 (if (assoc type org-link-protocols)
8864 (setcdr (assoc type org-link-protocols) (list follow export))
8865 (push (list type follow export) org-link-protocols)))
8867 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8868 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8870 ;;;###autoload
8871 (defun org-store-link (arg)
8872 "\\<org-mode-map>Store an org-link to the current location.
8873 This link is added to `org-stored-links' and can later be inserted
8874 into an org-buffer with \\[org-insert-link].
8876 For some link types, a prefix arg is interpreted:
8877 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8878 For file links, arg negates `org-context-in-file-links'."
8879 (interactive "P")
8880 (org-load-modules-maybe)
8881 (setq org-store-link-plist nil) ; reset
8882 (org-with-limited-levels
8883 (let (link cpltxt desc description search txt custom-id agenda-link)
8884 (cond
8886 ((run-hook-with-args-until-success 'org-store-link-functions)
8887 (setq link (plist-get org-store-link-plist :link)
8888 desc (or (plist-get org-store-link-plist :description) link)))
8890 ((org-src-edit-buffer-p)
8891 (let (label gc)
8892 (while (or (not label)
8893 (save-excursion
8894 (save-restriction
8895 (widen)
8896 (goto-char (point-min))
8897 (re-search-forward
8898 (regexp-quote (format org-coderef-label-format label))
8899 nil t))))
8900 (when label (message "Label exists already") (sit-for 2))
8901 (setq label (read-string "Code line label: " label)))
8902 (end-of-line 1)
8903 (setq link (format org-coderef-label-format label))
8904 (setq gc (- 79 (length link)))
8905 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8906 (insert link)
8907 (setq link (concat "(" label ")") desc nil)))
8909 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8910 ;; We are in the agenda, link to referenced location
8911 (let ((m (or (get-text-property (point) 'org-hd-marker)
8912 (get-text-property (point) 'org-marker))))
8913 (when m
8914 (org-with-point-at m
8915 (setq agenda-link
8916 (if (org-called-interactively-p 'any)
8917 (call-interactively 'org-store-link)
8918 (org-store-link nil)))))))
8920 ((eq major-mode 'calendar-mode)
8921 (let ((cd (calendar-cursor-to-date)))
8922 (setq link
8923 (format-time-string
8924 (car org-time-stamp-formats)
8925 (apply 'encode-time
8926 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8927 nil nil nil))))
8928 (org-store-link-props :type "calendar" :date cd)))
8930 ((eq major-mode 'help-mode)
8931 (setq link (concat "help:" (save-excursion
8932 (goto-char (point-min))
8933 (looking-at "^[^ ]+")
8934 (match-string 0))))
8935 (org-store-link-props :type "help"))
8937 ((eq major-mode 'w3-mode)
8938 (setq cpltxt (if (and (buffer-name)
8939 (not (string-match "Untitled" (buffer-name))))
8940 (buffer-name)
8941 (url-view-url t))
8942 link (url-view-url t))
8943 (org-store-link-props :type "w3" :url (url-view-url t)))
8945 ((eq major-mode 'w3m-mode)
8946 (setq cpltxt (or w3m-current-title w3m-current-url)
8947 link w3m-current-url)
8948 (org-store-link-props :type "w3m" :url (url-view-url t)))
8950 ((setq search (run-hook-with-args-until-success
8951 'org-create-file-search-functions))
8952 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8953 "::" search))
8954 (setq cpltxt (or description link)))
8956 ((eq major-mode 'image-mode)
8957 (setq cpltxt (concat "file:"
8958 (abbreviate-file-name buffer-file-name))
8959 link cpltxt)
8960 (org-store-link-props :type "image" :file buffer-file-name))
8962 ((eq major-mode 'dired-mode)
8963 ;; link to the file in the current line
8964 (let ((file (dired-get-filename nil t)))
8965 (setq file (if file
8966 (abbreviate-file-name
8967 (expand-file-name (dired-get-filename nil t)))
8968 ;; otherwise, no file so use current directory.
8969 default-directory))
8970 (setq cpltxt (concat "file:" file)
8971 link cpltxt)))
8973 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8974 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8975 (cond
8976 ((org-in-regexp "<<\\(.*?\\)>>")
8977 (setq cpltxt
8978 (concat "file:"
8979 (abbreviate-file-name
8980 (buffer-file-name (buffer-base-buffer)))
8981 "::" (match-string 1))
8982 link cpltxt))
8983 ((and (featurep 'org-id)
8984 (or (eq org-link-to-org-use-id t)
8985 (and (org-called-interactively-p 'any)
8986 (or (eq org-link-to-org-use-id 'create-if-interactive)
8987 (and (eq org-link-to-org-use-id
8988 'create-if-interactive-and-no-custom-id)
8989 (not custom-id))))
8990 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8991 ;; We can make a link using the ID.
8992 (setq link (condition-case nil
8993 (prog1 (org-id-store-link)
8994 (setq desc (plist-get org-store-link-plist :description)))
8995 (error
8996 ;; probably before first headline, link to file only
8997 (concat "file:"
8998 (abbreviate-file-name
8999 (buffer-file-name (buffer-base-buffer))))))))
9001 ;; Just link to current headline
9002 (setq cpltxt (concat "file:"
9003 (abbreviate-file-name
9004 (buffer-file-name (buffer-base-buffer)))))
9005 ;; Add a context search string
9006 (when (org-xor org-context-in-file-links arg)
9007 (setq txt (cond
9008 ((org-at-heading-p) nil)
9009 ((org-region-active-p)
9010 (buffer-substring (region-beginning) (region-end)))))
9011 (when (or (null txt) (string-match "\\S-" txt))
9012 (setq cpltxt
9013 (concat cpltxt "::"
9014 (condition-case nil
9015 (org-make-org-heading-search-string txt)
9016 (error "")))
9017 desc (or (nth 4 (ignore-errors
9018 (org-heading-components))) "NONE"))))
9019 (if (string-match "::\\'" cpltxt)
9020 (setq cpltxt (substring cpltxt 0 -2)))
9021 (setq link cpltxt))))
9023 ((buffer-file-name (buffer-base-buffer))
9024 ;; Just link to this file here.
9025 (setq cpltxt (concat "file:"
9026 (abbreviate-file-name
9027 (buffer-file-name (buffer-base-buffer)))))
9028 ;; Add a context string
9029 (when (org-xor org-context-in-file-links arg)
9030 (setq txt (if (org-region-active-p)
9031 (buffer-substring (region-beginning) (region-end))
9032 (buffer-substring (point-at-bol) (point-at-eol))))
9033 ;; Only use search option if there is some text.
9034 (when (string-match "\\S-" txt)
9035 (setq cpltxt
9036 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9037 desc "NONE")))
9038 (setq link cpltxt))
9040 ((org-called-interactively-p 'interactive)
9041 (error "Cannot link to a buffer which is not visiting a file"))
9043 (t (setq link nil)))
9045 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9046 (setq link (or link cpltxt)
9047 desc (or desc cpltxt))
9048 (if (equal desc "NONE") (setq desc nil))
9050 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9051 (progn
9052 (setq org-stored-links
9053 (cons (list link desc) org-stored-links))
9054 (message "Stored: %s" (or desc link))
9055 (when custom-id
9056 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9057 "::#" custom-id))
9058 (setq org-stored-links
9059 (cons (list link desc) org-stored-links))))
9060 (or agenda-link (and link (org-make-link-string link desc)))))))
9062 (defun org-store-link-props (&rest plist)
9063 "Store link properties, extract names and addresses."
9064 (let (x adr)
9065 (when (setq x (plist-get plist :from))
9066 (setq adr (mail-extract-address-components x))
9067 (setq plist (plist-put plist :fromname (car adr)))
9068 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9069 (when (setq x (plist-get plist :to))
9070 (setq adr (mail-extract-address-components x))
9071 (setq plist (plist-put plist :toname (car adr)))
9072 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9073 (let ((from (plist-get plist :from))
9074 (to (plist-get plist :to)))
9075 (when (and from to org-from-is-user-regexp)
9076 (setq plist
9077 (plist-put plist :fromto
9078 (if (string-match org-from-is-user-regexp from)
9079 (concat "to %t")
9080 (concat "from %f"))))))
9081 (setq org-store-link-plist plist))
9083 (defun org-add-link-props (&rest plist)
9084 "Add these properties to the link property list."
9085 (let (key value)
9086 (while plist
9087 (setq key (pop plist) value (pop plist))
9088 (setq org-store-link-plist
9089 (plist-put org-store-link-plist key value)))))
9091 (defun org-email-link-description (&optional fmt)
9092 "Return the description part of an email link.
9093 This takes information from `org-store-link-plist' and formats it
9094 according to FMT (default from `org-email-link-description-format')."
9095 (setq fmt (or fmt org-email-link-description-format))
9096 (let* ((p org-store-link-plist)
9097 (to (plist-get p :toaddress))
9098 (from (plist-get p :fromaddress))
9099 (table
9100 (list
9101 (cons "%c" (plist-get p :fromto))
9102 (cons "%F" (plist-get p :from))
9103 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9104 (cons "%T" (plist-get p :to))
9105 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9106 (cons "%s" (plist-get p :subject))
9107 (cons "%d" (plist-get p :date))
9108 (cons "%m" (plist-get p :message-id)))))
9109 (when (string-match "%c" fmt)
9110 ;; Check if the user wrote this message
9111 (if (and org-from-is-user-regexp from to
9112 (save-match-data (string-match org-from-is-user-regexp from)))
9113 (setq fmt (replace-match "to %t" t t fmt))
9114 (setq fmt (replace-match "from %f" t t fmt))))
9115 (org-replace-escapes fmt table)))
9117 (defun org-make-org-heading-search-string (&optional string heading)
9118 "Make search string for STRING or current headline."
9119 (interactive)
9120 (let ((s (or string (org-get-heading)))
9121 (lines org-context-in-file-links))
9122 (unless (and string (not heading))
9123 ;; We are using a headline, clean up garbage in there.
9124 (if (string-match org-todo-regexp s)
9125 (setq s (replace-match "" t t s)))
9126 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9127 (setq s (replace-match "" t t s)))
9128 (setq s (org-trim s))
9129 (if (string-match (concat "^\\(" org-quote-string "\\|"
9130 org-comment-string "\\)") s)
9131 (setq s (replace-match "" t t s)))
9132 (while (string-match org-ts-regexp s)
9133 (setq s (replace-match "" t t s))))
9134 (or string (setq s (concat "*" s))) ; Add * for headlines
9135 (when (and string (integerp lines) (> lines 0))
9136 (let ((slines (org-split-string s "\n")))
9137 (when (< lines (length slines))
9138 (setq s (mapconcat
9139 'identity
9140 (reverse (nthcdr (- (length slines) lines)
9141 (reverse slines))) "\n")))))
9142 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9144 (defun org-make-link-string (link &optional description)
9145 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9146 (unless (string-match "\\S-" link)
9147 (error "Empty link"))
9148 (when (and description
9149 (stringp description)
9150 (not (string-match "\\S-" description)))
9151 (setq description nil))
9152 (when (stringp description)
9153 ;; Remove brackets from the description, they are fatal.
9154 (while (string-match "\\[" description)
9155 (setq description (replace-match "{" t t description)))
9156 (while (string-match "\\]" description)
9157 (setq description (replace-match "}" t t description))))
9158 (when (equal link description)
9159 ;; No description needed, it is identical
9160 (setq description nil))
9161 (when (and (not description)
9162 (not (string-match (org-image-file-name-regexp) link))
9163 (not (equal link (org-link-escape link))))
9164 (setq description (org-extract-attributes link)))
9165 (setq link
9166 (cond ((string-match (org-image-file-name-regexp) link) link)
9167 ((string-match org-link-types-re link)
9168 (concat (match-string 1 link)
9169 (org-link-escape (substring link (match-end 1)))))
9170 (t (org-link-escape link))))
9171 (concat "[[" link "]"
9172 (if description (concat "[" description "]") "")
9173 "]"))
9175 (defconst org-link-escape-chars
9176 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9177 "List of characters that should be escaped in link.
9178 This is the list that is used for internal purposes.")
9180 (defconst org-link-escape-chars-browser
9181 '(?\ )
9182 "List of escapes for characters that are problematic in links.
9183 This is the list that is used before handing over to the browser.")
9185 (defun org-link-escape (text &optional table merge)
9186 "Return percent escaped representation of TEXT.
9187 TEXT is a string with the text to escape.
9188 Optional argument TABLE is a list with characters that should be
9189 escaped. When nil, `org-link-escape-chars' is used.
9190 If optional argument MERGE is set, merge TABLE into
9191 `org-link-escape-chars'."
9192 (cond
9193 ((and table merge)
9194 (mapc (lambda (defchr)
9195 (unless (member defchr table)
9196 (setq table (cons defchr table)))) org-link-escape-chars))
9197 ((null table)
9198 (setq table org-link-escape-chars)))
9199 (mapconcat
9200 (lambda (char)
9201 (if (or (member char table)
9202 (and (or (< char 32) (= char 37) (> char 126))
9203 org-url-hexify-p))
9204 (mapconcat (lambda (sequence-element)
9205 (format "%%%.2X" sequence-element))
9206 (or (encode-coding-char char 'utf-8)
9207 (error "Unable to percent escape character: %s"
9208 (char-to-string char))) "")
9209 (char-to-string char))) text ""))
9211 (defun org-link-unescape (str)
9212 "Unhex hexified Unicode strings as returned from the JavaScript function
9213 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9214 (unless (and (null str) (string= "" str))
9215 (let ((pos 0) (case-fold-search t) unhexed)
9216 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9217 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9218 (setq str (replace-match unhexed t t str))
9219 (setq pos (+ pos (length unhexed))))))
9220 str)
9222 (defun org-link-unescape-compound (hex)
9223 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9224 Note: this function also decodes single byte encodings like
9225 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9226 (save-match-data
9227 (let* ((bytes (cdr (split-string hex "%")))
9228 (ret "")
9229 (eat 0)
9230 (sum 0))
9231 (while bytes
9232 (let* ((val (string-to-number (pop bytes) 16))
9233 (shift-xor
9234 (if (= 0 eat)
9235 (cond
9236 ((>= val 252) (cons 6 252))
9237 ((>= val 248) (cons 5 248))
9238 ((>= val 240) (cons 4 240))
9239 ((>= val 224) (cons 3 224))
9240 ((>= val 192) (cons 2 192))
9241 (t (cons 0 0)))
9242 (cons 6 128))))
9243 (if (>= val 192) (setq eat (car shift-xor)))
9244 (setq val (logxor val (cdr shift-xor)))
9245 (setq sum (+ (lsh sum (car shift-xor)) val))
9246 (if (> eat 0) (setq eat (- eat 1)))
9247 (cond
9248 ((= 0 eat) ;multi byte
9249 (setq ret (concat ret (org-char-to-string sum)))
9250 (setq sum 0))
9251 ((not bytes) ; single byte(s)
9252 (setq ret (org-link-unescape-single-byte-sequence hex))))
9253 )) ;; end (while bytes
9254 ret )))
9256 (defun org-link-unescape-single-byte-sequence (hex)
9257 "Unhexify hex-encoded single byte character sequences."
9258 (mapconcat (lambda (byte)
9259 (char-to-string (string-to-number byte 16)))
9260 (cdr (split-string hex "%")) ""))
9262 (defun org-xor (a b)
9263 "Exclusive or."
9264 (if a (not b) b))
9266 (defun org-fixup-message-id-for-http (s)
9267 "Replace special characters in a message id, so it can be used in an http query."
9268 (when (string-match "%" s)
9269 (setq s (mapconcat (lambda (c)
9270 (if (eq c ?%)
9271 "%25"
9272 (char-to-string c)))
9273 s "")))
9274 (while (string-match "<" s)
9275 (setq s (replace-match "%3C" t t s)))
9276 (while (string-match ">" s)
9277 (setq s (replace-match "%3E" t t s)))
9278 (while (string-match "@" s)
9279 (setq s (replace-match "%40" t t s)))
9282 (defun org-link-prettify (link)
9283 "Return a human-readable representation of LINK.
9284 The car of LINK must be a raw link the cdr of LINK must be either
9285 a link description or nil."
9286 (let ((desc (or (cadr link) "<no description>")))
9287 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9288 "<" (car link) ">")))
9290 ;;;###autoload
9291 (defun org-insert-link-global ()
9292 "Insert a link like Org-mode does.
9293 This command can be called in any mode to insert a link in Org-mode syntax."
9294 (interactive)
9295 (org-load-modules-maybe)
9296 (org-run-like-in-org-mode 'org-insert-link))
9298 (defun org-insert-all-links (&optional keep)
9299 "Insert all links in `org-stored-links'."
9300 (interactive "P")
9301 (let ((links (copy-sequence org-stored-links)) l)
9302 (while (setq l (if keep (pop links) (pop org-stored-links)))
9303 (insert "- ")
9304 (org-insert-link nil (car l) (cadr l))
9305 (insert "\n"))))
9307 (defun org-link-fontify-links-to-this-file ()
9308 "Fontify links to the current file in `org-stored-links'."
9309 (let ((f (buffer-file-name)) a b)
9310 (setq a (mapcar (lambda(l)
9311 (let ((ll (car l)))
9312 (when (and (string-match "^file:\\(.+\\)::" ll)
9313 (equal f (expand-file-name (match-string 1 ll))))
9314 ll)))
9315 org-stored-links))
9316 (when (featurep 'org-id)
9317 (setq b (mapcar (lambda(l)
9318 (let ((ll (car l)))
9319 (when (and (string-match "^id:\\(.+\\)$" ll)
9320 (equal f (expand-file-name
9321 (or (org-id-find-id-file
9322 (match-string 1 ll)) ""))))
9323 ll)))
9324 org-stored-links)))
9325 (mapcar (lambda(l)
9326 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9327 (delq nil (append a b)))))
9329 (defvar org-link-links-in-this-file nil)
9330 (defun org-insert-link (&optional complete-file link-location default-description)
9331 "Insert a link. At the prompt, enter the link.
9333 Completion can be used to insert any of the link protocol prefixes like
9334 http or ftp in use.
9336 The history can be used to select a link previously stored with
9337 `org-store-link'. When the empty string is entered (i.e. if you just
9338 press RET at the prompt), the link defaults to the most recently
9339 stored link. As SPC triggers completion in the minibuffer, you need to
9340 use M-SPC or C-q SPC to force the insertion of a space character.
9342 You will also be prompted for a description, and if one is given, it will
9343 be displayed in the buffer instead of the link.
9345 If there is already a link at point, this command will allow you to edit link
9346 and description parts.
9348 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9349 be selected using completion. The path to the file will be relative to the
9350 current directory if the file is in the current directory or a subdirectory.
9351 Otherwise, the link will be the absolute path as completed in the minibuffer
9352 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9353 option `org-link-file-path-type'.
9355 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9356 the current directory or below.
9358 With three \\[universal-argument] prefixes, negate the meaning of
9359 `org-keep-stored-link-after-insertion'.
9361 If `org-make-link-description-function' is non-nil, this function will be
9362 called with the link target, and the result will be the default
9363 link description.
9365 If the LINK-LOCATION parameter is non-nil, this value will be
9366 used as the link location instead of reading one interactively.
9368 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9369 be used as the default description."
9370 (interactive "P")
9371 (let* ((wcf (current-window-configuration))
9372 (origbuf (current-buffer))
9373 (region (if (org-region-active-p)
9374 (buffer-substring (region-beginning) (region-end))))
9375 (remove (and region (list (region-beginning) (region-end))))
9376 (desc region)
9377 tmphist ; byte-compile incorrectly complains about this
9378 (link link-location)
9379 (abbrevs org-link-abbrev-alist-local)
9380 entry file all-prefixes auto-desc)
9381 (cond
9382 (link-location) ; specified by arg, just use it.
9383 ((org-in-regexp org-bracket-link-regexp 1)
9384 ;; We do have a link at point, and we are going to edit it.
9385 (setq remove (list (match-beginning 0) (match-end 0)))
9386 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9387 (setq link (read-string "Link: "
9388 (org-link-unescape
9389 (org-match-string-no-properties 1)))))
9390 ((or (org-in-regexp org-angle-link-re)
9391 (org-in-regexp org-plain-link-re))
9392 ;; Convert to bracket link
9393 (setq remove (list (match-beginning 0) (match-end 0))
9394 link (read-string "Link: "
9395 (org-remove-angle-brackets (match-string 0)))))
9396 ((member complete-file '((4) (16)))
9397 ;; Completing read for file names.
9398 (setq link (org-file-complete-link complete-file)))
9400 ;; Read link, with completion for stored links.
9401 (org-link-fontify-links-to-this-file)
9402 (org-switch-to-buffer-other-window "*Org Links*")
9403 (with-current-buffer "*Org Links*"
9404 (erase-buffer)
9405 (insert "Insert a link.
9406 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9407 (when org-stored-links
9408 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9409 (insert (mapconcat 'org-link-prettify
9410 (reverse org-stored-links) "\n")))
9411 (goto-char (point-min)))
9412 (let ((cw (selected-window)))
9413 (select-window (get-buffer-window "*Org Links*" 'visible))
9414 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9415 (unless (pos-visible-in-window-p (point-max))
9416 (org-fit-window-to-buffer))
9417 (and (window-live-p cw) (select-window cw)))
9418 ;; Fake a link history, containing the stored links.
9419 (setq tmphist (append (mapcar 'car org-stored-links)
9420 org-insert-link-history))
9421 (setq all-prefixes (append (mapcar 'car abbrevs)
9422 (mapcar 'car org-link-abbrev-alist)
9423 org-link-types))
9424 (unwind-protect
9425 (progn
9426 (setq link
9427 (org-completing-read
9428 "Link: "
9429 (append
9430 (mapcar (lambda (x) (concat x ":"))
9431 all-prefixes)
9432 (mapcar 'car org-stored-links))
9433 nil nil nil
9434 'tmphist
9435 (caar org-stored-links)))
9436 (if (not (string-match "\\S-" link))
9437 (error "No link selected"))
9438 (mapc (lambda(l)
9439 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9440 org-stored-links)
9441 (if (or (member link all-prefixes)
9442 (and (equal ":" (substring link -1))
9443 (member (substring link 0 -1) all-prefixes)
9444 (setq link (substring link 0 -1))))
9445 (setq link (with-current-buffer origbuf
9446 (org-link-try-special-completion link)))))
9447 (set-window-configuration wcf)
9448 (kill-buffer "*Org Links*"))
9449 (setq entry (assoc link org-stored-links))
9450 (or entry (push link org-insert-link-history))
9451 (setq desc (or desc (nth 1 entry)))))
9453 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9454 (not org-keep-stored-link-after-insertion))
9455 (setq org-stored-links (delq (assoc link org-stored-links)
9456 org-stored-links)))
9458 (if (string-match org-plain-link-re link)
9459 ;; URL-like link, normalize the use of angular brackets.
9460 (setq link (org-remove-angle-brackets link)))
9462 ;; Check if we are linking to the current file with a search option
9463 ;; If yes, simplify the link by using only the search option.
9464 (when (and buffer-file-name
9465 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9466 (let* ((path (match-string 1 link))
9467 (case-fold-search nil)
9468 (search (match-string 2 link)))
9469 (save-match-data
9470 (if (equal (file-truename buffer-file-name) (file-truename path))
9471 ;; We are linking to this same file, with a search option
9472 (setq link search)))))
9474 ;; Check if we can/should use a relative path. If yes, simplify the link
9475 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9476 (let* ((type (match-string 1 link))
9477 (path (match-string 2 link))
9478 (origpath path)
9479 (case-fold-search nil))
9480 (cond
9481 ((or (eq org-link-file-path-type 'absolute)
9482 (equal complete-file '(16)))
9483 (setq path (abbreviate-file-name (expand-file-name path))))
9484 ((eq org-link-file-path-type 'noabbrev)
9485 (setq path (expand-file-name path)))
9486 ((eq org-link-file-path-type 'relative)
9487 (setq path (file-relative-name path)))
9489 (save-match-data
9490 (if (string-match (concat "^" (regexp-quote
9491 (expand-file-name
9492 (file-name-as-directory
9493 default-directory))))
9494 (expand-file-name path))
9495 ;; We are linking a file with relative path name.
9496 (setq path (substring (expand-file-name path)
9497 (match-end 0)))
9498 (setq path (abbreviate-file-name (expand-file-name path)))))))
9499 (setq link (concat type path))
9500 (if (equal desc origpath)
9501 (setq desc path))))
9503 (if org-make-link-description-function
9504 (setq desc
9505 (or (condition-case nil
9506 (funcall org-make-link-description-function link desc)
9507 (error (progn (message "Can't get link description from `%s'"
9508 (symbol-name org-make-link-description-function))
9509 (sit-for 2) nil)))
9510 (read-string "Description: " default-description)))
9511 (if default-description (setq desc default-description)
9512 (setq desc (or (and auto-desc desc)
9513 (read-string "Description: " desc)))))
9515 (unless (string-match "\\S-" desc) (setq desc nil))
9516 (if remove (apply 'delete-region remove))
9517 (insert (org-make-link-string link desc))))
9519 (defun org-link-try-special-completion (type)
9520 "If there is completion support for link type TYPE, offer it."
9521 (let ((fun (intern (concat "org-" type "-complete-link"))))
9522 (if (functionp fun)
9523 (funcall fun)
9524 (read-string "Link (no completion support): " (concat type ":")))))
9526 (defun org-file-complete-link (&optional arg)
9527 "Create a file link using completion."
9528 (let (file link)
9529 (setq file (org-iread-file-name "File: "))
9530 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9531 (pwd1 (file-name-as-directory (abbreviate-file-name
9532 (expand-file-name ".")))))
9533 (cond
9534 ((equal arg '(16))
9535 (setq link (concat
9536 "file:"
9537 (abbreviate-file-name (expand-file-name file)))))
9538 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9539 (setq link (concat "file:" (match-string 1 file))))
9540 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9541 (expand-file-name file))
9542 (setq link (concat
9543 "file:" (match-string 1 (expand-file-name file)))))
9544 (t (setq link (concat "file:" file)))))
9545 link))
9547 (defun org-iread-file-name (&rest args)
9548 "Read-file-name using `ido-mode' speedup if available.
9549 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9550 See `read-file-name' for a description of parameters."
9551 (org-without-partial-completion
9552 (if (and org-completion-use-ido
9553 (fboundp 'ido-read-file-name)
9554 (boundp 'ido-mode) ido-mode
9555 (listp (second args)))
9556 (let ((ido-enter-matching-directory nil))
9557 (apply 'ido-read-file-name args))
9558 (apply 'read-file-name args))))
9560 (defun org-completing-read (&rest args)
9561 "Completing-read with SPACE being a normal character."
9562 (let ((enable-recursive-minibuffers t)
9563 (minibuffer-local-completion-map
9564 (copy-keymap minibuffer-local-completion-map)))
9565 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9566 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9567 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9568 (apply 'org-icompleting-read args)))
9570 (defun org-completing-read-no-i (&rest args)
9571 (let (org-completion-use-ido org-completion-use-iswitchb)
9572 (apply 'org-completing-read args)))
9574 (defun org-iswitchb-completing-read (prompt choices &rest args)
9575 "Use iswitch as a completing-read replacement to choose from choices.
9576 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9577 from."
9578 (let* ((iswitchb-use-virtual-buffers nil)
9579 (iswitchb-make-buflist-hook
9580 (lambda ()
9581 (setq iswitchb-temp-buflist choices))))
9582 (iswitchb-read-buffer prompt)))
9584 (defun org-icompleting-read (&rest args)
9585 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9586 (org-without-partial-completion
9587 (if (and org-completion-use-ido
9588 (fboundp 'ido-completing-read)
9589 (boundp 'ido-mode) ido-mode
9590 (listp (second args)))
9591 (let ((ido-enter-matching-directory nil))
9592 (apply 'ido-completing-read (concat (car args))
9593 (if (consp (car (nth 1 args)))
9594 (mapcar 'car (nth 1 args))
9595 (nth 1 args))
9596 (cddr args)))
9597 (if (and org-completion-use-iswitchb
9598 (boundp 'iswitchb-mode) iswitchb-mode
9599 (listp (second args)))
9600 (apply 'org-iswitchb-completing-read (concat (car args))
9601 (if (consp (car (nth 1 args)))
9602 (mapcar 'car (nth 1 args))
9603 (nth 1 args))
9604 (cddr args))
9605 (apply 'completing-read args)))))
9607 (defun org-extract-attributes (s)
9608 "Extract the attributes cookie from a string and set as text property."
9609 (let (a attr (start 0) key value)
9610 (save-match-data
9611 (when (string-match "{{\\([^}]+\\)}}$" s)
9612 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9613 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9614 (setq key (match-string 1 a) value (match-string 2 a)
9615 start (match-end 0)
9616 attr (plist-put attr (intern key) value))))
9617 (org-add-props s nil 'org-attr attr))
9620 (defun org-extract-attributes-from-string (tag)
9621 (let (key value attr)
9622 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9623 (setq key (match-string 1 tag) value (match-string 2 tag)
9624 tag (replace-match "" t t tag)
9625 attr (plist-put attr (intern key) value)))
9626 (cons tag attr)))
9628 (defun org-attributes-to-string (plist)
9629 "Format a property list into an HTML attribute list."
9630 (let ((s "") key value)
9631 (while plist
9632 (setq key (pop plist) value (pop plist))
9633 (and value
9634 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9637 ;;; Opening/following a link
9639 (defvar org-link-search-failed nil)
9641 (defvar org-open-link-functions nil
9642 "Hook for functions finding a plain text link.
9643 These functions must take a single argument, the link content.
9644 They will be called for links that look like [[link text][description]]
9645 when LINK TEXT does not have a protocol like \"http:\" and does not look
9646 like a filename (e.g. \"./blue.png\").
9648 These functions will be called *before* Org attempts to resolve the
9649 link by doing text searches in the current buffer - so if you want a
9650 link \"[[target]]\" to still find \"<<target>>\", your function should
9651 handle this as a special case.
9653 When the function does handle the link, it must return a non-nil value.
9654 If it decides that it is not responsible for this link, it must return
9655 nil to indicate that that Org-mode can continue with other options
9656 like exact and fuzzy text search.")
9658 (defun org-next-link ()
9659 "Move forward to the next link.
9660 If the link is in hidden text, expose it."
9661 (interactive)
9662 (when (and org-link-search-failed (eq this-command last-command))
9663 (goto-char (point-min))
9664 (message "Link search wrapped back to beginning of buffer"))
9665 (setq org-link-search-failed nil)
9666 (let* ((pos (point))
9667 (ct (org-context))
9668 (a (assoc :link ct)))
9669 (if a (goto-char (nth 2 a)))
9670 (if (re-search-forward org-any-link-re nil t)
9671 (progn
9672 (goto-char (match-beginning 0))
9673 (if (outline-invisible-p) (org-show-context)))
9674 (goto-char pos)
9675 (setq org-link-search-failed t)
9676 (error "No further link found"))))
9678 (defun org-previous-link ()
9679 "Move backward to the previous link.
9680 If the link is in hidden text, expose it."
9681 (interactive)
9682 (when (and org-link-search-failed (eq this-command last-command))
9683 (goto-char (point-max))
9684 (message "Link search wrapped back to end of buffer"))
9685 (setq org-link-search-failed nil)
9686 (let* ((pos (point))
9687 (ct (org-context))
9688 (a (assoc :link ct)))
9689 (if a (goto-char (nth 1 a)))
9690 (if (re-search-backward org-any-link-re nil t)
9691 (progn
9692 (goto-char (match-beginning 0))
9693 (if (outline-invisible-p) (org-show-context)))
9694 (goto-char pos)
9695 (setq org-link-search-failed t)
9696 (error "No further link found"))))
9698 (defun org-translate-link (s)
9699 "Translate a link string if a translation function has been defined."
9700 (if (and org-link-translation-function
9701 (fboundp org-link-translation-function)
9702 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9703 (progn
9704 (setq s (funcall org-link-translation-function
9705 (match-string 1 s) (match-string 2 s)))
9706 (concat (car s) ":" (cdr s)))
9709 (defun org-translate-link-from-planner (type path)
9710 "Translate a link from Emacs Planner syntax so that Org can follow it.
9711 This is still an experimental function, your mileage may vary."
9712 (cond
9713 ((member type '("http" "https" "news" "ftp"))
9714 ;; standard Internet links are the same.
9715 nil)
9716 ((and (equal type "irc") (string-match "^//" path))
9717 ;; Planner has two / at the beginning of an irc link, we have 1.
9718 ;; We should have zero, actually....
9719 (setq path (substring path 1)))
9720 ((and (equal type "lisp") (string-match "^/" path))
9721 ;; Planner has a slash, we do not.
9722 (setq type "elisp" path (substring path 1)))
9723 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9724 ;; A typical message link. Planner has the id after the final slash,
9725 ;; we separate it with a hash mark
9726 (setq path (concat (match-string 1 path) "#"
9727 (org-remove-angle-brackets (match-string 2 path)))))
9729 (cons type path))
9731 (defun org-find-file-at-mouse (ev)
9732 "Open file link or URL at mouse."
9733 (interactive "e")
9734 (mouse-set-point ev)
9735 (org-open-at-point 'in-emacs))
9737 (defun org-open-at-mouse (ev)
9738 "Open file link or URL at mouse.
9739 See the docstring of `org-open-file' for details."
9740 (interactive "e")
9741 (mouse-set-point ev)
9742 (if (eq major-mode 'org-agenda-mode)
9743 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9744 (org-open-at-point))
9746 (defvar org-window-config-before-follow-link nil
9747 "The window configuration before following a link.
9748 This is saved in case the need arises to restore it.")
9750 (defvar org-open-link-marker (make-marker)
9751 "Marker pointing to the location where `org-open-at-point; was called.")
9753 ;;;###autoload
9754 (defun org-open-at-point-global ()
9755 "Follow a link like Org-mode does.
9756 This command can be called in any mode to follow a link that has
9757 Org-mode syntax."
9758 (interactive)
9759 (org-run-like-in-org-mode 'org-open-at-point))
9761 ;;;###autoload
9762 (defun org-open-link-from-string (s &optional arg reference-buffer)
9763 "Open a link in the string S, as if it was in Org-mode."
9764 (interactive "sLink: \nP")
9765 (let ((reference-buffer (or reference-buffer (current-buffer))))
9766 (with-temp-buffer
9767 (let ((org-inhibit-startup (not reference-buffer)))
9768 (org-mode)
9769 (insert s)
9770 (goto-char (point-min))
9771 (when reference-buffer
9772 (setq org-link-abbrev-alist-local
9773 (with-current-buffer reference-buffer
9774 org-link-abbrev-alist-local)))
9775 (org-open-at-point arg reference-buffer)))))
9777 (defvar org-open-at-point-functions nil
9778 "Hook that is run when following a link at point.
9780 Functions in this hook must return t if they identify and follow
9781 a link at point. If they don't find anything interesting at point,
9782 they must return nil.")
9784 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9785 (defun org-open-at-point (&optional arg reference-buffer)
9786 "Open link at or after point.
9787 If there is no link at point, this function will search forward up to
9788 the end of the current line.
9789 Normally, files will be opened by an appropriate application. If the
9790 optional prefix argument ARG is non-nil, Emacs will visit the file.
9791 With a double prefix argument, try to open outside of Emacs, in the
9792 application the system uses for this file type."
9793 (interactive "P")
9794 ;; if in a code block, then open the block's results
9795 (unless (call-interactively #'org-babel-open-src-block-result)
9796 (org-load-modules-maybe)
9797 (move-marker org-open-link-marker (point))
9798 (setq org-window-config-before-follow-link (current-window-configuration))
9799 (org-remove-occur-highlights nil nil t)
9800 (cond
9801 ((and (org-at-heading-p)
9802 (not (org-at-timestamp-p t))
9803 (not (org-in-regexp
9804 (concat org-plain-link-re "\\|"
9805 org-bracket-link-regexp "\\|"
9806 org-angle-link-re "\\|"
9807 "[ \t]:[^ \t\n]+:[ \t]*$")))
9808 (not (get-text-property (point) 'org-linked-text)))
9809 (or (org-offer-links-in-entry arg)
9810 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9811 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9812 ((and (org-at-timestamp-p t)
9813 (not (org-in-regexp org-bracket-link-regexp)))
9814 (org-follow-timestamp-link))
9815 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9816 (not (org-in-regexp org-any-link-re)))
9817 (org-footnote-action))
9819 (let (type path link line search (pos (point)))
9820 (catch 'match
9821 (save-excursion
9822 (skip-chars-forward "^]\n\r")
9823 (when (org-in-regexp org-bracket-link-regexp 1)
9824 (setq link (org-extract-attributes
9825 (org-link-unescape (org-match-string-no-properties 1))))
9826 (while (string-match " *\n *" link)
9827 (setq link (replace-match " " t t link)))
9828 (setq link (org-link-expand-abbrev link))
9829 (cond
9830 ((or (file-name-absolute-p link)
9831 (string-match "^\\.\\.?/" link))
9832 (setq type "file" path link))
9833 ((string-match org-link-re-with-space3 link)
9834 (setq type (match-string 1 link) path (match-string 2 link)))
9835 ((string-match "^help:+\\(.+\\)" link)
9836 (setq type "help" path (match-string 1 link)))
9837 (t (setq type "thisfile" path link)))
9838 (throw 'match t)))
9840 (when (get-text-property (point) 'org-linked-text)
9841 (setq type "thisfile"
9842 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9843 (1+ (point)) (point))
9844 path (buffer-substring
9845 (or (previous-single-property-change pos 'org-linked-text)
9846 (point-min))
9847 (or (next-single-property-change pos 'org-linked-text)
9848 (point-max))))
9849 (throw 'match t))
9851 (save-excursion
9852 (when (or (org-in-regexp org-angle-link-re)
9853 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9854 (save-match-data (not (looking-back "\\[\\[")))))
9855 (setq type (match-string 1)
9856 path (org-link-unescape (match-string 2)))
9857 (throw 'match t)))
9858 (save-excursion
9859 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9860 (setq type "tags"
9861 path (match-string 1))
9862 (while (string-match ":" path)
9863 (setq path (replace-match "+" t t path)))
9864 (throw 'match t)))
9865 (when (org-in-regexp "<\\([^><\n]+\\)>")
9866 (setq type "tree-match"
9867 path (match-string 1))
9868 (throw 'match t)))
9869 (unless path
9870 (error "No link found"))
9872 ;; switch back to reference buffer
9873 ;; needed when if called in a temporary buffer through
9874 ;; org-open-link-from-string
9875 (with-current-buffer (or reference-buffer (current-buffer))
9877 ;; Remove any trailing spaces in path
9878 (if (string-match " +\\'" path)
9879 (setq path (replace-match "" t t path)))
9880 (if (and org-link-translation-function
9881 (fboundp org-link-translation-function))
9882 ;; Check if we need to translate the link
9883 (let ((tmp (funcall org-link-translation-function type path)))
9884 (setq type (car tmp) path (cdr tmp))))
9886 (cond
9888 ((assoc type org-link-protocols)
9889 (funcall (nth 1 (assoc type org-link-protocols)) path))
9891 ((equal type "help")
9892 (let ((f-or-v (intern path)))
9893 (cond ((fboundp f-or-v)
9894 (describe-function f-or-v))
9895 ((boundp f-or-v)
9896 (describe-variable f-or-v))
9897 (t (error "Not a known function or variable")))))
9899 ((equal type "mailto")
9900 (let ((cmd (car org-link-mailto-program))
9901 (args (cdr org-link-mailto-program)) args1
9902 (address path) (subject "") a)
9903 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9904 (setq address (match-string 1 path)
9905 subject (org-link-escape (match-string 2 path))))
9906 (while args
9907 (cond
9908 ((not (stringp (car args))) (push (pop args) args1))
9909 (t (setq a (pop args))
9910 (if (string-match "%a" a)
9911 (setq a (replace-match address t t a)))
9912 (if (string-match "%s" a)
9913 (setq a (replace-match subject t t a)))
9914 (push a args1))))
9915 (apply cmd (nreverse args1))))
9917 ((member type '("http" "https" "ftp" "news"))
9918 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9919 (org-link-escape
9920 path org-link-escape-chars-browser)
9921 path))))
9923 ((string= type "doi")
9924 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9925 (org-link-escape
9926 path org-link-escape-chars-browser)
9927 path))))
9929 ((member type '("message"))
9930 (browse-url (concat type ":" path)))
9932 ((string= type "tags")
9933 (org-tags-view arg path))
9935 ((string= type "tree-match")
9936 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9938 ((string= type "file")
9939 (if (string-match "::\\([0-9]+\\)\\'" path)
9940 (setq line (string-to-number (match-string 1 path))
9941 path (substring path 0 (match-beginning 0)))
9942 (if (string-match "::\\(.+\\)\\'" path)
9943 (setq search (match-string 1 path)
9944 path (substring path 0 (match-beginning 0)))))
9945 (if (string-match "[*?{]" (file-name-nondirectory path))
9946 (dired path)
9947 (org-open-file path arg line search)))
9949 ((string= type "shell")
9950 (let ((buf (generate-new-buffer "*Org Shell Output"))
9951 (cmd path))
9952 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9953 (string-match org-confirm-shell-link-not-regexp cmd))
9954 (not org-confirm-shell-link-function)
9955 (funcall org-confirm-shell-link-function
9956 (format "Execute \"%s\" in shell? "
9957 (org-add-props cmd nil
9958 'face 'org-warning))))
9959 (progn
9960 (message "Executing %s" cmd)
9961 (shell-command cmd buf)
9962 (if (featurep 'midnight)
9963 (setq clean-buffer-list-kill-buffer-names
9964 (cons buf clean-buffer-list-kill-buffer-names))))
9965 (error "Abort"))))
9967 ((string= type "elisp")
9968 (let ((cmd path))
9969 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9970 (string-match org-confirm-elisp-link-not-regexp cmd))
9971 (not org-confirm-elisp-link-function)
9972 (funcall org-confirm-elisp-link-function
9973 (format "Execute \"%s\" as elisp? "
9974 (org-add-props cmd nil
9975 'face 'org-warning))))
9976 (message "%s => %s" cmd
9977 (if (equal (string-to-char cmd) ?\()
9978 (eval (read cmd))
9979 (call-interactively (read cmd))))
9980 (error "Abort"))))
9982 ((and (string= type "thisfile")
9983 (run-hook-with-args-until-success
9984 'org-open-link-functions path)))
9986 ((string= type "thisfile")
9987 (if arg
9988 (switch-to-buffer-other-window
9989 (org-get-buffer-for-internal-link (current-buffer)))
9990 (org-mark-ring-push))
9991 (let ((cmd `(org-link-search
9992 ,path
9993 ,(cond ((equal arg '(4)) ''occur)
9994 ((equal arg '(16)) ''org-occur))
9995 ,pos)))
9996 (condition-case nil (let ((org-link-search-inhibit-query t))
9997 (eval cmd))
9998 (error (progn (widen) (eval cmd))))))
10000 (t (browse-url-at-point)))))))
10001 (move-marker org-open-link-marker nil)
10002 (run-hook-with-args 'org-follow-link-hook)))
10004 (defun org-offer-links-in-entry (&optional nth zero)
10005 "Offer links in the current entry and follow the selected link.
10006 If there is only one link, follow it immediately as well.
10007 If NTH is an integer, immediately pick the NTH link found.
10008 If ZERO is a string, check also this string for a link, and if
10009 there is one, offer it as link number zero."
10010 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10011 "\\(" org-angle-link-re "\\)\\|"
10012 "\\(" org-plain-link-re "\\)"))
10013 (cnt ?0)
10014 (in-emacs (if (integerp nth) nil nth))
10015 have-zero end links link c)
10016 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10017 (push (match-string 0 zero) links)
10018 (setq cnt (1- cnt) have-zero t))
10019 (save-excursion
10020 (org-back-to-heading t)
10021 (setq end (save-excursion (outline-next-heading) (point)))
10022 (while (re-search-forward re end t)
10023 (push (match-string 0) links))
10024 (setq links (org-uniquify (reverse links))))
10026 (cond
10027 ((null links)
10028 (message "No links"))
10029 ((equal (length links) 1)
10030 (setq link (list (car links))))
10031 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10032 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10033 (t ; we have to select a link
10034 (save-excursion
10035 (save-window-excursion
10036 (delete-other-windows)
10037 (with-output-to-temp-buffer "*Select Link*"
10038 (mapc (lambda (l)
10039 (if (not (string-match org-bracket-link-regexp l))
10040 (princ (format "[%c] %s\n" (incf cnt)
10041 (org-remove-angle-brackets l)))
10042 (if (match-end 3)
10043 (princ (format "[%c] %s (%s)\n" (incf cnt)
10044 (match-string 3 l) (match-string 1 l)))
10045 (princ (format "[%c] %s\n" (incf cnt)
10046 (match-string 1 l))))))
10047 links))
10048 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10049 (message "Select link to open, RET to open all:")
10050 (setq c (read-char-exclusive))
10051 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10052 (when (equal c ?q) (error "Abort"))
10053 (if (equal c ?\C-m)
10054 (setq link links)
10055 (setq nth (- c ?0))
10056 (if have-zero (setq nth (1+ nth)))
10057 (unless (and (integerp nth) (>= (length links) nth))
10058 (error "Invalid link selection"))
10059 (setq link (list (nth (1- nth) links))))))
10060 (if link
10061 (let ((buf (current-buffer)))
10062 (dolist (l link)
10063 (org-open-link-from-string l in-emacs buf))
10065 nil)))
10067 ;; Add special file links that specify the way of opening
10069 (org-add-link-type "file+sys" 'org-open-file-with-system)
10070 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10071 (defun org-open-file-with-system (path)
10072 "Open file at PATH using the system way of opening it."
10073 (org-open-file path 'system))
10074 (defun org-open-file-with-emacs (path)
10075 "Open file at PATH in Emacs."
10076 (org-open-file path 'emacs))
10077 (defun org-remove-file-link-modifiers ()
10078 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10079 (goto-char (point-min))
10080 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10081 (org-if-unprotected
10082 (replace-match "file:" t t))))
10083 (eval-after-load "org-exp"
10084 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10085 'org-remove-file-link-modifiers))
10087 ;;;; Time estimates
10089 (defun org-get-effort (&optional pom)
10090 "Get the effort estimate for the current entry."
10091 (org-entry-get pom org-effort-property))
10093 ;;; File search
10095 (defvar org-create-file-search-functions nil
10096 "List of functions to construct the right search string for a file link.
10097 These functions are called in turn with point at the location to
10098 which the link should point.
10100 A function in the hook should first test if it would like to
10101 handle this file type, for example by checking the `major-mode'
10102 or the file extension. If it decides not to handle this file, it
10103 should just return nil to give other functions a chance. If it
10104 does handle the file, it must return the search string to be used
10105 when following the link. The search string will be part of the
10106 file link, given after a double colon, and `org-open-at-point'
10107 will automatically search for it. If special measures must be
10108 taken to make the search successful, another function should be
10109 added to the companion hook `org-execute-file-search-functions',
10110 which see.
10112 A function in this hook may also use `setq' to set the variable
10113 `description' to provide a suggestion for the descriptive text to
10114 be used for this link when it gets inserted into an Org-mode
10115 buffer with \\[org-insert-link].")
10117 (defvar org-execute-file-search-functions nil
10118 "List of functions to execute a file search triggered by a link.
10120 Functions added to this hook must accept a single argument, the
10121 search string that was part of the file link, the part after the
10122 double colon. The function must first check if it would like to
10123 handle this search, for example by checking the `major-mode' or
10124 the file extension. If it decides not to handle this search, it
10125 should just return nil to give other functions a chance. If it
10126 does handle the search, it must return a non-nil value to keep
10127 other functions from trying.
10129 Each function can access the current prefix argument through the
10130 variable `current-prefix-argument'. Note that a single prefix is
10131 used to force opening a link in Emacs, so it may be good to only
10132 use a numeric or double prefix to guide the search function.
10134 In case this is needed, a function in this hook can also restore
10135 the window configuration before `org-open-at-point' was called using:
10137 (set-window-configuration org-window-config-before-follow-link)")
10139 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10140 (defun org-link-search (s &optional type avoid-pos stealth)
10141 "Search for a link search option.
10142 If S is surrounded by forward slashes, it is interpreted as a
10143 regular expression. In org-mode files, this will create an `org-occur'
10144 sparse tree. In ordinary files, `occur' will be used to list matches.
10145 If the current buffer is in `dired-mode', grep will be used to search
10146 in all files. If AVOID-POS is given, ignore matches near that position.
10148 When optional argument STEALTH is non-nil, do not modify
10149 visibility around point, thus ignoring
10150 `org-show-hierarchy-above', `org-show-following-heading' and
10151 `org-show-siblings' variables."
10152 (let ((case-fold-search t)
10153 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10154 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10155 (append '(("") (" ") ("\t") ("\n"))
10156 org-emphasis-alist)
10157 "\\|") "\\)"))
10158 (pos (point))
10159 (pre nil) (post nil)
10160 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10161 (cond
10162 ;; First check if there are any special search functions
10163 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10164 ;; Now try the builtin stuff
10165 ((and (equal (string-to-char s0) ?#)
10166 (> (length s0) 1)
10167 (save-excursion
10168 (goto-char (point-min))
10169 (and
10170 (re-search-forward
10171 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10172 (setq type 'dedicated
10173 pos (match-beginning 0))))
10174 ;; There is an exact target for this
10175 (goto-char pos)
10176 (org-back-to-heading t)))
10177 ((save-excursion
10178 (goto-char (point-min))
10179 (and
10180 (re-search-forward
10181 (concat "<<" (regexp-quote s0) ">>") nil t)
10182 (setq type 'dedicated
10183 pos (match-beginning 0))))
10184 ;; There is an exact target for this
10185 (goto-char pos))
10186 ((save-excursion
10187 (goto-char (point-min))
10188 (and
10189 (re-search-forward
10190 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10191 (setq type 'dedicated pos (match-beginning 0))))
10192 ;; Found an invisible target.
10193 (goto-char pos))
10194 ((save-excursion
10195 (goto-char (point-min))
10196 (and
10197 (re-search-forward
10198 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10199 (setq type 'dedicated pos (match-beginning 0))))
10200 ;; Found an element with a matching #+name affiliated keyword.
10201 (goto-char pos))
10202 ((and (string-match "^(\\(.*\\))$" s0)
10203 (save-excursion
10204 (goto-char (point-min))
10205 (and
10206 (re-search-forward
10207 (concat "[^[]" (regexp-quote
10208 (format org-coderef-label-format
10209 (match-string 1 s0))))
10210 nil t)
10211 (setq type 'dedicated
10212 pos (1+ (match-beginning 0))))))
10213 ;; There is a coderef target for this
10214 (goto-char pos))
10215 ((string-match "^/\\(.*\\)/$" s)
10216 ;; A regular expression
10217 (cond
10218 ((derived-mode-p 'org-mode)
10219 (org-occur (match-string 1 s)))
10220 ;;((eq major-mode 'dired-mode)
10221 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10222 (t (org-do-occur (match-string 1 s)))))
10223 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10224 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10225 (goto-char (point-min))
10226 (cond
10227 ((let (case-fold-search)
10228 (re-search-forward (format org-complex-heading-regexp-format
10229 (regexp-quote s))
10230 nil t))
10231 ;; OK, found a match
10232 (setq type 'dedicated)
10233 (goto-char (match-beginning 0)))
10234 ((and (not org-link-search-inhibit-query)
10235 (eq org-link-search-must-match-exact-headline 'query-to-create)
10236 (y-or-n-p "No match - create this as a new heading? "))
10237 (goto-char (point-max))
10238 (or (bolp) (newline))
10239 (insert "* " s "\n")
10240 (beginning-of-line 0))
10242 (goto-char pos)
10243 (error "No match"))))
10245 ;; A normal search string
10246 (when (equal (string-to-char s) ?*)
10247 ;; Anchor on headlines, post may include tags.
10248 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10249 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10250 s (substring s 1)))
10251 (remove-text-properties
10252 0 (length s)
10253 '(face nil mouse-face nil keymap nil fontified nil) s)
10254 ;; Make a series of regular expressions to find a match
10255 (setq words (org-split-string s "[ \n\r\t]+")
10257 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10258 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10259 "\\)" markers)
10260 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10261 re2a (concat "[ \t\r\n]" re2a_)
10262 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10263 re4 (concat "[^a-zA-Z_]" re4_)
10265 re1 (concat pre re2 post)
10266 re3 (concat pre (if pre re4_ re4) post)
10267 re5 (concat pre ".*" re4)
10268 re2 (concat pre re2)
10269 re2a (concat pre (if pre re2a_ re2a))
10270 re4 (concat pre (if pre re4_ re4))
10271 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10272 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10273 re5 "\\)"
10275 (cond
10276 ((eq type 'org-occur) (org-occur reall))
10277 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10278 (t (goto-char (point-min))
10279 (setq type 'fuzzy)
10280 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10281 (org-search-not-self 1 re1 nil t)
10282 (org-search-not-self 1 re2 nil t)
10283 (org-search-not-self 1 re2a nil t)
10284 (org-search-not-self 1 re3 nil t)
10285 (org-search-not-self 1 re4 nil t)
10286 (org-search-not-self 1 re5 nil t)
10288 (goto-char (match-beginning 1))
10289 (goto-char pos)
10290 (error "No match"))))))
10291 (and (derived-mode-p 'org-mode)
10292 (not stealth)
10293 (org-show-context 'link-search))
10294 type))
10296 (defun org-search-not-self (group &rest args)
10297 "Execute `re-search-forward', but only accept matches that do not
10298 enclose the position of `org-open-link-marker'."
10299 (let ((m org-open-link-marker))
10300 (catch 'exit
10301 (while (apply 're-search-forward args)
10302 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10303 (goto-char (match-end group))
10304 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10305 (> (match-beginning 0) (marker-position m))
10306 (< (match-end 0) (marker-position m)))
10307 (save-match-data
10308 (or (not (org-in-regexp
10309 org-bracket-link-analytic-regexp 1))
10310 (not (match-end 4)) ; no description
10311 (and (<= (match-beginning 4) (point))
10312 (>= (match-end 4) (point))))))
10313 (throw 'exit (point))))))))
10315 (defun org-get-buffer-for-internal-link (buffer)
10316 "Return a buffer to be used for displaying the link target of internal links."
10317 (cond
10318 ((not org-display-internal-link-with-indirect-buffer)
10319 buffer)
10320 ((string-match "(Clone)$" (buffer-name buffer))
10321 (message "Buffer is already a clone, not making another one")
10322 ;; we also do not modify visibility in this case
10323 buffer)
10324 (t ; make a new indirect buffer for displaying the link
10325 (let* ((bn (buffer-name buffer))
10326 (ibn (concat bn "(Clone)"))
10327 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10328 (with-current-buffer ib (org-overview))
10329 ib))))
10331 (defun org-do-occur (regexp &optional cleanup)
10332 "Call the Emacs command `occur'.
10333 If CLEANUP is non-nil, remove the printout of the regular expression
10334 in the *Occur* buffer. This is useful if the regex is long and not useful
10335 to read."
10336 (occur regexp)
10337 (when cleanup
10338 (let ((cwin (selected-window)) win beg end)
10339 (when (setq win (get-buffer-window "*Occur*"))
10340 (select-window win))
10341 (goto-char (point-min))
10342 (when (re-search-forward "match[a-z]+" nil t)
10343 (setq beg (match-end 0))
10344 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10345 (setq end (1- (match-beginning 0)))))
10346 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10347 (goto-char (point-min))
10348 (select-window cwin))))
10350 ;;; The mark ring for links jumps
10352 (defvar org-mark-ring nil
10353 "Mark ring for positions before jumps in Org-mode.")
10354 (defvar org-mark-ring-last-goto nil
10355 "Last position in the mark ring used to go back.")
10356 ;; Fill and close the ring
10357 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10358 (loop for i from 1 to org-mark-ring-length do
10359 (push (make-marker) org-mark-ring))
10360 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10361 org-mark-ring)
10363 (defun org-mark-ring-push (&optional pos buffer)
10364 "Put the current position or POS into the mark ring and rotate it."
10365 (interactive)
10366 (setq pos (or pos (point)))
10367 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10368 (move-marker (car org-mark-ring)
10369 (or pos (point))
10370 (or buffer (current-buffer)))
10371 (message "%s"
10372 (substitute-command-keys
10373 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10375 (defun org-mark-ring-goto (&optional n)
10376 "Jump to the previous position in the mark ring.
10377 With prefix arg N, jump back that many stored positions. When
10378 called several times in succession, walk through the entire ring.
10379 Org-mode commands jumping to a different position in the current file,
10380 or to another Org-mode file, automatically push the old position
10381 onto the ring."
10382 (interactive "p")
10383 (let (p m)
10384 (if (eq last-command this-command)
10385 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10386 (setq p org-mark-ring))
10387 (setq org-mark-ring-last-goto p)
10388 (setq m (car p))
10389 (org-pop-to-buffer-same-window (marker-buffer m))
10390 (goto-char m)
10391 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10393 (defun org-remove-angle-brackets (s)
10394 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10395 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10397 (defun org-add-angle-brackets (s)
10398 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10399 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10401 (defun org-remove-double-quotes (s)
10402 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10403 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10406 ;;; Following specific links
10408 (defun org-follow-timestamp-link ()
10409 "Open an agenda view for the time-stamp date/range at point."
10410 (cond
10411 ((org-at-date-range-p t)
10412 (let ((org-agenda-start-on-weekday)
10413 (t1 (match-string 1))
10414 (t2 (match-string 2)) tt1 tt2)
10415 (setq tt1 (time-to-days (org-time-string-to-time t1))
10416 tt2 (time-to-days (org-time-string-to-time t2)))
10417 (let ((org-agenda-buffer-tmp-name
10418 (format "*Org Agenda(a:%s)"
10419 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10420 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10421 ((org-at-timestamp-p t)
10422 (let ((org-agenda-buffer-tmp-name
10423 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10424 (org-agenda-list nil (time-to-days (org-time-string-to-time
10425 (substring (match-string 1) 0 10)))
10426 1)))
10427 (t (error "This should not happen"))))
10430 ;;; Following file links
10431 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10432 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10433 (declare-function mailcap-mime-info
10434 "mailcap" (string &optional request no-decode))
10435 (defvar org-wait nil)
10436 (defun org-open-file (path &optional in-emacs line search)
10437 "Open the file at PATH.
10438 First, this expands any special file name abbreviations. Then the
10439 configuration variable `org-file-apps' is checked if it contains an
10440 entry for this file type, and if yes, the corresponding command is launched.
10442 If no application is found, Emacs simply visits the file.
10444 With optional prefix argument IN-EMACS, Emacs will visit the file.
10445 With a double \\[universal-argument] \\[universal-argument] \
10446 prefix arg, Org tries to avoid opening in Emacs
10447 and to use an external application to visit the file.
10449 Optional LINE specifies a line to go to, optional SEARCH a string
10450 to search for. If LINE or SEARCH is given, the file will be
10451 opened in Emacs, unless an entry from org-file-apps that makes
10452 use of groups in a regexp matches.
10454 If you want to change the way frames are used when following a
10455 link, please customize `org-link-frame-setup'.
10457 If the file does not exist, an error is thrown."
10458 (let* ((file (if (equal path "")
10459 buffer-file-name
10460 (substitute-in-file-name (expand-file-name path))))
10461 (file-apps (append org-file-apps (org-default-apps)))
10462 (apps (org-remove-if
10463 'org-file-apps-entry-match-against-dlink-p file-apps))
10464 (apps-dlink (org-remove-if-not
10465 'org-file-apps-entry-match-against-dlink-p file-apps))
10466 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10467 (dirp (if remp nil (file-directory-p file)))
10468 (file (if (and dirp org-open-directory-means-index-dot-org)
10469 (concat (file-name-as-directory file) "index.org")
10470 file))
10471 (a-m-a-p (assq 'auto-mode apps))
10472 (dfile (downcase file))
10473 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10474 (link (cond ((and (eq line nil)
10475 (eq search nil))
10476 file)
10477 (line
10478 (concat file "::" (number-to-string line)))
10479 (search
10480 (concat file "::" search))))
10481 (dlink (downcase link))
10482 (old-buffer (current-buffer))
10483 (old-pos (point))
10484 (old-mode major-mode)
10485 ext cmd link-match-data)
10486 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10487 (setq ext (match-string 1 dfile))
10488 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10489 (setq ext (match-string 1 dfile))))
10490 (cond
10491 ((member in-emacs '((16) system))
10492 (setq cmd (cdr (assoc 'system apps))))
10493 (in-emacs (setq cmd 'emacs))
10495 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10496 (and dirp (cdr (assoc 'directory apps)))
10497 ; first, try matching against apps-dlink
10498 ; if we get a match here, store the match data for later
10499 (let ((match (assoc-default dlink apps-dlink
10500 'string-match)))
10501 (if match
10502 (progn (setq link-match-data (match-data))
10503 match)
10504 (progn (setq in-emacs (or in-emacs line search))
10505 nil))) ; if we have no match in apps-dlink,
10506 ; always open the file in emacs if line or search
10507 ; is given (for backwards compatibility)
10508 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10509 'string-match)
10510 (cdr (assoc ext apps))
10511 (cdr (assoc t apps))))))
10512 (when (eq cmd 'system)
10513 (setq cmd (cdr (assoc 'system apps))))
10514 (when (eq cmd 'default)
10515 (setq cmd (cdr (assoc t apps))))
10516 (when (eq cmd 'mailcap)
10517 (require 'mailcap)
10518 (mailcap-parse-mailcaps)
10519 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10520 (command (mailcap-mime-info mime-type)))
10521 (if (stringp command)
10522 (setq cmd command)
10523 (setq cmd 'emacs))))
10524 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10525 (not (file-exists-p file))
10526 (not org-open-non-existing-files))
10527 (error "No such file: %s" file))
10528 (cond
10529 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10530 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10531 (while (string-match "['\"]%s['\"]" cmd)
10532 (setq cmd (replace-match "%s" t t cmd)))
10533 (while (string-match "%s" cmd)
10534 (setq cmd (replace-match
10535 (save-match-data
10536 (shell-quote-argument
10537 (convert-standard-filename file)))
10538 t t cmd)))
10540 ;; Replace "%1", "%2" etc. in command with group matches from regex
10541 (save-match-data
10542 (let ((match-index 1)
10543 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10544 (set-match-data link-match-data)
10545 (while (<= match-index number-of-groups)
10546 (let ((regex (concat "%" (number-to-string match-index)))
10547 (replace-with (match-string match-index dlink)))
10548 (while (string-match regex cmd)
10549 (setq cmd (replace-match replace-with t t cmd))))
10550 (setq match-index (+ match-index 1)))))
10552 (save-window-excursion
10553 (message "Running %s...done" cmd)
10554 (start-process-shell-command cmd nil cmd)
10555 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10556 ((or (stringp cmd)
10557 (eq cmd 'emacs))
10558 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10559 (widen)
10560 (if line (org-goto-line line)
10561 (if search (org-link-search search))))
10562 ((consp cmd)
10563 (let ((file (convert-standard-filename file)))
10564 (save-match-data
10565 (set-match-data link-match-data)
10566 (eval cmd))))
10567 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10568 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10569 (or (not (equal old-buffer (current-buffer)))
10570 (not (equal old-pos (point))))
10571 (org-mark-ring-push old-pos old-buffer))))
10573 (defun org-file-apps-entry-match-against-dlink-p (entry)
10574 "This function returns non-nil if `entry' uses a regular
10575 expression which should be matched against the whole link by
10576 org-open-file.
10578 It assumes that is the case when the entry uses a regular
10579 expression which has at least one grouping construct and the
10580 action is either a lisp form or a command string containing
10581 '%1', i.e. using at least one subexpression match as a
10582 parameter."
10583 (let ((selector (car entry))
10584 (action (cdr entry)))
10585 (if (stringp selector)
10586 (and (> (regexp-opt-depth selector) 0)
10587 (or (and (stringp action)
10588 (string-match "%[0-9]" action))
10589 (consp action)))
10590 nil)))
10592 (defun org-default-apps ()
10593 "Return the default applications for this operating system."
10594 (cond
10595 ((eq system-type 'darwin)
10596 org-file-apps-defaults-macosx)
10597 ((eq system-type 'windows-nt)
10598 org-file-apps-defaults-windowsnt)
10599 (t org-file-apps-defaults-gnu)))
10601 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10602 "Convert extensions to regular expressions in the cars of LIST.
10603 Also, weed out any non-string entries, because the return value is used
10604 only for regexp matching.
10605 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10606 point to the symbol `emacs', indicating that the file should
10607 be opened in Emacs."
10608 (append
10609 (delq nil
10610 (mapcar (lambda (x)
10611 (if (not (stringp (car x)))
10613 (if (string-match "\\W" (car x))
10615 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10616 list))
10617 (if add-auto-mode
10618 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10620 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10621 (defun org-file-remote-p (file)
10622 "Test whether FILE specifies a location on a remote system.
10623 Return non-nil if the location is indeed remote.
10625 For example, the filename \"/user@host:/foo\" specifies a location
10626 on the system \"/user@host:\"."
10627 (cond ((fboundp 'file-remote-p)
10628 (file-remote-p file))
10629 ((fboundp 'tramp-handle-file-remote-p)
10630 (tramp-handle-file-remote-p file))
10631 ((and (boundp 'ange-ftp-name-format)
10632 (string-match (car ange-ftp-name-format) file))
10633 t)))
10636 ;;;; Refiling
10638 (defun org-get-org-file ()
10639 "Read a filename, with default directory `org-directory'."
10640 (let ((default (or org-default-notes-file remember-data-file)))
10641 (read-file-name (format "File name [%s]: " default)
10642 (file-name-as-directory org-directory)
10643 default)))
10645 (defun org-notes-order-reversed-p ()
10646 "Check if the current file should receive notes in reversed order."
10647 (cond
10648 ((not org-reverse-note-order) nil)
10649 ((eq t org-reverse-note-order) t)
10650 ((not (listp org-reverse-note-order)) nil)
10651 (t (catch 'exit
10652 (let ((all org-reverse-note-order)
10653 entry)
10654 (while (setq entry (pop all))
10655 (if (string-match (car entry) buffer-file-name)
10656 (throw 'exit (cdr entry))))
10657 nil)))))
10659 (defvar org-refile-target-table nil
10660 "The list of refile targets, created by `org-refile'.")
10662 (defvar org-agenda-new-buffers nil
10663 "Buffers created to visit agenda files.")
10665 (defvar org-refile-cache nil
10666 "Cache for refile targets.")
10668 (defvar org-refile-markers nil
10669 "All the markers used for caching refile locations.")
10671 (defun org-refile-marker (pos)
10672 "Get a new refile marker, but only if caching is in use."
10673 (if (not org-refile-use-cache)
10675 (let ((m (make-marker)))
10676 (move-marker m pos)
10677 (push m org-refile-markers)
10678 m)))
10680 (defun org-refile-cache-clear ()
10681 "Clear the refile cache and disable all the markers."
10682 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10683 (setq org-refile-markers nil)
10684 (setq org-refile-cache nil)
10685 (message "Refile cache has been cleared"))
10687 (defun org-refile-cache-check-set (set)
10688 "Check if all the markers in the cache still have live buffers."
10689 (let (marker)
10690 (catch 'exit
10691 (while (and set (setq marker (nth 3 (pop set))))
10692 ;; if org-refile-use-outline-path is 'file, marker may be nil
10693 (when (and marker (null (marker-buffer marker)))
10694 (message "not found") (sit-for 3)
10695 (throw 'exit nil)))
10696 t)))
10698 (defun org-refile-cache-put (set &rest identifiers)
10699 "Push the refile targets SET into the cache, under IDENTIFIERS."
10700 (let* ((key (sha1 (prin1-to-string identifiers)))
10701 (entry (assoc key org-refile-cache)))
10702 (if entry
10703 (setcdr entry set)
10704 (push (cons key set) org-refile-cache))))
10706 (defun org-refile-cache-get (&rest identifiers)
10707 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10708 (cond
10709 ((not org-refile-cache) nil)
10710 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10712 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10713 org-refile-cache))))
10714 (and set (org-refile-cache-check-set set) set)))))
10716 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10717 "Produce a table with refile targets."
10718 (let ((case-fold-search nil)
10719 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10720 (entries (or org-refile-targets '((nil . (:level . 1)))))
10721 targets tgs txt re files f desc descre fast-path-p level pos0)
10722 (message "Getting targets...")
10723 (with-current-buffer (or default-buffer (current-buffer))
10724 (while (setq entry (pop entries))
10725 (setq files (car entry) desc (cdr entry))
10726 (setq fast-path-p nil)
10727 (cond
10728 ((null files) (setq files (list (current-buffer))))
10729 ((eq files 'org-agenda-files)
10730 (setq files (org-agenda-files 'unrestricted)))
10731 ((and (symbolp files) (fboundp files))
10732 (setq files (funcall files)))
10733 ((and (symbolp files) (boundp files))
10734 (setq files (symbol-value files))))
10735 (if (stringp files) (setq files (list files)))
10736 (cond
10737 ((eq (car desc) :tag)
10738 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10739 ((eq (car desc) :todo)
10740 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10741 ((eq (car desc) :regexp)
10742 (setq descre (cdr desc)))
10743 ((eq (car desc) :level)
10744 (setq descre (concat "^\\*\\{" (number-to-string
10745 (if org-odd-levels-only
10746 (1- (* 2 (cdr desc)))
10747 (cdr desc)))
10748 "\\}[ \t]")))
10749 ((eq (car desc) :maxlevel)
10750 (setq fast-path-p t)
10751 (setq descre (concat "^\\*\\{1," (number-to-string
10752 (if org-odd-levels-only
10753 (1- (* 2 (cdr desc)))
10754 (cdr desc)))
10755 "\\}[ \t]")))
10756 (t (error "Bad refiling target description %s" desc)))
10757 (while (setq f (pop files))
10758 (with-current-buffer
10759 (if (bufferp f) f (org-get-agenda-file-buffer f))
10761 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10762 (progn
10763 (if (bufferp f) (setq f (buffer-file-name
10764 (buffer-base-buffer f))))
10765 (setq f (and f (expand-file-name f)))
10766 (if (eq org-refile-use-outline-path 'file)
10767 (push (list (file-name-nondirectory f) f nil nil) tgs))
10768 (save-excursion
10769 (save-restriction
10770 (widen)
10771 (goto-char (point-min))
10772 (while (re-search-forward descre nil t)
10773 (goto-char (setq pos0 (point-at-bol)))
10774 (catch 'next
10775 (when org-refile-target-verify-function
10776 (save-match-data
10777 (or (funcall org-refile-target-verify-function)
10778 (throw 'next t))))
10779 (when (and (looking-at org-complex-heading-regexp)
10780 (not (member (match-string 4) excluded-entries))
10781 (match-string 4))
10782 (setq level (org-reduced-level
10783 (- (match-end 1) (match-beginning 1)))
10784 txt (org-link-display-format (match-string 4))
10785 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10786 re (format org-complex-heading-regexp-format
10787 (regexp-quote (match-string 4))))
10788 (when org-refile-use-outline-path
10789 (setq txt (mapconcat
10790 'org-protect-slash
10791 (append
10792 (if (eq org-refile-use-outline-path
10793 'file)
10794 (list (file-name-nondirectory
10795 (buffer-file-name
10796 (buffer-base-buffer))))
10797 (if (eq org-refile-use-outline-path
10798 'full-file-path)
10799 (list (buffer-file-name
10800 (buffer-base-buffer)))))
10801 (org-get-outline-path fast-path-p
10802 level txt)
10803 (list txt))
10804 "/")))
10805 (push (list txt f re (org-refile-marker (point)))
10806 tgs)))
10807 (when (= (point) pos0)
10808 ;; verification function has not moved point
10809 (goto-char (point-at-eol))))))))
10810 (when org-refile-use-cache
10811 (org-refile-cache-put tgs (buffer-file-name) descre))
10812 (setq targets (append tgs targets))
10813 ))))
10814 (message "Getting targets...done")
10815 (nreverse targets)))
10817 (defun org-protect-slash (s)
10818 (while (string-match "/" s)
10819 (setq s (replace-match "\\" t t s)))
10822 (defvar org-olpa (make-vector 20 nil))
10824 (defun org-get-outline-path (&optional fastp level heading)
10825 "Return the outline path to the current entry, as a list.
10827 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10828 routine which makes outline path derivations for an entire file,
10829 avoiding backtracing. Refile target collection makes use of that."
10830 (if fastp
10831 (progn
10832 (if (> level 19)
10833 (error "Outline path failure, more than 19 levels"))
10834 (loop for i from level upto 19 do
10835 (aset org-olpa i nil))
10836 (prog1
10837 (delq nil (append org-olpa nil))
10838 (aset org-olpa level heading)))
10839 (let (rtn case-fold-search)
10840 (save-excursion
10841 (save-restriction
10842 (widen)
10843 (while (org-up-heading-safe)
10844 (when (looking-at org-complex-heading-regexp)
10845 (push (org-match-string-no-properties 4) rtn)))
10846 rtn)))))
10848 (defun org-format-outline-path (path &optional width prefix separator)
10849 "Format the outline path PATH for display.
10850 WIDTH is the maximum number of characters that is available.
10851 PREFIX is a prefix to be included in the returned string,
10852 such as the file name.
10853 SEPARATOR is inserted between the different parts of the path,
10854 the default is \"/\"."
10855 (setq width (or width 79))
10856 (if prefix (setq width (- width (length prefix))))
10857 (if (not path)
10858 (or prefix "")
10859 (let* ((nsteps (length path))
10860 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10861 (maxwidth (if (<= total-width width)
10862 10000 ;; everything fits
10863 ;; we need to shorten the level headings
10864 (/ (- width nsteps) nsteps)))
10865 (org-odd-levels-only nil)
10866 (n 0)
10867 (total (1+ (length prefix))))
10868 (setq maxwidth (max maxwidth 10))
10869 (concat prefix
10870 (if prefix (or separator "/"))
10871 (mapconcat
10872 (lambda (h)
10873 (setq n (1+ n))
10874 (if (and (= n nsteps) (< maxwidth 10000))
10875 (setq maxwidth (- total-width total)))
10876 (if (< (length h) maxwidth)
10877 (progn (setq total (+ total (length h) 1)) h)
10878 (setq h (substring h 0 (- maxwidth 2))
10879 total (+ total maxwidth 1))
10880 (if (string-match "[ \t]+\\'" h)
10881 (setq h (substring h 0 (match-beginning 0))))
10882 (setq h (concat h "..")))
10883 (org-add-props h nil 'face
10884 (nth (% (1- n) org-n-level-faces)
10885 org-level-faces))
10887 path (or separator "/"))))))
10889 (defun org-display-outline-path (&optional file current separator just-return-string)
10890 "Display the current outline path in the echo area.
10892 If FILE is non-nil, prepend the output with the file name.
10893 If CURRENT is non-nil, append the current heading to the output.
10894 SEPARATOR is passed through to `org-format-outline-path'. It separates
10895 the different parts of the path and defaults to \"/\".
10896 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10897 (interactive "P")
10898 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10899 (case-fold-search nil)
10900 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10901 res)
10902 (if current (setq path (append path
10903 (save-excursion
10904 (org-back-to-heading t)
10905 (if (looking-at org-complex-heading-regexp)
10906 (list (match-string 4)))))))
10907 (setq res
10908 (org-format-outline-path
10909 path
10910 (1- (frame-width))
10911 (and file bfn (concat (file-name-nondirectory bfn) separator))
10912 separator))
10913 (if just-return-string
10914 (org-no-properties res)
10915 (message "%s" res))))
10917 (defvar org-refile-history nil
10918 "History for refiling operations.")
10920 (defvar org-after-refile-insert-hook nil
10921 "Hook run after `org-refile' has inserted its stuff at the new location.
10922 Note that this is still *before* the stuff will be removed from
10923 the *old* location.")
10925 (defvar org-capture-last-stored-marker)
10926 (defvar org-refile-keep nil
10927 "Non-nil means `org-refile' will copy instead of refile.")
10929 (defun org-copy ()
10930 "Like `org-refile', but copy."
10931 (interactive)
10932 (let ((org-refile-keep t))
10933 (funcall 'org-refile nil nil nil "Copy")))
10935 (defun org-refile (&optional goto default-buffer rfloc msg)
10936 "Move the entry or entries at point to another heading.
10937 The list of target headings is compiled using the information in
10938 `org-refile-targets', which see.
10940 At the target location, the entry is filed as a subitem of the target
10941 heading. Depending on `org-reverse-note-order', the new subitem will
10942 either be the first or the last subitem.
10944 If there is an active region, all entries in that region will be moved.
10945 However, the region must fulfill the requirement that the first heading
10946 is the first one sets the top-level of the moved text - at most siblings
10947 below it are allowed.
10949 With prefix arg GOTO, the command will only visit the target location
10950 and not actually move anything.
10952 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10953 go to the location where the last refiling operation has put the subtree.
10954 With a prefix argument of `2', refile to the running clock.
10956 RFLOC can be a refile location obtained in a different way.
10958 MSG is a string to replace \"Refile\" in the default prompt with
10959 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10961 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10963 If you are using target caching (see `org-refile-use-cache'),
10964 you have to clear the target cache in order to find new targets.
10965 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10966 prefix argument (`C-u C-u C-u C-c C-w')."
10968 (interactive "P")
10969 (if (member goto '(0 (64)))
10970 (org-refile-cache-clear)
10971 (let* ((actionmsg (or msg "Refile"))
10972 (cbuf (current-buffer))
10973 (regionp (org-region-active-p))
10974 (region-start (and regionp (region-beginning)))
10975 (region-end (and regionp (region-end)))
10976 (region-length (and regionp (- region-end region-start)))
10977 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10978 pos it nbuf file re level reversed)
10979 (setq last-command nil)
10980 (when regionp
10981 (goto-char region-start)
10982 (or (bolp) (goto-char (point-at-bol)))
10983 (setq region-start (point))
10984 (unless (or (org-kill-is-subtree-p
10985 (buffer-substring region-start region-end))
10986 (prog1 org-refile-active-region-within-subtree
10987 (org-toggle-heading)))
10988 (error "The region is not a (sequence of) subtree(s)")))
10989 (if (equal goto '(16))
10990 (org-refile-goto-last-stored)
10991 (when (or
10992 (and (equal goto 2)
10993 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10994 (prog1
10995 (setq it (list (or org-clock-heading "running clock")
10996 (buffer-file-name
10997 (marker-buffer org-clock-hd-marker))
10999 (marker-position org-clock-hd-marker)))
11000 (setq goto nil)))
11001 (setq it (or rfloc
11002 (let (heading-text)
11003 (save-excursion
11004 (unless goto
11005 (org-back-to-heading t)
11006 (setq heading-text
11007 (nth 4 (org-heading-components))))
11009 (org-refile-get-location
11010 (cond (goto "Goto")
11011 (regionp (concat actionmsg " region to"))
11012 (t (concat actionmsg " subtree \""
11013 heading-text "\" to")))
11014 default-buffer
11015 (and (not (equal '(4) goto))
11016 org-refile-allow-creating-parent-nodes)
11017 goto))))))
11018 (setq file (nth 1 it)
11019 re (nth 2 it)
11020 pos (nth 3 it))
11021 (if (and (not goto)
11023 (equal (buffer-file-name) file)
11024 (if regionp
11025 (and (>= pos region-start)
11026 (<= pos region-end))
11027 (and (>= pos (point))
11028 (< pos (save-excursion
11029 (org-end-of-subtree t t))))))
11030 (error "Cannot refile to position inside the tree or region"))
11032 (setq nbuf (or (find-buffer-visiting file)
11033 (find-file-noselect file)))
11034 (if goto
11035 (progn
11036 (org-pop-to-buffer-same-window nbuf)
11037 (goto-char pos)
11038 (org-show-context 'org-goto))
11039 (if regionp
11040 (progn
11041 (org-kill-new (buffer-substring region-start region-end))
11042 (org-save-markers-in-region region-start region-end))
11043 (org-copy-subtree 1 nil t))
11044 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11045 (find-file-noselect file)))
11046 (setq reversed (org-notes-order-reversed-p))
11047 (save-excursion
11048 (save-restriction
11049 (widen)
11050 (if pos
11051 (progn
11052 (goto-char pos)
11053 (looking-at org-outline-regexp)
11054 (setq level (org-get-valid-level (funcall outline-level) 1))
11055 (goto-char
11056 (if reversed
11057 (or (outline-next-heading) (point-max))
11058 (or (save-excursion (org-get-next-sibling))
11059 (org-end-of-subtree t t)
11060 (point-max)))))
11061 (setq level 1)
11062 (if (not reversed)
11063 (goto-char (point-max))
11064 (goto-char (point-min))
11065 (or (outline-next-heading) (goto-char (point-max)))))
11066 (if (not (bolp)) (newline))
11067 (org-paste-subtree level)
11068 (when org-log-refile
11069 (org-add-log-setup 'refile nil nil 'findpos
11070 org-log-refile)
11071 (unless (eq org-log-refile 'note)
11072 (save-excursion (org-add-log-note))))
11073 (and org-auto-align-tags
11074 (let ((org-loop-over-headlines-in-active-region nil))
11075 (org-set-tags nil t)))
11076 (with-demoted-errors
11077 (bookmark-set "org-refile-last-stored"))
11078 ;; If we are refiling for capture, make sure that the
11079 ;; last-capture pointers point here
11080 (when (org-bound-and-true-p org-refile-for-capture)
11081 (with-demoted-errors
11082 (bookmark-set "org-capture-last-stored-marker"))
11083 (move-marker org-capture-last-stored-marker (point)))
11084 (if (fboundp 'deactivate-mark) (deactivate-mark))
11085 (run-hooks 'org-after-refile-insert-hook))))
11086 (unless org-refile-keep
11087 (if regionp
11088 (delete-region (point) (+ (point) region-length))
11089 (org-cut-subtree)))
11090 (when (featurep 'org-inlinetask)
11091 (org-inlinetask-remove-END-maybe))
11092 (setq org-markers-to-move nil)
11093 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11095 (defun org-refile-goto-last-stored ()
11096 "Go to the location where the last refile was stored."
11097 (interactive)
11098 (bookmark-jump "org-refile-last-stored")
11099 (message "This is the location of the last refile"))
11101 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11102 no-exclude)
11103 "Prompt the user for a refile location, using PROMPT.
11104 PROMPT should not be suffixed with a colon and a space, because
11105 this function appends the default value from
11106 `org-refile-history' automatically, if that is not empty.
11107 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11108 this is used for the GOTO interface."
11109 (let ((org-refile-targets org-refile-targets)
11110 (org-refile-use-outline-path org-refile-use-outline-path)
11111 excluded-entries)
11112 (when (and (derived-mode-p 'org-mode)
11113 (not org-refile-use-cache)
11114 (not no-exclude))
11115 (org-map-tree
11116 (lambda()
11117 (setq excluded-entries
11118 (append excluded-entries (list (org-get-heading t t)))))))
11119 (setq org-refile-target-table
11120 (org-refile-get-targets default-buffer excluded-entries)))
11121 (unless org-refile-target-table
11122 (error "No refile targets"))
11123 (let* ((cbuf (current-buffer))
11124 (partial-completion-mode nil)
11125 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11126 (cfunc (if (and org-refile-use-outline-path
11127 org-outline-path-complete-in-steps)
11128 'org-olpath-completing-read
11129 'org-icompleting-read))
11130 (extra (if org-refile-use-outline-path "/" ""))
11131 (cbnex (concat (buffer-name) extra))
11132 (filename (and cfn (expand-file-name cfn)))
11133 (tbl (mapcar
11134 (lambda (x)
11135 (if (and (not (member org-refile-use-outline-path
11136 '(file full-file-path)))
11137 (not (equal filename (nth 1 x))))
11138 (cons (concat (car x) extra " ("
11139 (file-name-nondirectory (nth 1 x)) ")")
11140 (cdr x))
11141 (cons (concat (car x) extra) (cdr x))))
11142 org-refile-target-table))
11143 (completion-ignore-case t)
11144 cdef
11145 (prompt (concat prompt
11146 (or (and (car org-refile-history)
11147 (concat " (default " (car org-refile-history) ")"))
11148 (and (assoc cbnex tbl) (setq cdef cbnex)
11149 (concat " (default " cbnex ")"))) ": "))
11150 pa answ parent-target child parent old-hist)
11151 (setq old-hist org-refile-history)
11152 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11153 nil 'org-refile-history (or cdef (car org-refile-history))))
11154 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11155 (org-refile-check-position pa)
11156 (if pa
11157 (progn
11158 (when (or (not org-refile-history)
11159 (not (eq old-hist org-refile-history))
11160 (not (equal (car pa) (car org-refile-history))))
11161 (setq org-refile-history
11162 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11163 org-refile-history
11164 (cdr org-refile-history))))
11165 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11166 (pop org-refile-history)))
11168 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11169 (progn
11170 (setq parent (match-string 1 answ)
11171 child (match-string 2 answ))
11172 (setq parent-target (or (assoc parent tbl)
11173 (assoc (concat parent "/") tbl)))
11174 (when (and parent-target
11175 (or (eq new-nodes t)
11176 (and (eq new-nodes 'confirm)
11177 (y-or-n-p (format "Create new node \"%s\"? "
11178 child)))))
11179 (org-refile-new-child parent-target child)))
11180 (error "Invalid target location")))))
11182 (declare-function org-string-nw-p "org-macs" (s))
11183 (defun org-refile-check-position (refile-pointer)
11184 "Check if the refile pointer matches the headline to which it points."
11185 (let* ((file (nth 1 refile-pointer))
11186 (re (nth 2 refile-pointer))
11187 (pos (nth 3 refile-pointer))
11188 buffer)
11189 (if (and (not (markerp pos)) (not file))
11190 (error "Please save the buffer to a file before refiling")
11191 (when (org-string-nw-p re)
11192 (setq buffer (if (markerp pos)
11193 (marker-buffer pos)
11194 (or (find-buffer-visiting file)
11195 (find-file-noselect file))))
11196 (with-current-buffer buffer
11197 (save-excursion
11198 (save-restriction
11199 (widen)
11200 (goto-char pos)
11201 (beginning-of-line 1)
11202 (unless (org-looking-at-p re)
11203 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11205 (defun org-refile-new-child (parent-target child)
11206 "Use refile target PARENT-TARGET to add new CHILD below it."
11207 (unless parent-target
11208 (error "Cannot find parent for new node"))
11209 (let ((file (nth 1 parent-target))
11210 (pos (nth 3 parent-target))
11211 level)
11212 (with-current-buffer (or (find-buffer-visiting file)
11213 (find-file-noselect file))
11214 (save-excursion
11215 (save-restriction
11216 (widen)
11217 (if pos
11218 (goto-char pos)
11219 (goto-char (point-max))
11220 (if (not (bolp)) (newline)))
11221 (when (looking-at org-outline-regexp)
11222 (setq level (funcall outline-level))
11223 (org-end-of-subtree t t))
11224 (org-back-over-empty-lines)
11225 (insert "\n" (make-string
11226 (if pos (org-get-valid-level level 1) 1) ?*)
11227 " " child "\n")
11228 (beginning-of-line 0)
11229 (list (concat (car parent-target) "/" child) file "" (point)))))))
11231 (defun org-olpath-completing-read (prompt collection &rest args)
11232 "Read an outline path like a file name."
11233 (let ((thetable collection)
11234 (org-completion-use-ido nil) ; does not work with ido.
11235 (org-completion-use-iswitchb nil)) ; or iswitchb
11236 (apply
11237 'org-icompleting-read prompt
11238 (lambda (string predicate &optional flag)
11239 (let (rtn r f (l (length string)))
11240 (cond
11241 ((eq flag nil)
11242 ;; try completion
11243 (try-completion string thetable))
11244 ((eq flag t)
11245 ;; all-completions
11246 (setq rtn (all-completions string thetable predicate))
11247 (mapcar
11248 (lambda (x)
11249 (setq r (substring x l))
11250 (if (string-match " ([^)]*)$" x)
11251 (setq f (match-string 0 x))
11252 (setq f ""))
11253 (if (string-match "/" r)
11254 (concat string (substring r 0 (match-end 0)) f)
11256 rtn))
11257 ((eq flag 'lambda)
11258 ;; exact match?
11259 (assoc string thetable)))))
11260 args)))
11262 ;;;; Dynamic blocks
11264 (defun org-find-dblock (name)
11265 "Find the first dynamic block with name NAME in the buffer.
11266 If not found, stay at current position and return nil."
11267 (let ((case-fold-search t) pos)
11268 (save-excursion
11269 (goto-char (point-min))
11270 (setq pos (and (re-search-forward
11271 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11272 (match-beginning 0))))
11273 (if pos (goto-char pos))
11274 pos))
11276 (defconst org-dblock-start-re
11277 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11278 "Matches the start line of a dynamic block, with parameters.")
11280 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11281 "Matches the end of a dynamic block.")
11283 (defun org-create-dblock (plist)
11284 "Create a dynamic block section, with parameters taken from PLIST.
11285 PLIST must contain a :name entry which is used as name of the block."
11286 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11287 (end-of-line 1)
11288 (newline))
11289 (let ((col (current-column))
11290 (name (plist-get plist :name)))
11291 (insert "#+BEGIN: " name)
11292 (while plist
11293 (if (eq (car plist) :name)
11294 (setq plist (cddr plist))
11295 (insert " " (prin1-to-string (pop plist)))))
11296 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11297 (beginning-of-line -2)))
11299 (defun org-prepare-dblock ()
11300 "Prepare dynamic block for refresh.
11301 This empties the block, puts the cursor at the insert position and returns
11302 the property list including an extra property :name with the block name."
11303 (unless (looking-at org-dblock-start-re)
11304 (error "Not at a dynamic block"))
11305 (let* ((begdel (1+ (match-end 0)))
11306 (name (org-no-properties (match-string 1)))
11307 (params (append (list :name name)
11308 (read (concat "(" (match-string 3) ")")))))
11309 (save-excursion
11310 (beginning-of-line 1)
11311 (skip-chars-forward " \t")
11312 (setq params (plist-put params :indentation-column (current-column))))
11313 (unless (re-search-forward org-dblock-end-re nil t)
11314 (error "Dynamic block not terminated"))
11315 (setq params
11316 (append params
11317 (list :content (buffer-substring
11318 begdel (match-beginning 0)))))
11319 (delete-region begdel (match-beginning 0))
11320 (goto-char begdel)
11321 (open-line 1)
11322 params))
11324 (defun org-map-dblocks (&optional command)
11325 "Apply COMMAND to all dynamic blocks in the current buffer.
11326 If COMMAND is not given, use `org-update-dblock'."
11327 (let ((cmd (or command 'org-update-dblock)))
11328 (save-excursion
11329 (goto-char (point-min))
11330 (while (re-search-forward org-dblock-start-re nil t)
11331 (goto-char (match-beginning 0))
11332 (save-excursion
11333 (condition-case nil
11334 (funcall cmd)
11335 (error (message "Error during update of dynamic block"))))
11336 (unless (re-search-forward org-dblock-end-re nil t)
11337 (error "Dynamic block not terminated"))))))
11339 (defun org-dblock-update (&optional arg)
11340 "User command for updating dynamic blocks.
11341 Update the dynamic block at point. With prefix ARG, update all dynamic
11342 blocks in the buffer."
11343 (interactive "P")
11344 (if arg
11345 (org-update-all-dblocks)
11346 (or (looking-at org-dblock-start-re)
11347 (org-beginning-of-dblock))
11348 (org-update-dblock)))
11350 (defun org-update-dblock ()
11351 "Update the dynamic block at point.
11352 This means to empty the block, parse for parameters and then call
11353 the correct writing function."
11354 (interactive)
11355 (save-window-excursion
11356 (let* ((pos (point))
11357 (line (org-current-line))
11358 (params (org-prepare-dblock))
11359 (name (plist-get params :name))
11360 (indent (plist-get params :indentation-column))
11361 (cmd (intern (concat "org-dblock-write:" name))))
11362 (message "Updating dynamic block `%s' at line %d..." name line)
11363 (funcall cmd params)
11364 (message "Updating dynamic block `%s' at line %d...done" name line)
11365 (goto-char pos)
11366 (when (and indent (> indent 0))
11367 (setq indent (make-string indent ?\ ))
11368 (save-excursion
11369 (org-beginning-of-dblock)
11370 (forward-line 1)
11371 (while (not (looking-at org-dblock-end-re))
11372 (insert indent)
11373 (beginning-of-line 2))
11374 (when (looking-at org-dblock-end-re)
11375 (and (looking-at "[ \t]+")
11376 (replace-match ""))
11377 (insert indent)))))))
11379 (defun org-beginning-of-dblock ()
11380 "Find the beginning of the dynamic block at point.
11381 Error if there is no such block at point."
11382 (let ((pos (point))
11383 beg)
11384 (end-of-line 1)
11385 (if (and (re-search-backward org-dblock-start-re nil t)
11386 (setq beg (match-beginning 0))
11387 (re-search-forward org-dblock-end-re nil t)
11388 (> (match-end 0) pos))
11389 (goto-char beg)
11390 (goto-char pos)
11391 (error "Not in a dynamic block"))))
11393 (defun org-update-all-dblocks ()
11394 "Update all dynamic blocks in the buffer.
11395 This function can be used in a hook."
11396 (interactive)
11397 (when (derived-mode-p 'org-mode)
11398 (org-map-dblocks 'org-update-dblock)))
11401 ;;;; Completion
11403 (defconst org-additional-option-like-keywords
11404 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11405 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11406 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11407 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11408 "BEGIN:" "END:"
11409 "ORGTBL" "TBLFM:" "TBLNAME:"
11410 "BEGIN_EXAMPLE" "END_EXAMPLE"
11411 "BEGIN_VERBATIM" "END_VERBATIM"
11412 "BEGIN_QUOTE" "END_QUOTE"
11413 "BEGIN_VERSE" "END_VERSE"
11414 "BEGIN_CENTER" "END_CENTER"
11415 "BEGIN_SRC" "END_SRC"
11416 "BEGIN_RESULT" "END_RESULT"
11417 "BEGIN_lstlisting" "END_lstlisting"
11418 "NAME:" "RESULTS:"
11419 "HEADER:" "HEADERS:"
11420 "COLUMNS:" "PROPERTY:"
11421 "CAPTION:" "LABEL:"
11422 "SETUPFILE:"
11423 "INCLUDE:" "INDEX:"
11424 "BIND:"
11425 "MACRO:"))
11427 (defconst org-options-keywords
11428 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11429 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11430 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11431 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11432 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11433 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11434 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11436 (defconst org-additional-option-like-keywords-for-flyspell
11437 (delete-dups
11438 (split-string
11439 (mapconcat (lambda(k)
11440 (replace-regexp-in-string
11441 "_\\|:" " "
11442 (concat k " " (downcase k) " " (upcase k))))
11443 (append org-options-keywords org-additional-option-like-keywords)
11444 " ")
11445 " +" t)))
11447 (defcustom org-structure-template-alist
11449 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11450 "<src lang=\"?\">\n\n</src>")
11451 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11452 "<example>\n?\n</example>")
11453 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11454 "<quote>\n?\n</quote>")
11455 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11456 "<verse>\n?\n</verse>")
11457 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11458 "<center>\n?\n</center>")
11459 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11460 "<literal style=\"latex\">\n?\n</literal>")
11461 ("L" "#+LaTeX: "
11462 "<literal style=\"latex\">?</literal>")
11463 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11464 "<literal style=\"html\">\n?\n</literal>")
11465 ("H" "#+HTML: "
11466 "<literal style=\"html\">?</literal>")
11467 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11468 ("A" "#+ASCII: ")
11469 ("i" "#+INDEX: ?"
11470 "#+INDEX: ?")
11471 ("I" "#+INCLUDE: %file ?"
11472 "<include file=%file markup=\"?\">")
11474 "Structure completion elements.
11475 This is a list of abbreviation keys and values. The value gets inserted
11476 if you type `<' followed by the key and then press the completion key,
11477 usually `M-TAB'. %file will be replaced by a file name after prompting
11478 for the file using completion. The cursor will be placed at the position
11479 of the `?` in the template.
11480 There are two templates for each key, the first uses the original Org syntax,
11481 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11482 the default when the /org-mtags.el/ module has been loaded. See also the
11483 variable `org-mtags-prefer-muse-templates'."
11484 :group 'org-completion
11485 :type '(repeat
11486 (string :tag "Key")
11487 (string :tag "Template")
11488 (string :tag "Muse Template")))
11490 (defun org-try-structure-completion ()
11491 "Try to complete a structure template before point.
11492 This looks for strings like \"<e\" on an otherwise empty line and
11493 expands them."
11494 (let ((l (buffer-substring (point-at-bol) (point)))
11496 (when (and (looking-at "[ \t]*$")
11497 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11498 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11499 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11500 (match-beginning 1)) a)
11501 t)))
11503 (defun org-complete-expand-structure-template (start cell)
11504 "Expand a structure template."
11505 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11506 (rpl (nth (if musep 2 1) cell))
11507 (ind ""))
11508 (delete-region start (point))
11509 (when (string-match "\\`#\\+" rpl)
11510 (cond
11511 ((bolp))
11512 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11513 (setq ind (buffer-substring (point-at-bol) (point))))
11514 (t (newline))))
11515 (setq start (point))
11516 (if (string-match "%file" rpl)
11517 (setq rpl (replace-match
11518 (concat
11519 "\""
11520 (save-match-data
11521 (abbreviate-file-name (read-file-name "Include file: ")))
11522 "\"")
11523 t t rpl)))
11524 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11525 (concat "\n" ind)))
11526 (insert rpl)
11527 (if (re-search-backward "\\?" start t) (delete-char 1))))
11529 ;;;; TODO, DEADLINE, Comments
11531 (defun org-toggle-comment ()
11532 "Change the COMMENT state of an entry."
11533 (interactive)
11534 (save-excursion
11535 (org-back-to-heading)
11536 (let (case-fold-search)
11537 (cond
11538 ((looking-at (format org-heading-keyword-regexp-format
11539 org-comment-string))
11540 (goto-char (match-end 1))
11541 (looking-at (concat " +" org-comment-string))
11542 (replace-match "" t t)
11543 (when (eolp) (insert " ")))
11544 ((looking-at org-outline-regexp)
11545 (goto-char (match-end 0))
11546 (insert org-comment-string " "))))))
11548 (defvar org-last-todo-state-is-todo nil
11549 "This is non-nil when the last TODO state change led to a TODO state.
11550 If the last change removed the TODO tag or switched to DONE, then
11551 this is nil.")
11553 (defvar org-setting-tags nil) ; dynamically skipped
11555 (defvar org-todo-setup-filter-hook nil
11556 "Hook for functions that pre-filter todo specs.
11557 Each function takes a todo spec and returns either nil or the spec
11558 transformed into canonical form." )
11560 (defvar org-todo-get-default-hook nil
11561 "Hook for functions that get a default item for todo.
11562 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11563 nil or a string to be used for the todo mark." )
11565 (defvar org-agenda-headline-snapshot-before-repeat)
11567 (defun org-current-effective-time ()
11568 "Return current time adjusted for `org-extend-today-until' variable."
11569 (let* ((ct (org-current-time))
11570 (dct (decode-time ct))
11571 (ct1
11572 (cond
11573 (org-use-last-clock-out-time-as-effective-time
11574 (or (org-clock-get-last-clock-out-time) ct))
11575 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11576 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11577 (t ct))))
11578 ct1))
11580 (defun org-todo-yesterday (&optional arg)
11581 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11582 (interactive "P")
11583 (if (eq major-mode 'org-agenda-mode)
11584 (apply 'org-agenda-todo-yesterday arg)
11585 (let* ((hour (third (decode-time
11586 (org-current-time))))
11587 (org-extend-today-until (1+ hour)))
11588 (org-todo arg))))
11590 (defvar org-block-entry-blocking ""
11591 "First entry preventing the TODO state change.")
11593 (defun org-todo (&optional arg)
11594 "Change the TODO state of an item.
11595 The state of an item is given by a keyword at the start of the heading,
11596 like
11597 *** TODO Write paper
11598 *** DONE Call mom
11600 The different keywords are specified in the variable `org-todo-keywords'.
11601 By default the available states are \"TODO\" and \"DONE\".
11602 So for this example: when the item starts with TODO, it is changed to DONE.
11603 When it starts with DONE, the DONE is removed. And when neither TODO nor
11604 DONE are present, add TODO at the beginning of the heading.
11606 With \\[universal-argument] prefix arg, use completion to determine the new \
11607 state.
11608 With numeric prefix arg, switch to that state.
11609 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11610 keywords (nextset).
11611 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11612 With a numeric prefix arg of 0, inhibit note taking for the change.
11614 For calling through lisp, arg is also interpreted in the following way:
11615 'none -> empty state
11616 \"\"(empty string) -> switch to empty state
11617 'done -> switch to DONE
11618 'nextset -> switch to the next set of keywords
11619 'previousset -> switch to the previous set of keywords
11620 \"WAITING\" -> switch to the specified keyword, but only if it
11621 really is a member of `org-todo-keywords'."
11622 (interactive "P")
11623 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11624 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11625 'region-start-level 'region))
11626 org-loop-over-headlines-in-active-region)
11627 (org-map-entries
11628 `(org-todo ,arg)
11629 org-loop-over-headlines-in-active-region
11630 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11631 (if (equal arg '(16)) (setq arg 'nextset))
11632 (let ((org-blocker-hook org-blocker-hook)
11633 (case-fold-search nil))
11634 (when (equal arg '(64))
11635 (setq arg nil org-blocker-hook nil))
11636 (when (and org-blocker-hook
11637 (or org-inhibit-blocking
11638 (org-entry-get nil "NOBLOCKING")))
11639 (setq org-blocker-hook nil))
11640 (save-excursion
11641 (catch 'exit
11642 (org-back-to-heading t)
11643 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11644 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11645 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11646 (let* ((match-data (match-data))
11647 (startpos (point-at-bol))
11648 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11649 (org-log-done org-log-done)
11650 (org-log-repeat org-log-repeat)
11651 (org-todo-log-states org-todo-log-states)
11652 (org-inhibit-logging
11653 (if (equal arg 0)
11654 (progn (setq arg nil) 'note) org-inhibit-logging))
11655 (this (match-string 1))
11656 (hl-pos (match-beginning 0))
11657 (head (org-get-todo-sequence-head this))
11658 (ass (assoc head org-todo-kwd-alist))
11659 (interpret (nth 1 ass))
11660 (done-word (nth 3 ass))
11661 (final-done-word (nth 4 ass))
11662 (org-last-state (or this ""))
11663 (completion-ignore-case t)
11664 (member (member this org-todo-keywords-1))
11665 (tail (cdr member))
11666 (org-state (cond
11667 ((and org-todo-key-trigger
11668 (or (and (equal arg '(4))
11669 (eq org-use-fast-todo-selection 'prefix))
11670 (and (not arg) org-use-fast-todo-selection
11671 (not (eq org-use-fast-todo-selection
11672 'prefix)))))
11673 ;; Use fast selection
11674 (org-fast-todo-selection))
11675 ((and (equal arg '(4))
11676 (or (not org-use-fast-todo-selection)
11677 (not org-todo-key-trigger)))
11678 ;; Read a state with completion
11679 (org-icompleting-read
11680 "State: " (mapcar (lambda(x) (list x))
11681 org-todo-keywords-1)
11682 nil t))
11683 ((eq arg 'right)
11684 (if this
11685 (if tail (car tail) nil)
11686 (car org-todo-keywords-1)))
11687 ((eq arg 'left)
11688 (if (equal member org-todo-keywords-1)
11690 (if this
11691 (nth (- (length org-todo-keywords-1)
11692 (length tail) 2)
11693 org-todo-keywords-1)
11694 (org-last org-todo-keywords-1))))
11695 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11696 (setq arg nil))) ; hack to fall back to cycling
11697 (arg
11698 ;; user or caller requests a specific state
11699 (cond
11700 ((equal arg "") nil)
11701 ((eq arg 'none) nil)
11702 ((eq arg 'done) (or done-word (car org-done-keywords)))
11703 ((eq arg 'nextset)
11704 (or (car (cdr (member head org-todo-heads)))
11705 (car org-todo-heads)))
11706 ((eq arg 'previousset)
11707 (let ((org-todo-heads (reverse org-todo-heads)))
11708 (or (car (cdr (member head org-todo-heads)))
11709 (car org-todo-heads))))
11710 ((car (member arg org-todo-keywords-1)))
11711 ((stringp arg)
11712 (error "State `%s' not valid in this file" arg))
11713 ((nth (1- (prefix-numeric-value arg))
11714 org-todo-keywords-1))))
11715 ((null member) (or head (car org-todo-keywords-1)))
11716 ((equal this final-done-word) nil) ;; -> make empty
11717 ((null tail) nil) ;; -> first entry
11718 ((memq interpret '(type priority))
11719 (if (eq this-command last-command)
11720 (car tail)
11721 (if (> (length tail) 0)
11722 (or done-word (car org-done-keywords))
11723 nil)))
11725 (car tail))))
11726 (org-state (or
11727 (run-hook-with-args-until-success
11728 'org-todo-get-default-hook org-state org-last-state)
11729 org-state))
11730 (next (if org-state (concat " " org-state " ") " "))
11731 (change-plist (list :type 'todo-state-change :from this :to org-state
11732 :position startpos))
11733 dolog now-done-p)
11734 (when org-blocker-hook
11735 (setq org-last-todo-state-is-todo
11736 (not (member this org-done-keywords)))
11737 (unless (save-excursion
11738 (save-match-data
11739 (org-with-wide-buffer
11740 (run-hook-with-args-until-failure
11741 'org-blocker-hook change-plist))))
11742 (if (org-called-interactively-p 'interactive)
11743 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11744 this org-state org-block-entry-blocking)
11745 ;; fail silently
11746 (message "TODO state change from %s to %s blocked (by \"%s\")"
11747 this org-state org-block-entry-blocking)
11748 (throw 'exit nil))))
11749 (store-match-data match-data)
11750 (replace-match next t t)
11751 (unless (pos-visible-in-window-p hl-pos)
11752 (message "TODO state changed to %s" (org-trim next)))
11753 (unless head
11754 (setq head (org-get-todo-sequence-head org-state)
11755 ass (assoc head org-todo-kwd-alist)
11756 interpret (nth 1 ass)
11757 done-word (nth 3 ass)
11758 final-done-word (nth 4 ass)))
11759 (when (memq arg '(nextset previousset))
11760 (message "Keyword-Set %d/%d: %s"
11761 (- (length org-todo-sets) -1
11762 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11763 (length org-todo-sets)
11764 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11765 (setq org-last-todo-state-is-todo
11766 (not (member org-state org-done-keywords)))
11767 (setq now-done-p (and (member org-state org-done-keywords)
11768 (not (member this org-done-keywords))))
11769 (and logging (org-local-logging logging))
11770 (when (and (or org-todo-log-states org-log-done)
11771 (not (eq org-inhibit-logging t))
11772 (not (memq arg '(nextset previousset))))
11773 ;; we need to look at recording a time and note
11774 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11775 (nth 2 (assoc this org-todo-log-states))))
11776 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11777 (setq dolog 'time))
11778 (when (and org-state
11779 (member org-state org-not-done-keywords)
11780 (not (member this org-not-done-keywords)))
11781 ;; This is now a todo state and was not one before
11782 ;; If there was a CLOSED time stamp, get rid of it.
11783 (org-add-planning-info nil nil 'closed))
11784 (when (and now-done-p org-log-done)
11785 ;; It is now done, and it was not done before
11786 (org-add-planning-info 'closed (org-current-effective-time))
11787 (if (and (not dolog) (eq 'note org-log-done))
11788 (org-add-log-setup 'done org-state this 'findpos 'note)))
11789 (when (and org-state dolog)
11790 ;; This is a non-nil state, and we need to log it
11791 (org-add-log-setup 'state org-state this 'findpos dolog)))
11792 ;; Fixup tag positioning
11793 (org-todo-trigger-tag-changes org-state)
11794 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11795 (when org-provide-todo-statistics
11796 (org-update-parent-todo-statistics))
11797 (run-hooks 'org-after-todo-state-change-hook)
11798 (if (and arg (not (member org-state org-done-keywords)))
11799 (setq head (org-get-todo-sequence-head org-state)))
11800 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11801 ;; Do we need to trigger a repeat?
11802 (when now-done-p
11803 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11804 ;; This is for the agenda, take a snapshot of the headline.
11805 (save-match-data
11806 (setq org-agenda-headline-snapshot-before-repeat
11807 (org-get-heading))))
11808 (org-auto-repeat-maybe org-state))
11809 ;; Fixup cursor location if close to the keyword
11810 (if (and (outline-on-heading-p)
11811 (not (bolp))
11812 (save-excursion (beginning-of-line 1)
11813 (looking-at org-todo-line-regexp))
11814 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11815 (progn
11816 (goto-char (or (match-end 2) (match-end 1)))
11817 (and (looking-at " ") (just-one-space))))
11818 (when org-trigger-hook
11819 (save-excursion
11820 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11822 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11823 "Block turning an entry into a TODO, using the hierarchy.
11824 This checks whether the current task should be blocked from state
11825 changes. Such blocking occurs when:
11827 1. The task has children which are not all in a completed state.
11829 2. A task has a parent with the property :ORDERED:, and there
11830 are siblings prior to the current task with incomplete
11831 status.
11833 3. The parent of the task is blocked because it has siblings that should
11834 be done first, or is child of a block grandparent TODO entry."
11836 (if (not org-enforce-todo-dependencies)
11837 t ; if locally turned off don't block
11838 (catch 'dont-block
11839 ;; If this is not a todo state change, or if this entry is already DONE,
11840 ;; do not block
11841 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11842 (member (plist-get change-plist :from)
11843 (cons 'done org-done-keywords))
11844 (member (plist-get change-plist :to)
11845 (cons 'todo org-not-done-keywords))
11846 (not (plist-get change-plist :to)))
11847 (throw 'dont-block t))
11848 ;; If this task has children, and any are undone, it's blocked
11849 (save-excursion
11850 (org-back-to-heading t)
11851 (let ((this-level (funcall outline-level)))
11852 (outline-next-heading)
11853 (let ((child-level (funcall outline-level)))
11854 (while (and (not (eobp))
11855 (> child-level this-level))
11856 ;; this todo has children, check whether they are all
11857 ;; completed
11858 (if (and (not (org-entry-is-done-p))
11859 (org-entry-is-todo-p))
11860 (progn (setq org-block-entry-blocking (org-get-heading))
11861 (throw 'dont-block nil)))
11862 (outline-next-heading)
11863 (setq child-level (funcall outline-level))))))
11864 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11865 ;; any previous siblings are undone, it's blocked
11866 (save-excursion
11867 (org-back-to-heading t)
11868 (let* ((pos (point))
11869 (parent-pos (and (org-up-heading-safe) (point))))
11870 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11871 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11872 (forward-line 1)
11873 (re-search-forward org-not-done-heading-regexp pos t))
11874 (setq org-block-entry-blocking (match-string 0))
11875 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11876 ;; Search further up the hierarchy, to see if an ancestor is blocked
11877 (while t
11878 (goto-char parent-pos)
11879 (if (not (looking-at org-not-done-heading-regexp))
11880 (throw 'dont-block t)) ; do not block, parent is not a TODO
11881 (setq pos (point))
11882 (setq parent-pos (and (org-up-heading-safe) (point)))
11883 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11884 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11885 (forward-line 1)
11886 (re-search-forward org-not-done-heading-regexp pos t)
11887 (setq org-block-entry-blocking (org-get-heading)))
11888 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11890 (defcustom org-track-ordered-property-with-tag nil
11891 "Should the ORDERED property also be shown as a tag?
11892 The ORDERED property decides if an entry should require subtasks to be
11893 completed in sequence. Since a property is not very visible, setting
11894 this option means that toggling the ORDERED property with the command
11895 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11896 not relevant for the behavior, but it makes things more visible.
11898 Note that toggling the tag with tags commands will not change the property
11899 and therefore not influence behavior!
11901 This can be t, meaning the tag ORDERED should be used, It can also be a
11902 string to select a different tag for this task."
11903 :group 'org-todo
11904 :type '(choice
11905 (const :tag "No tracking" nil)
11906 (const :tag "Track with ORDERED tag" t)
11907 (string :tag "Use other tag")))
11909 (defun org-toggle-ordered-property ()
11910 "Toggle the ORDERED property of the current entry.
11911 For better visibility, you can track the value of this property with a tag.
11912 See variable `org-track-ordered-property-with-tag'."
11913 (interactive)
11914 (let* ((t1 org-track-ordered-property-with-tag)
11915 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11916 (save-excursion
11917 (org-back-to-heading)
11918 (if (org-entry-get nil "ORDERED")
11919 (progn
11920 (org-delete-property "ORDERED")
11921 (and tag (org-toggle-tag tag 'off))
11922 (message "Subtasks can be completed in arbitrary order"))
11923 (org-entry-put nil "ORDERED" "t")
11924 (and tag (org-toggle-tag tag 'on))
11925 (message "Subtasks must be completed in sequence")))))
11927 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11928 (defun org-block-todo-from-checkboxes (change-plist)
11929 "Block turning an entry into a TODO, using checkboxes.
11930 This checks whether the current task should be blocked from state
11931 changes because there are unchecked boxes in this entry."
11932 (if (not org-enforce-todo-checkbox-dependencies)
11933 t ; if locally turned off don't block
11934 (catch 'dont-block
11935 ;; If this is not a todo state change, or if this entry is already DONE,
11936 ;; do not block
11937 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11938 (member (plist-get change-plist :from)
11939 (cons 'done org-done-keywords))
11940 (member (plist-get change-plist :to)
11941 (cons 'todo org-not-done-keywords))
11942 (not (plist-get change-plist :to)))
11943 (throw 'dont-block t))
11944 ;; If this task has checkboxes that are not checked, it's blocked
11945 (save-excursion
11946 (org-back-to-heading t)
11947 (let ((beg (point)) end)
11948 (outline-next-heading)
11949 (setq end (point))
11950 (goto-char beg)
11951 (if (org-list-search-forward
11952 (concat (org-item-beginning-re)
11953 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11954 "\\[[- ]\\]")
11955 end t)
11956 (progn
11957 (if (boundp 'org-blocked-by-checkboxes)
11958 (setq org-blocked-by-checkboxes t))
11959 (throw 'dont-block nil)))))
11960 t))) ; do not block
11962 (defun org-entry-blocked-p ()
11963 "Is the current entry blocked?"
11964 (if (org-entry-get nil "NOBLOCKING")
11965 nil ;; Never block this entry
11966 (not
11967 (run-hook-with-args-until-failure
11968 'org-blocker-hook
11969 (list :type 'todo-state-change
11970 :position (point)
11971 :from 'todo
11972 :to 'done)))))
11974 (defun org-update-statistics-cookies (all)
11975 "Update the statistics cookie, either from TODO or from checkboxes.
11976 This should be called with the cursor in a line with a statistics cookie."
11977 (interactive "P")
11978 (if all
11979 (progn
11980 (org-update-checkbox-count 'all)
11981 (org-map-entries 'org-update-parent-todo-statistics))
11982 (if (not (org-at-heading-p))
11983 (org-update-checkbox-count)
11984 (let ((pos (move-marker (make-marker) (point)))
11985 end l1 l2)
11986 (ignore-errors (org-back-to-heading t))
11987 (if (not (org-at-heading-p))
11988 (org-update-checkbox-count)
11989 (setq l1 (org-outline-level))
11990 (setq end (save-excursion
11991 (outline-next-heading)
11992 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11993 (point)))
11994 (if (and (save-excursion
11995 (re-search-forward
11996 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11997 (not (save-excursion (re-search-forward
11998 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11999 (org-update-checkbox-count)
12000 (if (and l2 (> l2 l1))
12001 (progn
12002 (goto-char end)
12003 (org-update-parent-todo-statistics))
12004 (goto-char pos)
12005 (beginning-of-line 1)
12006 (while (re-search-forward
12007 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12008 (point-at-eol) t)
12009 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12010 (goto-char pos)
12011 (move-marker pos nil)))))
12013 (defvar org-entry-property-inherited-from) ;; defined below
12014 (defun org-update-parent-todo-statistics ()
12015 "Update any statistics cookie in the parent of the current headline.
12016 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12017 the entire subtree and this will travel up the hierarchy and update
12018 statistics everywhere."
12019 (let* ((prop (save-excursion (org-up-heading-safe)
12020 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12021 (recursive (or (not org-hierarchical-todo-statistics)
12022 (and prop (string-match "\\<recursive\\>" prop))))
12023 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12025 (first t)
12026 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12027 level ltoggle l1 new ndel
12028 (cnt-all 0) (cnt-done 0) is-percent kwd
12029 checkbox-beg ov ovs ove cookie-present)
12030 (catch 'exit
12031 (save-excursion
12032 (beginning-of-line 1)
12033 (setq ltoggle (funcall outline-level))
12034 ;; Three situations are to consider:
12036 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12037 ;; to the top-level ancestor on the headline;
12039 ;; 2. If parent has "recursive" property, repeat up to the
12040 ;; headline setting that property, taking inheritance into
12041 ;; account;
12043 ;; 3. Else, move up to direct parent and proceed only once.
12044 (while (and (setq level (org-up-heading-safe))
12045 (or recursive first)
12046 (>= (point) lim))
12047 (setq first nil cookie-present nil)
12048 (unless (and level
12049 (not (string-match
12050 "\\<checkbox\\>"
12051 (downcase (or (org-entry-get nil "COOKIE_DATA")
12052 "")))))
12053 (throw 'exit nil))
12054 (while (re-search-forward box-re (point-at-eol) t)
12055 (setq cnt-all 0 cnt-done 0 cookie-present t)
12056 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12057 (save-match-data
12058 (unless (outline-next-heading) (throw 'exit nil))
12059 (while (and (looking-at org-complex-heading-regexp)
12060 (> (setq l1 (length (match-string 1))) level))
12061 (setq kwd (and (or recursive (= l1 ltoggle))
12062 (match-string 2)))
12063 (if (or (eq org-provide-todo-statistics 'all-headlines)
12064 (and (listp org-provide-todo-statistics)
12065 (or (member kwd org-provide-todo-statistics)
12066 (member kwd org-done-keywords))))
12067 (setq cnt-all (1+ cnt-all))
12068 (if (eq org-provide-todo-statistics t)
12069 (and kwd (setq cnt-all (1+ cnt-all)))))
12070 (and (member kwd org-done-keywords)
12071 (setq cnt-done (1+ cnt-done)))
12072 (outline-next-heading)))
12073 (setq new
12074 (if is-percent
12075 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12076 (format "[%d/%d]" cnt-done cnt-all))
12077 ndel (- (match-end 0) checkbox-beg))
12078 ;; handle overlays when updating cookie from column view
12079 (when (setq ov (car (overlays-at checkbox-beg)))
12080 (setq ovs (overlay-start ov) ove (overlay-end ov))
12081 (delete-overlay ov))
12082 (goto-char checkbox-beg)
12083 (insert new)
12084 (delete-region (point) (+ (point) ndel))
12085 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12086 (when ov (move-overlay ov ovs ove)))
12087 (when cookie-present
12088 (run-hook-with-args 'org-after-todo-statistics-hook
12089 cnt-done (- cnt-all cnt-done))))))
12090 (run-hooks 'org-todo-statistics-hook)))
12092 (defvar org-after-todo-statistics-hook nil
12093 "Hook that is called after a TODO statistics cookie has been updated.
12094 Each function is called with two arguments: the number of not-done entries
12095 and the number of done entries.
12097 For example, the following function, when added to this hook, will switch
12098 an entry to DONE when all children are done, and back to TODO when new
12099 entries are set to a TODO status. Note that this hook is only called
12100 when there is a statistics cookie in the headline!
12102 (defun org-summary-todo (n-done n-not-done)
12103 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12104 (let (org-log-done org-log-states) ; turn off logging
12105 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12108 (defvar org-todo-statistics-hook nil
12109 "Hook that is run whenever Org thinks TODO statistics should be updated.
12110 This hook runs even if there is no statistics cookie present, in which case
12111 `org-after-todo-statistics-hook' would not run.")
12113 (defun org-todo-trigger-tag-changes (state)
12114 "Apply the changes defined in `org-todo-state-tags-triggers'."
12115 (let ((l org-todo-state-tags-triggers)
12116 changes)
12117 (when (or (not state) (equal state ""))
12118 (setq changes (append changes (cdr (assoc "" l)))))
12119 (when (and (stringp state) (> (length state) 0))
12120 (setq changes (append changes (cdr (assoc state l)))))
12121 (when (member state org-not-done-keywords)
12122 (setq changes (append changes (cdr (assoc 'todo l)))))
12123 (when (member state org-done-keywords)
12124 (setq changes (append changes (cdr (assoc 'done l)))))
12125 (dolist (c changes)
12126 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12128 (defun org-local-logging (value)
12129 "Get logging settings from a property VALUE."
12130 (let* (words w a)
12131 ;; directly set the variables, they are already local.
12132 (setq org-log-done nil
12133 org-log-repeat nil
12134 org-todo-log-states nil)
12135 (setq words (org-split-string value))
12136 (while (setq w (pop words))
12137 (cond
12138 ((setq a (assoc w org-startup-options))
12139 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12140 (set (nth 1 a) (nth 2 a))))
12141 ((setq a (org-extract-log-state-settings w))
12142 (and (member (car a) org-todo-keywords-1)
12143 (push a org-todo-log-states)))))))
12145 (defun org-get-todo-sequence-head (kwd)
12146 "Return the head of the TODO sequence to which KWD belongs.
12147 If KWD is not set, check if there is a text property remembering the
12148 right sequence."
12149 (let (p)
12150 (cond
12151 ((not kwd)
12152 (or (get-text-property (point-at-bol) 'org-todo-head)
12153 (progn
12154 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12155 nil (point-at-eol)))
12156 (get-text-property p 'org-todo-head))))
12157 ((not (member kwd org-todo-keywords-1))
12158 (car org-todo-keywords-1))
12159 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12161 (defun org-fast-todo-selection ()
12162 "Fast TODO keyword selection with single keys.
12163 Returns the new TODO keyword, or nil if no state change should occur."
12164 (let* ((fulltable org-todo-key-alist)
12165 (done-keywords org-done-keywords) ;; needed for the faces.
12166 (maxlen (apply 'max (mapcar
12167 (lambda (x)
12168 (if (stringp (car x)) (string-width (car x)) 0))
12169 fulltable)))
12170 (expert nil)
12171 (fwidth (+ maxlen 3 1 3))
12172 (ncol (/ (- (window-width) 4) fwidth))
12173 tg cnt e c tbl
12174 groups ingroup)
12175 (save-excursion
12176 (save-window-excursion
12177 (if expert
12178 (set-buffer (get-buffer-create " *Org todo*"))
12179 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12180 (erase-buffer)
12181 (org-set-local 'org-done-keywords done-keywords)
12182 (setq tbl fulltable cnt 0)
12183 (while (setq e (pop tbl))
12184 (cond
12185 ((equal e '(:startgroup))
12186 (push '() groups) (setq ingroup t)
12187 (when (not (= cnt 0))
12188 (setq cnt 0)
12189 (insert "\n"))
12190 (insert "{ "))
12191 ((equal e '(:endgroup))
12192 (setq ingroup nil cnt 0)
12193 (insert "}\n"))
12194 ((equal e '(:newline))
12195 (when (not (= cnt 0))
12196 (setq cnt 0)
12197 (insert "\n")
12198 (setq e (car tbl))
12199 (while (equal (car tbl) '(:newline))
12200 (insert "\n")
12201 (setq tbl (cdr tbl)))))
12203 (setq tg (car e) c (cdr e))
12204 (if ingroup (push tg (car groups)))
12205 (setq tg (org-add-props tg nil 'face
12206 (org-get-todo-face tg)))
12207 (if (and (= cnt 0) (not ingroup)) (insert " "))
12208 (insert "[" c "] " tg (make-string
12209 (- fwidth 4 (length tg)) ?\ ))
12210 (when (= (setq cnt (1+ cnt)) ncol)
12211 (insert "\n")
12212 (if ingroup (insert " "))
12213 (setq cnt 0)))))
12214 (insert "\n")
12215 (goto-char (point-min))
12216 (if (not expert) (org-fit-window-to-buffer))
12217 (message "[a-z..]:Set [SPC]:clear")
12218 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12219 (cond
12220 ((or (= c ?\C-g)
12221 (and (= c ?q) (not (rassoc c fulltable))))
12222 (setq quit-flag t))
12223 ((= c ?\ ) nil)
12224 ((setq e (rassoc c fulltable) tg (car e))
12226 (t (setq quit-flag t)))))))
12228 (defun org-entry-is-todo-p ()
12229 (member (org-get-todo-state) org-not-done-keywords))
12231 (defun org-entry-is-done-p ()
12232 (member (org-get-todo-state) org-done-keywords))
12234 (defun org-get-todo-state ()
12235 (save-excursion
12236 (org-back-to-heading t)
12237 (and (looking-at org-todo-line-regexp)
12238 (match-end 2)
12239 (match-string 2))))
12241 (defun org-at-date-range-p (&optional inactive-ok)
12242 "Is the cursor inside a date range?"
12243 (interactive)
12244 (save-excursion
12245 (catch 'exit
12246 (let ((pos (point)))
12247 (skip-chars-backward "^[<\r\n")
12248 (skip-chars-backward "<[")
12249 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12250 (>= (match-end 0) pos)
12251 (throw 'exit t))
12252 (skip-chars-backward "^<[\r\n")
12253 (skip-chars-backward "<[")
12254 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12255 (>= (match-end 0) pos)
12256 (throw 'exit t)))
12257 nil)))
12259 (defun org-get-repeat (&optional tagline)
12260 "Check if there is a deadline/schedule with repeater in this entry."
12261 (save-match-data
12262 (save-excursion
12263 (org-back-to-heading t)
12264 (and (re-search-forward (if tagline
12265 (concat tagline "\\s-*" org-repeat-re)
12266 org-repeat-re)
12267 (org-entry-end-position) t)
12268 (match-string-no-properties 1)))))
12270 (defvar org-last-changed-timestamp)
12271 (defvar org-last-inserted-timestamp)
12272 (defvar org-log-post-message)
12273 (defvar org-log-note-purpose)
12274 (defvar org-log-note-how)
12275 (defvar org-log-note-extra)
12276 (defun org-auto-repeat-maybe (done-word)
12277 "Check if the current headline contains a repeated deadline/schedule.
12278 If yes, set TODO state back to what it was and change the base date
12279 of repeating deadline/scheduled time stamps to new date.
12280 This function is run automatically after each state change to a DONE state."
12281 ;; last-state is dynamically scoped into this function
12282 (let* ((repeat (org-get-repeat))
12283 (aa (assoc org-last-state org-todo-kwd-alist))
12284 (interpret (nth 1 aa))
12285 (head (nth 2 aa))
12286 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12287 (msg "Entry repeats: ")
12288 (org-log-done nil)
12289 (org-todo-log-states nil)
12290 re type n what ts time to-state)
12291 (when repeat
12292 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12293 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12294 org-todo-repeat-to-state))
12295 (unless (and to-state (member to-state org-todo-keywords-1))
12296 (setq to-state (if (eq interpret 'type) org-last-state head)))
12297 (org-todo to-state)
12298 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12299 (org-entry-put nil "LAST_REPEAT" (format-time-string
12300 (org-time-stamp-format t t))))
12301 (when org-log-repeat
12302 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12303 (memq 'org-add-log-note post-command-hook))
12304 ;; OK, we are already setup for some record
12305 (if (eq org-log-repeat 'note)
12306 ;; make sure we take a note, not only a time stamp
12307 (setq org-log-note-how 'note))
12308 ;; Set up for taking a record
12309 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12310 org-last-state
12311 'findpos org-log-repeat)))
12312 (org-back-to-heading t)
12313 (org-add-planning-info nil nil 'closed)
12314 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12315 org-deadline-time-regexp "\\)\\|\\("
12316 org-ts-regexp "\\)"))
12317 (while (re-search-forward
12318 re (save-excursion (outline-next-heading) (point)) t)
12319 (setq type (if (match-end 1) org-scheduled-string
12320 (if (match-end 3) org-deadline-string "Plain:"))
12321 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12322 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12323 (setq n (string-to-number (match-string 2 ts))
12324 what (match-string 3 ts))
12325 (if (equal what "w") (setq n (* n 7) what "d"))
12326 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12327 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12328 ;; Preparation, see if we need to modify the start date for the change
12329 (when (match-end 1)
12330 (setq time (save-match-data (org-time-string-to-time ts)))
12331 (cond
12332 ((equal (match-string 1 ts) ".")
12333 ;; Shift starting date to today
12334 (org-timestamp-change
12335 (- (org-today) (time-to-days time))
12336 'day))
12337 ((equal (match-string 1 ts) "+")
12338 (let ((nshiftmax 10) (nshift 0))
12339 (while (or (= nshift 0)
12340 (<= (time-to-days time)
12341 (time-to-days (current-time))))
12342 (when (= (incf nshift) nshiftmax)
12343 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12344 (error "Abort")))
12345 (org-timestamp-change n (cdr (assoc what whata)))
12346 (org-at-timestamp-p t)
12347 (setq ts (match-string 1))
12348 (setq time (save-match-data (org-time-string-to-time ts)))))
12349 (org-timestamp-change (- n) (cdr (assoc what whata)))
12350 ;; rematch, so that we have everything in place for the real shift
12351 (org-at-timestamp-p t)
12352 (setq ts (match-string 1))
12353 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12354 (org-timestamp-change n (cdr (assoc what whata)))
12355 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12356 (setq org-log-post-message msg)
12357 (message "%s" msg))))
12359 (defun org-show-todo-tree (arg)
12360 "Make a compact tree which shows all headlines marked with TODO.
12361 The tree will show the lines where the regexp matches, and all higher
12362 headlines above the match.
12363 With a \\[universal-argument] prefix, prompt for a regexp to match.
12364 With a numeric prefix N, construct a sparse tree for the Nth element
12365 of `org-todo-keywords-1'."
12366 (interactive "P")
12367 (let ((case-fold-search nil)
12368 (kwd-re
12369 (cond ((null arg) org-not-done-regexp)
12370 ((equal arg '(4))
12371 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12372 (mapcar 'list org-todo-keywords-1))))
12373 (concat "\\("
12374 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12375 "\\)\\>")))
12376 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12377 (regexp-quote (nth (1- (prefix-numeric-value arg))
12378 org-todo-keywords-1)))
12379 (t (error "Invalid prefix argument: %s" arg)))))
12380 (message "%d TODO entries found"
12381 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12383 (defun org-deadline (&optional remove time)
12384 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12385 With argument REMOVE, remove any deadline from the item.
12386 With argument TIME, set the deadline at the corresponding date. TIME
12387 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12388 (interactive "P")
12389 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12390 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12391 'region-start-level 'region))
12392 org-loop-over-headlines-in-active-region)
12393 (org-map-entries
12394 `(org-deadline ',remove ,time)
12395 org-loop-over-headlines-in-active-region
12396 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12397 (let* ((old-date (org-entry-get nil "DEADLINE"))
12398 (repeater (and old-date
12399 (string-match
12400 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12401 old-date)
12402 (match-string 1 old-date))))
12403 (if remove
12404 (progn
12405 (when (and old-date org-log-redeadline)
12406 (org-add-log-setup 'deldeadline nil old-date 'findpos
12407 org-log-redeadline))
12408 (org-remove-timestamp-with-keyword org-deadline-string)
12409 (message "Item no longer has a deadline."))
12410 (org-add-planning-info 'deadline time 'closed)
12411 (when (and old-date org-log-redeadline
12412 (not (equal old-date
12413 (substring org-last-inserted-timestamp 1 -1))))
12414 (org-add-log-setup 'redeadline nil old-date 'findpos
12415 org-log-redeadline))
12416 (when repeater
12417 (save-excursion
12418 (org-back-to-heading t)
12419 (when (re-search-forward (concat org-deadline-string " "
12420 org-last-inserted-timestamp)
12421 (save-excursion
12422 (outline-next-heading) (point)) t)
12423 (goto-char (1- (match-end 0)))
12424 (insert " " repeater)
12425 (setq org-last-inserted-timestamp
12426 (concat (substring org-last-inserted-timestamp 0 -1)
12427 " " repeater
12428 (substring org-last-inserted-timestamp -1))))))
12429 (message "Deadline on %s" org-last-inserted-timestamp)))))
12431 (defun org-schedule (&optional remove time)
12432 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12433 With argument REMOVE, remove any scheduling date from the item.
12434 With argument TIME, scheduled at the corresponding date. TIME can
12435 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12436 (interactive "P")
12437 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12438 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12439 'region-start-level 'region))
12440 org-loop-over-headlines-in-active-region)
12441 (org-map-entries
12442 `(org-schedule ',remove ,time)
12443 org-loop-over-headlines-in-active-region
12444 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12445 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12446 (repeater (and old-date
12447 (string-match
12448 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12449 old-date)
12450 (match-string 1 old-date))))
12451 (if remove
12452 (progn
12453 (when (and old-date org-log-reschedule)
12454 (org-add-log-setup 'delschedule nil old-date 'findpos
12455 org-log-reschedule))
12456 (org-remove-timestamp-with-keyword org-scheduled-string)
12457 (message "Item is no longer scheduled."))
12458 (org-add-planning-info 'scheduled time 'closed)
12459 (when (and old-date org-log-reschedule
12460 (not (equal old-date
12461 (substring org-last-inserted-timestamp 1 -1))))
12462 (org-add-log-setup 'reschedule nil old-date 'findpos
12463 org-log-reschedule))
12464 (when repeater
12465 (save-excursion
12466 (org-back-to-heading t)
12467 (when (re-search-forward (concat org-scheduled-string " "
12468 org-last-inserted-timestamp)
12469 (save-excursion
12470 (outline-next-heading) (point)) t)
12471 (goto-char (1- (match-end 0)))
12472 (insert " " repeater)
12473 (setq org-last-inserted-timestamp
12474 (concat (substring org-last-inserted-timestamp 0 -1)
12475 " " repeater
12476 (substring org-last-inserted-timestamp -1))))))
12477 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12479 (defun org-get-scheduled-time (pom &optional inherit)
12480 "Get the scheduled time as a time tuple, of a format suitable
12481 for calling org-schedule with, or if there is no scheduling,
12482 returns nil."
12483 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12484 (when time
12485 (apply 'encode-time (org-parse-time-string time)))))
12487 (defun org-get-deadline-time (pom &optional inherit)
12488 "Get the deadline as a time tuple, of a format suitable for
12489 calling org-deadline with, or if there is no scheduling, returns
12490 nil."
12491 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12492 (when time
12493 (apply 'encode-time (org-parse-time-string time)))))
12495 (defun org-remove-timestamp-with-keyword (keyword)
12496 "Remove all time stamps with KEYWORD in the current entry."
12497 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12498 beg)
12499 (save-excursion
12500 (org-back-to-heading t)
12501 (setq beg (point))
12502 (outline-next-heading)
12503 (while (re-search-backward re beg t)
12504 (replace-match "")
12505 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12506 (equal (char-before) ?\ ))
12507 (backward-delete-char 1)
12508 (if (string-match "^[ \t]*$" (buffer-substring
12509 (point-at-bol) (point-at-eol)))
12510 (delete-region (point-at-bol)
12511 (min (point-max) (1+ (point-at-eol))))))))))
12513 (defun org-add-planning-info (what &optional time &rest remove)
12514 "Insert new timestamp with keyword in the line directly after the headline.
12515 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12516 If non is given, the user is prompted for a date.
12517 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12518 be removed."
12519 (interactive)
12520 (let (org-time-was-given org-end-time-was-given ts
12521 end default-time default-input)
12523 (catch 'exit
12524 (when (and (memq what '(scheduled deadline))
12525 (or (not time)
12526 (and (stringp time)
12527 (string-match "^[-+]+[0-9]" time))))
12528 ;; Try to get a default date/time from existing timestamp
12529 (save-excursion
12530 (org-back-to-heading t)
12531 (setq end (save-excursion (outline-next-heading) (point)))
12532 (when (re-search-forward (if (eq what 'scheduled)
12533 org-scheduled-time-regexp
12534 org-deadline-time-regexp)
12535 end t)
12536 (setq ts (match-string 1)
12537 default-time
12538 (apply 'encode-time (org-parse-time-string ts))
12539 default-input (and ts (org-get-compact-tod ts))))))
12540 (when what
12541 (setq time
12542 (if (stringp time)
12543 ;; This is a string (relative or absolute), set proper date
12544 (apply 'encode-time
12545 (org-read-date-analyze
12546 time default-time (decode-time default-time)))
12547 ;; If necessary, get the time from the user
12548 (or time (org-read-date nil 'to-time nil nil
12549 default-time default-input)))))
12551 (when (and org-insert-labeled-timestamps-at-point
12552 (member what '(scheduled deadline)))
12553 (insert
12554 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12555 (org-insert-time-stamp time org-time-was-given
12556 nil nil nil (list org-end-time-was-given))
12557 (setq what nil))
12558 (save-excursion
12559 (save-restriction
12560 (let (col list elt ts buffer-invisibility-spec)
12561 (org-back-to-heading t)
12562 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12563 (goto-char (match-end 1))
12564 (setq col (current-column))
12565 (goto-char (match-end 0))
12566 (if (eobp) (insert "\n") (forward-char 1))
12567 (when (and (not what)
12568 (not (looking-at
12569 (concat "[ \t]*"
12570 org-keyword-time-not-clock-regexp))))
12571 ;; Nothing to add, nothing to remove...... :-)
12572 (throw 'exit nil))
12573 (if (and (not (looking-at org-outline-regexp))
12574 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12575 "[^\r\n]*"))
12576 (not (equal (match-string 1) org-clock-string)))
12577 (narrow-to-region (match-beginning 0) (match-end 0))
12578 (insert-before-markers "\n")
12579 (backward-char 1)
12580 (narrow-to-region (point) (point))
12581 (and org-adapt-indentation (org-indent-to-column col)))
12582 ;; Check if we have to remove something.
12583 (setq list (cons what remove))
12584 (while list
12585 (setq elt (pop list))
12586 (when (or (and (eq elt 'scheduled)
12587 (re-search-forward org-scheduled-time-regexp nil t))
12588 (and (eq elt 'deadline)
12589 (re-search-forward org-deadline-time-regexp nil t))
12590 (and (eq elt 'closed)
12591 (re-search-forward org-closed-time-regexp nil t)))
12592 (replace-match "")
12593 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12594 (and (looking-at "[ \t]+") (replace-match ""))
12595 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12596 (when what
12597 (insert
12598 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12599 (cond ((eq what 'scheduled) org-scheduled-string)
12600 ((eq what 'deadline) org-deadline-string)
12601 ((eq what 'closed) org-closed-string))
12602 " ")
12603 (setq ts (org-insert-time-stamp
12604 time
12605 (or org-time-was-given
12606 (and (eq what 'closed) org-log-done-with-time))
12607 (eq what 'closed)
12608 nil nil (list org-end-time-was-given)))
12609 (insert
12610 (if (not (or (bolp) (eq (char-before) ?\ )
12611 (memq (char-after) '(32 10))
12612 (eobp))) " " ""))
12613 (end-of-line 1))
12614 (goto-char (point-min))
12615 (widen)
12616 (if (and (looking-at "[ \t]*\n")
12617 (equal (char-before) ?\n))
12618 (delete-region (1- (point)) (point-at-eol)))
12619 ts))))))
12621 (defvar org-log-note-marker (make-marker))
12622 (defvar org-log-note-purpose nil)
12623 (defvar org-log-note-state nil)
12624 (defvar org-log-note-previous-state nil)
12625 (defvar org-log-note-how nil)
12626 (defvar org-log-note-extra nil)
12627 (defvar org-log-note-window-configuration nil)
12628 (defvar org-log-note-return-to (make-marker))
12629 (defvar org-log-note-effective-time nil
12630 "Remembered current time so that dynamically scoped
12631 `org-extend-today-until' affects tha timestamps in state change
12632 log")
12634 (defvar org-log-post-message nil
12635 "Message to be displayed after a log note has been stored.
12636 The auto-repeater uses this.")
12638 (defun org-add-note ()
12639 "Add a note to the current entry.
12640 This is done in the same way as adding a state change note."
12641 (interactive)
12642 (org-add-log-setup 'note nil nil 'findpos nil))
12644 (defvar org-property-end-re)
12645 (defun org-add-log-setup (&optional purpose state prev-state
12646 findpos how extra)
12647 "Set up the post command hook to take a note.
12648 If this is about to TODO state change, the new state is expected in STATE.
12649 When FINDPOS is non-nil, find the correct position for the note in
12650 the current entry. If not, assume that it can be inserted at point.
12651 HOW is an indicator what kind of note should be created.
12652 EXTRA is additional text that will be inserted into the notes buffer."
12653 (let* ((org-log-into-drawer (org-log-into-drawer))
12654 (drawer (cond ((stringp org-log-into-drawer)
12655 org-log-into-drawer)
12656 (org-log-into-drawer "LOGBOOK"))))
12657 (save-restriction
12658 (save-excursion
12659 (when findpos
12660 (org-back-to-heading t)
12661 (narrow-to-region (point) (save-excursion
12662 (outline-next-heading) (point)))
12663 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12664 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12665 "[^\r\n]*\\)?"))
12666 (goto-char (match-end 0))
12667 (cond
12668 (drawer
12669 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12670 nil t)
12671 (progn
12672 (goto-char (match-end 0))
12673 (or org-log-states-order-reversed
12674 (and (re-search-forward org-property-end-re nil t)
12675 (goto-char (1- (match-beginning 0))))))
12676 (insert "\n:" drawer ":\n:END:")
12677 (beginning-of-line 0)
12678 (org-indent-line)
12679 (beginning-of-line 2)
12680 (org-indent-line)
12681 (end-of-line 0)))
12682 ((and org-log-state-notes-insert-after-drawers
12683 (save-excursion
12684 (forward-line) (looking-at org-drawer-regexp)))
12685 (forward-line)
12686 (while (looking-at org-drawer-regexp)
12687 (goto-char (match-end 0))
12688 (re-search-forward org-property-end-re (point-max) t)
12689 (forward-line))
12690 (forward-line -1)))
12691 (unless org-log-states-order-reversed
12692 (and (= (char-after) ?\n) (forward-char 1))
12693 (org-skip-over-state-notes)
12694 (skip-chars-backward " \t\n\r")))
12695 (move-marker org-log-note-marker (point))
12696 (setq org-log-note-purpose purpose
12697 org-log-note-state state
12698 org-log-note-previous-state prev-state
12699 org-log-note-how how
12700 org-log-note-extra extra
12701 org-log-note-effective-time (org-current-effective-time))
12702 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12704 (defun org-skip-over-state-notes ()
12705 "Skip past the list of State notes in an entry."
12706 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12707 (when (ignore-errors (goto-char (org-in-item-p)))
12708 (let* ((struct (org-list-struct))
12709 (prevs (org-list-prevs-alist struct)))
12710 (while (looking-at "[ \t]*- State")
12711 (goto-char (or (org-list-get-next-item (point) struct prevs)
12712 (org-list-get-item-end (point) struct)))))))
12714 (defun org-add-log-note (&optional purpose)
12715 "Pop up a window for taking a note, and add this note later at point."
12716 (remove-hook 'post-command-hook 'org-add-log-note)
12717 (setq org-log-note-window-configuration (current-window-configuration))
12718 (delete-other-windows)
12719 (move-marker org-log-note-return-to (point))
12720 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12721 (goto-char org-log-note-marker)
12722 (org-switch-to-buffer-other-window "*Org Note*")
12723 (erase-buffer)
12724 (if (memq org-log-note-how '(time state))
12725 (let (current-prefix-arg) (org-store-log-note))
12726 (let ((org-inhibit-startup t)) (org-mode))
12727 (insert (format "# Insert note for %s.
12728 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12729 (cond
12730 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12731 ((eq org-log-note-purpose 'done) "closed todo item")
12732 ((eq org-log-note-purpose 'state)
12733 (format "state change from \"%s\" to \"%s\""
12734 (or org-log-note-previous-state "")
12735 (or org-log-note-state "")))
12736 ((eq org-log-note-purpose 'reschedule)
12737 "rescheduling")
12738 ((eq org-log-note-purpose 'delschedule)
12739 "no longer scheduled")
12740 ((eq org-log-note-purpose 'redeadline)
12741 "changing deadline")
12742 ((eq org-log-note-purpose 'deldeadline)
12743 "removing deadline")
12744 ((eq org-log-note-purpose 'refile)
12745 "refiling")
12746 ((eq org-log-note-purpose 'note)
12747 "this entry")
12748 (t (error "This should not happen")))))
12749 (if org-log-note-extra (insert org-log-note-extra))
12750 (org-set-local 'org-finish-function 'org-store-log-note)
12751 (run-hooks 'org-log-buffer-setup-hook)))
12753 (defvar org-note-abort nil) ; dynamically scoped
12754 (defun org-store-log-note ()
12755 "Finish taking a log note, and insert it to where it belongs."
12756 (let ((txt (buffer-string)))
12757 (kill-buffer (current-buffer))
12758 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12759 lines ind bul)
12760 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12761 (setq txt (replace-match "" t t txt)))
12762 (if (string-match "\\s-+\\'" txt)
12763 (setq txt (replace-match "" t t txt)))
12764 (setq lines (org-split-string txt "\n"))
12765 (when (and note (string-match "\\S-" note))
12766 (setq note
12767 (org-replace-escapes
12768 note
12769 (list (cons "%u" (user-login-name))
12770 (cons "%U" user-full-name)
12771 (cons "%t" (format-time-string
12772 (org-time-stamp-format 'long 'inactive)
12773 org-log-note-effective-time))
12774 (cons "%T" (format-time-string
12775 (org-time-stamp-format 'long nil)
12776 org-log-note-effective-time))
12777 (cons "%d" (format-time-string
12778 (org-time-stamp-format nil 'inactive)
12779 org-log-note-effective-time))
12780 (cons "%D" (format-time-string
12781 (org-time-stamp-format nil nil)
12782 org-log-note-effective-time))
12783 (cons "%s" (if org-log-note-state
12784 (concat "\"" org-log-note-state "\"")
12785 ""))
12786 (cons "%S" (if org-log-note-previous-state
12787 (concat "\"" org-log-note-previous-state "\"")
12788 "\"\"")))))
12789 (if lines (setq note (concat note " \\\\")))
12790 (push note lines))
12791 (when (or current-prefix-arg org-note-abort)
12792 (when org-log-into-drawer
12793 (org-remove-empty-drawer-at
12794 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12795 org-log-note-marker))
12796 (setq lines nil))
12797 (when lines
12798 (with-current-buffer (marker-buffer org-log-note-marker)
12799 (save-excursion
12800 (goto-char org-log-note-marker)
12801 (move-marker org-log-note-marker nil)
12802 (end-of-line 1)
12803 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12804 (setq ind (save-excursion
12805 (if (ignore-errors (goto-char (org-in-item-p)))
12806 (let ((struct (org-list-struct)))
12807 (org-list-get-ind
12808 (org-list-get-top-point struct) struct))
12809 (skip-chars-backward " \r\t\n")
12810 (cond
12811 ((and (org-at-heading-p)
12812 org-adapt-indentation)
12813 (1+ (org-current-level)))
12814 ((org-at-heading-p) 0)
12815 (t (org-get-indentation))))))
12816 (setq bul (org-list-bullet-string "-"))
12817 (org-indent-line-to ind)
12818 (insert bul (pop lines))
12819 (let ((ind-body (+ (length bul) ind)))
12820 (while lines
12821 (insert "\n")
12822 (org-indent-line-to ind-body)
12823 (insert (pop lines))))
12824 (message "Note stored")
12825 (org-back-to-heading t)
12826 (org-cycle-hide-drawers 'children))))))
12827 (set-window-configuration org-log-note-window-configuration)
12828 (with-current-buffer (marker-buffer org-log-note-return-to)
12829 (goto-char org-log-note-return-to))
12830 (move-marker org-log-note-return-to nil)
12831 (and org-log-post-message (message "%s" org-log-post-message)))
12833 (defun org-remove-empty-drawer-at (drawer pos)
12834 "Remove an empty drawer DRAWER at position POS.
12835 POS may also be a marker."
12836 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12837 (save-excursion
12838 (save-restriction
12839 (widen)
12840 (goto-char pos)
12841 (if (org-in-regexp
12842 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12843 (replace-match ""))))))
12845 (defvar org-ts-type nil)
12846 (defun org-sparse-tree (&optional arg type)
12847 "Create a sparse tree, prompt for the details.
12848 This command can create sparse trees. You first need to select the type
12849 of match used to create the tree:
12851 t Show all TODO entries.
12852 T Show entries with a specific TODO keyword.
12853 m Show entries selected by a tags/property match.
12854 p Enter a property name and its value (both with completion on existing
12855 names/values) and show entries with that property.
12856 r Show entries matching a regular expression (`/' can be used as well).
12857 b Show deadlines and scheduled items before a date.
12858 a Show deadlines and scheduled items after a date.
12859 d Show deadlines due within `org-deadline-warning-days'.
12860 D Show deadlines and scheduled items between a date range."
12861 (interactive "P")
12862 (let (ans kwd value ts-type)
12863 (setq type (or type org-sparse-tree-default-date-type))
12864 (setq org-ts-type type)
12865 (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"
12866 (cond ((eq type 'all) "all timestamps")
12867 ((eq type 'scheduled) "only scheduled")
12868 ((eq type 'deadline) "only deadline")
12869 ((eq type 'active) "only active timestamps")
12870 ((eq type 'inactive) "only inactive timestamps")
12871 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12872 (t "scheduled/deadline")))
12873 (setq ans (read-char-exclusive))
12874 (cond
12875 ((equal ans ?c)
12876 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12877 ((equal ans ?d)
12878 (call-interactively 'org-check-deadlines))
12879 ((equal ans ?b)
12880 (call-interactively 'org-check-before-date))
12881 ((equal ans ?a)
12882 (call-interactively 'org-check-after-date))
12883 ((equal ans ?D)
12884 (call-interactively 'org-check-dates-range))
12885 ((equal ans ?t)
12886 (call-interactively 'org-show-todo-tree))
12887 ((equal ans ?T)
12888 (org-show-todo-tree '(4)))
12889 ((member ans '(?T ?m))
12890 (call-interactively 'org-match-sparse-tree))
12891 ((member ans '(?p ?P))
12892 (setq kwd (org-icompleting-read "Property: "
12893 (mapcar 'list (org-buffer-property-keys))))
12894 (setq value (org-icompleting-read "Value: "
12895 (mapcar 'list (org-property-values kwd))))
12896 (unless (string-match "\\`{.*}\\'" value)
12897 (setq value (concat "\"" value "\"")))
12898 (org-match-sparse-tree arg (concat kwd "=" value)))
12899 ((member ans '(?r ?R ?/))
12900 (call-interactively 'org-occur))
12901 (t (error "No such sparse tree command \"%c\"" ans)))))
12903 (defvar org-occur-highlights nil
12904 "List of overlays used for occur matches.")
12905 (make-variable-buffer-local 'org-occur-highlights)
12906 (defvar org-occur-parameters nil
12907 "Parameters of the active org-occur calls.
12908 This is a list, each call to org-occur pushes as cons cell,
12909 containing the regular expression and the callback, onto the list.
12910 The list can contain several entries if `org-occur' has been called
12911 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12912 will only contain one set of parameters. When the highlights are
12913 removed (for example with `C-c C-c', or with the next edit (depending
12914 on `org-remove-highlights-with-change'), this variable is emptied
12915 as well.")
12916 (make-variable-buffer-local 'org-occur-parameters)
12918 (defun org-occur (regexp &optional keep-previous callback)
12919 "Make a compact tree which shows all matches of REGEXP.
12920 The tree will show the lines where the regexp matches, and all higher
12921 headlines above the match. It will also show the heading after the match,
12922 to make sure editing the matching entry is easy.
12923 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12924 call to `org-occur' will be kept, to allow stacking of calls to this
12925 command.
12926 If CALLBACK is non-nil, it is a function which is called to confirm
12927 that the match should indeed be shown."
12928 (interactive "sRegexp: \nP")
12929 (when (equal regexp "")
12930 (error "Regexp cannot be empty"))
12931 (unless keep-previous
12932 (org-remove-occur-highlights nil nil t))
12933 (push (cons regexp callback) org-occur-parameters)
12934 (let ((cnt 0))
12935 (save-excursion
12936 (goto-char (point-min))
12937 (if (or (not keep-previous) ; do not want to keep
12938 (not org-occur-highlights)) ; no previous matches
12939 ;; hide everything
12940 (org-overview))
12941 (while (re-search-forward regexp nil t)
12942 (when (or (not callback)
12943 (save-match-data (funcall callback)))
12944 (setq cnt (1+ cnt))
12945 (when org-highlight-sparse-tree-matches
12946 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12947 (org-show-context 'occur-tree))))
12948 (when org-remove-highlights-with-change
12949 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12950 nil 'local))
12951 (unless org-sparse-tree-open-archived-trees
12952 (org-hide-archived-subtrees (point-min) (point-max)))
12953 (run-hooks 'org-occur-hook)
12954 (if (org-called-interactively-p 'interactive)
12955 (message "%d match(es) for regexp %s" cnt regexp))
12956 cnt))
12958 (defun org-occur-next-match (&optional n reset)
12959 "Function for `next-error-function' to find sparse tree matches.
12960 N is the number of matches to move, when negative move backwards.
12961 RESET is entirely ignored - this function always goes back to the
12962 starting point when no match is found."
12963 (let* ((limit (if (< n 0) (point-min) (point-max)))
12964 (search-func (if (< n 0)
12965 'previous-single-char-property-change
12966 'next-single-char-property-change))
12967 (n (abs n))
12968 (pos (point))
12970 (catch 'exit
12971 (while (setq p1 (funcall search-func (point) 'org-type))
12972 (when (equal p1 limit)
12973 (goto-char pos)
12974 (error "No more matches"))
12975 (when (equal (get-char-property p1 'org-type) 'org-occur)
12976 (setq n (1- n))
12977 (when (= n 0)
12978 (goto-char p1)
12979 (throw 'exit (point))))
12980 (goto-char p1))
12981 (goto-char p1)
12982 (error "No more matches"))))
12984 (defun org-show-context (&optional key)
12985 "Make sure point and context are visible.
12986 How much context is shown depends upon the variables
12987 `org-show-hierarchy-above', `org-show-following-heading',
12988 `org-show-entry-below' and `org-show-siblings'."
12989 (let ((heading-p (org-at-heading-p t))
12990 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12991 (following-p (org-get-alist-option org-show-following-heading key))
12992 (entry-p (org-get-alist-option org-show-entry-below key))
12993 (siblings-p (org-get-alist-option org-show-siblings key)))
12994 (catch 'exit
12995 ;; Show heading or entry text
12996 (if (and heading-p (not entry-p))
12997 (org-flag-heading nil) ; only show the heading
12998 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12999 (org-show-hidden-entry))) ; show entire entry
13000 (when following-p
13001 ;; Show next sibling, or heading below text
13002 (save-excursion
13003 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13004 (org-flag-heading nil))))
13005 (when siblings-p (org-show-siblings))
13006 (when hierarchy-p
13007 ;; show all higher headings, possibly with siblings
13008 (save-excursion
13009 (while (and (condition-case nil
13010 (progn (org-up-heading-all 1) t)
13011 (error nil))
13012 (not (bobp)))
13013 (org-flag-heading nil)
13014 (when siblings-p (org-show-siblings))))))))
13016 (defvar org-reveal-start-hook nil
13017 "Hook run before revealing a location.")
13019 (defun org-reveal (&optional siblings)
13020 "Show current entry, hierarchy above it, and the following headline.
13021 This can be used to show a consistent set of context around locations
13022 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13023 not t for the search context.
13025 With optional argument SIBLINGS, on each level of the hierarchy all
13026 siblings are shown. This repairs the tree structure to what it would
13027 look like when opened with hierarchical calls to `org-cycle'.
13028 With double optional argument \\[universal-argument] \\[universal-argument], \
13029 go to the parent and show the
13030 entire tree."
13031 (interactive "P")
13032 (run-hooks 'org-reveal-start-hook)
13033 (let ((org-show-hierarchy-above t)
13034 (org-show-following-heading t)
13035 (org-show-siblings (if siblings t org-show-siblings)))
13036 (org-show-context nil))
13037 (when (equal siblings '(16))
13038 (save-excursion
13039 (when (org-up-heading-safe)
13040 (org-show-subtree)
13041 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13043 (defun org-highlight-new-match (beg end)
13044 "Highlight from BEG to END and mark the highlight is an occur headline."
13045 (let ((ov (make-overlay beg end)))
13046 (overlay-put ov 'face 'secondary-selection)
13047 (overlay-put ov 'org-type 'org-occur)
13048 (push ov org-occur-highlights)))
13050 (defun org-remove-occur-highlights (&optional beg end noremove)
13051 "Remove the occur highlights from the buffer.
13052 BEG and END are ignored. If NOREMOVE is nil, remove this function
13053 from the `before-change-functions' in the current buffer."
13054 (interactive)
13055 (unless org-inhibit-highlight-removal
13056 (mapc 'delete-overlay org-occur-highlights)
13057 (setq org-occur-highlights nil)
13058 (setq org-occur-parameters nil)
13059 (unless noremove
13060 (remove-hook 'before-change-functions
13061 'org-remove-occur-highlights 'local))))
13063 ;;;; Priorities
13065 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13066 "Regular expression matching the priority indicator.")
13068 (defvar org-remove-priority-next-time nil)
13070 (defun org-priority-up ()
13071 "Increase the priority of the current item."
13072 (interactive)
13073 (org-priority 'up))
13075 (defun org-priority-down ()
13076 "Decrease the priority of the current item."
13077 (interactive)
13078 (org-priority 'down))
13080 (defun org-priority (&optional action show)
13081 "Change the priority of an item.
13082 ACTION can be `set', `up', `down', or a character."
13083 (interactive "P")
13084 (if (equal action '(4))
13085 (org-show-priority)
13086 (unless org-enable-priority-commands
13087 (error "Priority commands are disabled"))
13088 (setq action (or action 'set))
13089 (let (current new news have remove)
13090 (save-excursion
13091 (org-back-to-heading t)
13092 (if (looking-at org-priority-regexp)
13093 (setq current (string-to-char (match-string 2))
13094 have t))
13095 (cond
13096 ((eq action 'remove)
13097 (setq remove t new ?\ ))
13098 ((or (eq action 'set)
13099 (if (featurep 'xemacs) (characterp action) (integerp action)))
13100 (if (not (eq action 'set))
13101 (setq new action)
13102 (message "Priority %c-%c, SPC to remove: "
13103 org-highest-priority org-lowest-priority)
13104 (save-match-data
13105 (setq new (read-char-exclusive))))
13106 (if (and (= (upcase org-highest-priority) org-highest-priority)
13107 (= (upcase org-lowest-priority) org-lowest-priority))
13108 (setq new (upcase new)))
13109 (cond ((equal new ?\ ) (setq remove t))
13110 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13111 (error "Priority must be between `%c' and `%c'"
13112 org-highest-priority org-lowest-priority))))
13113 ((eq action 'up)
13114 (setq new (if have
13115 (1- current) ; normal cycling
13116 ;; last priority was empty
13117 (if (eq last-command this-command)
13118 org-lowest-priority ; wrap around empty to lowest
13119 ;; default
13120 (if org-priority-start-cycle-with-default
13121 org-default-priority
13122 (1- org-default-priority))))))
13123 ((eq action 'down)
13124 (setq new (if have
13125 (1+ current) ; normal cycling
13126 ;; last priority was empty
13127 (if (eq last-command this-command)
13128 org-highest-priority ; wrap around empty to highest
13129 ;; default
13130 (if org-priority-start-cycle-with-default
13131 org-default-priority
13132 (1+ org-default-priority))))))
13133 (t (error "Invalid action")))
13134 (if (or (< (upcase new) org-highest-priority)
13135 (> (upcase new) org-lowest-priority))
13136 (if (and (memq action '(up down))
13137 (not have) (not (eq last-command this-command)))
13138 ;; `new' is from default priority
13139 (error
13140 "The default can not be set, see `org-default-priority' why")
13141 ;; normal cycling: `new' is beyond highest/lowest priority
13142 ;; and is wrapped around to the empty priority
13143 (setq remove t)))
13144 (setq news (format "%c" new))
13145 (if have
13146 (if remove
13147 (replace-match "" t t nil 1)
13148 (replace-match news t t nil 2))
13149 (if remove
13150 (error "No priority cookie found in line")
13151 (let ((case-fold-search nil))
13152 (looking-at org-todo-line-regexp))
13153 (if (match-end 2)
13154 (progn
13155 (goto-char (match-end 2))
13156 (insert " [#" news "]"))
13157 (goto-char (match-beginning 3))
13158 (insert "[#" news "] "))))
13159 (org-preserve-lc (org-set-tags nil 'align)))
13160 (if remove
13161 (message "Priority removed")
13162 (message "Priority of current item set to %s" news)))))
13164 (defun org-show-priority ()
13165 "Show the priority of the current item.
13166 This priority is composed of the main priority given with the [#A] cookies,
13167 and by additional input from the age of a schedules or deadline entry."
13168 (interactive)
13169 (let ((pri (if (eq major-mode 'org-agenda-mode)
13170 (org-get-at-bol 'priority)
13171 (save-excursion
13172 (save-match-data
13173 (beginning-of-line)
13174 (and (looking-at org-heading-regexp)
13175 (org-get-priority (match-string 0))))))))
13176 (message "Priority is %d" (if pri pri -1000))))
13178 (defun org-get-priority (s)
13179 "Find priority cookie and return priority."
13180 (if (functionp org-get-priority-function)
13181 (funcall org-get-priority-function)
13182 (save-match-data
13183 (if (not (string-match org-priority-regexp s))
13184 (* 1000 (- org-lowest-priority org-default-priority))
13185 (* 1000 (- org-lowest-priority
13186 (string-to-char (match-string 2 s))))))))
13188 ;;;; Tags
13190 (defvar org-agenda-archives-mode)
13191 (defvar org-map-continue-from nil
13192 "Position from where mapping should continue.
13193 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13195 (defvar org-scanner-tags nil
13196 "The current tag list while the tags scanner is running.")
13197 (defvar org-trust-scanner-tags nil
13198 "Should `org-get-tags-at' use the tags for the scanner.
13199 This is for internal dynamical scoping only.
13200 When this is non-nil, the function `org-get-tags-at' will return the value
13201 of `org-scanner-tags' instead of building the list by itself. This
13202 can lead to large speed-ups when the tags scanner is used in a file with
13203 many entries, and when the list of tags is retrieved, for example to
13204 obtain a list of properties. Building the tags list for each entry in such
13205 a file becomes an N^2 operation - but with this variable set, it scales
13206 as N.")
13208 (defun org-scan-tags (action matcher todo-only &optional start-level)
13209 "Scan headline tags with inheritance and produce output ACTION.
13211 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13212 or `agenda' to produce an entry list for an agenda view. It can also be
13213 a Lisp form or a function that should be called at each matched headline, in
13214 this case the return value is a list of all return values from these calls.
13216 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13217 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13218 only lines with a not-done TODO keyword are included in the output.
13219 This should be the same variable that was scoped into
13220 and set by `org-make-tags-matcher' when it constructed MATCHER.
13222 START-LEVEL can be a string with asterisks, reducing the scope to
13223 headlines matching this string."
13224 (require 'org-agenda)
13225 (let* ((re (concat "^"
13226 (if start-level
13227 ;; Get the correct level to match
13228 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13229 org-outline-regexp)
13230 " *\\(\\<\\("
13231 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13232 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13233 (props (list 'face 'default
13234 'done-face 'org-agenda-done
13235 'undone-face 'default
13236 'mouse-face 'highlight
13237 'org-not-done-regexp org-not-done-regexp
13238 'org-todo-regexp org-todo-regexp
13239 'org-complex-heading-regexp org-complex-heading-regexp
13240 'help-echo
13241 (format "mouse-2 or RET jump to org file %s"
13242 (abbreviate-file-name
13243 (or (buffer-file-name (buffer-base-buffer))
13244 (buffer-name (buffer-base-buffer)))))))
13245 (case-fold-search nil)
13246 (org-map-continue-from nil)
13247 lspos tags tags-list
13248 (tags-alist (list (cons 0 org-file-tags)))
13249 (llast 0) rtn rtn1 level category i txt
13250 todo marker entry priority)
13251 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13252 (setq action (list 'lambda nil action)))
13253 (save-excursion
13254 (goto-char (point-min))
13255 (when (eq action 'sparse-tree)
13256 (org-overview)
13257 (org-remove-occur-highlights))
13258 (while (re-search-forward re nil t)
13259 (setq org-map-continue-from nil)
13260 (catch :skip
13261 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13262 tags (if (match-end 4) (org-match-string-no-properties 4)))
13263 (goto-char (setq lspos (match-beginning 0)))
13264 (setq level (org-reduced-level (org-outline-level))
13265 category (org-get-category))
13266 (setq i llast llast level)
13267 ;; remove tag lists from same and sublevels
13268 (while (>= i level)
13269 (when (setq entry (assoc i tags-alist))
13270 (setq tags-alist (delete entry tags-alist)))
13271 (setq i (1- i)))
13272 ;; add the next tags
13273 (when tags
13274 (setq tags (org-split-string tags ":")
13275 tags-alist
13276 (cons (cons level tags) tags-alist)))
13277 ;; compile tags for current headline
13278 (setq tags-list
13279 (if org-use-tag-inheritance
13280 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13281 tags)
13282 org-scanner-tags tags-list)
13283 (when org-use-tag-inheritance
13284 (setcdr (car tags-alist)
13285 (mapcar (lambda (x)
13286 (setq x (copy-sequence x))
13287 (org-add-prop-inherited x))
13288 (cdar tags-alist))))
13289 (when (and tags org-use-tag-inheritance
13290 (or (not (eq t org-use-tag-inheritance))
13291 org-tags-exclude-from-inheritance))
13292 ;; selective inheritance, remove uninherited ones
13293 (setcdr (car tags-alist)
13294 (org-remove-uninherited-tags (cdar tags-alist))))
13295 (when (and
13297 ;; eval matcher only when the todo condition is OK
13298 (and (or (not todo-only) (member todo org-not-done-keywords))
13299 (let ((case-fold-search t) (org-trust-scanner-tags t))
13300 (eval matcher)))
13302 ;; Call the skipper, but return t if it does not skip,
13303 ;; so that the `and' form continues evaluating
13304 (progn
13305 (unless (eq action 'sparse-tree) (org-agenda-skip))
13308 ;; Check if timestamps are deselecting this entry
13309 (or (not todo-only)
13310 (and (member todo org-not-done-keywords)
13311 (or (not org-agenda-tags-todo-honor-ignore-options)
13312 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13314 ;; Extra check for the archive tag
13315 ;; FIXME: Does the skipper already do this????
13317 (not (member org-archive-tag tags-list))
13318 ;; we have an archive tag, should we use this anyway?
13319 (or (not org-agenda-skip-archived-trees)
13320 (and (eq action 'agenda) org-agenda-archives-mode))))
13322 ;; select this headline
13323 (cond
13324 ((eq action 'sparse-tree)
13325 (and org-highlight-sparse-tree-matches
13326 (org-get-heading) (match-end 0)
13327 (org-highlight-new-match
13328 (match-beginning 1) (match-end 1)))
13329 (org-show-context 'tags-tree))
13330 ((eq action 'agenda)
13331 (setq txt (org-agenda-format-item
13333 (concat
13334 (if (eq org-tags-match-list-sublevels 'indented)
13335 (make-string (1- level) ?.) "")
13336 (org-get-heading))
13337 level category
13338 tags-list)
13339 priority (org-get-priority txt))
13340 (goto-char lspos)
13341 (setq marker (org-agenda-new-marker))
13342 (org-add-props txt props
13343 'org-marker marker 'org-hd-marker marker 'org-category category
13344 'todo-state todo
13345 'priority priority 'type "tagsmatch")
13346 (push txt rtn))
13347 ((functionp action)
13348 (setq org-map-continue-from nil)
13349 (save-excursion
13350 (setq rtn1 (funcall action))
13351 (push rtn1 rtn)))
13352 (t (error "Invalid action")))
13354 ;; if we are to skip sublevels, jump to end of subtree
13355 (unless org-tags-match-list-sublevels
13356 (org-end-of-subtree t)
13357 (backward-char 1))))
13358 ;; Get the correct position from where to continue
13359 (if org-map-continue-from
13360 (goto-char org-map-continue-from)
13361 (and (= (point) lspos) (end-of-line 1)))))
13362 (when (and (eq action 'sparse-tree)
13363 (not org-sparse-tree-open-archived-trees))
13364 (org-hide-archived-subtrees (point-min) (point-max)))
13365 (nreverse rtn)))
13367 (defun org-remove-uninherited-tags (tags)
13368 "Remove all tags that are not inherited from the list TAGS."
13369 (cond
13370 ((eq org-use-tag-inheritance t)
13371 (if org-tags-exclude-from-inheritance
13372 (org-delete-all org-tags-exclude-from-inheritance tags)
13373 tags))
13374 ((not org-use-tag-inheritance) nil)
13375 ((stringp org-use-tag-inheritance)
13376 (delq nil (mapcar
13377 (lambda (x)
13378 (if (and (string-match org-use-tag-inheritance x)
13379 (not (member x org-tags-exclude-from-inheritance)))
13380 x nil))
13381 tags)))
13382 ((listp org-use-tag-inheritance)
13383 (delq nil (mapcar
13384 (lambda (x)
13385 (if (member x org-use-tag-inheritance) x nil))
13386 tags)))))
13388 (defun org-match-sparse-tree (&optional todo-only match)
13389 "Create a sparse tree according to tags string MATCH.
13390 MATCH can contain positive and negative selection of tags, like
13391 \"+WORK+URGENT-WITHBOSS\".
13392 If optional argument TODO-ONLY is non-nil, only select lines that are
13393 also TODO lines."
13394 (interactive "P")
13395 (org-agenda-prepare-buffers (list (current-buffer)))
13396 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13398 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13400 (defvar org-cached-props nil)
13401 (defun org-cached-entry-get (pom property)
13402 (if (or (eq t org-use-property-inheritance)
13403 (and (stringp org-use-property-inheritance)
13404 (string-match org-use-property-inheritance property))
13405 (and (listp org-use-property-inheritance)
13406 (member property org-use-property-inheritance)))
13407 ;; Caching is not possible, check it directly
13408 (org-entry-get pom property 'inherit)
13409 ;; Get all properties, so that we can do complicated checks easily
13410 (cdr (assoc property (or org-cached-props
13411 (setq org-cached-props
13412 (org-entry-properties pom)))))))
13414 (defun org-global-tags-completion-table (&optional files)
13415 "Return the list of all tags in all agenda buffer/files.
13416 Optional FILES argument is a list of files which can be used
13417 instead of the agenda files."
13418 (save-excursion
13419 (org-uniquify
13420 (delq nil
13421 (apply 'append
13422 (mapcar
13423 (lambda (file)
13424 (set-buffer (find-file-noselect file))
13425 (append (org-get-buffer-tags)
13426 (mapcar (lambda (x) (if (stringp (car-safe x))
13427 (list (car-safe x)) nil))
13428 org-tag-alist)))
13429 (if (and files (car files))
13430 files
13431 (org-agenda-files))))))))
13433 (defun org-make-tags-matcher (match)
13434 "Create the TAGS/TODO matcher form for the selection string MATCH.
13436 The variable `todo-only' is scoped dynamically into this function.
13437 It will be set to t if the matcher restricts matching to TODO entries,
13438 otherwise will not be touched.
13440 Returns a cons of the selection string MATCH and the constructed
13441 lisp form implementing the matcher. The matcher is to be evaluated
13442 at an Org entry, with point on the headline, and returns t if the
13443 entry matches the selection string MATCH. The returned lisp form
13444 references two variables with information about the entry, which
13445 must be bound around the form's evaluation: todo, the TODO keyword
13446 at the entry (or nil of none); and tags-list, the list of all tags
13447 at the entry including inherited ones. Additionally, the category
13448 of the entry (if any) must be specified as the text property
13449 'org-category on the headline.
13451 See also `org-scan-tags'.
13453 (declare (special todo-only))
13454 (unless (boundp 'todo-only)
13455 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13456 (unless match
13457 ;; Get a new match request, with completion
13458 (let ((org-last-tags-completion-table
13459 (org-global-tags-completion-table)))
13460 (setq match (org-completing-read-no-i
13461 "Match: " 'org-tags-completion-function nil nil nil
13462 'org-tags-history))))
13464 ;; Parse the string and create a lisp form
13465 (let ((match0 match)
13466 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13467 minus tag mm
13468 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13469 orterms term orlist re-p str-p level-p level-op time-p
13470 prop-p pn pv po gv rest)
13471 (if (string-match "/+" match)
13472 ;; match contains also a todo-matching request
13473 (progn
13474 (setq tagsmatch (substring match 0 (match-beginning 0))
13475 todomatch (substring match (match-end 0)))
13476 (if (string-match "^!" todomatch)
13477 (setq todo-only t todomatch (substring todomatch 1)))
13478 (if (string-match "^\\s-*$" todomatch)
13479 (setq todomatch nil)))
13480 ;; only matching tags
13481 (setq tagsmatch match todomatch nil))
13483 ;; Make the tags matcher
13484 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13485 (setq tagsmatcher t)
13486 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13487 (while (setq term (pop orterms))
13488 (while (and (equal (substring term -1) "\\") orterms)
13489 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13490 (while (string-match re term)
13491 (setq rest (substring term (match-end 0))
13492 minus (and (match-end 1)
13493 (equal (match-string 1 term) "-"))
13494 tag (save-match-data (replace-regexp-in-string
13495 "\\\\-" "-"
13496 (match-string 2 term)))
13497 re-p (equal (string-to-char tag) ?{)
13498 level-p (match-end 4)
13499 prop-p (match-end 5)
13500 mm (cond
13501 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13502 (level-p
13503 (setq level-op (org-op-to-function (match-string 3 term)))
13504 `(,level-op level ,(string-to-number
13505 (match-string 4 term))))
13506 (prop-p
13507 (setq pn (match-string 5 term)
13508 po (match-string 6 term)
13509 pv (match-string 7 term)
13510 re-p (equal (string-to-char pv) ?{)
13511 str-p (equal (string-to-char pv) ?\")
13512 time-p (save-match-data
13513 (string-match "^\"[[<].*[]>]\"$" pv))
13514 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13515 (if time-p (setq pv (org-matcher-time pv)))
13516 (setq po (org-op-to-function po (if time-p 'time str-p)))
13517 (cond
13518 ((equal pn "CATEGORY")
13519 (setq gv '(get-text-property (point) 'org-category)))
13520 ((equal pn "TODO")
13521 (setq gv 'todo))
13523 (setq gv `(org-cached-entry-get nil ,pn))))
13524 (if re-p
13525 (if (eq po 'org<>)
13526 `(not (string-match ,pv (or ,gv "")))
13527 `(string-match ,pv (or ,gv "")))
13528 (if str-p
13529 `(,po (or ,gv "") ,pv)
13530 `(,po (string-to-number (or ,gv ""))
13531 ,(string-to-number pv) ))))
13532 (t `(member ,tag tags-list)))
13533 mm (if minus (list 'not mm) mm)
13534 term rest)
13535 (push mm tagsmatcher))
13536 (push (if (> (length tagsmatcher) 1)
13537 (cons 'and tagsmatcher)
13538 (car tagsmatcher))
13539 orlist)
13540 (setq tagsmatcher nil))
13541 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13542 (setq tagsmatcher
13543 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13544 ;; Make the todo matcher
13545 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13546 (setq todomatcher t)
13547 (setq orterms (org-split-string todomatch "|") orlist nil)
13548 (while (setq term (pop orterms))
13549 (while (string-match re term)
13550 (setq minus (and (match-end 1)
13551 (equal (match-string 1 term) "-"))
13552 kwd (match-string 2 term)
13553 re-p (equal (string-to-char kwd) ?{)
13554 term (substring term (match-end 0))
13555 mm (if re-p
13556 `(string-match ,(substring kwd 1 -1) todo)
13557 (list 'equal 'todo kwd))
13558 mm (if minus (list 'not mm) mm))
13559 (push mm todomatcher))
13560 (push (if (> (length todomatcher) 1)
13561 (cons 'and todomatcher)
13562 (car todomatcher))
13563 orlist)
13564 (setq todomatcher nil))
13565 (setq todomatcher (if (> (length orlist) 1)
13566 (cons 'or orlist) (car orlist))))
13568 ;; Return the string and lisp forms of the matcher
13569 (setq matcher (if todomatcher
13570 (list 'and tagsmatcher todomatcher)
13571 tagsmatcher))
13572 (when todo-only
13573 (setq matcher (list 'and '(member todo org-not-done-keywords)
13574 matcher)))
13575 (cons match0 matcher)))
13577 (defun org-op-to-function (op &optional stringp)
13578 "Turn an operator into the appropriate function."
13579 (setq op
13580 (cond
13581 ((equal op "<" ) '(< string< org-time<))
13582 ((equal op ">" ) '(> org-string> org-time>))
13583 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13584 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13585 ((member op '("=" "==")) '(= string= org-time=))
13586 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13587 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13589 (defun org<> (a b) (not (= a b)))
13590 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13591 (defun org-string>= (a b) (not (string< a b)))
13592 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13593 (defun org-string<> (a b) (not (string= a b)))
13594 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13595 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13596 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13597 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13598 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13599 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13600 (defun org-2ft (s)
13601 "Convert S to a floating point time.
13602 If S is already a number, just return it. If it is a string, parse
13603 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13604 (cond
13605 ((numberp s) s)
13606 ((stringp s)
13607 (condition-case nil
13608 (float-time (apply 'encode-time (org-parse-time-string s)))
13609 (error 0.)))
13610 (t 0.)))
13612 (defun org-time-today ()
13613 "Time in seconds today at 0:00.
13614 Returns the float number of seconds since the beginning of the
13615 epoch to the beginning of today (00:00)."
13616 (float-time (apply 'encode-time
13617 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13619 (defun org-matcher-time (s)
13620 "Interpret a time comparison value."
13621 (save-match-data
13622 (cond
13623 ((string= s "<now>") (float-time))
13624 ((string= s "<today>") (org-time-today))
13625 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13626 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13627 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13628 (+ (org-time-today)
13629 (* (string-to-number (match-string 1 s))
13630 (cdr (assoc (match-string 2 s)
13631 '(("d" . 86400.0) ("w" . 604800.0)
13632 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13633 (t (org-2ft s)))))
13635 (defun org-match-any-p (re list)
13636 "Does re match any element of list?"
13637 (setq list (mapcar (lambda (x) (string-match re x)) list))
13638 (delq nil list))
13640 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13641 (defvar org-tags-overlay (make-overlay 1 1))
13642 (org-detach-overlay org-tags-overlay)
13644 (defun org-get-local-tags-at (&optional pos)
13645 "Get a list of tags defined in the current headline."
13646 (org-get-tags-at pos 'local))
13648 (defun org-get-local-tags ()
13649 "Get a list of tags defined in the current headline."
13650 (org-get-tags-at nil 'local))
13652 (defun org-get-tags-at (&optional pos local)
13653 "Get a list of all headline tags applicable at POS.
13654 POS defaults to point. If tags are inherited, the list contains
13655 the targets in the same sequence as the headlines appear, i.e.
13656 the tags of the current headline come last.
13657 When LOCAL is non-nil, only return tags from the current headline,
13658 ignore inherited ones."
13659 (interactive)
13660 (if (and org-trust-scanner-tags
13661 (or (not pos) (equal pos (point)))
13662 (not local))
13663 org-scanner-tags
13664 (let (tags ltags lastpos parent)
13665 (save-excursion
13666 (save-restriction
13667 (widen)
13668 (goto-char (or pos (point)))
13669 (save-match-data
13670 (catch 'done
13671 (condition-case nil
13672 (progn
13673 (org-back-to-heading t)
13674 (while (not (equal lastpos (point)))
13675 (setq lastpos (point))
13676 (when (looking-at
13677 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13678 (setq ltags (org-split-string
13679 (org-match-string-no-properties 1) ":"))
13680 (when parent
13681 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13682 (setq tags (append
13683 (if parent
13684 (org-remove-uninherited-tags ltags)
13685 ltags)
13686 tags)))
13687 (or org-use-tag-inheritance (throw 'done t))
13688 (if local (throw 'done t))
13689 (or (org-up-heading-safe) (error nil))
13690 (setq parent t)))
13691 (error nil)))))
13692 (if local
13693 tags
13694 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13696 (defun org-add-prop-inherited (s)
13697 (add-text-properties 0 (length s) '(inherited t) s)
13700 (defun org-toggle-tag (tag &optional onoff)
13701 "Toggle the tag TAG for the current line.
13702 If ONOFF is `on' or `off', don't toggle but set to this state."
13703 (let (res current)
13704 (save-excursion
13705 (org-back-to-heading t)
13706 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13707 (point-at-eol) t)
13708 (progn
13709 (setq current (match-string 1))
13710 (replace-match ""))
13711 (setq current ""))
13712 (setq current (nreverse (org-split-string current ":")))
13713 (cond
13714 ((eq onoff 'on)
13715 (setq res t)
13716 (or (member tag current) (push tag current)))
13717 ((eq onoff 'off)
13718 (or (not (member tag current)) (setq current (delete tag current))))
13719 (t (if (member tag current)
13720 (setq current (delete tag current))
13721 (setq res t)
13722 (push tag current))))
13723 (end-of-line 1)
13724 (if current
13725 (progn
13726 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13727 (org-set-tags nil t))
13728 (delete-horizontal-space))
13729 (run-hooks 'org-after-tags-change-hook))
13730 res))
13732 (defun org-align-tags-here (to-col)
13733 ;; Assumes that this is a headline
13734 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13735 (beginning-of-line 1)
13736 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13737 (< pos (match-beginning 2)))
13738 (progn
13739 (setq tags-l (- (match-end 2) (match-beginning 2)))
13740 (goto-char (match-beginning 1))
13741 (insert " ")
13742 (delete-region (point) (1+ (match-beginning 2)))
13743 (setq ncol (max (current-column)
13744 (1+ col)
13745 (if (> to-col 0)
13746 to-col
13747 (- (abs to-col) tags-l))))
13748 (setq p (point))
13749 (insert (make-string (- ncol (current-column)) ?\ ))
13750 (setq ncol (current-column))
13751 (when indent-tabs-mode (tabify p (point-at-eol)))
13752 (org-move-to-column (min ncol col) t))
13753 (goto-char pos))))
13755 (defun org-set-tags-command (&optional arg just-align)
13756 "Call the set-tags command for the current entry."
13757 (interactive "P")
13758 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13759 (org-set-tags arg just-align)
13760 (save-excursion
13761 (org-back-to-heading t)
13762 (org-set-tags arg just-align))))
13764 (defun org-set-tags-to (data)
13765 "Set the tags of the current entry to DATA, replacing the current tags.
13766 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13767 If DATA is nil or the empty string, any tags will be removed."
13768 (interactive "sTags: ")
13769 (setq data
13770 (cond
13771 ((eq data nil) "")
13772 ((equal data "") "")
13773 ((stringp data)
13774 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13775 ":"))
13776 ((listp data)
13777 (concat ":" (mapconcat 'identity data ":") ":"))))
13778 (when data
13779 (save-excursion
13780 (org-back-to-heading t)
13781 (when (looking-at org-complex-heading-regexp)
13782 (if (match-end 5)
13783 (progn
13784 (goto-char (match-beginning 5))
13785 (insert data)
13786 (delete-region (point) (point-at-eol))
13787 (org-set-tags nil 'align))
13788 (goto-char (point-at-eol))
13789 (insert " " data)
13790 (org-set-tags nil 'align)))
13791 (beginning-of-line 1)
13792 (if (looking-at ".*?\\([ \t]+\\)$")
13793 (delete-region (match-beginning 1) (match-end 1))))))
13795 (defun org-align-all-tags ()
13796 "Align the tags i all headings."
13797 (interactive)
13798 (save-excursion
13799 (or (ignore-errors (org-back-to-heading t))
13800 (outline-next-heading))
13801 (if (org-at-heading-p)
13802 (org-set-tags t)
13803 (message "No headings"))))
13805 (defvar org-indent-indentation-per-level)
13806 (defun org-set-tags (&optional arg just-align)
13807 "Set the tags for the current headline.
13808 With prefix ARG, realign all tags in headings in the current buffer."
13809 (interactive "P")
13810 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13811 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13812 'region-start-level 'region))
13813 org-loop-over-headlines-in-active-region)
13814 (org-map-entries
13815 ;; We don't use ARG and JUST-ALIGN here these args are not
13816 ;; useful when looping over headlines
13817 `(org-set-tags)
13818 org-loop-over-headlines-in-active-region
13819 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13820 (let* ((re org-outline-regexp-bol)
13821 (current (unless arg (org-get-tags-string)))
13822 (col (current-column))
13823 (org-setting-tags t)
13824 table current-tags inherited-tags ; computed below when needed
13825 tags p0 c0 c1 rpl di tc level)
13826 (if arg
13827 (save-excursion
13828 (goto-char (point-min))
13829 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13830 (while (re-search-forward re nil t)
13831 (org-set-tags nil t)
13832 (end-of-line 1)))
13833 (message "All tags realigned to column %d" org-tags-column))
13834 (if just-align
13835 (setq tags current)
13836 ;; Get a new set of tags from the user
13837 (save-excursion
13838 (setq table (append org-tag-persistent-alist
13839 (or org-tag-alist (org-get-buffer-tags))
13840 (and
13841 org-complete-tags-always-offer-all-agenda-tags
13842 (org-global-tags-completion-table
13843 (org-agenda-files))))
13844 org-last-tags-completion-table table
13845 current-tags (org-split-string current ":")
13846 inherited-tags (nreverse
13847 (nthcdr (length current-tags)
13848 (nreverse (org-get-tags-at))))
13849 tags
13850 (if (or (eq t org-use-fast-tag-selection)
13851 (and org-use-fast-tag-selection
13852 (delq nil (mapcar 'cdr table))))
13853 (org-fast-tag-selection
13854 current-tags inherited-tags table
13855 (if org-fast-tag-selection-include-todo
13856 org-todo-key-alist))
13857 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13858 (org-trim
13859 (org-icompleting-read "Tags: "
13860 'org-tags-completion-function
13861 nil nil current 'org-tags-history))))))
13862 (while (string-match "[-+&]+" tags)
13863 ;; No boolean logic, just a list
13864 (setq tags (replace-match ":" t t tags))))
13866 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13868 (if org-tags-sort-function
13869 (setq tags (mapconcat 'identity
13870 (sort (org-split-string
13871 tags (org-re "[^[:alnum:]_@#%]+"))
13872 org-tags-sort-function) ":")))
13874 (if (string-match "\\`[\t ]*\\'" tags)
13875 (setq tags "")
13876 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13877 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13879 ;; Insert new tags at the correct column
13880 (beginning-of-line 1)
13881 (setq level (or (and (looking-at org-outline-regexp)
13882 (- (match-end 0) (point) 1))
13884 (cond
13885 ((and (equal current "") (equal tags "")))
13886 ((re-search-forward
13887 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13888 (point-at-eol) t)
13889 (if (equal tags "")
13890 (setq rpl "")
13891 (goto-char (match-beginning 0))
13892 (setq c0 (current-column)
13893 ;; compute offset for the case of org-indent-mode active
13894 di (if org-indent-mode
13895 (* (1- org-indent-indentation-per-level) (1- level))
13897 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13898 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13899 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13900 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13901 (replace-match rpl t t)
13902 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13903 tags)
13904 (t (error "Tags alignment failed")))
13905 (org-move-to-column col)
13906 (unless just-align
13907 (run-hooks 'org-after-tags-change-hook))))))
13909 (defun org-change-tag-in-region (beg end tag off)
13910 "Add or remove TAG for each entry in the region.
13911 This works in the agenda, and also in an org-mode buffer."
13912 (interactive
13913 (list (region-beginning) (region-end)
13914 (let ((org-last-tags-completion-table
13915 (if (derived-mode-p 'org-mode)
13916 (org-get-buffer-tags)
13917 (org-global-tags-completion-table))))
13918 (org-icompleting-read
13919 "Tag: " 'org-tags-completion-function nil nil nil
13920 'org-tags-history))
13921 (progn
13922 (message "[s]et or [r]emove? ")
13923 (equal (read-char-exclusive) ?r))))
13924 (if (fboundp 'deactivate-mark) (deactivate-mark))
13925 (let ((agendap (equal major-mode 'org-agenda-mode))
13926 l1 l2 m buf pos newhead (cnt 0))
13927 (goto-char end)
13928 (setq l2 (1- (org-current-line)))
13929 (goto-char beg)
13930 (setq l1 (org-current-line))
13931 (loop for l from l1 to l2 do
13932 (org-goto-line l)
13933 (setq m (get-text-property (point) 'org-hd-marker))
13934 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13935 (and agendap m))
13936 (setq buf (if agendap (marker-buffer m) (current-buffer))
13937 pos (if agendap m (point)))
13938 (with-current-buffer buf
13939 (save-excursion
13940 (save-restriction
13941 (goto-char pos)
13942 (setq cnt (1+ cnt))
13943 (org-toggle-tag tag (if off 'off 'on))
13944 (setq newhead (org-get-heading)))))
13945 (and agendap (org-agenda-change-all-lines newhead m))))
13946 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13948 (defun org-tags-completion-function (string predicate &optional flag)
13949 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13950 (confirm (lambda (x) (stringp (car x)))))
13951 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13952 (setq s1 (match-string 1 string)
13953 s2 (match-string 2 string))
13954 (setq s1 "" s2 string))
13955 (cond
13956 ((eq flag nil)
13957 ;; try completion
13958 (setq rtn (try-completion s2 ctable confirm))
13959 (if (stringp rtn)
13960 (setq rtn
13961 (concat s1 s2 (substring rtn (length s2))
13962 (if (and org-add-colon-after-tag-completion
13963 (assoc rtn ctable))
13964 ":" ""))))
13965 rtn)
13966 ((eq flag t)
13967 ;; all-completions
13968 (all-completions s2 ctable confirm)
13970 ((eq flag 'lambda)
13971 ;; exact match?
13972 (assoc s2 ctable)))
13975 (defun org-fast-tag-insert (kwd tags face &optional end)
13976 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13977 (insert (format "%-12s" (concat kwd ":"))
13978 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13979 (or end "")))
13981 (defun org-fast-tag-show-exit (flag)
13982 (save-excursion
13983 (org-goto-line 3)
13984 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13985 (replace-match ""))
13986 (when flag
13987 (end-of-line 1)
13988 (org-move-to-column (- (window-width) 19) t)
13989 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13991 (defun org-set-current-tags-overlay (current prefix)
13992 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13993 (if (featurep 'xemacs)
13994 (org-overlay-display org-tags-overlay (concat prefix s)
13995 'secondary-selection)
13996 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13997 (org-overlay-display org-tags-overlay (concat prefix s)))))
13999 (defvar org-last-tag-selection-key nil)
14000 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14001 "Fast tag selection with single keys.
14002 CURRENT is the current list of tags in the headline, INHERITED is the
14003 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14004 possibly with grouping information. TODO-TABLE is a similar table with
14005 TODO keywords, should these have keys assigned to them.
14006 If the keys are nil, a-z are automatically assigned.
14007 Returns the new tags string, or nil to not change the current settings."
14008 (let* ((fulltable (append table todo-table))
14009 (maxlen (apply 'max (mapcar
14010 (lambda (x)
14011 (if (stringp (car x)) (string-width (car x)) 0))
14012 fulltable)))
14013 (buf (current-buffer))
14014 (expert (eq org-fast-tag-selection-single-key 'expert))
14015 (buffer-tags nil)
14016 (fwidth (+ maxlen 3 1 3))
14017 (ncol (/ (- (window-width) 4) fwidth))
14018 (i-face 'org-done)
14019 (c-face 'org-todo)
14020 tg cnt e c char c1 c2 ntable tbl rtn
14021 ov-start ov-end ov-prefix
14022 (exit-after-next org-fast-tag-selection-single-key)
14023 (done-keywords org-done-keywords)
14024 groups ingroup)
14025 (save-excursion
14026 (beginning-of-line 1)
14027 (if (looking-at
14028 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14029 (setq ov-start (match-beginning 1)
14030 ov-end (match-end 1)
14031 ov-prefix "")
14032 (setq ov-start (1- (point-at-eol))
14033 ov-end (1+ ov-start))
14034 (skip-chars-forward "^\n\r")
14035 (setq ov-prefix
14036 (concat
14037 (buffer-substring (1- (point)) (point))
14038 (if (> (current-column) org-tags-column)
14040 (make-string (- org-tags-column (current-column)) ?\ ))))))
14041 (move-overlay org-tags-overlay ov-start ov-end)
14042 (save-window-excursion
14043 (if expert
14044 (set-buffer (get-buffer-create " *Org tags*"))
14045 (delete-other-windows)
14046 (split-window-vertically)
14047 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14048 (erase-buffer)
14049 (org-set-local 'org-done-keywords done-keywords)
14050 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14051 (org-fast-tag-insert "Current" current c-face "\n\n")
14052 (org-fast-tag-show-exit exit-after-next)
14053 (org-set-current-tags-overlay current ov-prefix)
14054 (setq tbl fulltable char ?a cnt 0)
14055 (while (setq e (pop tbl))
14056 (cond
14057 ((equal (car e) :startgroup)
14058 (push '() groups) (setq ingroup t)
14059 (when (not (= cnt 0))
14060 (setq cnt 0)
14061 (insert "\n"))
14062 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14063 ((equal (car e) :endgroup)
14064 (setq ingroup nil cnt 0)
14065 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14066 ((equal e '(:newline))
14067 (when (not (= cnt 0))
14068 (setq cnt 0)
14069 (insert "\n")
14070 (setq e (car tbl))
14071 (while (equal (car tbl) '(:newline))
14072 (insert "\n")
14073 (setq tbl (cdr tbl)))))
14075 (setq tg (copy-sequence (car e)) c2 nil)
14076 (if (cdr e)
14077 (setq c (cdr e))
14078 ;; automatically assign a character.
14079 (setq c1 (string-to-char
14080 (downcase (substring
14081 tg (if (= (string-to-char tg) ?@) 1 0)))))
14082 (if (or (rassoc c1 ntable) (rassoc c1 table))
14083 (while (or (rassoc char ntable) (rassoc char table))
14084 (setq char (1+ char)))
14085 (setq c2 c1))
14086 (setq c (or c2 char)))
14087 (if ingroup (push tg (car groups)))
14088 (setq tg (org-add-props tg nil 'face
14089 (cond
14090 ((not (assoc tg table))
14091 (org-get-todo-face tg))
14092 ((member tg current) c-face)
14093 ((member tg inherited) i-face))))
14094 (if (and (= cnt 0) (not ingroup)) (insert " "))
14095 (insert "[" c "] " tg (make-string
14096 (- fwidth 4 (length tg)) ?\ ))
14097 (push (cons tg c) ntable)
14098 (when (= (setq cnt (1+ cnt)) ncol)
14099 (insert "\n")
14100 (if ingroup (insert " "))
14101 (setq cnt 0)))))
14102 (setq ntable (nreverse ntable))
14103 (insert "\n")
14104 (goto-char (point-min))
14105 (if (not expert) (org-fit-window-to-buffer))
14106 (setq rtn
14107 (catch 'exit
14108 (while t
14109 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14110 (if (not groups) "no " "")
14111 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14112 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14113 (setq org-last-tag-selection-key c)
14114 (cond
14115 ((= c ?\r) (throw 'exit t))
14116 ((= c ?!)
14117 (setq groups (not groups))
14118 (goto-char (point-min))
14119 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14120 ((= c ?\C-c)
14121 (if (not expert)
14122 (org-fast-tag-show-exit
14123 (setq exit-after-next (not exit-after-next)))
14124 (setq expert nil)
14125 (delete-other-windows)
14126 (set-window-buffer (split-window-vertically) " *Org tags*")
14127 (org-switch-to-buffer-other-window " *Org tags*")
14128 (org-fit-window-to-buffer)))
14129 ((or (= c ?\C-g)
14130 (and (= c ?q) (not (rassoc c ntable))))
14131 (org-detach-overlay org-tags-overlay)
14132 (setq quit-flag t))
14133 ((= c ?\ )
14134 (setq current nil)
14135 (if exit-after-next (setq exit-after-next 'now)))
14136 ((= c ?\t)
14137 (condition-case nil
14138 (setq tg (org-icompleting-read
14139 "Tag: "
14140 (or buffer-tags
14141 (with-current-buffer buf
14142 (org-get-buffer-tags)))))
14143 (quit (setq tg "")))
14144 (when (string-match "\\S-" tg)
14145 (add-to-list 'buffer-tags (list tg))
14146 (if (member tg current)
14147 (setq current (delete tg current))
14148 (push tg current)))
14149 (if exit-after-next (setq exit-after-next 'now)))
14150 ((setq e (rassoc c todo-table) tg (car e))
14151 (with-current-buffer buf
14152 (save-excursion (org-todo tg)))
14153 (if exit-after-next (setq exit-after-next 'now)))
14154 ((setq e (rassoc c ntable) tg (car e))
14155 (if (member tg current)
14156 (setq current (delete tg current))
14157 (loop for g in groups do
14158 (if (member tg g)
14159 (mapc (lambda (x)
14160 (setq current (delete x current)))
14161 g)))
14162 (push tg current))
14163 (if exit-after-next (setq exit-after-next 'now))))
14165 ;; Create a sorted list
14166 (setq current
14167 (sort current
14168 (lambda (a b)
14169 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14170 (if (eq exit-after-next 'now) (throw 'exit t))
14171 (goto-char (point-min))
14172 (beginning-of-line 2)
14173 (delete-region (point) (point-at-eol))
14174 (org-fast-tag-insert "Current" current c-face)
14175 (org-set-current-tags-overlay current ov-prefix)
14176 (while (re-search-forward
14177 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14178 (setq tg (match-string 1))
14179 (add-text-properties
14180 (match-beginning 1) (match-end 1)
14181 (list 'face
14182 (cond
14183 ((member tg current) c-face)
14184 ((member tg inherited) i-face)
14185 (t (get-text-property (match-beginning 1) 'face))))))
14186 (goto-char (point-min)))))
14187 (org-detach-overlay org-tags-overlay)
14188 (if rtn
14189 (mapconcat 'identity current ":")
14190 nil))))
14192 (defun org-get-tags-string ()
14193 "Get the TAGS string in the current headline."
14194 (unless (org-at-heading-p t)
14195 (error "Not on a heading"))
14196 (save-excursion
14197 (beginning-of-line 1)
14198 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14199 (org-match-string-no-properties 1)
14200 "")))
14202 (defun org-get-tags ()
14203 "Get the list of tags specified in the current headline."
14204 (org-split-string (org-get-tags-string) ":"))
14206 (defun org-get-buffer-tags ()
14207 "Get a table of all tags used in the buffer, for completion."
14208 (let (tags)
14209 (save-excursion
14210 (goto-char (point-min))
14211 (while (re-search-forward
14212 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14213 (when (equal (char-after (point-at-bol 0)) ?*)
14214 (mapc (lambda (x) (add-to-list 'tags x))
14215 (org-split-string (org-match-string-no-properties 1) ":")))))
14216 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14217 (mapcar 'list tags)))
14219 ;;;; The mapping API
14221 (defun org-map-entries (func &optional match scope &rest skip)
14222 "Call FUNC at each headline selected by MATCH in SCOPE.
14224 FUNC is a function or a lisp form. The function will be called without
14225 arguments, with the cursor positioned at the beginning of the headline.
14226 The return values of all calls to the function will be collected and
14227 returned as a list.
14229 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14230 does not need to preserve point. After evaluation, the cursor will be
14231 moved to the end of the line (presumably of the headline of the
14232 processed entry) and search continues from there. Under some
14233 circumstances, this may not produce the wanted results. For example,
14234 if you have removed (e.g. archived) the current (sub)tree it could
14235 mean that the next entry will be skipped entirely. In such cases, you
14236 can specify the position from where search should continue by making
14237 FUNC set the variable `org-map-continue-from' to the desired buffer
14238 position.
14240 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14241 Only headlines that are matched by this query will be considered during
14242 the iteration. When MATCH is nil or t, all headlines will be
14243 visited by the iteration.
14245 SCOPE determines the scope of this command. It can be any of:
14247 nil The current buffer, respecting the restriction if any
14248 tree The subtree started with the entry at point
14249 region The entries within the active region, if any
14250 region-start-level
14251 The entries within the active region, but only those at
14252 the same level than the first one.
14253 file The current buffer, without restriction
14254 file-with-archives
14255 The current buffer, and any archives associated with it
14256 agenda All agenda files
14257 agenda-with-archives
14258 All agenda files with any archive files associated with them
14259 \(file1 file2 ...)
14260 If this is a list, all files in the list will be scanned
14262 The remaining args are treated as settings for the skipping facilities of
14263 the scanner. The following items can be given here:
14265 archive skip trees with the archive tag.
14266 comment skip trees with the COMMENT keyword
14267 function or Emacs Lisp form:
14268 will be used as value for `org-agenda-skip-function', so whenever
14269 the function returns t, FUNC will not be called for that
14270 entry and search will continue from the point where the
14271 function leaves it.
14273 If your function needs to retrieve the tags including inherited tags
14274 at the *current* entry, you can use the value of the variable
14275 `org-scanner-tags' which will be much faster than getting the value
14276 with `org-get-tags-at'. If your function gets properties with
14277 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14278 to t around the call to `org-entry-properties' to get the same speedup.
14279 Note that if your function moves around to retrieve tags and properties at
14280 a *different* entry, you cannot use these techniques."
14281 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14282 (not (org-region-active-p)))
14283 (let* ((org-agenda-archives-mode nil) ; just to make sure
14284 (org-agenda-skip-archived-trees (memq 'archive skip))
14285 (org-agenda-skip-comment-trees (memq 'comment skip))
14286 (org-agenda-skip-function
14287 (car (org-delete-all '(comment archive) skip)))
14288 (org-tags-match-list-sublevels t)
14289 (start-level (eq scope 'region-start-level))
14290 matcher file res
14291 org-todo-keywords-for-agenda
14292 org-done-keywords-for-agenda
14293 org-todo-keyword-alist-for-agenda
14294 org-drawers-for-agenda
14295 org-tag-alist-for-agenda
14296 todo-only)
14298 (cond
14299 ((eq match t) (setq matcher t))
14300 ((eq match nil) (setq matcher t))
14301 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14303 (save-excursion
14304 (save-restriction
14305 (cond ((eq scope 'tree)
14306 (org-back-to-heading t)
14307 (org-narrow-to-subtree)
14308 (setq scope nil))
14309 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14310 (org-region-active-p))
14311 ;; If needed, set start-level to a string like "2"
14312 (when start-level
14313 (save-excursion
14314 (goto-char (region-beginning))
14315 (unless (org-at-heading-p) (outline-next-heading))
14316 (setq start-level (org-current-level))))
14317 (narrow-to-region (region-beginning)
14318 (save-excursion
14319 (goto-char (region-end))
14320 (unless (and (bolp) (org-at-heading-p))
14321 (outline-next-heading))
14322 (point)))
14323 (setq scope nil)))
14325 (if (not scope)
14326 (progn
14327 (org-agenda-prepare-buffers
14328 (list (buffer-file-name (current-buffer))))
14329 (setq res (org-scan-tags func matcher todo-only start-level)))
14330 ;; Get the right scope
14331 (cond
14332 ((and scope (listp scope) (symbolp (car scope)))
14333 (setq scope (eval scope)))
14334 ((eq scope 'agenda)
14335 (setq scope (org-agenda-files t)))
14336 ((eq scope 'agenda-with-archives)
14337 (setq scope (org-agenda-files t))
14338 (setq scope (org-add-archive-files scope)))
14339 ((eq scope 'file)
14340 (setq scope (list (buffer-file-name))))
14341 ((eq scope 'file-with-archives)
14342 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14343 (org-agenda-prepare-buffers scope)
14344 (while (setq file (pop scope))
14345 (with-current-buffer (org-find-base-buffer-visiting file)
14346 (save-excursion
14347 (save-restriction
14348 (widen)
14349 (goto-char (point-min))
14350 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14351 res)))
14353 ;;;; Properties
14355 ;;; Setting and retrieving properties
14357 (defconst org-special-properties
14358 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14359 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14360 "The special properties valid in Org-mode.
14362 These are properties that are not defined in the property drawer,
14363 but in some other way.")
14365 (defconst org-default-properties
14366 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14367 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14368 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14369 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14370 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14371 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14372 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14373 "Some properties that are used by Org-mode for various purposes.
14374 Being in this list makes sure that they are offered for completion.")
14376 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14377 "Regular expression matching the first line of a property drawer.")
14379 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14380 "Regular expression matching the last line of a property drawer.")
14382 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14383 "Regular expression matching the first line of a property drawer.")
14385 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14386 "Regular expression matching the first line of a property drawer.")
14388 (defconst org-property-drawer-re
14389 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14390 org-property-end-re "\\)\n?")
14391 "Matches an entire property drawer.")
14393 (defconst org-clock-drawer-re
14394 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14395 org-property-end-re "\\)\n?")
14396 "Matches an entire clock drawer.")
14398 (defsubst org-re-property (property)
14399 "Return a regexp matching a PROPERTY line.
14400 Match group 1 will be set to the value."
14401 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14403 (defsubst org-re-property-keyword (property)
14404 "Return a regexp matching a PROPERTY line, possibly with no
14405 value for the property."
14406 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14408 (defun org-property-action ()
14409 "Do an action on properties."
14410 (interactive)
14411 (let (c)
14412 (org-at-property-p)
14413 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14414 (setq c (read-char-exclusive))
14415 (cond
14416 ((equal c ?s)
14417 (call-interactively 'org-set-property))
14418 ((equal c ?d)
14419 (call-interactively 'org-delete-property))
14420 ((equal c ?D)
14421 (call-interactively 'org-delete-property-globally))
14422 ((equal c ?c)
14423 (call-interactively 'org-compute-property-at-point))
14424 (t (error "No such property action %c" c)))))
14426 (defun org-inc-effort ()
14427 "Increment the value of the effort property in the current entry."
14428 (interactive)
14429 (org-set-effort nil t))
14431 (defun org-set-effort (&optional value increment)
14432 "Set the effort property of the current entry.
14433 With numerical prefix arg, use the nth allowed value, 0 stands for the
14434 10th allowed value.
14436 When INCREMENT is non-nil, set the property to the next allowed value."
14437 (interactive "P")
14438 (if (equal value 0) (setq value 10))
14439 (let* ((completion-ignore-case t)
14440 (prop org-effort-property)
14441 (cur (org-entry-get nil prop))
14442 (allowed (org-property-get-allowed-values nil prop 'table))
14443 (existing (mapcar 'list (org-property-values prop)))
14445 (val (cond
14446 ((stringp value) value)
14447 ((and allowed (integerp value))
14448 (or (car (nth (1- value) allowed))
14449 (car (org-last allowed))))
14450 ((and allowed increment)
14451 (or (caadr (member (list cur) allowed))
14452 (error "Allowed effort values are not set")))
14453 (allowed
14454 (message "Select 1-9,0, [RET%s]: %s"
14455 (if cur (concat "=" cur) "")
14456 (mapconcat 'car allowed " "))
14457 (setq rpl (read-char-exclusive))
14458 (if (equal rpl ?\r)
14460 (setq rpl (- rpl ?0))
14461 (if (equal rpl 0) (setq rpl 10))
14462 (if (and (> rpl 0) (<= rpl (length allowed)))
14463 (car (nth (1- rpl) allowed))
14464 (org-completing-read "Effort: " allowed nil))))
14466 (let (org-completion-use-ido org-completion-use-iswitchb)
14467 (org-completing-read
14468 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14469 (concat "[" cur "]") "")
14470 ": ")
14471 existing nil nil "" nil cur))))))
14472 (unless (equal (org-entry-get nil prop) val)
14473 (org-entry-put nil prop val))
14474 (message "%s is now %s" prop val)))
14476 (defun org-at-property-p ()
14477 "Is cursor inside a property drawer?"
14478 (save-excursion
14479 (beginning-of-line 1)
14480 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14481 (save-match-data ;; Used by calling procedures
14482 (let ((p (point))
14483 (range (unless (org-before-first-heading-p)
14484 (org-get-property-block))))
14485 (and range (<= (car range) p) (< p (cdr range))))))))
14487 (defun org-get-property-block (&optional beg end force)
14488 "Return the (beg . end) range of the body of the property drawer.
14489 BEG and END are the beginning and end of the current subtree, or of
14490 the part before the first headline. If they are not given, they will
14491 be found. If the drawer does not exist and FORCE is non-nil, create
14492 the drawer."
14493 (catch 'exit
14494 (save-excursion
14495 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14496 (progn (org-back-to-heading t) (point))))
14497 (end (or end (and (not (outline-next-heading)) (point-max))
14498 (point))))
14499 (goto-char beg)
14500 (if (re-search-forward org-property-start-re end t)
14501 (setq beg (1+ (match-end 0)))
14502 (if force
14503 (save-excursion
14504 (org-insert-property-drawer)
14505 (setq end (progn (outline-next-heading) (point))))
14506 (throw 'exit nil))
14507 (goto-char beg)
14508 (if (re-search-forward org-property-start-re end t)
14509 (setq beg (1+ (match-end 0)))))
14510 (if (re-search-forward org-property-end-re end t)
14511 (setq end (match-beginning 0))
14512 (or force (throw 'exit nil))
14513 (goto-char beg)
14514 (setq end beg)
14515 (org-indent-line)
14516 (insert ":END:\n"))
14517 (cons beg end)))))
14519 (defun org-entry-properties (&optional pom which specific)
14520 "Get all properties of the entry at point-or-marker POM.
14521 This includes the TODO keyword, the tags, time strings for deadline,
14522 scheduled, and clocking, and any additional properties defined in the
14523 entry. The return value is an alist, keys may occur multiple times
14524 if the property key was used several times.
14525 POM may also be nil, in which case the current entry is used.
14526 If WHICH is nil or `all', get all properties. If WHICH is
14527 `special' or `standard', only get that subclass. If WHICH
14528 is a string only get exactly this property. SPECIFIC can be a string, the
14529 specific property we are interested in. Specifying it can speed
14530 things up because then unnecessary parsing is avoided."
14531 (setq which (or which 'all))
14532 (org-with-point-at pom
14533 (let ((clockstr (substring org-clock-string 0 -1))
14534 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14535 (case-fold-search nil)
14536 beg end range props sum-props key key1 value string clocksum clocksumt)
14537 (save-excursion
14538 (when (condition-case nil
14539 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14540 (error nil))
14541 (setq beg (point))
14542 (setq sum-props (get-text-property (point) 'org-summaries))
14543 (setq clocksum (get-text-property (point) :org-clock-minutes)
14544 clocksumt (get-text-property (point) :org-clock-minutes-today))
14545 (outline-next-heading)
14546 (setq end (point))
14547 (when (memq which '(all special))
14548 ;; Get the special properties, like TODO and tags
14549 (goto-char beg)
14550 (when (and (or (not specific) (string= specific "TODO"))
14551 (looking-at org-todo-line-regexp) (match-end 2))
14552 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14553 (when (and (or (not specific) (string= specific "PRIORITY"))
14554 (looking-at org-priority-regexp))
14555 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14556 (when (or (not specific) (string= specific "FILE"))
14557 (push (cons "FILE" buffer-file-name) props))
14558 (when (and (or (not specific) (string= specific "TAGS"))
14559 (setq value (org-get-tags-string))
14560 (string-match "\\S-" value))
14561 (push (cons "TAGS" value) props))
14562 (when (and (or (not specific) (string= specific "ALLTAGS"))
14563 (setq value (org-get-tags-at)))
14564 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14565 ":"))
14566 props))
14567 (when (or (not specific) (string= specific "BLOCKED"))
14568 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14569 (when (or (not specific)
14570 (member specific
14571 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14572 "TIMESTAMP" "TIMESTAMP_IA")))
14573 (catch 'match
14574 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14575 (setq key (if (match-end 1)
14576 (substring (org-match-string-no-properties 1)
14577 0 -1))
14578 string (if (equal key clockstr)
14579 (org-trim
14580 (buffer-substring-no-properties
14581 (match-beginning 3) (goto-char
14582 (point-at-eol))))
14583 (substring (org-match-string-no-properties 3)
14584 1 -1)))
14585 ;; Get the correct property name from the key. This is
14586 ;; necessary if the user has configured time keywords.
14587 (setq key1 (concat key ":"))
14588 (cond
14589 ((not key)
14590 (setq key
14591 (if (= (char-after (match-beginning 3)) ?\[)
14592 "TIMESTAMP_IA" "TIMESTAMP")))
14593 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14594 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14595 ((equal key1 org-closed-string) (setq key "CLOSED"))
14596 ((equal key1 org-clock-string) (setq key "CLOCK")))
14597 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14598 (progn
14599 (push (cons key string) props)
14600 ;; no need to search further if match is found
14601 (throw 'match t))
14602 (when (or (equal key "CLOCK") (not (assoc key props)))
14603 (push (cons key string) props)))))))
14605 (when (memq which '(all standard))
14606 ;; Get the standard properties, like :PROP: ...
14607 (setq range (org-get-property-block beg end))
14608 (when range
14609 (goto-char (car range))
14610 (while (re-search-forward
14611 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14612 (cdr range) t)
14613 (setq key (org-match-string-no-properties 1)
14614 value (org-trim (or (org-match-string-no-properties 2) "")))
14615 (unless (member key excluded)
14616 (push (cons key (or value "")) props)))))
14617 (if clocksum
14618 (push (cons "CLOCKSUM"
14619 (org-columns-number-to-string (/ (float clocksum) 60.)
14620 'add_times))
14621 props))
14622 (if clocksumt
14623 (push (cons "CLOCKSUM_T"
14624 (org-columns-number-to-string (/ (float clocksumt) 60.)
14625 'add_times))
14626 props))
14627 (unless (assoc "CATEGORY" props)
14628 (push (cons "CATEGORY" (org-get-category)) props))
14629 (append sum-props (nreverse props)))))))
14631 (defun org-entry-get (pom property &optional inherit literal-nil)
14632 "Get value of PROPERTY for entry or content at point-or-marker POM.
14633 If INHERIT is non-nil and the entry does not have the property,
14634 then also check higher levels of the hierarchy.
14635 If INHERIT is the symbol `selective', use inheritance only if the setting
14636 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14637 If the property is present but empty, the return value is the empty string.
14638 If the property is not present at all, nil is returned.
14640 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14641 do not interpret it as the list atom nil. This is used for inheritance
14642 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14643 (org-with-point-at pom
14644 (if (and inherit (if (eq inherit 'selective)
14645 (org-property-inherit-p property)
14647 (org-entry-get-with-inheritance property literal-nil)
14648 (if (member property org-special-properties)
14649 ;; We need a special property. Use `org-entry-properties' to
14650 ;; retrieve it, but specify the wanted property
14651 (cdr (assoc property (org-entry-properties nil 'special property)))
14652 (let* ((range (org-get-property-block))
14653 (props (list (or (assoc property org-file-properties)
14654 (assoc property org-global-properties)
14655 (assoc property org-global-properties-fixed))))
14656 (ap (lambda (key)
14657 (when (re-search-forward
14658 (org-re-property key) (cdr range) t)
14659 (setq props
14660 (org-update-property-plist
14662 (if (match-end 1)
14663 (org-match-string-no-properties 1) "")
14664 props)))))
14665 val)
14666 (when (and range (goto-char (car range)))
14667 (funcall ap property)
14668 (goto-char (car range))
14669 (while (funcall ap (concat property "+")))
14670 (setq val (cdr (assoc property props)))
14671 (when val (if literal-nil val (org-not-nil val)))))))))
14673 (defun org-property-or-variable-value (var &optional inherit)
14674 "Check if there is a property fixing the value of VAR.
14675 If yes, return this value. If not, return the current value of the variable."
14676 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14677 (if (and prop (stringp prop) (string-match "\\S-" prop))
14678 (read prop)
14679 (symbol-value var))))
14681 (defun org-entry-delete (pom property)
14682 "Delete the property PROPERTY from entry at point-or-marker POM."
14683 (org-with-point-at pom
14684 (if (member property org-special-properties)
14685 nil ; cannot delete these properties.
14686 (let ((range (org-get-property-block)))
14687 (if (and range
14688 (goto-char (car range))
14689 (re-search-forward
14690 (org-re-property property)
14691 (cdr range) t))
14692 (progn
14693 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14695 nil)))))
14697 ;; Multi-values properties are properties that contain multiple values
14698 ;; These values are assumed to be single words, separated by whitespace.
14699 (defun org-entry-add-to-multivalued-property (pom property value)
14700 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14701 (let* ((old (org-entry-get pom property))
14702 (values (and old (org-split-string old "[ \t]"))))
14703 (setq value (org-entry-protect-space value))
14704 (unless (member value values)
14705 (setq values (cons value values))
14706 (org-entry-put pom property
14707 (mapconcat 'identity values " ")))))
14709 (defun org-entry-remove-from-multivalued-property (pom property value)
14710 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14711 (let* ((old (org-entry-get pom property))
14712 (values (and old (org-split-string old "[ \t]"))))
14713 (setq value (org-entry-protect-space value))
14714 (when (member value values)
14715 (setq values (delete value values))
14716 (org-entry-put pom property
14717 (mapconcat 'identity values " ")))))
14719 (defun org-entry-member-in-multivalued-property (pom property value)
14720 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14721 (let* ((old (org-entry-get pom property))
14722 (values (and old (org-split-string old "[ \t]"))))
14723 (setq value (org-entry-protect-space value))
14724 (member value values)))
14726 (defun org-entry-get-multivalued-property (pom property)
14727 "Return a list of values in a multivalued property."
14728 (let* ((value (org-entry-get pom property))
14729 (values (and value (org-split-string value "[ \t]"))))
14730 (mapcar 'org-entry-restore-space values)))
14732 (defun org-entry-put-multivalued-property (pom property &rest values)
14733 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14734 VALUES should be a list of strings. Spaces will be protected."
14735 (org-entry-put pom property
14736 (mapconcat 'org-entry-protect-space values " "))
14737 (let* ((value (org-entry-get pom property))
14738 (values (and value (org-split-string value "[ \t]"))))
14739 (mapcar 'org-entry-restore-space values)))
14741 (defun org-entry-protect-space (s)
14742 "Protect spaces and newline in string S."
14743 (while (string-match " " s)
14744 (setq s (replace-match "%20" t t s)))
14745 (while (string-match "\n" s)
14746 (setq s (replace-match "%0A" t t s)))
14749 (defun org-entry-restore-space (s)
14750 "Restore spaces and newline in string S."
14751 (while (string-match "%20" s)
14752 (setq s (replace-match " " t t s)))
14753 (while (string-match "%0A" s)
14754 (setq s (replace-match "\n" t t s)))
14757 (defvar org-entry-property-inherited-from (make-marker)
14758 "Marker pointing to the entry from where a property was inherited.
14759 Each call to `org-entry-get-with-inheritance' will set this marker to the
14760 location of the entry where the inheritance search matched. If there was
14761 no match, the marker will point nowhere.
14762 Note that also `org-entry-get' calls this function, if the INHERIT flag
14763 is set.")
14765 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14766 "Get PROPERTY of entry or content at point, search higher levels if needed.
14767 The search will stop at the first ancestor which has the property defined.
14768 If the value found is \"nil\", return nil to show that the property
14769 should be considered as undefined (this is the meaning of nil here).
14770 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14771 (move-marker org-entry-property-inherited-from nil)
14772 (let (tmp)
14773 (save-excursion
14774 (save-restriction
14775 (widen)
14776 (catch 'ex
14777 (while t
14778 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14779 (or (ignore-errors (org-back-to-heading t))
14780 (goto-char (point-min)))
14781 (move-marker org-entry-property-inherited-from (point))
14782 (throw 'ex tmp))
14783 (or (ignore-errors (org-up-heading-safe))
14784 (throw 'ex nil))))))
14785 (setq tmp (or tmp
14786 (cdr (assoc property org-file-properties))
14787 (cdr (assoc property org-global-properties))
14788 (cdr (assoc property org-global-properties-fixed))))
14789 (if literal-nil tmp (org-not-nil tmp))))
14791 (defvar org-property-changed-functions nil
14792 "Hook called when the value of a property has changed.
14793 Each hook function should accept two arguments, the name of the property
14794 and the new value.")
14796 (defun org-entry-put (pom property value)
14797 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14798 (org-with-point-at pom
14799 (org-back-to-heading t)
14800 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14801 range)
14802 (cond
14803 ((equal property "TODO")
14804 (when (and (stringp value) (string-match "\\S-" value)
14805 (not (member value org-todo-keywords-1)))
14806 (error "\"%s\" is not a valid TODO state" value))
14807 (if (or (not value)
14808 (not (string-match "\\S-" value)))
14809 (setq value 'none))
14810 (org-todo value)
14811 (org-set-tags nil 'align))
14812 ((equal property "PRIORITY")
14813 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14814 (string-to-char value) ?\ ))
14815 (org-set-tags nil 'align))
14816 ((equal property "CLOCKSUM")
14817 (if (not (re-search-forward
14818 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14819 (error "Cannot find a clock log")
14820 (goto-char (- (match-end 1) 2))
14821 (cond
14822 ((eq value 'earlier) (org-timestamp-down))
14823 ((eq value 'later) (org-timestamp-up)))
14824 (org-clock-sum-current-item)))
14825 ((equal property "SCHEDULED")
14826 (if (re-search-forward org-scheduled-time-regexp end t)
14827 (cond
14828 ((eq value 'earlier) (org-timestamp-change -1 'day))
14829 ((eq value 'later) (org-timestamp-change 1 'day))
14830 (t (call-interactively 'org-schedule)))
14831 (call-interactively 'org-schedule)))
14832 ((equal property "DEADLINE")
14833 (if (re-search-forward org-deadline-time-regexp end t)
14834 (cond
14835 ((eq value 'earlier) (org-timestamp-change -1 'day))
14836 ((eq value 'later) (org-timestamp-change 1 'day))
14837 (t (call-interactively 'org-deadline)))
14838 (call-interactively 'org-deadline)))
14839 ((member property org-special-properties)
14840 (error "The %s property can not yet be set with `org-entry-put'"
14841 property))
14842 (t ; a non-special property
14843 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14844 (setq range (org-get-property-block beg end 'force))
14845 (goto-char (car range))
14846 (if (re-search-forward
14847 (org-re-property-keyword property) (cdr range) t)
14848 (progn
14849 (delete-region (match-beginning 0) (match-end 0))
14850 (goto-char (match-beginning 0)))
14851 (goto-char (cdr range))
14852 (insert "\n")
14853 (backward-char 1)
14854 (org-indent-line))
14855 (insert ":" property ":")
14856 (and value (insert " " value))
14857 (org-indent-line)))))
14858 (run-hook-with-args 'org-property-changed-functions property value)))
14860 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14861 "Get all property keys in the current buffer.
14862 With INCLUDE-SPECIALS, also list the special properties that reflect things
14863 like tags and TODO state.
14864 With INCLUDE-DEFAULTS, also include properties that has special meaning
14865 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14866 and others.
14867 With INCLUDE-COLUMNS, also include property names given in COLUMN
14868 formats in the current buffer."
14869 (let (rtn range cfmt s p)
14870 (save-excursion
14871 (save-restriction
14872 (widen)
14873 (goto-char (point-min))
14874 (while (re-search-forward org-property-start-re nil t)
14875 (setq range (org-get-property-block))
14876 (goto-char (car range))
14877 (while (re-search-forward
14878 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14879 (cdr range) t)
14880 (add-to-list 'rtn (org-match-string-no-properties 1)))
14881 (outline-next-heading))))
14883 (when include-specials
14884 (setq rtn (append org-special-properties rtn)))
14886 (when include-defaults
14887 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14888 (add-to-list 'rtn org-effort-property))
14890 (when include-columns
14891 (save-excursion
14892 (save-restriction
14893 (widen)
14894 (goto-char (point-min))
14895 (while (re-search-forward
14896 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14897 nil t)
14898 (setq cfmt (match-string 2) s 0)
14899 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14900 cfmt s)
14901 (setq s (match-end 0)
14902 p (match-string 1 cfmt))
14903 (unless (or (equal p "ITEM")
14904 (member p org-special-properties))
14905 (add-to-list 'rtn (match-string 1 cfmt))))))))
14907 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14909 (defun org-property-values (key)
14910 "Return a list of all values of property KEY in the current buffer."
14911 (save-excursion
14912 (save-restriction
14913 (widen)
14914 (goto-char (point-min))
14915 (let ((re (org-re-property key))
14916 values)
14917 (while (re-search-forward re nil t)
14918 (add-to-list 'values (org-trim (match-string 1))))
14919 (delete "" values)))))
14921 (defun org-insert-property-drawer ()
14922 "Insert a property drawer into the current entry."
14923 (org-back-to-heading t)
14924 (looking-at org-outline-regexp)
14925 (let ((indent (if org-adapt-indentation
14926 (- (match-end 0) (match-beginning 0))
14928 (beg (point))
14929 (re (concat "^[ \t]*" org-keyword-time-regexp))
14930 end hiddenp)
14931 (outline-next-heading)
14932 (setq end (point))
14933 (goto-char beg)
14934 (while (re-search-forward re end t))
14935 (setq hiddenp (outline-invisible-p))
14936 (end-of-line 1)
14937 (and (equal (char-after) ?\n) (forward-char 1))
14938 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14939 (if (member (match-string 1) '("CLOCK:" ":END:"))
14940 ;; just skip this line
14941 (beginning-of-line 2)
14942 ;; Drawer start, find the end
14943 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14944 (beginning-of-line 1)))
14945 (org-skip-over-state-notes)
14946 (skip-chars-backward " \t\n\r")
14947 (if (eq (char-before) ?*) (forward-char 1))
14948 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14949 (beginning-of-line 0)
14950 (org-indent-to-column indent)
14951 (beginning-of-line 2)
14952 (org-indent-to-column indent)
14953 (beginning-of-line 0)
14954 (if hiddenp
14955 (save-excursion
14956 (org-back-to-heading t)
14957 (hide-entry))
14958 (org-flag-drawer t))))
14960 (defun org-insert-drawer (&optional arg drawer)
14961 "Insert a drawer at point.
14963 Optional argument DRAWER, when non-nil, is a string representing
14964 drawer's name. Otherwise, the user is prompted for a name.
14966 If a region is active, insert the drawer around that region
14967 instead.
14969 Point is left between drawer's boundaries."
14970 (interactive "P")
14971 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14972 "LOGBOOK"))
14973 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14974 ;; internally by Org. They are meant to be inserted
14975 ;; automatically.
14976 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14977 ;; Remove system drawers from list. Note: For some reason,
14978 ;; `org-completing-read' ignores the predicate while
14979 ;; `completing-read' handles it fine.
14980 (drawer (if arg "PROPERTIES"
14981 (or drawer
14982 (completing-read
14983 "Drawer: " org-drawers
14984 (lambda (d) (not (member d system-drawers))))))))
14985 (cond
14986 ;; With C-u, fall back on `org-insert-property-drawer'
14987 (arg (org-insert-property-drawer))
14988 ;; With an active region, insert a drawer at point.
14989 ((not (org-region-active-p))
14990 (progn
14991 (unless (bolp) (insert "\n"))
14992 (insert (format ":%s:\n\n:END:\n" drawer))
14993 (forward-line -2)))
14994 ;; Otherwise, insert the drawer at point
14996 (let ((rbeg (region-beginning))
14997 (rend (copy-marker (region-end))))
14998 (unwind-protect
14999 (progn
15000 (goto-char rbeg)
15001 (beginning-of-line)
15002 (when (save-excursion
15003 (re-search-forward org-outline-regexp-bol rend t))
15004 (error "Drawers cannot contain headlines"))
15005 ;; Position point at the beginning of the first
15006 ;; non-blank line in region. Insert drawer's opening
15007 ;; there, then indent it.
15008 (org-skip-whitespace)
15009 (beginning-of-line)
15010 (insert ":" drawer ":\n")
15011 (forward-line -1)
15012 (indent-for-tab-command)
15013 ;; Move point to the beginning of the first blank line
15014 ;; after the last non-blank line in region. Insert
15015 ;; drawer's closing, then indent it.
15016 (goto-char rend)
15017 (skip-chars-backward " \r\t\n")
15018 (insert "\n:END:")
15019 (deactivate-mark t)
15020 (indent-for-tab-command)
15021 (unless (eolp) (insert "\n")))
15022 ;; Clear marker, whatever the outcome of insertion is.
15023 (set-marker rend nil)))))))
15025 (defvar org-property-set-functions-alist nil
15026 "Property set function alist.
15027 Each entry should have the following format:
15029 (PROPERTY . READ-FUNCTION)
15031 The read function will be called with the same argument as
15032 `org-completing-read'.")
15034 (defun org-set-property-function (property)
15035 "Get the function that should be used to set PROPERTY.
15036 This is computed according to `org-property-set-functions-alist'."
15037 (or (cdr (assoc property org-property-set-functions-alist))
15038 'org-completing-read))
15040 (defun org-read-property-value (property)
15041 "Read PROPERTY value from user."
15042 (let* ((completion-ignore-case t)
15043 (allowed (org-property-get-allowed-values nil property 'table))
15044 (cur (org-entry-get nil property))
15045 (prompt (concat property " value"
15046 (if (and cur (string-match "\\S-" cur))
15047 (concat " [" cur "]") "") ": "))
15048 (set-function (org-set-property-function property))
15049 (val (if allowed
15050 (funcall set-function prompt allowed nil
15051 (not (get-text-property 0 'org-unrestricted
15052 (caar allowed))))
15053 (let (org-completion-use-ido org-completion-use-iswitchb)
15054 (funcall set-function prompt
15055 (mapcar 'list (org-property-values property))
15056 nil nil "" nil cur)))))
15057 (if (equal val "")
15059 val)))
15061 (defvar org-last-set-property nil)
15062 (defun org-read-property-name ()
15063 "Read a property name."
15064 (let* ((completion-ignore-case t)
15065 (keys (org-buffer-property-keys nil t t))
15066 (default-prop (or (save-excursion
15067 (save-match-data
15068 (beginning-of-line)
15069 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15070 (null (string= (match-string 1) "END"))
15071 (match-string 1))))
15072 org-last-set-property))
15073 (property (org-icompleting-read
15074 (concat "Property"
15075 (if default-prop (concat " [" default-prop "]") "")
15076 ": ")
15077 (mapcar 'list keys)
15078 nil nil nil nil
15079 default-prop
15081 (if (member property keys)
15082 property
15083 (or (cdr (assoc (downcase property)
15084 (mapcar (lambda (x) (cons (downcase x) x))
15085 keys)))
15086 property))))
15088 (defun org-set-property (property value)
15089 "In the current entry, set PROPERTY to VALUE.
15090 When called interactively, this will prompt for a property name, offering
15091 completion on existing and default properties. And then it will prompt
15092 for a value, offering completion either on allowed values (via an inherited
15093 xxx_ALL property) or on existing values in other instances of this property
15094 in the current file."
15095 (interactive (list nil nil))
15096 (let* ((property (or property (org-read-property-name)))
15097 (value (or value (org-read-property-value property)))
15098 (fn (cdr (assoc property org-properties-postprocess-alist))))
15099 (setq org-last-set-property property)
15100 ;; Possibly postprocess the inserted value:
15101 (when fn (setq value (funcall fn value)))
15102 (unless (equal (org-entry-get nil property) value)
15103 (org-entry-put nil property value))))
15105 (defun org-delete-property (property)
15106 "In the current entry, delete PROPERTY."
15107 (interactive
15108 (let* ((completion-ignore-case t)
15109 (prop (org-icompleting-read "Property: "
15110 (org-entry-properties nil 'standard))))
15111 (list prop)))
15112 (message "Property %s %s" property
15113 (if (org-entry-delete nil property)
15114 "deleted"
15115 "was not present in the entry")))
15117 (defun org-delete-property-globally (property)
15118 "Remove PROPERTY globally, from all entries."
15119 (interactive
15120 (let* ((completion-ignore-case t)
15121 (prop (org-icompleting-read
15122 "Globally remove property: "
15123 (mapcar 'list (org-buffer-property-keys)))))
15124 (list prop)))
15125 (save-excursion
15126 (save-restriction
15127 (widen)
15128 (goto-char (point-min))
15129 (let ((cnt 0))
15130 (while (re-search-forward
15131 (org-re-property property)
15132 nil t)
15133 (setq cnt (1+ cnt))
15134 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15135 (message "Property \"%s\" removed from %d entries" property cnt)))))
15137 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15139 (defun org-compute-property-at-point ()
15140 "Compute the property at point.
15141 This looks for an enclosing column format, extracts the operator and
15142 then applies it to the property in the column format's scope."
15143 (interactive)
15144 (unless (org-at-property-p)
15145 (error "Not at a property"))
15146 (let ((prop (org-match-string-no-properties 2)))
15147 (org-columns-get-format-and-top-level)
15148 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15149 (error "No operator defined for property %s" prop))
15150 (org-columns-compute prop)))
15152 (defvar org-property-allowed-value-functions nil
15153 "Hook for functions supplying allowed values for a specific property.
15154 The functions must take a single argument, the name of the property, and
15155 return a flat list of allowed values. If \":ETC\" is one of
15156 the values, this means that these values are intended as defaults for
15157 completion, but that other values should be allowed too.
15158 The functions must return nil if they are not responsible for this
15159 property.")
15161 (defun org-property-get-allowed-values (pom property &optional table)
15162 "Get allowed values for the property PROPERTY.
15163 When TABLE is non-nil, return an alist that can directly be used for
15164 completion."
15165 (let (vals)
15166 (cond
15167 ((equal property "TODO")
15168 (setq vals (org-with-point-at pom
15169 (append org-todo-keywords-1 '("")))))
15170 ((equal property "PRIORITY")
15171 (let ((n org-lowest-priority))
15172 (while (>= n org-highest-priority)
15173 (push (char-to-string n) vals)
15174 (setq n (1- n)))))
15175 ((member property org-special-properties))
15176 ((setq vals (run-hook-with-args-until-success
15177 'org-property-allowed-value-functions property)))
15179 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15180 (when (and vals (string-match "\\S-" vals))
15181 (setq vals (car (read-from-string (concat "(" vals ")"))))
15182 (setq vals (mapcar (lambda (x)
15183 (cond ((stringp x) x)
15184 ((numberp x) (number-to-string x))
15185 ((symbolp x) (symbol-name x))
15186 (t "???")))
15187 vals)))))
15188 (when (member ":ETC" vals)
15189 (setq vals (remove ":ETC" vals))
15190 (org-add-props (car vals) '(org-unrestricted t)))
15191 (if table (mapcar 'list vals) vals)))
15193 (defun org-property-previous-allowed-value (&optional previous)
15194 "Switch to the next allowed value for this property."
15195 (interactive)
15196 (org-property-next-allowed-value t))
15198 (defun org-property-next-allowed-value (&optional previous)
15199 "Switch to the next allowed value for this property."
15200 (interactive)
15201 (unless (org-at-property-p)
15202 (error "Not at a property"))
15203 (let* ((key (match-string 2))
15204 (value (match-string 3))
15205 (allowed (or (org-property-get-allowed-values (point) key)
15206 (and (member value '("[ ]" "[-]" "[X]"))
15207 '("[ ]" "[X]"))))
15208 nval)
15209 (unless allowed
15210 (error "Allowed values for this property have not been defined"))
15211 (if previous (setq allowed (reverse allowed)))
15212 (if (member value allowed)
15213 (setq nval (car (cdr (member value allowed)))))
15214 (setq nval (or nval (car allowed)))
15215 (if (equal nval value)
15216 (error "Only one allowed value for this property"))
15217 (org-at-property-p)
15218 (replace-match (concat " :" key ": " nval) t t)
15219 (org-indent-line)
15220 (beginning-of-line 1)
15221 (skip-chars-forward " \t")
15222 (run-hook-with-args 'org-property-changed-functions key nval)))
15224 (defun org-find-olp (path &optional this-buffer)
15225 "Return a marker pointing to the entry at outline path OLP.
15226 If anything goes wrong, throw an error.
15227 You can wrap this call to catch the error like this:
15229 (condition-case msg
15230 (org-mobile-locate-entry (match-string 4))
15231 (error (nth 1 msg)))
15233 The return value will then be either a string with the error message,
15234 or a marker if everything is OK.
15236 If THIS-BUFFER is set, the outline path does not contain a file,
15237 only headings."
15238 (let* ((file (if this-buffer buffer-file-name (pop path)))
15239 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15240 (level 1)
15241 (lmin 1)
15242 (lmax 1)
15243 limit re end found pos heading cnt flevel)
15244 (unless buffer (error "File not found :%s" file))
15245 (with-current-buffer buffer
15246 (save-excursion
15247 (save-restriction
15248 (widen)
15249 (setq limit (point-max))
15250 (goto-char (point-min))
15251 (while (setq heading (pop path))
15252 (setq re (format org-complex-heading-regexp-format
15253 (regexp-quote heading)))
15254 (setq cnt 0 pos (point))
15255 (while (re-search-forward re end t)
15256 (setq level (- (match-end 1) (match-beginning 1)))
15257 (if (and (>= level lmin) (<= level lmax))
15258 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15259 (when (= cnt 0) (error "Heading not found on level %d: %s"
15260 lmax heading))
15261 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15262 lmax heading))
15263 (goto-char found)
15264 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15265 (setq end (save-excursion (org-end-of-subtree t t))))
15266 (when (org-at-heading-p)
15267 (move-marker (make-marker) (point))))))))
15269 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15270 "Find node HEADING in BUFFER.
15271 Return a marker to the heading if it was found, or nil if not.
15272 If POS-ONLY is set, return just the position instead of a marker.
15274 The heading text must match exact, but it may have a TODO keyword,
15275 a priority cookie and tags in the standard locations."
15276 (with-current-buffer (or buffer (current-buffer))
15277 (save-excursion
15278 (save-restriction
15279 (widen)
15280 (goto-char (point-min))
15281 (let (case-fold-search)
15282 (if (re-search-forward
15283 (format org-complex-heading-regexp-format
15284 (regexp-quote heading)) nil t)
15285 (if pos-only
15286 (match-beginning 0)
15287 (move-marker (make-marker) (match-beginning 0)))))))))
15289 (defun org-find-exact-heading-in-directory (heading &optional dir)
15290 "Find Org node headline HEADING in all .org files in directory DIR.
15291 When the target headline is found, return a marker to this location."
15292 (let ((files (directory-files (or dir default-directory)
15293 nil "\\`[^.#].*\\.org\\'"))
15294 file visiting m buffer)
15295 (catch 'found
15296 (while (setq file (pop files))
15297 (message "trying %s" file)
15298 (setq visiting (org-find-base-buffer-visiting file))
15299 (setq buffer (or visiting (find-file-noselect file)))
15300 (setq m (org-find-exact-headline-in-buffer
15301 heading buffer))
15302 (when (and (not m) (not visiting)) (kill-buffer buffer))
15303 (and m (throw 'found m))))))
15305 (defun org-find-entry-with-id (ident)
15306 "Locate the entry that contains the ID property with exact value IDENT.
15307 IDENT can be a string, a symbol or a number, this function will search for
15308 the string representation of it.
15309 Return the position where this entry starts, or nil if there is no such entry."
15310 (interactive "sID: ")
15311 (let ((id (cond
15312 ((stringp ident) ident)
15313 ((symbol-name ident) (symbol-name ident))
15314 ((numberp ident) (number-to-string ident))
15315 (t (error "IDENT %s must be a string, symbol or number" ident))))
15316 (case-fold-search nil))
15317 (save-excursion
15318 (save-restriction
15319 (widen)
15320 (goto-char (point-min))
15321 (when (re-search-forward
15322 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15323 nil t)
15324 (org-back-to-heading t)
15325 (point))))))
15327 ;;;; Timestamps
15329 (defvar org-last-changed-timestamp nil)
15330 (defvar org-last-inserted-timestamp nil
15331 "The last time stamp inserted with `org-insert-time-stamp'.")
15332 (defvar org-time-was-given) ; dynamically scoped parameter
15333 (defvar org-end-time-was-given) ; dynamically scoped parameter
15334 (defvar org-ts-what) ; dynamically scoped parameter
15336 (defun org-time-stamp (arg &optional inactive)
15337 "Prompt for a date/time and insert a time stamp.
15338 If the user specifies a time like HH:MM or if this command is
15339 called with at least one prefix argument, the time stamp contains
15340 the date and the time. Otherwise, only the date is be included.
15342 All parts of a date not specified by the user is filled in from
15343 the current date/time. So if you just press return without
15344 typing anything, the time stamp will represent the current
15345 date/time.
15347 If there is already a timestamp at the cursor, it will be
15348 modified.
15350 With two universal prefix arguments, insert an active timestamp
15351 with the current time without prompting the user."
15352 (interactive "P")
15353 (let* ((ts nil)
15354 (default-time
15355 ;; Default time is either today, or, when entering a range,
15356 ;; the range start.
15357 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15358 (save-excursion
15359 (re-search-backward
15360 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15361 (- (point) 20) t)))
15362 (apply 'encode-time (org-parse-time-string (match-string 1)))
15363 (current-time)))
15364 (default-input (and ts (org-get-compact-tod ts)))
15365 (repeater (save-excursion
15366 (save-match-data
15367 (beginning-of-line)
15368 (when (re-search-forward
15369 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15370 (save-excursion (progn (end-of-line) (point))) t)
15371 (match-string 0)))))
15372 org-time-was-given org-end-time-was-given time)
15373 (cond
15374 ((and (org-at-timestamp-p t)
15375 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15376 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15377 (insert "--")
15378 (setq time (let ((this-command this-command))
15379 (org-read-date arg 'totime nil nil
15380 default-time default-input inactive)))
15381 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15382 ((org-at-timestamp-p t)
15383 (setq time (let ((this-command this-command))
15384 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15385 (when (org-at-timestamp-p t) ; just to get the match data
15386 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15387 (replace-match "")
15388 (setq org-last-changed-timestamp
15389 (org-insert-time-stamp
15390 time (or org-time-was-given arg)
15391 inactive nil nil (list org-end-time-was-given)))
15392 (when repeater (goto-char (1- (point))) (insert " " repeater)
15393 (setq org-last-changed-timestamp
15394 (concat (substring org-last-inserted-timestamp 0 -1)
15395 " " repeater ">"))))
15396 (message "Timestamp updated"))
15397 ((equal arg '(16))
15398 (org-insert-time-stamp (current-time) t))
15400 (setq time (let ((this-command this-command))
15401 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15402 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15403 nil nil (list org-end-time-was-given))))))
15405 ;; FIXME: can we use this for something else, like computing time differences?
15406 (defun org-get-compact-tod (s)
15407 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15408 (let* ((t1 (match-string 1 s))
15409 (h1 (string-to-number (match-string 2 s)))
15410 (m1 (string-to-number (match-string 3 s)))
15411 (t2 (and (match-end 4) (match-string 5 s)))
15412 (h2 (and t2 (string-to-number (match-string 6 s))))
15413 (m2 (and t2 (string-to-number (match-string 7 s))))
15414 dh dm)
15415 (if (not t2)
15417 (setq dh (- h2 h1) dm (- m2 m1))
15418 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15419 (concat t1 "+" (number-to-string dh)
15420 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15422 (defun org-time-stamp-inactive (&optional arg)
15423 "Insert an inactive time stamp.
15424 An inactive time stamp is enclosed in square brackets instead of angle
15425 brackets. It is inactive in the sense that it does not trigger agenda entries,
15426 does not link to the calendar and cannot be changed with the S-cursor keys.
15427 So these are more for recording a certain time/date."
15428 (interactive "P")
15429 (org-time-stamp arg 'inactive))
15431 (defvar org-date-ovl (make-overlay 1 1))
15432 (overlay-put org-date-ovl 'face 'org-date-selected)
15433 (org-detach-overlay org-date-ovl)
15435 (defvar org-ans1) ; dynamically scoped parameter
15436 (defvar org-ans2) ; dynamically scoped parameter
15438 (defvar org-plain-time-of-day-regexp) ; defined below
15440 (defvar org-overriding-default-time nil) ; dynamically scoped
15441 (defvar org-read-date-overlay nil)
15442 (defvar org-dcst nil) ; dynamically scoped
15443 (defvar org-read-date-history nil)
15444 (defvar org-read-date-final-answer nil)
15445 (defvar org-read-date-analyze-futurep nil)
15446 (defvar org-read-date-analyze-forced-year nil)
15447 (defvar org-read-date-inactive)
15449 (defun org-read-date (&optional org-with-time to-time from-string prompt
15450 default-time default-input inactive)
15451 "Read a date, possibly a time, and make things smooth for the user.
15452 The prompt will suggest to enter an ISO date, but you can also enter anything
15453 which will at least partially be understood by `parse-time-string'.
15454 Unrecognized parts of the date will default to the current day, month, year,
15455 hour and minute. If this command is called to replace a timestamp at point,
15456 or to enter the second timestamp of a range, the default time is taken
15457 from the existing stamp. Furthermore, the command prefers the future,
15458 so if you are giving a date where the year is not given, and the day-month
15459 combination is already past in the current year, it will assume you
15460 mean next year. For details, see the manual. A few examples:
15462 3-2-5 --> 2003-02-05
15463 feb 15 --> currentyear-02-15
15464 2/15 --> currentyear-02-15
15465 sep 12 9 --> 2009-09-12
15466 12:45 --> today 12:45
15467 22 sept 0:34 --> currentyear-09-22 0:34
15468 12 --> currentyear-currentmonth-12
15469 Fri --> nearest Friday (today or later)
15470 etc.
15472 Furthermore you can specify a relative date by giving, as the *first* thing
15473 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15474 change in days weeks, months, years.
15475 With a single plus or minus, the date is relative to today. With a double
15476 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15477 +4d --> four days from today
15478 +4 --> same as above
15479 +2w --> two weeks from today
15480 ++5 --> five days from default date
15482 The function understands only English month and weekday abbreviations.
15484 While prompting, a calendar is popped up - you can also select the
15485 date with the mouse (button 1). The calendar shows a period of three
15486 months. To scroll it to other months, use the keys `>' and `<'.
15487 If you don't like the calendar, turn it off with
15488 \(setq org-read-date-popup-calendar nil)
15490 With optional argument TO-TIME, the date will immediately be converted
15491 to an internal time.
15492 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15493 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15494 still enter a time, and this function will inform the calling routine
15495 about this change. The calling routine may then choose to change the
15496 format used to insert the time stamp into the buffer to include the time.
15497 With optional argument FROM-STRING, read from this string instead from
15498 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15499 the time/date that is used for everything that is not specified by the
15500 user."
15501 (require 'parse-time)
15502 (let* ((org-time-stamp-rounding-minutes
15503 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15504 (org-dcst org-display-custom-times)
15505 (ct (org-current-time))
15506 (org-def (or org-overriding-default-time default-time ct))
15507 (org-defdecode (decode-time org-def))
15508 (dummy (progn
15509 (when (< (nth 2 org-defdecode) org-extend-today-until)
15510 (setcar (nthcdr 2 org-defdecode) -1)
15511 (setcar (nthcdr 1 org-defdecode) 59)
15512 (setq org-def (apply 'encode-time org-defdecode)
15513 org-defdecode (decode-time org-def)))))
15514 (calendar-frame-setup nil)
15515 (calendar-setup nil)
15516 (calendar-move-hook nil)
15517 (calendar-view-diary-initially-flag nil)
15518 (calendar-view-holidays-initially-flag nil)
15519 (timestr (format-time-string
15520 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15521 (prompt (concat (if prompt (concat prompt " ") "")
15522 (format "Date+time [%s]: " timestr)))
15523 ans (org-ans0 "") org-ans1 org-ans2 final)
15525 (cond
15526 (from-string (setq ans from-string))
15527 (org-read-date-popup-calendar
15528 (save-excursion
15529 (save-window-excursion
15530 (calendar)
15531 (org-eval-in-calendar '(setq cursor-type nil) t)
15532 (unwind-protect
15533 (progn
15534 (calendar-forward-day (- (time-to-days org-def)
15535 (calendar-absolute-from-gregorian
15536 (calendar-current-date))))
15537 (org-eval-in-calendar nil t)
15538 (let* ((old-map (current-local-map))
15539 (map (copy-keymap calendar-mode-map))
15540 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15541 (org-defkey map (kbd "RET") 'org-calendar-select)
15542 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15543 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15544 (org-defkey minibuffer-local-map [(meta shift left)]
15545 (lambda () (interactive)
15546 (org-eval-in-calendar '(calendar-backward-month 1))))
15547 (org-defkey minibuffer-local-map [(meta shift right)]
15548 (lambda () (interactive)
15549 (org-eval-in-calendar '(calendar-forward-month 1))))
15550 (org-defkey minibuffer-local-map [(meta shift up)]
15551 (lambda () (interactive)
15552 (org-eval-in-calendar '(calendar-backward-year 1))))
15553 (org-defkey minibuffer-local-map [(meta shift down)]
15554 (lambda () (interactive)
15555 (org-eval-in-calendar '(calendar-forward-year 1))))
15556 (org-defkey minibuffer-local-map [?\e (shift left)]
15557 (lambda () (interactive)
15558 (org-eval-in-calendar '(calendar-backward-month 1))))
15559 (org-defkey minibuffer-local-map [?\e (shift right)]
15560 (lambda () (interactive)
15561 (org-eval-in-calendar '(calendar-forward-month 1))))
15562 (org-defkey minibuffer-local-map [?\e (shift up)]
15563 (lambda () (interactive)
15564 (org-eval-in-calendar '(calendar-backward-year 1))))
15565 (org-defkey minibuffer-local-map [?\e (shift down)]
15566 (lambda () (interactive)
15567 (org-eval-in-calendar '(calendar-forward-year 1))))
15568 (org-defkey minibuffer-local-map [(shift up)]
15569 (lambda () (interactive)
15570 (org-eval-in-calendar '(calendar-backward-week 1))))
15571 (org-defkey minibuffer-local-map [(shift down)]
15572 (lambda () (interactive)
15573 (org-eval-in-calendar '(calendar-forward-week 1))))
15574 (org-defkey minibuffer-local-map [(shift left)]
15575 (lambda () (interactive)
15576 (org-eval-in-calendar '(calendar-backward-day 1))))
15577 (org-defkey minibuffer-local-map [(shift right)]
15578 (lambda () (interactive)
15579 (org-eval-in-calendar '(calendar-forward-day 1))))
15580 (org-defkey minibuffer-local-map ">"
15581 (lambda () (interactive)
15582 (org-eval-in-calendar '(scroll-calendar-left 1))))
15583 (org-defkey minibuffer-local-map "<"
15584 (lambda () (interactive)
15585 (org-eval-in-calendar '(scroll-calendar-right 1))))
15586 (org-defkey minibuffer-local-map "\C-v"
15587 (lambda () (interactive)
15588 (org-eval-in-calendar
15589 '(calendar-scroll-left-three-months 1))))
15590 (org-defkey minibuffer-local-map "\M-v"
15591 (lambda () (interactive)
15592 (org-eval-in-calendar
15593 '(calendar-scroll-right-three-months 1))))
15594 (run-hooks 'org-read-date-minibuffer-setup-hook)
15595 (unwind-protect
15596 (progn
15597 (use-local-map map)
15598 (setq org-read-date-inactive inactive)
15599 (add-hook 'post-command-hook 'org-read-date-display)
15600 (setq org-ans0 (read-string prompt default-input
15601 'org-read-date-history nil))
15602 ;; org-ans0: from prompt
15603 ;; org-ans1: from mouse click
15604 ;; org-ans2: from calendar motion
15605 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15606 (remove-hook 'post-command-hook 'org-read-date-display)
15607 (use-local-map old-map)
15608 (when org-read-date-overlay
15609 (delete-overlay org-read-date-overlay)
15610 (setq org-read-date-overlay nil)))))
15611 (bury-buffer "*Calendar*")))))
15613 (t ; Naked prompt only
15614 (unwind-protect
15615 (setq ans (read-string prompt default-input
15616 'org-read-date-history timestr))
15617 (when org-read-date-overlay
15618 (delete-overlay org-read-date-overlay)
15619 (setq org-read-date-overlay nil)))))
15621 (setq final (org-read-date-analyze ans org-def org-defdecode))
15623 (when org-read-date-analyze-forced-year
15624 (message "Year was forced into %s"
15625 (if org-read-date-force-compatible-dates
15626 "compatible range (1970-2037)"
15627 "range representable on this machine"))
15628 (ding))
15630 ;; One round trip to get rid of 34th of August and stuff like that....
15631 (setq final (decode-time (apply 'encode-time final)))
15633 (setq org-read-date-final-answer ans)
15635 (if to-time
15636 (apply 'encode-time final)
15637 (if (and (boundp 'org-time-was-given) org-time-was-given)
15638 (format "%04d-%02d-%02d %02d:%02d"
15639 (nth 5 final) (nth 4 final) (nth 3 final)
15640 (nth 2 final) (nth 1 final))
15641 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15643 (defvar org-def)
15644 (defvar org-defdecode)
15645 (defvar org-with-time)
15646 (defun org-read-date-display ()
15647 "Display the current date prompt interpretation in the minibuffer."
15648 (when org-read-date-display-live
15649 (when org-read-date-overlay
15650 (delete-overlay org-read-date-overlay))
15651 (when (minibufferp (current-buffer))
15652 (save-excursion
15653 (end-of-line 1)
15654 (while (not (equal (buffer-substring
15655 (max (point-min) (- (point) 4)) (point))
15656 " "))
15657 (insert " ")))
15658 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15659 " " (or org-ans1 org-ans2)))
15660 (org-end-time-was-given nil)
15661 (f (org-read-date-analyze ans org-def org-defdecode))
15662 (fmts (if org-dcst
15663 org-time-stamp-custom-formats
15664 org-time-stamp-formats))
15665 (fmt (if (or org-with-time
15666 (and (boundp 'org-time-was-given) org-time-was-given))
15667 (cdr fmts)
15668 (car fmts)))
15669 (txt (format-time-string fmt (apply 'encode-time f)))
15670 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15671 (txt (concat "=> " txt)))
15672 (when (and org-end-time-was-given
15673 (string-match org-plain-time-of-day-regexp txt))
15674 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15675 org-end-time-was-given
15676 (substring txt (match-end 0)))))
15677 (when org-read-date-analyze-futurep
15678 (setq txt (concat txt " (=>F)")))
15679 (setq org-read-date-overlay
15680 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15681 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15683 (defun org-read-date-analyze (ans org-def org-defdecode)
15684 "Analyze the combined answer of the date prompt."
15685 ;; FIXME: cleanup and comment
15686 (let ((nowdecode (decode-time (current-time)))
15687 delta deltan deltaw deltadef year month day
15688 hour minute second wday pm h2 m2 tl wday1
15689 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15690 (setq org-read-date-analyze-futurep nil
15691 org-read-date-analyze-forced-year nil)
15692 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15693 (setq ans "+0"))
15695 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15696 (setq ans (replace-match "" t t ans)
15697 deltan (car delta)
15698 deltaw (nth 1 delta)
15699 deltadef (nth 2 delta)))
15701 ;; Check if there is an iso week date in there. If yes, store the
15702 ;; info and postpone interpreting it until the rest of the parsing
15703 ;; is done.
15704 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15705 (setq iso-year (if (match-end 1)
15706 (org-small-year-to-year
15707 (string-to-number (match-string 1 ans))))
15708 iso-weekday (if (match-end 3)
15709 (string-to-number (match-string 3 ans)))
15710 iso-week (string-to-number (match-string 2 ans)))
15711 (setq ans (replace-match "" t t ans)))
15713 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15714 (when (string-match
15715 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15716 (setq year (if (match-end 2)
15717 (string-to-number (match-string 2 ans))
15718 (progn (setq kill-year t)
15719 (string-to-number (format-time-string "%Y"))))
15720 month (string-to-number (match-string 3 ans))
15721 day (string-to-number (match-string 4 ans)))
15722 (if (< year 100) (setq year (+ 2000 year)))
15723 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15724 t nil ans)))
15726 ;; Help matching dotted european dates
15727 (when (string-match
15728 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15729 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15730 (setq kill-year t)
15731 (string-to-number (format-time-string "%Y")))
15732 day (string-to-number (match-string 1 ans))
15733 month (string-to-number (match-string 2 ans))
15734 ans (replace-match (format "%04d-%02d-%02d" year month day)
15735 t nil ans)))
15737 ;; Help matching american dates, like 5/30 or 5/30/7
15738 (when (string-match
15739 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15740 (setq year (if (match-end 4)
15741 (string-to-number (match-string 4 ans))
15742 (progn (setq kill-year t)
15743 (string-to-number (format-time-string "%Y"))))
15744 month (string-to-number (match-string 1 ans))
15745 day (string-to-number (match-string 2 ans)))
15746 (if (< year 100) (setq year (+ 2000 year)))
15747 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15748 t nil ans)))
15749 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15750 ;; If there is a time with am/pm, and *no* time without it, we convert
15751 ;; so that matching will be successful.
15752 (loop for i from 1 to 2 do ; twice, for end time as well
15753 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15754 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15755 (setq hour (string-to-number (match-string 1 ans))
15756 minute (if (match-end 3)
15757 (string-to-number (match-string 3 ans))
15759 pm (equal ?p
15760 (string-to-char (downcase (match-string 4 ans)))))
15761 (if (and (= hour 12) (not pm))
15762 (setq hour 0)
15763 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15764 (setq ans (replace-match (format "%02d:%02d" hour minute)
15765 t t ans))))
15767 ;; Check if a time range is given as a duration
15768 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15769 (setq hour (string-to-number (match-string 1 ans))
15770 h2 (+ hour (string-to-number (match-string 3 ans)))
15771 minute (string-to-number (match-string 2 ans))
15772 m2 (+ minute (if (match-end 5) (string-to-number
15773 (match-string 5 ans))0)))
15774 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15775 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15776 t t ans)))
15778 ;; Check if there is a time range
15779 (when (boundp 'org-end-time-was-given)
15780 (setq org-time-was-given nil)
15781 (when (and (string-match org-plain-time-of-day-regexp ans)
15782 (match-end 8))
15783 (setq org-end-time-was-given (match-string 8 ans))
15784 (setq ans (concat (substring ans 0 (match-beginning 7))
15785 (substring ans (match-end 7))))))
15787 (setq tl (parse-time-string ans)
15788 day (or (nth 3 tl) (nth 3 org-defdecode))
15789 month (or (nth 4 tl)
15790 (if (and org-read-date-prefer-future
15791 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15792 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15793 (nth 4 org-defdecode)))
15794 year (or (and (not kill-year) (nth 5 tl))
15795 (if (and org-read-date-prefer-future
15796 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15797 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15798 (nth 5 org-defdecode)))
15799 hour (or (nth 2 tl) (nth 2 org-defdecode))
15800 minute (or (nth 1 tl) (nth 1 org-defdecode))
15801 second (or (nth 0 tl) 0)
15802 wday (nth 6 tl))
15804 (when (and (eq org-read-date-prefer-future 'time)
15805 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15806 (equal day (nth 3 nowdecode))
15807 (equal month (nth 4 nowdecode))
15808 (equal year (nth 5 nowdecode))
15809 (nth 2 tl)
15810 (or (< (nth 2 tl) (nth 2 nowdecode))
15811 (and (= (nth 2 tl) (nth 2 nowdecode))
15812 (nth 1 tl)
15813 (< (nth 1 tl) (nth 1 nowdecode)))))
15814 (setq day (1+ day)
15815 futurep t))
15817 ;; Special date definitions below
15818 (cond
15819 (iso-week
15820 ;; There was an iso week
15821 (require 'cal-iso)
15822 (setq futurep nil)
15823 (setq year (or iso-year year)
15824 day (or iso-weekday wday 1)
15825 wday nil ; to make sure that the trigger below does not match
15826 iso-date (calendar-gregorian-from-absolute
15827 (calendar-absolute-from-iso
15828 (list iso-week day year))))
15829 ; FIXME: Should we also push ISO weeks into the future?
15830 ; (when (and org-read-date-prefer-future
15831 ; (not iso-year)
15832 ; (< (calendar-absolute-from-gregorian iso-date)
15833 ; (time-to-days (current-time))))
15834 ; (setq year (1+ year)
15835 ; iso-date (calendar-gregorian-from-absolute
15836 ; (calendar-absolute-from-iso
15837 ; (list iso-week day year)))))
15838 (setq month (car iso-date)
15839 year (nth 2 iso-date)
15840 day (nth 1 iso-date)))
15841 (deltan
15842 (setq futurep nil)
15843 (unless deltadef
15844 (let ((now (decode-time (current-time))))
15845 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15846 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15847 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15848 ((equal deltaw "m") (setq month (+ month deltan)))
15849 ((equal deltaw "y") (setq year (+ year deltan)))))
15850 ((and wday (not (nth 3 tl)))
15851 ;; Weekday was given, but no day, so pick that day in the week
15852 ;; on or after the derived date.
15853 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15854 (unless (equal wday wday1)
15855 (setq day (+ day (% (- wday wday1 -7) 7))))))
15856 (if (and (boundp 'org-time-was-given)
15857 (nth 2 tl))
15858 (setq org-time-was-given t))
15859 (if (< year 100) (setq year (+ 2000 year)))
15860 ;; Check of the date is representable
15861 (if org-read-date-force-compatible-dates
15862 (progn
15863 (if (< year 1970)
15864 (setq year 1970 org-read-date-analyze-forced-year t))
15865 (if (> year 2037)
15866 (setq year 2037 org-read-date-analyze-forced-year t)))
15867 (condition-case nil
15868 (ignore (encode-time second minute hour day month year))
15869 (error
15870 (setq year (nth 5 org-defdecode))
15871 (setq org-read-date-analyze-forced-year t))))
15872 (setq org-read-date-analyze-futurep futurep)
15873 (list second minute hour day month year)))
15875 (defvar parse-time-weekdays)
15876 (defun org-read-date-get-relative (s today default)
15877 "Check string S for special relative date string.
15878 TODAY and DEFAULT are internal times, for today and for a default.
15879 Return shift list (N what def-flag)
15880 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15881 N is the number of WHATs to shift.
15882 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15883 the DEFAULT date rather than TODAY."
15884 (require 'parse-time)
15885 (when (and
15886 (string-match
15887 (concat
15888 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15889 "\\([0-9]+\\)?"
15890 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15891 "\\([ \t]\\|$\\)") s)
15892 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15893 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15894 (string-to-char (substring (match-string 1 s) -1))
15895 ?+))
15896 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15897 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15898 (what (if (match-end 3) (match-string 3 s) "d"))
15899 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15900 (date (if rel default today))
15901 (wday (nth 6 (decode-time date)))
15902 delta)
15903 (if wday1
15904 (progn
15905 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15906 (if (= dir ?-) (setq delta (- delta 7)))
15907 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15908 (list delta "d" rel))
15909 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15911 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15912 "Turn a user-specified date into the internal representation.
15913 The internal representation needed by the calendar is (month day year).
15914 This is a wrapper to handle the brain-dead convention in calendar that
15915 user function argument order change dependent on argument order."
15916 (if (boundp 'calendar-date-style)
15917 (cond
15918 ((eq calendar-date-style 'american)
15919 (list arg1 arg2 arg3))
15920 ((eq calendar-date-style 'european)
15921 (list arg2 arg1 arg3))
15922 ((eq calendar-date-style 'iso)
15923 (list arg2 arg3 arg1)))
15924 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15925 (if (org-bound-and-true-p european-calendar-style)
15926 (list arg2 arg1 arg3)
15927 (list arg1 arg2 arg3)))))
15929 (defun org-eval-in-calendar (form &optional keepdate)
15930 "Eval FORM in the calendar window and return to current window.
15931 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15932 otherwise stick to the current value of `org-ans2'."
15933 (let ((sf (selected-frame))
15934 (sw (selected-window)))
15935 (select-window (get-buffer-window "*Calendar*" t))
15936 (eval form)
15937 (when (and (not keepdate) (calendar-cursor-to-date))
15938 (let* ((date (calendar-cursor-to-date))
15939 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15940 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15941 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15942 (select-window sw)
15943 (org-select-frame-set-input-focus sf)))
15945 (defun org-calendar-select ()
15946 "Return to `org-read-date' with the date currently selected.
15947 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15948 (interactive)
15949 (when (calendar-cursor-to-date)
15950 (let* ((date (calendar-cursor-to-date))
15951 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15952 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15953 (if (active-minibuffer-window) (exit-minibuffer))))
15955 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15956 "Insert a date stamp for the date given by the internal TIME.
15957 WITH-HM means use the stamp format that includes the time of the day.
15958 INACTIVE means use square brackets instead of angular ones, so that the
15959 stamp will not contribute to the agenda.
15960 PRE and POST are optional strings to be inserted before and after the
15961 stamp.
15962 The command returns the inserted time stamp."
15963 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15964 stamp)
15965 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15966 (insert-before-markers (or pre ""))
15967 (when (listp extra)
15968 (setq extra (car extra))
15969 (if (and (stringp extra)
15970 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15971 (setq extra (format "-%02d:%02d"
15972 (string-to-number (match-string 1 extra))
15973 (string-to-number (match-string 2 extra))))
15974 (setq extra nil)))
15975 (when extra
15976 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15977 (insert-before-markers (setq stamp (format-time-string fmt time)))
15978 (insert-before-markers (or post ""))
15979 (setq org-last-inserted-timestamp stamp)))
15981 (defun org-toggle-time-stamp-overlays ()
15982 "Toggle the use of custom time stamp formats."
15983 (interactive)
15984 (setq org-display-custom-times (not org-display-custom-times))
15985 (unless org-display-custom-times
15986 (let ((p (point-min)) (bmp (buffer-modified-p)))
15987 (while (setq p (next-single-property-change p 'display))
15988 (if (and (get-text-property p 'display)
15989 (eq (get-text-property p 'face) 'org-date))
15990 (remove-text-properties
15991 p (setq p (next-single-property-change p 'display))
15992 '(display t))))
15993 (set-buffer-modified-p bmp)))
15994 (if (featurep 'xemacs)
15995 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15996 (org-restart-font-lock)
15997 (setq org-table-may-need-update t)
15998 (if org-display-custom-times
15999 (message "Time stamps are overlaid with custom format")
16000 (message "Time stamp overlays removed")))
16002 (defun org-display-custom-time (beg end)
16003 "Overlay modified time stamp format over timestamp between BEG and END."
16004 (let* ((ts (buffer-substring beg end))
16005 t1 w1 with-hm tf time str w2 (off 0))
16006 (save-match-data
16007 (setq t1 (org-parse-time-string ts t))
16008 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16009 (setq off (- (match-end 0) (match-beginning 0)))))
16010 (setq end (- end off))
16011 (setq w1 (- end beg)
16012 with-hm (and (nth 1 t1) (nth 2 t1))
16013 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16014 time (org-fix-decoded-time t1)
16015 str (org-add-props
16016 (format-time-string
16017 (substring tf 1 -1) (apply 'encode-time time))
16018 nil 'mouse-face 'highlight)
16019 w2 (length str))
16020 (if (not (= w2 w1))
16021 (add-text-properties (1+ beg) (+ 2 beg)
16022 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16023 (if (featurep 'xemacs)
16024 (progn
16025 (put-text-property beg end 'invisible t)
16026 (put-text-property beg end 'end-glyph (make-glyph str)))
16027 (put-text-property beg end 'display str))))
16029 (defun org-translate-time (string)
16030 "Translate all timestamps in STRING to custom format.
16031 But do this only if the variable `org-display-custom-times' is set."
16032 (when org-display-custom-times
16033 (save-match-data
16034 (let* ((start 0)
16035 (re org-ts-regexp-both)
16036 t1 with-hm inactive tf time str beg end)
16037 (while (setq start (string-match re string start))
16038 (setq beg (match-beginning 0)
16039 end (match-end 0)
16040 t1 (save-match-data
16041 (org-parse-time-string (substring string beg end) t))
16042 with-hm (and (nth 1 t1) (nth 2 t1))
16043 inactive (equal (substring string beg (1+ beg)) "[")
16044 tf (funcall (if with-hm 'cdr 'car)
16045 org-time-stamp-custom-formats)
16046 time (org-fix-decoded-time t1)
16047 str (format-time-string
16048 (concat
16049 (if inactive "[" "<") (substring tf 1 -1)
16050 (if inactive "]" ">"))
16051 (apply 'encode-time time))
16052 string (replace-match str t t string)
16053 start (+ start (length str)))))))
16054 string)
16056 (defun org-fix-decoded-time (time)
16057 "Set 0 instead of nil for the first 6 elements of time.
16058 Don't touch the rest."
16059 (let ((n 0))
16060 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16062 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16064 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16065 "Difference between TIMESTAMP-STRING and now in days.
16066 If SECONDS is non-nil, return the difference in seconds."
16067 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16068 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16069 (funcall fdiff (current-time)))))
16071 (defun org-deadline-close (timestamp-string &optional ndays)
16072 "Is the time in TIMESTAMP-STRING close to the current date?"
16073 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16074 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16075 (not (org-entry-is-done-p))))
16077 (defun org-get-wdays (ts)
16078 "Get the deadline lead time appropriate for timestring TS."
16079 (cond
16080 ((<= org-deadline-warning-days 0)
16081 ;; 0 or negative, enforce this value no matter what
16082 (- org-deadline-warning-days))
16083 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16084 ;; lead time is specified.
16085 (floor (* (string-to-number (match-string 1 ts))
16086 (cdr (assoc (match-string 2 ts)
16087 '(("d" . 1) ("w" . 7)
16088 ("m" . 30.4) ("y" . 365.25)))))))
16089 ;; go for the default.
16090 (t org-deadline-warning-days)))
16092 (defun org-calendar-select-mouse (ev)
16093 "Return to `org-read-date' with the date currently selected.
16094 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16095 (interactive "e")
16096 (mouse-set-point ev)
16097 (when (calendar-cursor-to-date)
16098 (let* ((date (calendar-cursor-to-date))
16099 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16100 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16101 (if (active-minibuffer-window) (exit-minibuffer))))
16103 (defun org-check-deadlines (ndays)
16104 "Check if there are any deadlines due or past due.
16105 A deadline is considered due if it happens within `org-deadline-warning-days'
16106 days from today's date. If the deadline appears in an entry marked DONE,
16107 it is not shown. The prefix arg NDAYS can be used to test that many
16108 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16109 (interactive "P")
16110 (let* ((org-warn-days
16111 (cond
16112 ((equal ndays '(4)) 100000)
16113 (ndays (prefix-numeric-value ndays))
16114 (t (abs org-deadline-warning-days))))
16115 (case-fold-search nil)
16116 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16117 (callback
16118 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16120 (message "%d deadlines past-due or due within %d days"
16121 (org-occur regexp nil callback)
16122 org-warn-days)))
16124 (defsubst org-re-timestamp (type)
16125 "Return a regexp for timestamp TYPE.
16126 Allowed values for TYPE are:
16128 all: all timestamps
16129 active: only active timestamps (<...>)
16130 inactive: only inactive timestamps ([...])
16131 scheduled: only scheduled timestamps
16132 deadline: only deadline timestamps
16134 When TYPE is nil, fall back on returning a regexp that matches
16135 both scheduled and deadline timestamps."
16136 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16137 ((eq type 'active) org-ts-regexp)
16138 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16139 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16140 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16141 ((eq type 'scheduled-or-deadline)
16142 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16144 (defun org-check-before-date (date)
16145 "Check if there are deadlines or scheduled entries before DATE."
16146 (interactive (list (org-read-date)))
16147 (let ((case-fold-search nil)
16148 (regexp (org-re-timestamp org-ts-type))
16149 (callback
16150 (lambda () (time-less-p
16151 (org-time-string-to-time (match-string 1))
16152 (org-time-string-to-time date)))))
16153 (message "%d entries before %s"
16154 (org-occur regexp nil callback) date)))
16156 (defun org-check-after-date (date)
16157 "Check if there are deadlines or scheduled entries after DATE."
16158 (interactive (list (org-read-date)))
16159 (let ((case-fold-search nil)
16160 (regexp (org-re-timestamp org-ts-type))
16161 (callback
16162 (lambda () (not
16163 (time-less-p
16164 (org-time-string-to-time (match-string 1))
16165 (org-time-string-to-time date))))))
16166 (message "%d entries after %s"
16167 (org-occur regexp nil callback) date)))
16169 (defun org-check-dates-range (start-date end-date)
16170 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16171 (interactive (list (org-read-date nil nil nil "Range starts")
16172 (org-read-date nil nil nil "Range end")))
16173 (let ((case-fold-search nil)
16174 (regexp (org-re-timestamp org-ts-type))
16175 (callback
16176 (lambda ()
16177 (let ((match (match-string 1)))
16178 (and
16179 (not (time-less-p
16180 (org-time-string-to-time match)
16181 (org-time-string-to-time start-date)))
16182 (time-less-p
16183 (org-time-string-to-time match)
16184 (org-time-string-to-time end-date)))))))
16185 (message "%d entries between %s and %s"
16186 (org-occur regexp nil callback) start-date end-date)))
16188 (defun org-evaluate-time-range (&optional to-buffer)
16189 "Evaluate a time range by computing the difference between start and end.
16190 Normally the result is just printed in the echo area, but with prefix arg
16191 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16192 If the time range is actually in a table, the result is inserted into the
16193 next column.
16194 For time difference computation, a year is assumed to be exactly 365
16195 days in order to avoid rounding problems."
16196 (interactive "P")
16198 (org-clock-update-time-maybe)
16199 (save-excursion
16200 (unless (org-at-date-range-p t)
16201 (goto-char (point-at-bol))
16202 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16203 (if (not (org-at-date-range-p t))
16204 (error "Not at a time-stamp range, and none found in current line")))
16205 (let* ((ts1 (match-string 1))
16206 (ts2 (match-string 2))
16207 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16208 (match-end (match-end 0))
16209 (time1 (org-time-string-to-time ts1))
16210 (time2 (org-time-string-to-time ts2))
16211 (t1 (org-float-time time1))
16212 (t2 (org-float-time time2))
16213 (diff (abs (- t2 t1)))
16214 (negative (< (- t2 t1) 0))
16215 ;; (ys (floor (* 365 24 60 60)))
16216 (ds (* 24 60 60))
16217 (hs (* 60 60))
16218 (fy "%dy %dd %02d:%02d")
16219 (fy1 "%dy %dd")
16220 (fd "%dd %02d:%02d")
16221 (fd1 "%dd")
16222 (fh "%02d:%02d")
16223 y d h m align)
16224 (if havetime
16225 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16227 d (floor (/ diff ds)) diff (mod diff ds)
16228 h (floor (/ diff hs)) diff (mod diff hs)
16229 m (floor (/ diff 60)))
16230 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16232 d (floor (+ (/ diff ds) 0.5))
16233 h 0 m 0))
16234 (if (not to-buffer)
16235 (message "%s" (org-make-tdiff-string y d h m))
16236 (if (org-at-table-p)
16237 (progn
16238 (goto-char match-end)
16239 (setq align t)
16240 (and (looking-at " *|") (goto-char (match-end 0))))
16241 (goto-char match-end))
16242 (if (looking-at
16243 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16244 (replace-match ""))
16245 (if negative (insert " -"))
16246 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16247 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16248 (insert " " (format fh h m))))
16249 (if align (org-table-align))
16250 (message "Time difference inserted")))))
16252 (defun org-make-tdiff-string (y d h m)
16253 (let ((fmt "")
16254 (l nil))
16255 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16256 l (push y l)))
16257 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16258 l (push d l)))
16259 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16260 l (push h l)))
16261 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16262 l (push m l)))
16263 (apply 'format fmt (nreverse l))))
16265 (defun org-time-string-to-time (s &optional buffer pos)
16266 "Convert a timestamp string into internal time."
16267 (condition-case errdata
16268 (apply 'encode-time (org-parse-time-string s))
16269 (error (error "Bad timestamp `%s'%s\nError was: %s"
16270 s (if (not (and buffer pos))
16272 (format " at %d in buffer `%s'" pos buffer))
16273 (cdr errdata)))))
16275 (defun org-time-string-to-seconds (s)
16276 "Convert a timestamp string to a number of seconds."
16277 (org-float-time (org-time-string-to-time s)))
16279 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16280 "Convert a time stamp to an absolute day number.
16281 If there is a specifier for a cyclic time stamp, get the closest date to
16282 DAYNR.
16283 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16284 The variable date is bound by the calendar when this is called."
16285 (cond
16286 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16287 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16288 daynr
16289 (+ daynr 1000)))
16290 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16291 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16292 (time-to-days (current-time))) (match-string 0 s)
16293 prefer show-all))
16294 (t (time-to-days
16295 (condition-case errdata
16296 (apply 'encode-time (org-parse-time-string s))
16297 (error (error "Bad timestamp `%s'%s\nError was: %s"
16298 s (if (not (and buffer pos))
16300 (format " at %d in buffer `%s'" pos buffer))
16301 (cdr errdata))))))))
16303 (defun org-days-to-iso-week (days)
16304 "Return the iso week number."
16305 (require 'cal-iso)
16306 (car (calendar-iso-from-absolute days)))
16308 (defun org-small-year-to-year (year)
16309 "Convert 2-digit years into 4-digit years.
16310 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16311 The year 2000 cannot be abbreviated. Any year larger than 99
16312 is returned unchanged."
16313 (if (< year 38)
16314 (setq year (+ 2000 year))
16315 (if (< year 100)
16316 (setq year (+ 1900 year))))
16317 year)
16319 (defun org-time-from-absolute (d)
16320 "Return the time corresponding to date D.
16321 D may be an absolute day number, or a calendar-type list (month day year)."
16322 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16323 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16325 (defun org-calendar-holiday ()
16326 "List of holidays, for Diary display in Org-mode."
16327 (require 'holidays)
16328 (let ((hl (funcall
16329 (if (fboundp 'calendar-check-holidays)
16330 'calendar-check-holidays 'check-calendar-holidays) date)))
16331 (if hl (mapconcat 'identity hl "; "))))
16333 (defun org-diary-sexp-entry (sexp entry date)
16334 "Process a SEXP diary ENTRY for DATE."
16335 (require 'diary-lib)
16336 (let ((result (if calendar-debug-sexp
16337 (let ((stack-trace-on-error t))
16338 (eval (car (read-from-string sexp))))
16339 (condition-case nil
16340 (eval (car (read-from-string sexp)))
16341 (error
16342 (beep)
16343 (message "Bad sexp at line %d in %s: %s"
16344 (org-current-line)
16345 (buffer-file-name) sexp)
16346 (sleep-for 2))))))
16347 (cond ((stringp result) (split-string result "; "))
16348 ((and (consp result)
16349 (not (consp (cdr result)))
16350 (stringp (cdr result))) (cdr result))
16351 ((and (consp result)
16352 (stringp (car result))) result)
16353 (result entry))))
16355 (defun org-diary-to-ical-string (frombuf)
16356 "Get iCalendar entries from diary entries in buffer FROMBUF.
16357 This uses the icalendar.el library."
16358 (let* ((tmpdir (if (featurep 'xemacs)
16359 (temp-directory)
16360 temporary-file-directory))
16361 (tmpfile (make-temp-name
16362 (expand-file-name "orgics" tmpdir)))
16363 buf rtn b e)
16364 (with-current-buffer frombuf
16365 (icalendar-export-region (point-min) (point-max) tmpfile)
16366 (setq buf (find-buffer-visiting tmpfile))
16367 (set-buffer buf)
16368 (goto-char (point-min))
16369 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16370 (setq b (match-beginning 0)))
16371 (goto-char (point-max))
16372 (if (re-search-backward "^END:VEVENT" nil t)
16373 (setq e (match-end 0)))
16374 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16375 (kill-buffer buf)
16376 (delete-file tmpfile)
16377 rtn))
16379 (defun org-closest-date (start current change prefer show-all)
16380 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16381 When PREFER is `past', return a date that is either CURRENT or past.
16382 When PREFER is `future', return a date that is either CURRENT or future.
16383 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16384 ;; Make the proper lists from the dates
16385 (catch 'exit
16386 (let ((a1 '(("h" . hour)
16387 ("d" . day)
16388 ("w" . week)
16389 ("m" . month)
16390 ("y" . year)))
16391 (shour (nth 2 (org-parse-time-string start)))
16392 dn dw sday cday n1 n2 n0
16393 d m y y1 y2 date1 date2 nmonths nm ny m2)
16395 (setq start (org-date-to-gregorian start)
16396 current (org-date-to-gregorian
16397 (if show-all
16398 current
16399 (time-to-days (current-time))))
16400 sday (calendar-absolute-from-gregorian start)
16401 cday (calendar-absolute-from-gregorian current))
16403 (if (<= cday sday) (throw 'exit sday))
16405 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16406 (setq dn (string-to-number (match-string 1 change))
16407 dw (cdr (assoc (match-string 2 change) a1)))
16408 (error "Invalid change specifier: %s" change))
16409 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16410 (cond
16411 ((eq dw 'hour)
16412 (let ((missing-hours
16413 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16414 dn)))
16415 (setq n1 (if (zerop missing-hours) cday
16416 (- cday (1+ (floor (/ missing-hours 24)))))
16417 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16418 ((eq dw 'day)
16419 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16420 n2 (+ n1 dn)))
16421 ((eq dw 'year)
16422 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16423 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16424 (setq date1 (list m d y1)
16425 n1 (calendar-absolute-from-gregorian date1)
16426 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16427 n2 (calendar-absolute-from-gregorian date2)))
16428 ((eq dw 'month)
16429 ;; approx number of month between the two dates
16430 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16431 ;; How often does dn fit in there?
16432 (setq d (nth 1 start) m (car start) y (nth 2 start)
16433 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16434 m (+ m nm)
16435 ny (floor (/ m 12))
16436 y (+ y ny)
16437 m (- m (* ny 12)))
16438 (while (> m 12) (setq m (- m 12) y (1+ y)))
16439 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16440 (setq m2 (+ m dn) y2 y)
16441 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16442 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16443 (while (<= n2 cday)
16444 (setq n1 n2 m m2 y y2)
16445 (setq m2 (+ m dn) y2 y)
16446 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16447 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16448 ;; Make sure n1 is the earlier date
16449 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16450 (if show-all
16451 (cond
16452 ((eq prefer 'past) (if (= cday n2) n2 n1))
16453 ((eq prefer 'future) (if (= cday n1) n1 n2))
16454 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16455 (cond
16456 ((eq prefer 'past) (if (= cday n2) n2 n1))
16457 ((eq prefer 'future) (if (= cday n1) n1 n2))
16458 (t (if (= cday n1) n1 n2)))))))
16460 (defun org-date-to-gregorian (date)
16461 "Turn any specification of DATE into a Gregorian date for the calendar."
16462 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16463 ((and (listp date) (= (length date) 3)) date)
16464 ((stringp date)
16465 (setq date (org-parse-time-string date))
16466 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16467 ((listp date)
16468 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16470 (defun org-parse-time-string (s &optional nodefault)
16471 "Parse the standard Org-mode time string.
16472 This should be a lot faster than the normal `parse-time-string'.
16473 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16474 hour and minute fields will be nil if not given."
16475 (if (string-match org-ts-regexp0 s)
16476 (list 0
16477 (if (or (match-beginning 8) (not nodefault))
16478 (string-to-number (or (match-string 8 s) "0")))
16479 (if (or (match-beginning 7) (not nodefault))
16480 (string-to-number (or (match-string 7 s) "0")))
16481 (string-to-number (match-string 4 s))
16482 (string-to-number (match-string 3 s))
16483 (string-to-number (match-string 2 s))
16484 nil nil nil)
16485 (error "Not a standard Org-mode time string: %s" s)))
16487 (defun org-timestamp-up (&optional arg)
16488 "Increase the date item at the cursor by one.
16489 If the cursor is on the year, change the year. If it is on the month,
16490 the day or the time, change that.
16491 With prefix ARG, change by that many units."
16492 (interactive "p")
16493 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16495 (defun org-timestamp-down (&optional arg)
16496 "Decrease the date item at the cursor by one.
16497 If the cursor is on the year, change the year. If it is on the month,
16498 the day or the time, change that.
16499 With prefix ARG, change by that many units."
16500 (interactive "p")
16501 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16503 (defun org-timestamp-up-day (&optional arg)
16504 "Increase the date in the time stamp by one day.
16505 With prefix ARG, change that many days."
16506 (interactive "p")
16507 (if (and (not (org-at-timestamp-p t))
16508 (org-at-heading-p))
16509 (org-todo 'up)
16510 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16512 (defun org-timestamp-down-day (&optional arg)
16513 "Decrease the date in the time stamp by one day.
16514 With prefix ARG, change that many days."
16515 (interactive "p")
16516 (if (and (not (org-at-timestamp-p t))
16517 (org-at-heading-p))
16518 (org-todo 'down)
16519 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16521 (defun org-at-timestamp-p (&optional inactive-ok)
16522 "Determine if the cursor is in or at a timestamp."
16523 (interactive)
16524 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16525 (pos (point))
16526 (ans (or (looking-at tsr)
16527 (save-excursion
16528 (skip-chars-backward "^[<\n\r\t")
16529 (if (> (point) (point-min)) (backward-char 1))
16530 (and (looking-at tsr)
16531 (> (- (match-end 0) pos) -1))))))
16532 (and ans
16533 (boundp 'org-ts-what)
16534 (setq org-ts-what
16535 (cond
16536 ((= pos (match-beginning 0)) 'bracket)
16537 ;; Point is considered to be "on the bracket" whether
16538 ;; it's really on it or right after it.
16539 ((= pos (1- (match-end 0))) 'bracket)
16540 ((= pos (match-end 0)) 'after)
16541 ((org-pos-in-match-range pos 2) 'year)
16542 ((org-pos-in-match-range pos 3) 'month)
16543 ((org-pos-in-match-range pos 7) 'hour)
16544 ((org-pos-in-match-range pos 8) 'minute)
16545 ((or (org-pos-in-match-range pos 4)
16546 (org-pos-in-match-range pos 5)) 'day)
16547 ((and (> pos (or (match-end 8) (match-end 5)))
16548 (< pos (match-end 0)))
16549 (- pos (or (match-end 8) (match-end 5))))
16550 (t 'day))))
16551 ans))
16553 (defun org-toggle-timestamp-type ()
16554 "Toggle the type (<active> or [inactive]) of a time stamp."
16555 (interactive)
16556 (when (org-at-timestamp-p t)
16557 (let ((beg (match-beginning 0)) (end (match-end 0))
16558 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16559 (save-excursion
16560 (goto-char beg)
16561 (while (re-search-forward "[][<>]" end t)
16562 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16563 t t)))
16564 (message "Timestamp is now %sactive"
16565 (if (equal (char-after beg) ?<) "" "in")))))
16567 (defvar org-clock-history) ; defined in org-clock.el
16568 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16569 (defun org-timestamp-change (n &optional what updown)
16570 "Change the date in the time stamp at point.
16571 The date will be changed by N times WHAT. WHAT can be `day', `month',
16572 `year', `minute', `second'. If WHAT is not given, the cursor position
16573 in the timestamp determines what will be changed."
16574 (let ((origin (point)) origin-cat
16575 with-hm inactive
16576 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16577 org-ts-what
16578 extra rem
16579 ts time time0 fixnext clrgx)
16580 (if (not (org-at-timestamp-p t))
16581 (error "Not at a timestamp"))
16582 (if (and (not what) (eq org-ts-what 'bracket))
16583 (org-toggle-timestamp-type)
16584 ;; Point isn't on brackets. Remember the part of the time-stamp
16585 ;; the point was in. Indeed, size of time-stamps may change,
16586 ;; but point must be kept in the same category nonetheless.
16587 (setq origin-cat org-ts-what)
16588 (if (and (not what) (not (eq org-ts-what 'day))
16589 org-display-custom-times
16590 (get-text-property (point) 'display)
16591 (not (get-text-property (1- (point)) 'display)))
16592 (setq org-ts-what 'day))
16593 (setq org-ts-what (or what org-ts-what)
16594 inactive (= (char-after (match-beginning 0)) ?\[)
16595 ts (match-string 0))
16596 (replace-match "")
16597 (if (string-match
16598 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16600 (setq extra (match-string 1 ts)))
16601 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16602 (setq with-hm t))
16603 (setq time0 (org-parse-time-string ts))
16604 (when (and updown
16605 (eq org-ts-what 'minute)
16606 (not current-prefix-arg))
16607 ;; This looks like s-up and s-down. Change by one rounding step.
16608 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16609 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16610 (setcar (cdr time0) (+ (nth 1 time0)
16611 (if (> n 0) (- rem) (- dm rem))))))
16612 (setq time
16613 (encode-time (or (car time0) 0)
16614 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16615 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16616 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16617 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16618 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16619 (nthcdr 6 time0)))
16620 (when (and (member org-ts-what '(hour minute))
16621 extra
16622 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16623 (setq extra (org-modify-ts-extra
16624 extra
16625 (if (eq org-ts-what 'hour) 2 5)
16626 n dm)))
16627 (when (integerp org-ts-what)
16628 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16629 (if (eq what 'calendar)
16630 (let ((cal-date (org-get-date-from-calendar)))
16631 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16632 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16633 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16634 (setcar time0 (or (car time0) 0))
16635 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16636 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16637 (setq time (apply 'encode-time time0))))
16638 ;; Insert the new time-stamp, and ensure point stays in the same
16639 ;; category as before (i.e. not after the last position in that
16640 ;; category).
16641 (let ((pos (point)))
16642 ;; Stay before inserted string. `save-excursion' is of no use.
16643 (setq org-last-changed-timestamp
16644 (org-insert-time-stamp time with-hm inactive nil nil extra))
16645 (goto-char pos))
16646 (save-match-data
16647 (looking-at org-ts-regexp3)
16648 (goto-char (cond
16649 ;; `day' category ends before `hour' if any, or at
16650 ;; the end of the day name.
16651 ((eq origin-cat 'day)
16652 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16653 ((eq origin-cat 'hour) (min (match-end 7) origin))
16654 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16655 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16656 ;; `year' and `month' have both fixed size: point
16657 ;; couldn't have moved into another part.
16658 (t origin))))
16659 ;; Update clock if on a CLOCK line.
16660 (org-clock-update-time-maybe)
16661 ;; Maybe adjust the closest clock in `org-clock-history'
16662 (when org-clock-adjust-closest
16663 (if (not (and (org-at-clock-log-p)
16664 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16665 org-clock-history))))))
16666 (message "No clock to adjust")
16667 (cond ((save-excursion ; fix previous clock?
16668 (re-search-backward org-ts-regexp0 nil t)
16669 (org-looking-back (concat org-clock-string " \\[")))
16670 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16671 ((save-excursion ; fix next clock?
16672 (re-search-backward org-ts-regexp0 nil t)
16673 (looking-at (concat org-ts-regexp0 "\\] =>")))
16674 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16675 (save-window-excursion
16676 ;; Find closest clock to point, adjust the previous/next one in history
16677 (let* ((p (save-excursion (org-back-to-heading t)))
16678 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16679 (clfixnth
16680 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16681 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16682 (if (not clfixpos)
16683 (message "No clock to adjust")
16684 (save-excursion
16685 (org-goto-marker-or-bmk clfixpos)
16686 (org-show-subtree)
16687 (when (re-search-forward clrgx nil t)
16688 (goto-char (match-beginning 1))
16689 (let (org-clock-adjust-closest)
16690 (org-timestamp-change n org-ts-what updown))
16691 (message "Clock adjusted in %s for heading: %s"
16692 (file-name-nondirectory (buffer-file-name))
16693 (org-get-heading t t)))))))))
16694 ;; Try to recenter the calendar window, if any.
16695 (if (and org-calendar-follow-timestamp-change
16696 (get-buffer-window "*Calendar*" t)
16697 (memq org-ts-what '(day month year)))
16698 (org-recenter-calendar (time-to-days time))))))
16700 (defun org-modify-ts-extra (s pos n dm)
16701 "Change the different parts of the lead-time and repeat fields in timestamp."
16702 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16703 ng h m new rem)
16704 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16705 (cond
16706 ((or (org-pos-in-match-range pos 2)
16707 (org-pos-in-match-range pos 3))
16708 (setq m (string-to-number (match-string 3 s))
16709 h (string-to-number (match-string 2 s)))
16710 (if (org-pos-in-match-range pos 2)
16711 (setq h (+ h n))
16712 (setq n (* dm (org-no-warnings (signum n))))
16713 (when (not (= 0 (setq rem (% m dm))))
16714 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16715 (setq m (+ m n)))
16716 (if (< m 0) (setq m (+ m 60) h (1- h)))
16717 (if (> m 59) (setq m (- m 60) h (1+ h)))
16718 (setq h (min 24 (max 0 h)))
16719 (setq ng 1 new (format "-%02d:%02d" h m)))
16720 ((org-pos-in-match-range pos 6)
16721 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16722 ((org-pos-in-match-range pos 5)
16723 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16725 ((org-pos-in-match-range pos 9)
16726 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16727 ((org-pos-in-match-range pos 8)
16728 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16730 (when ng
16731 (setq s (concat
16732 (substring s 0 (match-beginning ng))
16734 (substring s (match-end ng))))))
16737 (defun org-recenter-calendar (date)
16738 "If the calendar is visible, recenter it to DATE."
16739 (let ((cwin (get-buffer-window "*Calendar*" t)))
16740 (when cwin
16741 (let ((calendar-move-hook nil))
16742 (with-selected-window cwin
16743 (calendar-goto-date (if (listp date) date
16744 (calendar-gregorian-from-absolute date))))))))
16746 (defun org-goto-calendar (&optional arg)
16747 "Go to the Emacs calendar at the current date.
16748 If there is a time stamp in the current line, go to that date.
16749 A prefix ARG can be used to force the current date."
16750 (interactive "P")
16751 (let ((tsr org-ts-regexp) diff
16752 (calendar-move-hook nil)
16753 (calendar-view-holidays-initially-flag nil)
16754 (calendar-view-diary-initially-flag nil))
16755 (if (or (org-at-timestamp-p)
16756 (save-excursion
16757 (beginning-of-line 1)
16758 (looking-at (concat ".*" tsr))))
16759 (let ((d1 (time-to-days (current-time)))
16760 (d2 (time-to-days
16761 (org-time-string-to-time (match-string 1)))))
16762 (setq diff (- d2 d1))))
16763 (calendar)
16764 (calendar-goto-today)
16765 (if (and diff (not arg)) (calendar-forward-day diff))))
16767 (defun org-get-date-from-calendar ()
16768 "Return a list (month day year) of date at point in calendar."
16769 (with-current-buffer "*Calendar*"
16770 (save-match-data
16771 (calendar-cursor-to-date))))
16773 (defun org-date-from-calendar ()
16774 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16775 If there is already a time stamp at the cursor position, update it."
16776 (interactive)
16777 (if (org-at-timestamp-p t)
16778 (org-timestamp-change 0 'calendar)
16779 (let ((cal-date (org-get-date-from-calendar)))
16780 (org-insert-time-stamp
16781 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16783 (defun org-minutes-to-clocksum-string (m)
16784 "Format number of minutes as a clocksum string.
16785 The format is determined by `org-time-clocksum-format',
16786 `org-time-clocksum-use-fractional' and
16787 `org-time-clocksum-fractional-format'."
16788 (let ((clocksum "") fmt n)
16789 ;; fractional format
16790 (if org-time-clocksum-use-fractional
16791 (cond
16792 ;; single format string
16793 ((stringp org-time-clocksum-fractional-format)
16794 (format org-time-clocksum-fractional-format (/ m 60.0)))
16795 ;; choice of fractional formats for different time units
16796 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16797 (> (/ (truncate m) (* 365 24 60)) 0))
16798 (format fmt (/ m (* 365 24 60.0))))
16799 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16800 (> (/ (truncate m) (* 30 24 60)) 0))
16801 (format fmt (/ m (* 30 24 60.0))))
16802 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16803 (> (/ (truncate m) (* 7 24 60)) 0))
16804 (format fmt (/ m (* 7 24 60.0))))
16805 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16806 (> (/ (truncate m) (* 24 60)) 0))
16807 (format fmt (/ m (* 24 60.0))))
16808 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16809 (> (/ (truncate m) 60) 0))
16810 (format fmt (/ m 60.0)))
16811 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16812 (format fmt m))
16813 ;; fall back to smallest time unit with a format
16814 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16815 (format fmt (/ m 60.0)))
16816 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16817 (format fmt (/ m (* 24 60.0))))
16818 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16819 (format fmt (/ m (* 7 24 60.0))))
16820 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16821 (format fmt (/ m (* 30 24 60.0))))
16822 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16823 (format fmt (/ m (* 365 24 60.0)))))
16824 ;; standard (non-fractional) format, with single format string
16825 (if (stringp org-time-clocksum-format)
16826 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16827 ;; separate formats components
16828 (and (setq fmt (plist-get org-time-clocksum-format :years))
16829 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16830 (plist-get org-time-clocksum-format :require-years))
16831 (setq clocksum (concat clocksum (format fmt n))
16832 m (- m (* n 365 24 60))))
16833 (and (setq fmt (plist-get org-time-clocksum-format :months))
16834 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16835 (plist-get org-time-clocksum-format :require-months))
16836 (setq clocksum (concat clocksum (format fmt n))
16837 m (- m (* n 30 24 60))))
16838 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16839 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16840 (plist-get org-time-clocksum-format :require-weeks))
16841 (setq clocksum (concat clocksum (format fmt n))
16842 m (- m (* n 7 24 60))))
16843 (and (setq fmt (plist-get org-time-clocksum-format :days))
16844 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16845 (plist-get org-time-clocksum-format :require-days))
16846 (setq clocksum (concat clocksum (format fmt n))
16847 m (- m (* n 24 60))))
16848 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16849 (or (> (setq n (/ (truncate m) 60)) 0)
16850 (plist-get org-time-clocksum-format :require-hours))
16851 (setq clocksum (concat clocksum (format fmt n))
16852 m (- m (* n 60))))
16853 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16854 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16855 (setq clocksum (concat clocksum (format fmt m))))
16856 ;; return formatted time duration
16857 clocksum))))
16859 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16860 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16861 "Org mode version 8.0")
16863 (defun org-hours-to-clocksum-string (n)
16864 (org-minutes-to-clocksum-string (* n 60)))
16866 (defun org-hh:mm-string-to-minutes (s)
16867 "Convert a string H:MM to a number of minutes.
16868 If the string is just a number, interpret it as minutes.
16869 In fact, the first hh:mm or number in the string will be taken,
16870 there can be extra stuff in the string.
16871 If no number is found, the return value is 0."
16872 (cond
16873 ((integerp s) s)
16874 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16875 (+ (* (string-to-number (match-string 1 s)) 60)
16876 (string-to-number (match-string 2 s))))
16877 ((string-match "\\([0-9]+\\)" s)
16878 (string-to-number (match-string 1 s)))
16879 (t 0)))
16881 (defcustom org-effort-durations
16882 `(("h" . 60)
16883 ("d" . ,(* 60 8))
16884 ("w" . ,(* 60 8 5))
16885 ("m" . ,(* 60 8 5 4))
16886 ("y" . ,(* 60 8 5 40)))
16887 "Conversion factor to minutes for an effort modifier.
16889 Each entry has the form (MODIFIER . MINUTES).
16891 In an effort string, a number followed by MODIFIER is multiplied
16892 by the specified number of MINUTES to obtain an effort in
16893 minutes.
16895 For example, if the value of this variable is ((\"hours\" . 60)), then an
16896 effort string \"2hours\" is equivalent to 120 minutes."
16897 :group 'org-agenda
16898 :version "24.1"
16899 :type '(alist :key-type (string :tag "Modifier")
16900 :value-type (number :tag "Minutes")))
16902 (defcustom org-image-actual-width t
16903 "Should we use the actual width of images when inlining them?
16905 When set to `t', always use the image width.
16907 When set to a number, use imagemagick (when available) to set
16908 the image's width to this value.
16910 When set to a number in a list, try to get the width from the
16911 #+ATTR.* keyword if it matches a width specification like
16912 width=\"[0-9]+\", and fall back on that number if none is found.
16914 When set to nil, try to get the width from an #+ATTR.* keyword
16915 and fall back on the original width if none is found.
16917 This requires Emacs >= 24.1, build with imagemagick support."
16918 :group 'org-appearance
16919 :version "24.3"
16920 :type '(choice
16921 (const :tag "Use the image width" t)
16922 (integer :tag "Use a number of pixels")
16923 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16924 (const :tag "Use #+ATTR* or don't resize" nil)))
16926 (defun org-duration-string-to-minutes (s &optional output-to-string)
16927 "Convert a duration string S to minutes.
16929 A bare number is interpreted as minutes, modifiers can be set by
16930 customizing `org-effort-durations' (which see).
16932 Entries containing a colon are interpreted as H:MM by
16933 `org-hh:mm-string-to-minutes'."
16934 (let ((result 0)
16935 (re (concat "\\([0-9.]+\\) *\\("
16936 (regexp-opt (mapcar 'car org-effort-durations))
16937 "\\)")))
16938 (while (string-match re s)
16939 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16940 (string-to-number (match-string 1 s))))
16941 (setq s (replace-match "" nil t s)))
16942 (setq result (floor result))
16943 (incf result (org-hh:mm-string-to-minutes s))
16944 (if output-to-string (number-to-string result) result)))
16946 ;;;; Files
16948 (defun org-save-all-org-buffers ()
16949 "Save all Org-mode buffers without user confirmation."
16950 (interactive)
16951 (message "Saving all Org-mode buffers...")
16952 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16953 (when (featurep 'org-id) (org-id-locations-save))
16954 (message "Saving all Org-mode buffers... done"))
16956 (defun org-revert-all-org-buffers ()
16957 "Revert all Org-mode buffers.
16958 Prompt for confirmation when there are unsaved changes.
16959 Be sure you know what you are doing before letting this function
16960 overwrite your changes.
16962 This function is useful in a setup where one tracks org files
16963 with a version control system, to revert on one machine after pulling
16964 changes from another. I believe the procedure must be like this:
16966 1. M-x org-save-all-org-buffers
16967 2. Pull changes from the other machine, resolve conflicts
16968 3. M-x org-revert-all-org-buffers"
16969 (interactive)
16970 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16971 (error "Abort"))
16972 (save-excursion
16973 (save-window-excursion
16974 (mapc
16975 (lambda (b)
16976 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16977 (with-current-buffer b buffer-file-name))
16978 (org-pop-to-buffer-same-window b)
16979 (revert-buffer t 'no-confirm)))
16980 (buffer-list))
16981 (when (and (featurep 'org-id) org-id-track-globally)
16982 (org-id-locations-load)))))
16984 ;;;; Agenda files
16986 ;;;###autoload
16987 (defun org-switchb (&optional arg)
16988 "Switch between Org buffers.
16989 With one prefix argument, restrict available buffers to files.
16990 With two prefix arguments, restrict available buffers to agenda files.
16992 Defaults to `iswitchb' for buffer name completion.
16993 Set `org-completion-use-ido' to make it use ido instead."
16994 (interactive "P")
16995 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16996 ((equal arg '(16)) (org-buffer-list 'agenda))
16997 (t (org-buffer-list))))
16998 (org-completion-use-iswitchb org-completion-use-iswitchb)
16999 (org-completion-use-ido org-completion-use-ido))
17000 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17001 (setq org-completion-use-iswitchb t))
17002 (org-pop-to-buffer-same-window
17003 (org-icompleting-read "Org buffer: "
17004 (mapcar 'list (mapcar 'buffer-name blist))
17005 nil t))))
17007 ;;; Define some older names previously used for this functionality
17008 ;;;###autoload
17009 (defalias 'org-ido-switchb 'org-switchb)
17010 ;;;###autoload
17011 (defalias 'org-iswitchb 'org-switchb)
17013 (defun org-buffer-list (&optional predicate exclude-tmp)
17014 "Return a list of Org buffers.
17015 PREDICATE can be `export', `files' or `agenda'.
17017 export restrict the list to Export buffers.
17018 files restrict the list to buffers visiting Org files.
17019 agenda restrict the list to buffers visiting agenda files.
17021 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17022 (let* ((bfn nil)
17023 (agenda-files (and (eq predicate 'agenda)
17024 (mapcar 'file-truename (org-agenda-files t))))
17025 (filter
17026 (cond
17027 ((eq predicate 'files)
17028 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17029 ((eq predicate 'export)
17030 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17031 ((eq predicate 'agenda)
17032 (lambda (b)
17033 (with-current-buffer b
17034 (and (derived-mode-p 'org-mode)
17035 (setq bfn (buffer-file-name b))
17036 (member (file-truename bfn) agenda-files)))))
17037 (t (lambda (b) (with-current-buffer b
17038 (or (derived-mode-p 'org-mode)
17039 (string-match "\*Org .*Export"
17040 (buffer-name b)))))))))
17041 (delq nil
17042 (mapcar
17043 (lambda(b)
17044 (if (and (funcall filter b)
17045 (or (not exclude-tmp)
17046 (not (string-match "tmp" (buffer-name b)))))
17048 nil))
17049 (buffer-list)))))
17051 (defun org-agenda-files (&optional unrestricted archives)
17052 "Get the list of agenda files.
17053 Optional UNRESTRICTED means return the full list even if a restriction
17054 is currently in place.
17055 When ARCHIVES is t, include all archive files that are really being
17056 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17057 `org-agenda-archives-mode' is t."
17058 (let ((files
17059 (cond
17060 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17061 ((stringp org-agenda-files) (org-read-agenda-file-list))
17062 ((listp org-agenda-files) org-agenda-files)
17063 (t (error "Invalid value of `org-agenda-files'")))))
17064 (setq files (apply 'append
17065 (mapcar (lambda (f)
17066 (if (file-directory-p f)
17067 (directory-files
17068 f t org-agenda-file-regexp)
17069 (list f)))
17070 files)))
17071 (when org-agenda-skip-unavailable-files
17072 (setq files (delq nil
17073 (mapcar (function
17074 (lambda (file)
17075 (and (file-readable-p file) file)))
17076 files))))
17077 (when (or (eq archives t)
17078 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17079 (setq files (org-add-archive-files files)))
17080 files))
17082 (defun org-agenda-file-p (&optional file)
17083 "Return non-nil, if FILE is an agenda file.
17084 If FILE is omitted, use the file associated with the current
17085 buffer."
17086 (member (or file (buffer-file-name))
17087 (org-agenda-files t)))
17089 (defun org-edit-agenda-file-list ()
17090 "Edit the list of agenda files.
17091 Depending on setup, this either uses customize to edit the variable
17092 `org-agenda-files', or it visits the file that is holding the list. In the
17093 latter case, the buffer is set up in a way that saving it automatically kills
17094 the buffer and restores the previous window configuration."
17095 (interactive)
17096 (if (stringp org-agenda-files)
17097 (let ((cw (current-window-configuration)))
17098 (find-file org-agenda-files)
17099 (org-set-local 'org-window-configuration cw)
17100 (org-add-hook 'after-save-hook
17101 (lambda ()
17102 (set-window-configuration
17103 (prog1 org-window-configuration
17104 (kill-buffer (current-buffer))))
17105 (org-install-agenda-files-menu)
17106 (message "New agenda file list installed"))
17107 nil 'local)
17108 (message "%s" (substitute-command-keys
17109 "Edit list and finish with \\[save-buffer]")))
17110 (customize-variable 'org-agenda-files)))
17112 (defun org-store-new-agenda-file-list (list)
17113 "Set new value for the agenda file list and save it correctly."
17114 (if (stringp org-agenda-files)
17115 (let ((fe (org-read-agenda-file-list t)) b u)
17116 (while (setq b (find-buffer-visiting org-agenda-files))
17117 (kill-buffer b))
17118 (with-temp-file org-agenda-files
17119 (insert
17120 (mapconcat
17121 (lambda (f) ;; Keep un-expanded entries.
17122 (if (setq u (assoc f fe))
17123 (cdr u)
17125 list "\n")
17126 "\n")))
17127 (let ((org-mode-hook nil) (org-inhibit-startup t)
17128 (org-insert-mode-line-in-empty-file nil))
17129 (setq org-agenda-files list)
17130 (customize-save-variable 'org-agenda-files org-agenda-files))))
17132 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17133 "Read the list of agenda files from a file.
17134 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17135 filenames, used by `org-store-new-agenda-file-list' to write back
17136 un-expanded file names."
17137 (when (file-directory-p org-agenda-files)
17138 (error "`org-agenda-files' cannot be a single directory"))
17139 (when (stringp org-agenda-files)
17140 (with-temp-buffer
17141 (insert-file-contents org-agenda-files)
17142 (mapcar
17143 (lambda (f)
17144 (let ((e (expand-file-name (substitute-in-file-name f)
17145 org-directory)))
17146 (if pair-with-expansion
17147 (cons e f)
17148 e)))
17149 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17151 ;;;###autoload
17152 (defun org-cycle-agenda-files ()
17153 "Cycle through the files in `org-agenda-files'.
17154 If the current buffer visits an agenda file, find the next one in the list.
17155 If the current buffer does not, find the first agenda file."
17156 (interactive)
17157 (let* ((fs (org-agenda-files t))
17158 (files (append fs (list (car fs))))
17159 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17160 file)
17161 (unless files (error "No agenda files"))
17162 (catch 'exit
17163 (while (setq file (pop files))
17164 (if (equal (file-truename file) tcf)
17165 (when (car files)
17166 (find-file (car files))
17167 (throw 'exit t))))
17168 (find-file (car fs)))
17169 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17171 (defun org-agenda-file-to-front (&optional to-end)
17172 "Move/add the current file to the top of the agenda file list.
17173 If the file is not present in the list, it is added to the front. If it is
17174 present, it is moved there. With optional argument TO-END, add/move to the
17175 end of the list."
17176 (interactive "P")
17177 (let ((org-agenda-skip-unavailable-files nil)
17178 (file-alist (mapcar (lambda (x)
17179 (cons (file-truename x) x))
17180 (org-agenda-files t)))
17181 (ctf (file-truename
17182 (or buffer-file-name
17183 (error "Please save the current buffer to a file"))))
17184 x had)
17185 (setq x (assoc ctf file-alist) had x)
17187 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17188 (if to-end
17189 (setq file-alist (append (delq x file-alist) (list x)))
17190 (setq file-alist (cons x (delq x file-alist))))
17191 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17192 (org-install-agenda-files-menu)
17193 (message "File %s to %s of agenda file list"
17194 (if had "moved" "added") (if to-end "end" "front"))))
17196 (defun org-remove-file (&optional file)
17197 "Remove current file from the list of files in variable `org-agenda-files'.
17198 These are the files which are being checked for agenda entries.
17199 Optional argument FILE means use this file instead of the current."
17200 (interactive)
17201 (let* ((org-agenda-skip-unavailable-files nil)
17202 (file (or file buffer-file-name
17203 (error "Current buffer does not visit a file")))
17204 (true-file (file-truename file))
17205 (afile (abbreviate-file-name file))
17206 (files (delq nil (mapcar
17207 (lambda (x)
17208 (if (equal true-file
17209 (file-truename x))
17210 nil x))
17211 (org-agenda-files t)))))
17212 (if (not (= (length files) (length (org-agenda-files t))))
17213 (progn
17214 (org-store-new-agenda-file-list files)
17215 (org-install-agenda-files-menu)
17216 (message "Removed file: %s" afile))
17217 (message "File was not in list: %s (not removed)" afile))))
17219 (defun org-file-menu-entry (file)
17220 (vector file (list 'find-file file) t))
17222 (defun org-check-agenda-file (file)
17223 "Make sure FILE exists. If not, ask user what to do."
17224 (when (not (file-exists-p file))
17225 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17226 (abbreviate-file-name file))
17227 (let ((r (downcase (read-char-exclusive))))
17228 (cond
17229 ((equal r ?r)
17230 (org-remove-file file)
17231 (throw 'nextfile t))
17232 (t (error "Abort"))))))
17234 (defun org-get-agenda-file-buffer (file)
17235 "Get a buffer visiting FILE. If the buffer needs to be created, add
17236 it to the list of buffers which might be released later."
17237 (let ((buf (org-find-base-buffer-visiting file)))
17238 (if buf
17239 buf ; just return it
17240 ;; Make a new buffer and remember it
17241 (setq buf (find-file-noselect file))
17242 (if buf (push buf org-agenda-new-buffers))
17243 buf)))
17245 (defun org-release-buffers (blist)
17246 "Release all buffers in list, asking the user for confirmation when needed.
17247 When a buffer is unmodified, it is just killed. When modified, it is saved
17248 \(if the user agrees) and then killed."
17249 (let (buf file)
17250 (while (setq buf (pop blist))
17251 (setq file (buffer-file-name buf))
17252 (when (and (buffer-modified-p buf)
17253 file
17254 (y-or-n-p (format "Save file %s? " file)))
17255 (with-current-buffer buf (save-buffer)))
17256 (kill-buffer buf))))
17258 (defun org-agenda-prepare-buffers (files)
17259 "Create buffers for all agenda files, protect archived trees and comments."
17260 (interactive)
17261 (let ((pa '(:org-archived t))
17262 (pc '(:org-comment t))
17263 (pall '(:org-archived t :org-comment t))
17264 (inhibit-read-only t)
17265 (rea (concat ":" org-archive-tag ":"))
17266 bmp file re)
17267 (save-excursion
17268 (save-restriction
17269 (while (setq file (pop files))
17270 (catch 'nextfile
17271 (if (bufferp file)
17272 (set-buffer file)
17273 (org-check-agenda-file file)
17274 (set-buffer (org-get-agenda-file-buffer file)))
17275 (widen)
17276 (setq bmp (buffer-modified-p))
17277 (org-refresh-category-properties)
17278 (setq org-todo-keywords-for-agenda
17279 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17280 (setq org-done-keywords-for-agenda
17281 (append org-done-keywords-for-agenda org-done-keywords))
17282 (setq org-todo-keyword-alist-for-agenda
17283 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17284 (setq org-drawers-for-agenda
17285 (append org-drawers-for-agenda org-drawers))
17286 (setq org-tag-alist-for-agenda
17287 (append org-tag-alist-for-agenda org-tag-alist))
17289 (save-excursion
17290 (remove-text-properties (point-min) (point-max) pall)
17291 (when org-agenda-skip-archived-trees
17292 (goto-char (point-min))
17293 (while (re-search-forward rea nil t)
17294 (if (org-at-heading-p t)
17295 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17296 (goto-char (point-min))
17297 (setq re (format org-heading-keyword-regexp-format
17298 org-comment-string))
17299 (while (re-search-forward re nil t)
17300 (add-text-properties
17301 (match-beginning 0) (org-end-of-subtree t) pc)))
17302 (set-buffer-modified-p bmp)))))
17303 (setq org-todo-keywords-for-agenda
17304 (org-uniquify org-todo-keywords-for-agenda))
17305 (setq org-todo-keyword-alist-for-agenda
17306 (org-uniquify org-todo-keyword-alist-for-agenda)
17307 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17309 ;;;; Embedded LaTeX
17311 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17312 "Keymap for the minor `org-cdlatex-mode'.")
17314 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17315 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17316 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17317 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17318 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17320 (defvar org-cdlatex-texmathp-advice-is-done nil
17321 "Flag remembering if we have applied the advice to texmathp already.")
17323 (define-minor-mode org-cdlatex-mode
17324 "Toggle the minor `org-cdlatex-mode'.
17325 This mode supports entering LaTeX environment and math in LaTeX fragments
17326 in Org-mode.
17327 \\{org-cdlatex-mode-map}"
17328 nil " OCDL" nil
17329 (when org-cdlatex-mode
17330 (require 'cdlatex)
17331 (run-hooks 'cdlatex-mode-hook)
17332 (cdlatex-compute-tables))
17333 (unless org-cdlatex-texmathp-advice-is-done
17334 (setq org-cdlatex-texmathp-advice-is-done t)
17335 (defadvice texmathp (around org-math-always-on activate)
17336 "Always return t in org-mode buffers.
17337 This is because we want to insert math symbols without dollars even outside
17338 the LaTeX math segments. If Orgmode thinks that point is actually inside
17339 an embedded LaTeX fragment, let texmathp do its job.
17340 \\[org-cdlatex-mode-map]"
17341 (interactive)
17342 (let (p)
17343 (cond
17344 ((not (derived-mode-p 'org-mode)) ad-do-it)
17345 ((eq this-command 'cdlatex-math-symbol)
17346 (setq ad-return-value t
17347 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17349 (let ((p (org-inside-LaTeX-fragment-p)))
17350 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17351 (setq ad-return-value t
17352 texmathp-why '("Org-mode embedded math" . 0))
17353 (if p ad-do-it)))))))))
17355 (defun turn-on-org-cdlatex ()
17356 "Unconditionally turn on `org-cdlatex-mode'."
17357 (org-cdlatex-mode 1))
17359 (defun org-inside-LaTeX-fragment-p ()
17360 "Test if point is inside a LaTeX fragment.
17361 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17362 sequence appearing also before point.
17363 Even though the matchers for math are configurable, this function assumes
17364 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17365 delimiters are skipped when they have been removed by customization.
17366 The return value is nil, or a cons cell with the delimiter and the
17367 position of this delimiter.
17369 This function does a reasonably good job, but can locally be fooled by
17370 for example currency specifications. For example it will assume being in
17371 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17372 fragments that are properly closed, but during editing, we have to live
17373 with the uncertainty caused by missing closing delimiters. This function
17374 looks only before point, not after."
17375 (catch 'exit
17376 (let ((pos (point))
17377 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17378 (lim (progn
17379 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17380 (point)))
17381 dd-on str (start 0) m re)
17382 (goto-char pos)
17383 (when dodollar
17384 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17385 re (nth 1 (assoc "$" org-latex-regexps)))
17386 (while (string-match re str start)
17387 (cond
17388 ((= (match-end 0) (length str))
17389 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17390 ((= (match-end 0) (- (length str) 5))
17391 (throw 'exit nil))
17392 (t (setq start (match-end 0))))))
17393 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17394 (goto-char pos)
17395 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17396 (and (match-beginning 2) (throw 'exit nil))
17397 ;; count $$
17398 (while (re-search-backward "\\$\\$" lim t)
17399 (setq dd-on (not dd-on)))
17400 (goto-char pos)
17401 (if dd-on (cons "$$" m))))))
17403 (defun org-inside-latex-macro-p ()
17404 "Is point inside a LaTeX macro or its arguments?"
17405 (save-match-data
17406 (org-in-regexp
17407 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17409 (defun org-try-cdlatex-tab ()
17410 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17411 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17412 - inside a LaTeX fragment, or
17413 - after the first word in a line, where an abbreviation expansion could
17414 insert a LaTeX environment."
17415 (when org-cdlatex-mode
17416 (cond
17417 ;; Before any word on the line: No expansion possible.
17418 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17419 ;; Just after first word on the line: Expand it. Make sure it
17420 ;; cannot happen on headlines, though.
17421 ((save-excursion
17422 (skip-chars-backward "a-zA-Z0-9*")
17423 (skip-chars-backward " \t")
17424 (and (bolp) (not (org-at-heading-p))))
17425 (cdlatex-tab) t)
17426 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17428 (defun org-cdlatex-underscore-caret (&optional arg)
17429 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17430 Revert to the normal definition outside of these fragments."
17431 (interactive "P")
17432 (if (org-inside-LaTeX-fragment-p)
17433 (call-interactively 'cdlatex-sub-superscript)
17434 (let (org-cdlatex-mode)
17435 (call-interactively (key-binding (vector last-input-event))))))
17437 (defun org-cdlatex-math-modify (&optional arg)
17438 "Execute `cdlatex-math-modify' in LaTeX fragments.
17439 Revert to the normal definition outside of these fragments."
17440 (interactive "P")
17441 (if (org-inside-LaTeX-fragment-p)
17442 (call-interactively 'cdlatex-math-modify)
17443 (let (org-cdlatex-mode)
17444 (call-interactively (key-binding (vector last-input-event))))))
17446 (defvar org-latex-fragment-image-overlays nil
17447 "List of overlays carrying the images of latex fragments.")
17448 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17450 (defun org-remove-latex-fragment-image-overlays ()
17451 "Remove all overlays with LaTeX fragment images in current buffer."
17452 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17453 (setq org-latex-fragment-image-overlays nil))
17455 (defun org-preview-latex-fragment (&optional subtree)
17456 "Preview the LaTeX fragment at point, or all locally or globally.
17457 If the cursor is in a LaTeX fragment, create the image and overlay
17458 it over the source code. If there is no fragment at point, display
17459 all fragments in the current text, from one headline to the next. With
17460 prefix SUBTREE, display all fragments in the current subtree. With a
17461 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17462 the cursor is before the first headline,
17463 display all fragments in the buffer.
17464 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17465 (interactive "P")
17466 (unless buffer-file-name
17467 (error "Can't preview LaTeX fragment in a non-file buffer"))
17468 (org-remove-latex-fragment-image-overlays)
17469 (save-excursion
17470 (save-restriction
17471 (let (beg end at msg)
17472 (cond
17473 ((or (equal subtree '(16))
17474 (not (save-excursion
17475 (re-search-backward org-outline-regexp-bol nil t))))
17476 (setq beg (point-min) end (point-max)
17477 msg "Creating images for buffer...%s"))
17478 ((equal subtree '(4))
17479 (org-back-to-heading)
17480 (setq beg (point) end (org-end-of-subtree t)
17481 msg "Creating images for subtree...%s"))
17483 (if (setq at (org-inside-LaTeX-fragment-p))
17484 (goto-char (max (point-min) (- (cdr at) 2)))
17485 (org-back-to-heading))
17486 (setq beg (point) end (progn (outline-next-heading) (point))
17487 msg (if at "Creating image...%s"
17488 "Creating images for entry...%s"))))
17489 (message msg "")
17490 (narrow-to-region beg end)
17491 (goto-char beg)
17492 (org-format-latex
17493 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17494 (file-name-nondirectory
17495 buffer-file-name)))
17496 default-directory 'overlays msg at 'forbuffer
17497 org-latex-create-formula-image-program)
17498 (message msg "done. Use `C-c C-c' to remove images.")))))
17500 (defvar org-latex-regexps
17501 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17502 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17503 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17504 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17505 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17506 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17507 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17508 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17509 "Regular expressions for matching embedded LaTeX.")
17511 (defvar org-export-have-math nil) ;; dynamic scoping
17512 (defun org-format-latex (prefix &optional dir overlays msg at
17513 forbuffer processing-type)
17514 "Replace LaTeX fragments with links to an image, and produce images.
17515 Some of the options can be changed using the variable
17516 `org-format-latex-options'."
17517 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17518 (let* ((prefixnodir (file-name-nondirectory prefix))
17519 (absprefix (expand-file-name prefix dir))
17520 (todir (file-name-directory absprefix))
17521 (opt org-format-latex-options)
17522 (optnew org-format-latex-options)
17523 (matchers (plist-get opt :matchers))
17524 (re-list org-latex-regexps)
17525 (org-format-latex-header-extra
17526 (plist-get (org-infile-export-plist) :latex-header-extra))
17527 (cnt 0) txt hash link beg end re e checkdir
17528 string
17529 m n block-type block linkfile movefile ov)
17530 ;; Check the different regular expressions
17531 (while (setq e (pop re-list))
17532 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17533 block (if block-type "\n\n" ""))
17534 (when (member m matchers)
17535 (goto-char (point-min))
17536 (while (re-search-forward re nil t)
17537 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17538 (not (get-text-property (match-beginning n)
17539 'org-protected))
17540 (or (not overlays)
17541 (not (eq (get-char-property (match-beginning n)
17542 'org-overlay-type)
17543 'org-latex-overlay))))
17544 (setq org-export-have-math t)
17545 (cond
17546 ((eq processing-type 'verbatim)
17547 ;; Leave the text verbatim, just protect it
17548 (add-text-properties (match-beginning n) (match-end n)
17549 '(org-protected t)))
17550 ((eq processing-type 'mathjax)
17551 ;; Prepare for MathJax processing
17552 (setq string (match-string n))
17553 (if (member m '("$" "$1"))
17554 (save-excursion
17555 (delete-region (match-beginning n) (match-end n))
17556 (goto-char (match-beginning n))
17557 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17558 "\\)")
17559 '(org-protected t))))
17560 (add-text-properties (match-beginning n) (match-end n)
17561 '(org-protected t))))
17562 ((or (eq processing-type 'dvipng)
17563 (eq processing-type 'imagemagick))
17564 ;; Process to an image
17565 (setq txt (match-string n)
17566 beg (match-beginning n) end (match-end n)
17567 cnt (1+ cnt))
17568 (let ((face (face-at-point))
17569 (fg (plist-get opt :foreground))
17570 (bg (plist-get opt :background))
17571 print-length print-level) ; make sure full list is printed
17572 (when forbuffer
17573 ; Get the colors from the face at point
17574 (goto-char beg)
17575 (when (eq fg 'auto)
17576 (setq fg (face-attribute face :foreground nil 'default)))
17577 (when (eq bg 'auto)
17578 (setq bg (face-attribute face :background nil 'default)))
17579 (setq optnew (copy-sequence opt))
17580 (plist-put optnew :foreground fg)
17581 (plist-put optnew :background bg))
17582 (setq hash (sha1 (prin1-to-string
17583 (list org-format-latex-header
17584 org-format-latex-header-extra
17585 org-export-latex-default-packages-alist
17586 org-export-latex-packages-alist
17587 org-format-latex-options
17588 forbuffer txt fg bg)))
17589 linkfile (format "%s_%s.png" prefix hash)
17590 movefile (format "%s_%s.png" absprefix hash)))
17591 (setq link (concat block "[[file:" linkfile "]]" block))
17592 (if msg (message msg cnt))
17593 (goto-char beg)
17594 (unless checkdir ; make sure the directory exists
17595 (setq checkdir t)
17596 (or (file-directory-p todir) (make-directory todir t)))
17597 (org-create-formula-image
17598 txt movefile optnew forbuffer processing-type)
17599 (if overlays
17600 (progn
17601 (mapc (lambda (o)
17602 (if (eq (overlay-get o 'org-overlay-type)
17603 'org-latex-overlay)
17604 (delete-overlay o)))
17605 (overlays-in beg end))
17606 (setq ov (make-overlay beg end))
17607 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17608 (if (featurep 'xemacs)
17609 (progn
17610 (overlay-put ov 'invisible t)
17611 (overlay-put
17612 ov 'end-glyph
17613 (make-glyph (vector 'png :file movefile))))
17614 (overlay-put
17615 ov 'display
17616 (list 'image :type 'png :file movefile :ascent 'center)))
17617 (push ov org-latex-fragment-image-overlays)
17618 (goto-char end))
17619 (delete-region beg end)
17620 (insert (org-add-props link
17621 (list 'org-latex-src
17622 (replace-regexp-in-string
17623 "\"" "" txt)
17624 'org-latex-src-embed-type
17625 (if block-type 'paragraph 'character))))))
17626 ((eq processing-type 'mathml)
17627 ;; Process to MathML
17628 (unless (save-match-data (org-format-latex-mathml-available-p))
17629 (error "LaTeX to MathML converter not configured"))
17630 (setq txt (match-string n)
17631 beg (match-beginning n) end (match-end n)
17632 cnt (1+ cnt))
17633 (if msg (message msg cnt))
17634 (goto-char beg)
17635 (delete-region beg end)
17636 (insert (org-format-latex-as-mathml
17637 txt block-type prefix dir)))
17639 (error "Unknown conversion type %s for latex fragments"
17640 processing-type)))))))))
17642 (defun org-create-math-formula (latex-frag &optional mathml-file)
17643 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17644 Use `org-latex-to-mathml-convert-command'. If the conversion is
17645 sucessful, return the portion between \"<math...> </math>\"
17646 elements otherwise return nil. When MATHML-FILE is specified,
17647 write the results in to that file. When invoked as an
17648 interactive command, prompt for LATEX-FRAG, with initial value
17649 set to the current active region and echo the results for user
17650 inspection."
17651 (interactive (list (let ((frag (when (org-region-active-p)
17652 (buffer-substring-no-properties
17653 (region-beginning) (region-end)))))
17654 (read-string "LaTeX Fragment: " frag nil frag))))
17655 (unless latex-frag (error "Invalid latex-frag"))
17656 (let* ((tmp-in-file (file-relative-name
17657 (make-temp-name (expand-file-name "ltxmathml-in"))))
17658 (ignore (write-region latex-frag nil tmp-in-file))
17659 (tmp-out-file (file-relative-name
17660 (make-temp-name (expand-file-name "ltxmathml-out"))))
17661 (cmd (format-spec
17662 org-latex-to-mathml-convert-command
17663 `((?j . ,(shell-quote-argument
17664 (expand-file-name org-latex-to-mathml-jar-file)))
17665 (?I . ,(shell-quote-argument tmp-in-file))
17666 (?o . ,(shell-quote-argument tmp-out-file)))))
17667 mathml shell-command-output)
17668 (when (org-called-interactively-p 'any)
17669 (unless (org-format-latex-mathml-available-p)
17670 (error "LaTeX to MathML converter not configured")))
17671 (message "Running %s" cmd)
17672 (setq shell-command-output (shell-command-to-string cmd))
17673 (setq mathml
17674 (when (file-readable-p tmp-out-file)
17675 (with-current-buffer (find-file-noselect tmp-out-file t)
17676 (goto-char (point-min))
17677 (when (re-search-forward
17678 (concat
17679 (regexp-quote
17680 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17681 "\\(.\\|\n\\)*"
17682 (regexp-quote "</math>")) nil t)
17683 (prog1 (match-string 0) (kill-buffer))))))
17684 (cond
17685 (mathml
17686 (setq mathml
17687 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17688 (when mathml-file
17689 (write-region mathml nil mathml-file))
17690 (when (org-called-interactively-p 'any)
17691 (message mathml)))
17692 ((message "LaTeX to MathML conversion failed")
17693 (message shell-command-output)))
17694 (delete-file tmp-in-file)
17695 (when (file-exists-p tmp-out-file)
17696 (delete-file tmp-out-file))
17697 mathml))
17699 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17700 prefix &optional dir)
17701 "Use `org-create-math-formula' but check local cache first."
17702 (let* ((absprefix (expand-file-name prefix dir))
17703 (print-length nil) (print-level nil)
17704 (formula-id (concat
17705 "formula-"
17706 (sha1
17707 (prin1-to-string
17708 (list latex-frag
17709 org-latex-to-mathml-convert-command)))))
17710 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17711 (formula-cache-dir (file-name-directory formula-cache)))
17713 (unless (file-directory-p formula-cache-dir)
17714 (make-directory formula-cache-dir t))
17716 (unless (file-exists-p formula-cache)
17717 (org-create-math-formula latex-frag formula-cache))
17719 (if (file-exists-p formula-cache)
17720 ;; Successful conversion. Return the link to MathML file.
17721 (org-add-props
17722 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17723 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17724 'org-latex-src-embed-type (if latex-frag-type
17725 'paragraph 'character)))
17726 ;; Failed conversion. Return the LaTeX fragment verbatim
17727 (add-text-properties
17728 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17729 latex-frag)))
17731 (defun org-create-formula-image (string tofile options buffer &optional type)
17732 "Create an image from LaTeX source using dvipng or convert.
17733 This function calls either `org-create-formula-image-with-dvipng'
17734 or `org-create-formula-image-with-imagemagick' depending on the
17735 value of `org-latex-create-formula-image-program' or on the value
17736 of the optional TYPE variable.
17738 Note: ultimately these two function should be combined as they
17739 share a good deal of logic."
17740 (org-check-external-command
17741 "latex" "needed to convert LaTeX fragments to images")
17742 (funcall
17743 (case (or type org-latex-create-formula-image-program)
17744 ('dvipng
17745 (org-check-external-command
17746 "dvipng" "needed to convert LaTeX fragments to images")
17747 #'org-create-formula-image-with-dvipng)
17748 ('imagemagick
17749 (org-check-external-command
17750 "convert" "you need to install imagemagick")
17751 #'org-create-formula-image-with-imagemagick)
17752 (t (error
17753 "invalid value of `org-latex-create-formula-image-program'")))
17754 string tofile options buffer))
17756 ;; This function borrows from Ganesh Swami's latex2png.el
17757 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17758 "This calls dvipng."
17759 (require 'org-latex)
17760 (let* ((tmpdir (if (featurep 'xemacs)
17761 (temp-directory)
17762 temporary-file-directory))
17763 (texfilebase (make-temp-name
17764 (expand-file-name "orgtex" tmpdir)))
17765 (texfile (concat texfilebase ".tex"))
17766 (dvifile (concat texfilebase ".dvi"))
17767 (pngfile (concat texfilebase ".png"))
17768 (fnh (if (featurep 'xemacs)
17769 (font-height (face-font 'default))
17770 (face-attribute 'default :height nil)))
17771 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17772 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17773 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17774 "Black"))
17775 (bg (or (plist-get options (if buffer :background :html-background))
17776 "Transparent")))
17777 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17778 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17779 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17780 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17781 (with-temp-file texfile
17782 (insert (org-splice-latex-header
17783 org-format-latex-header
17784 org-export-latex-default-packages-alist
17785 org-export-latex-packages-alist t
17786 org-format-latex-header-extra))
17787 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17788 (require 'org-latex)
17789 (org-export-latex-fix-inputenc))
17790 (let ((dir default-directory))
17791 (condition-case nil
17792 (progn
17793 (cd tmpdir)
17794 (call-process "latex" nil nil nil texfile))
17795 (error nil))
17796 (cd dir))
17797 (if (not (file-exists-p dvifile))
17798 (progn (message "Failed to create dvi file from %s" texfile) nil)
17799 (condition-case nil
17800 (if (featurep 'xemacs)
17801 (call-process "dvipng" nil nil nil
17802 "-fg" fg "-bg" bg
17803 "-T" "tight"
17804 "-o" pngfile
17805 dvifile)
17806 (call-process "dvipng" nil nil nil
17807 "-fg" fg "-bg" bg
17808 "-D" dpi
17809 ;;"-x" scale "-y" scale
17810 "-T" "tight"
17811 "-o" pngfile
17812 dvifile))
17813 (error nil))
17814 (if (not (file-exists-p pngfile))
17815 (if org-format-latex-signal-error
17816 (error "Failed to create png file from %s" texfile)
17817 (message "Failed to create png file from %s" texfile)
17818 nil)
17819 ;; Use the requested file name and clean up
17820 (copy-file pngfile tofile 'replace)
17821 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17822 (if (file-exists-p (concat texfilebase e))
17823 (delete-file (concat texfilebase e))))
17824 pngfile))))
17826 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17827 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17828 "This calls convert, which is included into imagemagick."
17829 (require 'org-latex)
17830 (let* ((tmpdir (if (featurep 'xemacs)
17831 (temp-directory)
17832 temporary-file-directory))
17833 (texfilebase (make-temp-name
17834 (expand-file-name "orgtex" tmpdir)))
17835 (texfile (concat texfilebase ".tex"))
17836 (pdffile (concat texfilebase ".pdf"))
17837 (pngfile (concat texfilebase ".png"))
17838 (fnh (if (featurep 'xemacs)
17839 (font-height (face-font 'default))
17840 (face-attribute 'default :height nil)))
17841 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17842 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17843 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17844 "black"))
17845 (bg (or (plist-get options (if buffer :background :html-background))
17846 "white")))
17847 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17848 (setq fg (org-latex-color-format fg)))
17849 (if (eq bg 'default) (setq bg (org-latex-color :background))
17850 (setq bg (org-latex-color-format
17851 (if (string= bg "Transparent") "white" bg))))
17852 (with-temp-file texfile
17853 (insert (org-splice-latex-header
17854 org-format-latex-header
17855 org-export-latex-default-packages-alist
17856 org-export-latex-packages-alist t
17857 org-format-latex-header-extra))
17858 (insert "\n\\begin{document}\n"
17859 "\\definecolor{fg}{rgb}{" fg "}\n"
17860 "\\definecolor{bg}{rgb}{" bg "}\n"
17861 "\n\\pagecolor{bg}\n"
17862 "\n{\\color{fg}\n"
17863 string
17864 "\n}\n"
17865 "\n\\end{document}\n" )
17866 (require 'org-latex)
17867 (org-export-latex-fix-inputenc))
17868 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17869 (condition-case nil
17870 (progn
17871 (cd tmpdir)
17872 (setq cmds org-latex-to-pdf-process)
17873 (while cmds
17874 (setq latex-frags-cmds (pop cmds))
17875 (if (listp latex-frags-cmds)
17876 (setq cmds nil)
17877 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17878 (while latex-frags-cmds
17879 (setq cmd (pop latex-frags-cmds))
17880 (while (string-match "%b" cmd)
17881 (setq cmd (replace-match
17882 (save-match-data
17883 (shell-quote-argument texfile))
17884 t t cmd)))
17885 (while (string-match "%f" cmd)
17886 (setq cmd (replace-match
17887 (save-match-data
17888 (shell-quote-argument (file-name-nondirectory texfile)))
17889 t t cmd)))
17890 (while (string-match "%o" cmd)
17891 (setq cmd (replace-match
17892 (save-match-data
17893 (shell-quote-argument (file-name-directory texfile)))
17894 t t cmd)))
17895 (setq cmd (split-string cmd))
17896 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17897 (error nil))
17898 (cd dir))
17899 (if (not (file-exists-p pdffile))
17900 (progn (message "Failed to create pdf file from %s" texfile) nil)
17901 (condition-case nil
17902 (if (featurep 'xemacs)
17903 (call-process "convert" nil nil nil
17904 "-density" "96"
17905 "-trim"
17906 "-antialias"
17907 pdffile
17908 "-quality" "100"
17909 ;; "-sharpen" "0x1.0"
17910 pngfile)
17911 (call-process "convert" nil nil nil
17912 "-density" dpi
17913 "-trim"
17914 "-antialias"
17915 pdffile
17916 "-quality" "100"
17917 ; "-sharpen" "0x1.0"
17918 pngfile))
17919 (error nil))
17920 (if (not (file-exists-p pngfile))
17921 (if org-format-latex-signal-error
17922 (error "Failed to create png file from %s" texfile)
17923 (message "Failed to create png file from %s" texfile)
17924 nil)
17925 ;; Use the requested file name and clean up
17926 (copy-file pngfile tofile 'replace)
17927 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17928 (if (file-exists-p (concat texfilebase e))
17929 (delete-file (concat texfilebase e))))
17930 pngfile))))
17932 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17933 "Fill a LaTeX header template TPL.
17934 In the template, the following place holders will be recognized:
17936 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17937 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17938 [PACKAGES] \\usepackage statements for PKG
17939 [NO-PACKAGES] do not include PKG
17940 [EXTRA] the string EXTRA
17941 [NO-EXTRA] do not include EXTRA
17943 For backward compatibility, if both the positive and the negative place
17944 holder is missing, the positive one (without the \"NO-\") will be
17945 assumed to be present at the end of the template.
17946 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17947 EXTRA is a string.
17948 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17949 (let (rpl (end ""))
17950 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17951 (setq rpl (if (or (match-end 1) (not def-pkg))
17952 "" (org-latex-packages-to-string def-pkg snippets-p t))
17953 tpl (replace-match rpl t t tpl))
17954 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17956 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17957 (setq rpl (if (or (match-end 1) (not pkg))
17958 "" (org-latex-packages-to-string pkg snippets-p t))
17959 tpl (replace-match rpl t t tpl))
17960 (if pkg (setq end
17961 (concat end "\n"
17962 (org-latex-packages-to-string pkg snippets-p)))))
17964 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17965 (setq rpl (if (or (match-end 1) (not extra))
17966 "" (concat extra "\n"))
17967 tpl (replace-match rpl t t tpl))
17968 (if (and extra (string-match "\\S-" extra))
17969 (setq end (concat end "\n" extra))))
17971 (if (string-match "\\S-" end)
17972 (concat tpl "\n" end)
17973 tpl)))
17975 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17976 "Turn an alist of packages into a string with the \\usepackage macros."
17977 (setq pkg (mapconcat (lambda(p)
17978 (cond
17979 ((stringp p) p)
17980 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17981 (format "%% Package %s omitted" (cadr p)))
17982 ((equal "" (car p))
17983 (format "\\usepackage{%s}" (cadr p)))
17985 (format "\\usepackage[%s]{%s}"
17986 (car p) (cadr p)))))
17988 "\n"))
17989 (if newline (concat pkg "\n") pkg))
17991 (defun org-dvipng-color (attr)
17992 "Return a RGB color specification for dvipng."
17993 (apply 'format "rgb %s %s %s"
17994 (mapcar 'org-normalize-color
17995 (if (featurep 'xemacs)
17996 (color-rgb-components
17997 (face-property 'default
17998 (cond ((eq attr :foreground) 'foreground)
17999 ((eq attr :background) 'background))))
18000 (color-values (face-attribute 'default attr nil))))))
18002 (defun org-dvipng-color-format (color-name)
18003 "Convert COLOR-NAME to a RGB color value for dvipng."
18004 (apply 'format "rgb %s %s %s"
18005 (mapcar 'org-normalize-color
18006 (color-values color-name))))
18008 (defun org-latex-color (attr)
18009 "Return a RGB color for the LaTeX color package."
18010 (apply 'format "%s,%s,%s"
18011 (mapcar 'org-normalize-color
18012 (if (featurep 'xemacs)
18013 (color-rgb-components
18014 (face-property 'default
18015 (cond ((eq attr :foreground) 'foreground)
18016 ((eq attr :background) 'background))))
18017 (color-values (face-attribute 'default attr nil))))))
18019 (defun org-latex-color-format (color-name)
18020 "Convert COLOR-NAME to a RGB color value."
18021 (apply 'format "%s,%s,%s"
18022 (mapcar 'org-normalize-color
18023 (color-values color-name))))
18025 (defun org-normalize-color (value)
18026 "Return string to be used as color value for an RGB component."
18027 (format "%g" (/ value 65535.0)))
18029 ;; Image display
18032 (defvar org-inline-image-overlays nil)
18033 (make-variable-buffer-local 'org-inline-image-overlays)
18035 (defun org-toggle-inline-images (&optional include-linked)
18036 "Toggle the display of inline images.
18037 INCLUDE-LINKED is passed to `org-display-inline-images'."
18038 (interactive "P")
18039 (if org-inline-image-overlays
18040 (progn
18041 (org-remove-inline-images)
18042 (message "Inline image display turned off"))
18043 (org-display-inline-images include-linked)
18044 (if (and (org-called-interactively-p)
18045 org-inline-image-overlays)
18046 (message "%d images displayed inline"
18047 (length org-inline-image-overlays))
18048 (message "No images to display inline"))))
18050 (defun org-redisplay-inline-images ()
18051 "Refresh the display of inline images."
18052 (interactive)
18053 (if (not org-inline-image-overlays)
18054 (org-toggle-inline-images)
18055 (org-toggle-inline-images)
18056 (org-toggle-inline-images)))
18058 (defun org-display-inline-images (&optional include-linked refresh beg end)
18059 "Display inline images.
18060 Normally only links without a description part are inlined, because this
18061 is how it will work for export. When INCLUDE-LINKED is set, also links
18062 with a description part will be inlined. This can be nice for a quick
18063 look at those images, but it does not reflect what exported files will look
18064 like.
18065 When REFRESH is set, refresh existing images between BEG and END.
18066 This will create new image displays only if necessary.
18067 BEG and END default to the buffer boundaries."
18068 (interactive "P")
18069 (unless refresh
18070 (org-remove-inline-images)
18071 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18072 (save-excursion
18073 (save-restriction
18074 (widen)
18075 (setq beg (or beg (point-min)) end (or end (point-max)))
18076 (goto-char beg)
18077 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18078 (substring (org-image-file-name-regexp) 0 -2)
18079 "\\)\\]" (if include-linked "" "\\]")))
18080 old file ov img type attrwidth width)
18081 (while (re-search-forward re end t)
18082 (setq old (get-char-property-and-overlay (match-beginning 1)
18083 'org-image-overlay)
18084 file (expand-file-name
18085 (concat (or (match-string 3) "") (match-string 4))))
18086 (when (image-type-available-p 'imagemagick)
18087 (setq attrwidth (if (or (listp org-image-actual-width)
18088 (null org-image-actual-width))
18089 (save-excursion
18090 (save-match-data
18091 (when (re-search-backward
18092 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18093 (save-excursion
18094 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18095 (string-to-number (match-string 1))))))
18096 width (cond ((eq org-image-actual-width t) nil)
18097 ((null org-image-actual-width) attrwidth)
18098 ((numberp org-image-actual-width)
18099 org-image-actual-width)
18100 ((listp org-image-actual-width)
18101 (or attrwidth (car org-image-actual-width))))
18102 type (if width 'imagemagick)))
18103 (when (file-exists-p file)
18104 (if (and (car-safe old) refresh)
18105 (image-refresh (overlay-get (cdr old) 'display))
18106 (setq img (save-match-data (create-image file type nil :width width)))
18107 (when img
18108 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18109 (overlay-put ov 'display img)
18110 (overlay-put ov 'face 'default)
18111 (overlay-put ov 'org-image-overlay t)
18112 (overlay-put ov 'modification-hooks
18113 (list 'org-display-inline-remove-overlay))
18114 (push ov org-inline-image-overlays)))))))))
18116 (define-obsolete-function-alias
18117 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18119 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18120 "Remove inline-display overlay if a corresponding region is modified."
18121 (let ((inhibit-modification-hooks t))
18122 (when (and ov after)
18123 (delete ov org-inline-image-overlays)
18124 (delete-overlay ov))))
18126 (defun org-remove-inline-images ()
18127 "Remove inline display of images."
18128 (interactive)
18129 (mapc 'delete-overlay org-inline-image-overlays)
18130 (setq org-inline-image-overlays nil))
18132 ;;;; Key bindings
18134 ;; Outline functions from `outline-mode-prefix-map'
18135 ;; that can be remapped in Org:
18136 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18137 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18138 (define-key org-mode-map [remap outline-forward-same-level]
18139 'org-forward-heading-same-level)
18140 (define-key org-mode-map [remap outline-backward-same-level]
18141 'org-backward-heading-same-level)
18142 (define-key org-mode-map [remap show-branches]
18143 'org-kill-note-or-show-branches)
18144 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18145 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18146 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18148 ;; Outline functions from `outline-mode-prefix-map' that can not
18149 ;; be remapped in Org:
18151 ;; - the column "key binding" shows whether the Outline function is still
18152 ;; available in Org mode on the same key that it has been bound to in
18153 ;; Outline mode:
18154 ;; - "overridden": key used for a different functionality in Org mode
18155 ;; - else: key still bound to the same Outline function in Org mode
18157 ;; | Outline function | key binding | Org replacement |
18158 ;; |------------------------------------+-------------+-----------------------|
18159 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18160 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18161 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18162 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18163 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18164 ;; | `show-entry' | overridden | no replacement |
18165 ;; | `show-children' | `C-c C-i' | visibility cycling |
18166 ;; | `show-branches' | `C-c C-k' | still same function |
18167 ;; | `show-subtree' | overridden | visibility cycling |
18168 ;; | `show-all' | overridden | no replacement |
18169 ;; | `hide-subtree' | overridden | visibility cycling |
18170 ;; | `hide-body' | overridden | no replacement |
18171 ;; | `hide-entry' | overridden | visibility cycling |
18172 ;; | `hide-leaves' | overridden | no replacement |
18173 ;; | `hide-sublevels' | overridden | no replacement |
18174 ;; | `hide-other' | overridden | no replacement |
18176 ;; Make `C-c C-x' a prefix key
18177 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18179 ;; TAB key with modifiers
18180 (org-defkey org-mode-map "\C-i" 'org-cycle)
18181 (org-defkey org-mode-map [(tab)] 'org-cycle)
18182 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18183 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18184 ;; The following line is necessary under Suse GNU/Linux
18185 (unless (featurep 'xemacs)
18186 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18187 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18188 (define-key org-mode-map [backtab] 'org-shifttab)
18190 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18191 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18192 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18194 ;; Cursor keys with modifiers
18195 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18196 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18197 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18198 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18200 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18201 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18202 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18203 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18205 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18206 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18207 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18208 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18210 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18211 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18212 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18213 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18215 ;; Babel keys
18216 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18217 (mapc (lambda (pair)
18218 (define-key org-babel-map (car pair) (cdr pair)))
18219 org-babel-key-bindings)
18221 ;;; Extra keys for tty access.
18222 ;; We only set them when really needed because otherwise the
18223 ;; menus don't show the simple keys
18225 (when (or org-use-extra-keys
18226 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18227 (not window-system))
18228 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18229 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18230 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18231 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18232 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18233 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18234 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18235 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18236 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18237 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18238 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18239 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18240 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18241 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18242 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18243 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18244 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18245 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18246 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18247 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18248 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18249 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18250 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18251 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18252 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18253 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18254 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18255 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18257 ;; All the other keys
18259 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18260 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18261 (if (boundp 'narrow-map)
18262 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18263 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18264 (if (boundp 'narrow-map)
18265 (org-defkey narrow-map "b" 'org-narrow-to-block)
18266 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18267 (if (boundp 'narrow-map)
18268 (org-defkey narrow-map "e" 'org-narrow-to-element)
18269 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18270 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18271 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18272 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18273 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18274 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18275 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18276 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18277 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18278 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18279 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18280 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18281 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18282 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18283 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18284 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18285 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18286 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18287 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18288 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18289 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18290 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18291 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18292 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18293 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18294 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18295 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18296 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18297 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18298 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18299 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18300 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18301 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18302 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18303 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18304 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18305 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18306 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18307 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18308 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18309 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18310 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18311 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18312 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18313 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18314 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18315 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18316 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18317 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18318 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18319 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18320 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18321 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18322 (org-defkey org-mode-map "\C-c^" 'org-sort)
18323 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18324 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18325 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18326 (org-defkey org-mode-map "\C-m" 'org-return)
18327 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18328 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18329 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18330 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18331 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18332 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18333 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18334 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18335 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18336 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18337 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18338 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18339 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18340 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18341 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18342 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18343 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18344 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18345 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18346 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18347 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18348 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18349 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18351 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18352 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18353 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18355 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18356 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18357 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18358 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18359 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18360 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18361 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18362 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18363 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18364 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18365 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18366 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18367 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18368 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18369 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18370 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18371 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18372 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18373 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18374 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18375 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18376 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18378 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18379 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18380 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18381 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18382 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18384 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18386 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18388 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18389 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18391 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18394 (when (featurep 'xemacs)
18395 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18398 (defconst org-speed-commands-default
18400 ("Outline Navigation")
18401 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18402 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18403 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18404 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18405 ("u" . (org-speed-move-safe 'outline-up-heading))
18406 ("j" . org-goto)
18407 ("g" . (org-refile t))
18408 ("Outline Visibility")
18409 ("c" . org-cycle)
18410 ("C" . org-shifttab)
18411 (" " . org-display-outline-path)
18412 (":" . org-columns)
18413 ("Outline Structure Editing")
18414 ("U" . org-shiftmetaup)
18415 ("D" . org-shiftmetadown)
18416 ("r" . org-metaright)
18417 ("l" . org-metaleft)
18418 ("R" . org-shiftmetaright)
18419 ("L" . org-shiftmetaleft)
18420 ("i" . (progn (forward-char 1) (call-interactively
18421 'org-insert-heading-respect-content)))
18422 ("^" . org-sort)
18423 ("w" . org-refile)
18424 ("a" . org-archive-subtree-default-with-confirmation)
18425 ("." . org-mark-subtree)
18426 ("#" . org-toggle-comment)
18427 ("Clock Commands")
18428 ("I" . org-clock-in)
18429 ("O" . org-clock-out)
18430 ("Meta Data Editing")
18431 ("t" . org-todo)
18432 ("," . (org-priority))
18433 ("0" . (org-priority ?\ ))
18434 ("1" . (org-priority ?A))
18435 ("2" . (org-priority ?B))
18436 ("3" . (org-priority ?C))
18437 (";" . org-set-tags-command)
18438 ("e" . org-set-effort)
18439 ("E" . org-inc-effort)
18440 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18441 (org-entry-put (point) "APPT_WARNTIME" m)))
18442 ("Agenda Views etc")
18443 ("v" . org-agenda)
18444 ("/" . org-sparse-tree)
18445 ("Misc")
18446 ("o" . org-open-at-point)
18447 ("?" . org-speed-command-help)
18448 ("<" . (org-agenda-set-restriction-lock 'subtree))
18449 (">" . (org-agenda-remove-restriction-lock))
18451 "The default speed commands.")
18453 (defun org-print-speed-command (e)
18454 (if (> (length (car e)) 1)
18455 (progn
18456 (princ "\n")
18457 (princ (car e))
18458 (princ "\n")
18459 (princ (make-string (length (car e)) ?-))
18460 (princ "\n"))
18461 (princ (car e))
18462 (princ " ")
18463 (if (symbolp (cdr e))
18464 (princ (symbol-name (cdr e)))
18465 (prin1 (cdr e)))
18466 (princ "\n")))
18468 (defun org-speed-command-help ()
18469 "Show the available speed commands."
18470 (interactive)
18471 (if (not org-use-speed-commands)
18472 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18473 (with-output-to-temp-buffer "*Help*"
18474 (princ "User-defined Speed commands\n===========================\n")
18475 (mapc 'org-print-speed-command org-speed-commands-user)
18476 (princ "\n")
18477 (princ "Built-in Speed commands\n=======================\n")
18478 (mapc 'org-print-speed-command org-speed-commands-default))
18479 (with-current-buffer "*Help*"
18480 (setq truncate-lines t))))
18482 (defun org-speed-move-safe (cmd)
18483 "Execute CMD, but make sure that the cursor always ends up in a headline.
18484 If not, return to the original position and throw an error."
18485 (interactive)
18486 (let ((pos (point)))
18487 (call-interactively cmd)
18488 (unless (and (bolp) (org-at-heading-p))
18489 (goto-char pos)
18490 (error "Boundary reached while executing %s" cmd))))
18492 (defvar org-self-insert-command-undo-counter 0)
18494 (defvar org-table-auto-blank-field) ; defined in org-table.el
18495 (defvar org-speed-command nil)
18497 (define-obsolete-function-alias
18498 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18500 (defun org-speed-command-activate (keys)
18501 "Hook for activating single-letter speed commands.
18502 `org-speed-commands-default' specifies a minimal command set.
18503 Use `org-speed-commands-user' for further customization."
18504 (when (or (and (bolp) (looking-at org-outline-regexp))
18505 (and (functionp org-use-speed-commands)
18506 (funcall org-use-speed-commands)))
18507 (cdr (assoc keys (append org-speed-commands-user
18508 org-speed-commands-default)))))
18510 (define-obsolete-function-alias
18511 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18513 (defun org-babel-speed-command-activate (keys)
18514 "Hook for activating single-letter code block commands."
18515 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18516 (cdr (assoc keys org-babel-key-bindings))))
18518 (defcustom org-speed-command-hook
18519 '(org-speed-command-default-hook org-babel-speed-command-hook)
18520 "Hook for activating speed commands at strategic locations.
18521 Hook functions are called in sequence until a valid handler is
18522 found.
18524 Each hook takes a single argument, a user-pressed command key
18525 which is also a `self-insert-command' from the global map.
18527 Within the hook, examine the cursor position and the command key
18528 and return nil or a valid handler as appropriate. Handler could
18529 be one of an interactive command, a function, or a form.
18531 Set `org-use-speed-commands' to non-nil value to enable this
18532 hook. The default setting is `org-speed-command-activate'."
18533 :group 'org-structure
18534 :version "24.1"
18535 :type 'hook)
18537 (defun org-self-insert-command (N)
18538 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18539 If the cursor is in a table looking at whitespace, the whitespace is
18540 overwritten, and the table is not marked as requiring realignment."
18541 (interactive "p")
18542 (org-check-before-invisible-edit 'insert)
18543 (cond
18544 ((and org-use-speed-commands
18545 (setq org-speed-command
18546 (run-hook-with-args-until-success
18547 'org-speed-command-hook (this-command-keys))))
18548 (cond
18549 ((commandp org-speed-command)
18550 (setq this-command org-speed-command)
18551 (call-interactively org-speed-command))
18552 ((functionp org-speed-command)
18553 (funcall org-speed-command))
18554 ((and org-speed-command (listp org-speed-command))
18555 (eval org-speed-command))
18556 (t (let (org-use-speed-commands)
18557 (call-interactively 'org-self-insert-command)))))
18558 ((and
18559 (org-table-p)
18560 (progn
18561 ;; check if we blank the field, and if that triggers align
18562 (and (featurep 'org-table) org-table-auto-blank-field
18563 (member last-command
18564 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18565 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18566 ;; got extra space, this field does not determine column width
18567 (let (org-table-may-need-update) (org-table-blank-field))
18568 ;; no extra space, this field may determine column width
18569 (org-table-blank-field)))
18571 (eq N 1)
18572 (looking-at "[^|\n]* |"))
18573 (let (org-table-may-need-update)
18574 (goto-char (1- (match-end 0)))
18575 (backward-delete-char 1)
18576 (goto-char (match-beginning 0))
18577 (self-insert-command N)))
18579 (setq org-table-may-need-update t)
18580 (self-insert-command N)
18581 (org-fix-tags-on-the-fly)
18582 (if org-self-insert-cluster-for-undo
18583 (if (not (eq last-command 'org-self-insert-command))
18584 (setq org-self-insert-command-undo-counter 1)
18585 (if (>= org-self-insert-command-undo-counter 20)
18586 (setq org-self-insert-command-undo-counter 1)
18587 (and (> org-self-insert-command-undo-counter 0)
18588 buffer-undo-list (listp buffer-undo-list)
18589 (not (cadr buffer-undo-list)) ; remove nil entry
18590 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18591 (setq org-self-insert-command-undo-counter
18592 (1+ org-self-insert-command-undo-counter))))))))
18594 (defun org-check-before-invisible-edit (kind)
18595 "Check is editing if kind KIND would be dangerous with invisible text around.
18596 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18597 ;; First, try to get out of here as quickly as possible, to reduce overhead
18598 (if (and org-catch-invisible-edits
18599 (or (not (boundp 'visible-mode)) (not visible-mode))
18600 (or (get-char-property (point) 'invisible)
18601 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18602 ;; OK, we need to take a closer look
18603 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18604 (invisible-before-point (if (bobp) nil (get-char-property
18605 (1- (point)) 'invisible)))
18606 (border-and-ok-direction
18608 ;; Check if we are acting predictably before invisible text
18609 (and invisible-at-point (not invisible-before-point)
18610 (memq kind '(insert delete-backward)))
18611 ;; Check if we are acting predictably after invisible text
18612 ;; This works not well, and I have turned it off. It seems
18613 ;; better to always show and stop after invisible text.
18614 ;; (and (not invisible-at-point) invisible-before-point
18615 ;; (memq kind '(insert delete)))
18617 (when (or (memq invisible-at-point '(outline org-hide-block t))
18618 (memq invisible-before-point '(outline org-hide-block t)))
18619 (if (eq org-catch-invisible-edits 'error)
18620 (error "Editing in invisible areas is prohibited - make visible first"))
18621 (if (and org-custom-properties-overlays
18622 (y-or-n-p "Display invisible properties in this buffer? "))
18623 (org-toggle-custom-properties-visibility)
18624 ;; Make the area visible
18625 (save-excursion
18626 (if invisible-before-point
18627 (goto-char (previous-single-char-property-change
18628 (point) 'invisible)))
18629 (org-cycle))
18630 (cond
18631 ((eq org-catch-invisible-edits 'show)
18632 ;; That's it, we do the edit after showing
18633 (message
18634 "Unfolding invisible region around point before editing")
18635 (sit-for 1))
18636 ((and (eq org-catch-invisible-edits 'smart)
18637 border-and-ok-direction)
18638 (message "Unfolding invisible region around point before editing"))
18640 ;; Don't do the edit, make the user repeat it in full visibility
18641 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18643 (defun org-fix-tags-on-the-fly ()
18644 (when (and (equal (char-after (point-at-bol)) ?*)
18645 (org-at-heading-p))
18646 (org-align-tags-here org-tags-column)))
18648 (defun org-delete-backward-char (N)
18649 "Like `delete-backward-char', insert whitespace at field end in tables.
18650 When deleting backwards, in tables this function will insert whitespace in
18651 front of the next \"|\" separator, to keep the table aligned. The table will
18652 still be marked for re-alignment if the field did fill the entire column,
18653 because, in this case the deletion might narrow the column."
18654 (interactive "p")
18655 (org-check-before-invisible-edit 'delete-backward)
18656 (if (and (org-table-p)
18657 (eq N 1)
18658 (string-match "|" (buffer-substring (point-at-bol) (point)))
18659 (looking-at ".*?|"))
18660 (let ((pos (point))
18661 (noalign (looking-at "[^|\n\r]* |"))
18662 (c org-table-may-need-update))
18663 (backward-delete-char N)
18664 (if (not overwrite-mode)
18665 (progn
18666 (skip-chars-forward "^|")
18667 (insert " ")
18668 (goto-char (1- pos))))
18669 ;; noalign: if there were two spaces at the end, this field
18670 ;; does not determine the width of the column.
18671 (if noalign (setq org-table-may-need-update c)))
18672 (backward-delete-char N)
18673 (org-fix-tags-on-the-fly)))
18675 (defun org-delete-char (N)
18676 "Like `delete-char', but insert whitespace at field end in tables.
18677 When deleting characters, in tables this function will insert whitespace in
18678 front of the next \"|\" separator, to keep the table aligned. The table will
18679 still be marked for re-alignment if the field did fill the entire column,
18680 because, in this case the deletion might narrow the column."
18681 (interactive "p")
18682 (org-check-before-invisible-edit 'delete)
18683 (if (and (org-table-p)
18684 (not (bolp))
18685 (not (= (char-after) ?|))
18686 (eq N 1))
18687 (if (looking-at ".*?|")
18688 (let ((pos (point))
18689 (noalign (looking-at "[^|\n\r]* |"))
18690 (c org-table-may-need-update))
18691 (replace-match (concat
18692 (substring (match-string 0) 1 -1)
18693 " |"))
18694 (goto-char pos)
18695 ;; noalign: if there were two spaces at the end, this field
18696 ;; does not determine the width of the column.
18697 (if noalign (setq org-table-may-need-update c)))
18698 (delete-char N))
18699 (delete-char N)
18700 (org-fix-tags-on-the-fly)))
18702 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18703 (put 'org-self-insert-command 'delete-selection t)
18704 (put 'orgtbl-self-insert-command 'delete-selection t)
18705 (put 'org-delete-char 'delete-selection 'supersede)
18706 (put 'org-delete-backward-char 'delete-selection 'supersede)
18707 (put 'org-yank 'delete-selection 'yank)
18709 ;; Make `flyspell-mode' delay after some commands
18710 (put 'org-self-insert-command 'flyspell-delayed t)
18711 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18712 (put 'org-delete-char 'flyspell-delayed t)
18713 (put 'org-delete-backward-char 'flyspell-delayed t)
18715 ;; Make pabbrev-mode expand after org-mode commands
18716 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18717 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18719 ;; How to do this: Measure non-white length of current string
18720 ;; If equal to column width, we should realign.
18722 (defun org-remap (map &rest commands)
18723 "In MAP, remap the functions given in COMMANDS.
18724 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18725 (let (new old)
18726 (while commands
18727 (setq old (pop commands) new (pop commands))
18728 (if (fboundp 'command-remapping)
18729 (org-defkey map (vector 'remap old) new)
18730 (substitute-key-definition old new map global-map)))))
18732 (when (eq org-enable-table-editor 'optimized)
18733 ;; If the user wants maximum table support, we need to hijack
18734 ;; some standard editing functions
18735 (org-remap org-mode-map
18736 'self-insert-command 'org-self-insert-command
18737 'delete-char 'org-delete-char
18738 'delete-backward-char 'org-delete-backward-char)
18739 (org-defkey org-mode-map "|" 'org-force-self-insert))
18741 (defvar org-ctrl-c-ctrl-c-hook nil
18742 "Hook for functions attaching themselves to `C-c C-c'.
18744 This can be used to add additional functionality to the C-c C-c
18745 key which executes context-dependent commands. This hook is run
18746 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18747 run after the last test.
18749 Each function will be called with no arguments. The function
18750 must check if the context is appropriate for it to act. If yes,
18751 it should do its thing and then return a non-nil value. If the
18752 context is wrong, just do nothing and return nil.")
18754 (defvar org-ctrl-c-ctrl-c-final-hook nil
18755 "Hook for functions attaching themselves to `C-c C-c'.
18757 This can be used to add additional functionality to the C-c C-c
18758 key which executes context-dependent commands. This hook is run
18759 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18760 before the first test.
18762 Each function will be called with no arguments. The function
18763 must check if the context is appropriate for it to act. If yes,
18764 it should do its thing and then return a non-nil value. If the
18765 context is wrong, just do nothing and return nil.")
18767 (defvar org-tab-first-hook nil
18768 "Hook for functions to attach themselves to TAB.
18769 See `org-ctrl-c-ctrl-c-hook' for more information.
18770 This hook runs as the first action when TAB is pressed, even before
18771 `org-cycle' messes around with the `outline-regexp' to cater for
18772 inline tasks and plain list item folding.
18773 If any function in this hook returns t, any other actions that
18774 would have been caused by TAB (such as table field motion or visibility
18775 cycling) will not occur.")
18777 (defvar org-tab-after-check-for-table-hook nil
18778 "Hook for functions to attach themselves to TAB.
18779 See `org-ctrl-c-ctrl-c-hook' for more information.
18780 This hook runs after it has been established that the cursor is not in a
18781 table, but before checking if the cursor is in a headline or if global cycling
18782 should be done.
18783 If any function in this hook returns t, not other actions like visibility
18784 cycling will be done.")
18786 (defvar org-tab-after-check-for-cycling-hook nil
18787 "Hook for functions to attach themselves to TAB.
18788 See `org-ctrl-c-ctrl-c-hook' for more information.
18789 This hook runs after it has been established that not table field motion and
18790 not visibility should be done because of current context. This is probably
18791 the place where a package like yasnippets can hook in.")
18793 (defvar org-tab-before-tab-emulation-hook nil
18794 "Hook for functions to attach themselves to TAB.
18795 See `org-ctrl-c-ctrl-c-hook' for more information.
18796 This hook runs after every other options for TAB have been exhausted, but
18797 before indentation and \t insertion takes place.")
18799 (defvar org-metaleft-hook nil
18800 "Hook for functions attaching themselves to `M-left'.
18801 See `org-ctrl-c-ctrl-c-hook' for more information.")
18802 (defvar org-metaright-hook nil
18803 "Hook for functions attaching themselves to `M-right'.
18804 See `org-ctrl-c-ctrl-c-hook' for more information.")
18805 (defvar org-metaup-hook nil
18806 "Hook for functions attaching themselves to `M-up'.
18807 See `org-ctrl-c-ctrl-c-hook' for more information.")
18808 (defvar org-metadown-hook nil
18809 "Hook for functions attaching themselves to `M-down'.
18810 See `org-ctrl-c-ctrl-c-hook' for more information.")
18811 (defvar org-shiftmetaleft-hook nil
18812 "Hook for functions attaching themselves to `M-S-left'.
18813 See `org-ctrl-c-ctrl-c-hook' for more information.")
18814 (defvar org-shiftmetaright-hook nil
18815 "Hook for functions attaching themselves to `M-S-right'.
18816 See `org-ctrl-c-ctrl-c-hook' for more information.")
18817 (defvar org-shiftmetaup-hook nil
18818 "Hook for functions attaching themselves to `M-S-up'.
18819 See `org-ctrl-c-ctrl-c-hook' for more information.")
18820 (defvar org-shiftmetadown-hook nil
18821 "Hook for functions attaching themselves to `M-S-down'.
18822 See `org-ctrl-c-ctrl-c-hook' for more information.")
18823 (defvar org-metareturn-hook nil
18824 "Hook for functions attaching themselves to `M-RET'.
18825 See `org-ctrl-c-ctrl-c-hook' for more information.")
18826 (defvar org-shiftup-hook nil
18827 "Hook for functions attaching themselves to `S-up'.
18828 See `org-ctrl-c-ctrl-c-hook' for more information.")
18829 (defvar org-shiftup-final-hook nil
18830 "Hook for functions attaching themselves to `S-up'.
18831 This one runs after all other options except shift-select have been excluded.
18832 See `org-ctrl-c-ctrl-c-hook' for more information.")
18833 (defvar org-shiftdown-hook nil
18834 "Hook for functions attaching themselves to `S-down'.
18835 See `org-ctrl-c-ctrl-c-hook' for more information.")
18836 (defvar org-shiftdown-final-hook nil
18837 "Hook for functions attaching themselves to `S-down'.
18838 This one runs after all other options except shift-select have been excluded.
18839 See `org-ctrl-c-ctrl-c-hook' for more information.")
18840 (defvar org-shiftleft-hook nil
18841 "Hook for functions attaching themselves to `S-left'.
18842 See `org-ctrl-c-ctrl-c-hook' for more information.")
18843 (defvar org-shiftleft-final-hook nil
18844 "Hook for functions attaching themselves to `S-left'.
18845 This one runs after all other options except shift-select have been excluded.
18846 See `org-ctrl-c-ctrl-c-hook' for more information.")
18847 (defvar org-shiftright-hook nil
18848 "Hook for functions attaching themselves to `S-right'.
18849 See `org-ctrl-c-ctrl-c-hook' for more information.")
18850 (defvar org-shiftright-final-hook nil
18851 "Hook for functions attaching themselves to `S-right'.
18852 This one runs after all other options except shift-select have been excluded.
18853 See `org-ctrl-c-ctrl-c-hook' for more information.")
18855 (defun org-modifier-cursor-error ()
18856 "Throw an error, a modified cursor command was applied in wrong context."
18857 (error "This command is active in special context like tables, headlines or items"))
18859 (defun org-shiftselect-error ()
18860 "Throw an error because Shift-Cursor command was applied in wrong context."
18861 (if (and (boundp 'shift-select-mode) shift-select-mode)
18862 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18863 (error "This command works only in special context like headlines or timestamps")))
18865 (defun org-call-for-shift-select (cmd)
18866 (let ((this-command-keys-shift-translated t))
18867 (call-interactively cmd)))
18869 (defun org-shifttab (&optional arg)
18870 "Global visibility cycling or move to previous table field.
18871 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18872 on context.
18873 See the individual commands for more information."
18874 (interactive "P")
18875 (cond
18876 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18877 ((integerp arg)
18878 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18879 (message "Content view to level: %d" arg)
18880 (org-content (prefix-numeric-value arg2))
18881 (setq org-cycle-global-status 'overview)))
18882 (t (call-interactively 'org-global-cycle))))
18884 (defun org-shiftmetaleft ()
18885 "Promote subtree or delete table column.
18886 Calls `org-promote-subtree', `org-outdent-item-tree', or
18887 `org-table-delete-column', depending on context. See the
18888 individual commands for more information."
18889 (interactive)
18890 (cond
18891 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18892 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18893 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18894 ((if (not (org-region-active-p)) (org-at-item-p)
18895 (save-excursion (goto-char (region-beginning))
18896 (org-at-item-p)))
18897 (call-interactively 'org-outdent-item-tree))
18898 (t (org-modifier-cursor-error))))
18900 (defun org-shiftmetaright ()
18901 "Demote subtree or insert table column.
18902 Calls `org-demote-subtree', `org-indent-item-tree', or
18903 `org-table-insert-column', depending on context. See the
18904 individual commands for more information."
18905 (interactive)
18906 (cond
18907 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18908 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18909 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18910 ((if (not (org-region-active-p)) (org-at-item-p)
18911 (save-excursion (goto-char (region-beginning))
18912 (org-at-item-p)))
18913 (call-interactively 'org-indent-item-tree))
18914 (t (org-modifier-cursor-error))))
18916 (defun org-shiftmetaup (&optional arg)
18917 "Move subtree up or kill table row.
18918 Calls `org-move-subtree-up' or `org-table-kill-row' or
18919 `org-move-item-up' or `org-timestamp-up', depending on context.
18920 See the individual commands for more information."
18921 (interactive "P")
18922 (cond
18923 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18924 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18925 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18926 ((org-at-item-p) (call-interactively 'org-move-item-up))
18927 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18928 (call-interactively 'org-timestamp-up)))
18929 (t (org-modifier-cursor-error))))
18931 (defun org-shiftmetadown (&optional arg)
18932 "Move subtree down or insert table row.
18933 Calls `org-move-subtree-down' or `org-table-insert-row' or
18934 `org-move-item-down' or `org-timestamp-up', depending on context.
18935 See the individual commands for more information."
18936 (interactive "P")
18937 (cond
18938 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18939 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18940 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18941 ((org-at-item-p) (call-interactively 'org-move-item-down))
18942 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18943 (call-interactively 'org-timestamp-down)))
18944 (t (org-modifier-cursor-error))))
18946 (defsubst org-hidden-tree-error ()
18947 (error
18948 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18950 (defun org-metaleft (&optional arg)
18951 "Promote heading or move table column to left.
18952 Calls `org-do-promote' or `org-table-move-column', depending on context.
18953 With no specific context, calls the Emacs default `backward-word'.
18954 See the individual commands for more information."
18955 (interactive "P")
18956 (cond
18957 ((run-hook-with-args-until-success 'org-metaleft-hook))
18958 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18959 ((org-with-limited-levels
18960 (or (org-at-heading-p)
18961 (and (org-region-active-p)
18962 (save-excursion
18963 (goto-char (region-beginning))
18964 (org-at-heading-p)))))
18965 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18966 (call-interactively 'org-do-promote))
18967 ;; At an inline task.
18968 ((org-at-heading-p)
18969 (call-interactively 'org-inlinetask-promote))
18970 ((or (org-at-item-p)
18971 (and (org-region-active-p)
18972 (save-excursion
18973 (goto-char (region-beginning))
18974 (org-at-item-p))))
18975 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18976 (call-interactively 'org-outdent-item))
18977 (t (call-interactively 'backward-word))))
18979 (defun org-metaright (&optional arg)
18980 "Demote a subtree, a list item or move table column to right.
18981 In front of a drawer or a block keyword, indent it correctly.
18982 With no specific context, calls the Emacs default `forward-word'.
18983 See the individual commands for more information."
18984 (interactive "P")
18985 (cond
18986 ((run-hook-with-args-until-success 'org-metaright-hook))
18987 ((org-at-table-p) (call-interactively 'org-table-move-column))
18988 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18989 ((org-at-block-p) (call-interactively 'org-indent-block))
18990 ((org-with-limited-levels
18991 (or (org-at-heading-p)
18992 (and (org-region-active-p)
18993 (save-excursion
18994 (goto-char (region-beginning))
18995 (org-at-heading-p)))))
18996 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18997 (call-interactively 'org-do-demote))
18998 ;; At an inline task.
18999 ((org-at-heading-p)
19000 (call-interactively 'org-inlinetask-demote))
19001 ((or (org-at-item-p)
19002 (and (org-region-active-p)
19003 (save-excursion
19004 (goto-char (region-beginning))
19005 (org-at-item-p))))
19006 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19007 (call-interactively 'org-indent-item))
19008 (t (call-interactively 'forward-word))))
19010 (defun org-check-for-hidden (what)
19011 "Check if there are hidden headlines/items in the current visual line.
19012 WHAT can be either `headlines' or `items'. If the current line is
19013 an outline or item heading and it has a folded subtree below it,
19014 this function returns t, nil otherwise."
19015 (let ((re (cond
19016 ((eq what 'headlines) org-outline-regexp-bol)
19017 ((eq what 'items) (org-item-beginning-re))
19018 (t (error "This should not happen"))))
19019 beg end)
19020 (save-excursion
19021 (catch 'exit
19022 (unless (org-region-active-p)
19023 (setq beg (point-at-bol))
19024 (beginning-of-line 2)
19025 (while (and (not (eobp)) ;; this is like `next-line'
19026 (get-char-property (1- (point)) 'invisible))
19027 (beginning-of-line 2))
19028 (setq end (point))
19029 (goto-char beg)
19030 (goto-char (point-at-eol))
19031 (setq end (max end (point)))
19032 (while (re-search-forward re end t)
19033 (if (get-char-property (match-beginning 0) 'invisible)
19034 (throw 'exit t))))
19035 nil))))
19037 (defun org-metaup (&optional arg)
19038 "Move subtree up or move table row up.
19039 Calls `org-move-subtree-up' or `org-table-move-row' or
19040 `org-move-item-up', depending on context. See the individual commands
19041 for more information."
19042 (interactive "P")
19043 (cond
19044 ((run-hook-with-args-until-success 'org-metaup-hook))
19045 ((org-region-active-p)
19046 (let* ((a (min (region-beginning) (region-end)))
19047 (b (1- (max (region-beginning) (region-end))))
19048 (c (save-excursion (goto-char a)
19049 (move-beginning-of-line 0)))
19050 (d (save-excursion (goto-char a)
19051 (move-end-of-line 0) (point))))
19052 (transpose-regions a b c d)
19053 (goto-char c)))
19054 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19055 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19056 ((org-at-item-p) (call-interactively 'org-move-item-up))
19057 (t (org-drag-element-backward))))
19059 (defun org-metadown (&optional arg)
19060 "Move subtree down or move table row down.
19061 Calls `org-move-subtree-down' or `org-table-move-row' or
19062 `org-move-item-down', depending on context. See the individual
19063 commands for more information."
19064 (interactive "P")
19065 (cond
19066 ((run-hook-with-args-until-success 'org-metadown-hook))
19067 ((org-region-active-p)
19068 (let* ((a (min (region-beginning) (region-end)))
19069 (b (max (region-beginning) (region-end)))
19070 (c (save-excursion (goto-char b)
19071 (move-beginning-of-line 1)))
19072 (d (save-excursion (goto-char b)
19073 (move-end-of-line 1) (1+ (point)))))
19074 (transpose-regions a b c d)
19075 (goto-char d)))
19076 ((org-at-table-p) (call-interactively 'org-table-move-row))
19077 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19078 ((org-at-item-p) (call-interactively 'org-move-item-down))
19079 (t (org-drag-element-forward))))
19081 (defun org-shiftup (&optional arg)
19082 "Increase item in timestamp or increase priority of current headline.
19083 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19084 depending on context. See the individual commands for more information."
19085 (interactive "P")
19086 (cond
19087 ((run-hook-with-args-until-success 'org-shiftup-hook))
19088 ((and org-support-shift-select (org-region-active-p))
19089 (org-call-for-shift-select 'previous-line))
19090 ((org-at-timestamp-p t)
19091 (call-interactively (if org-edit-timestamp-down-means-later
19092 'org-timestamp-down 'org-timestamp-up)))
19093 ((and (not (eq org-support-shift-select 'always))
19094 org-enable-priority-commands
19095 (org-at-heading-p))
19096 (call-interactively 'org-priority-up))
19097 ((and (not org-support-shift-select) (org-at-item-p))
19098 (call-interactively 'org-previous-item))
19099 ((org-clocktable-try-shift 'up arg))
19100 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19101 (org-support-shift-select
19102 (org-call-for-shift-select 'previous-line))
19103 (t (org-shiftselect-error))))
19105 (defun org-shiftdown (&optional arg)
19106 "Decrease item in timestamp or decrease priority of current headline.
19107 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19108 depending on context. See the individual commands for more information."
19109 (interactive "P")
19110 (cond
19111 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19112 ((and org-support-shift-select (org-region-active-p))
19113 (org-call-for-shift-select 'next-line))
19114 ((org-at-timestamp-p t)
19115 (call-interactively (if org-edit-timestamp-down-means-later
19116 'org-timestamp-up 'org-timestamp-down)))
19117 ((and (not (eq org-support-shift-select 'always))
19118 org-enable-priority-commands
19119 (org-at-heading-p))
19120 (call-interactively 'org-priority-down))
19121 ((and (not org-support-shift-select) (org-at-item-p))
19122 (call-interactively 'org-next-item))
19123 ((org-clocktable-try-shift 'down arg))
19124 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19125 (org-support-shift-select
19126 (org-call-for-shift-select 'next-line))
19127 (t (org-shiftselect-error))))
19129 (defun org-shiftright (&optional arg)
19130 "Cycle the thing at point or in the current line, depending on context.
19131 Depending on context, this does one of the following:
19133 - switch a timestamp at point one day into the future
19134 - on a headline, switch to the next TODO keyword.
19135 - on an item, switch entire list to the next bullet type
19136 - on a property line, switch to the next allowed value
19137 - on a clocktable definition line, move time block into the future"
19138 (interactive "P")
19139 (cond
19140 ((run-hook-with-args-until-success 'org-shiftright-hook))
19141 ((and org-support-shift-select (org-region-active-p))
19142 (org-call-for-shift-select 'forward-char))
19143 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19144 ((and (not (eq org-support-shift-select 'always))
19145 (org-at-heading-p))
19146 (let ((org-inhibit-logging
19147 (not org-treat-S-cursor-todo-selection-as-state-change))
19148 (org-inhibit-blocking
19149 (not org-treat-S-cursor-todo-selection-as-state-change)))
19150 (org-call-with-arg 'org-todo 'right)))
19151 ((or (and org-support-shift-select
19152 (not (eq org-support-shift-select 'always))
19153 (org-at-item-bullet-p))
19154 (and (not org-support-shift-select) (org-at-item-p)))
19155 (org-call-with-arg 'org-cycle-list-bullet nil))
19156 ((and (not (eq org-support-shift-select 'always))
19157 (org-at-property-p))
19158 (call-interactively 'org-property-next-allowed-value))
19159 ((org-clocktable-try-shift 'right arg))
19160 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19161 (org-support-shift-select
19162 (org-call-for-shift-select 'forward-char))
19163 (t (org-shiftselect-error))))
19165 (defun org-shiftleft (&optional arg)
19166 "Cycle the thing at point or in the current line, depending on context.
19167 Depending on context, this does one of the following:
19169 - switch a timestamp at point one day into the past
19170 - on a headline, switch to the previous TODO keyword.
19171 - on an item, switch entire list to the previous bullet type
19172 - on a property line, switch to the previous allowed value
19173 - on a clocktable definition line, move time block into the past"
19174 (interactive "P")
19175 (cond
19176 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19177 ((and org-support-shift-select (org-region-active-p))
19178 (org-call-for-shift-select 'backward-char))
19179 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19180 ((and (not (eq org-support-shift-select 'always))
19181 (org-at-heading-p))
19182 (let ((org-inhibit-logging
19183 (not org-treat-S-cursor-todo-selection-as-state-change))
19184 (org-inhibit-blocking
19185 (not org-treat-S-cursor-todo-selection-as-state-change)))
19186 (org-call-with-arg 'org-todo 'left)))
19187 ((or (and org-support-shift-select
19188 (not (eq org-support-shift-select 'always))
19189 (org-at-item-bullet-p))
19190 (and (not org-support-shift-select) (org-at-item-p)))
19191 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19192 ((and (not (eq org-support-shift-select 'always))
19193 (org-at-property-p))
19194 (call-interactively 'org-property-previous-allowed-value))
19195 ((org-clocktable-try-shift 'left arg))
19196 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19197 (org-support-shift-select
19198 (org-call-for-shift-select 'backward-char))
19199 (t (org-shiftselect-error))))
19201 (defun org-shiftcontrolright ()
19202 "Switch to next TODO set."
19203 (interactive)
19204 (cond
19205 ((and org-support-shift-select (org-region-active-p))
19206 (org-call-for-shift-select 'forward-word))
19207 ((and (not (eq org-support-shift-select 'always))
19208 (org-at-heading-p))
19209 (org-call-with-arg 'org-todo 'nextset))
19210 (org-support-shift-select
19211 (org-call-for-shift-select 'forward-word))
19212 (t (org-shiftselect-error))))
19214 (defun org-shiftcontrolleft ()
19215 "Switch to previous TODO set."
19216 (interactive)
19217 (cond
19218 ((and org-support-shift-select (org-region-active-p))
19219 (org-call-for-shift-select 'backward-word))
19220 ((and (not (eq org-support-shift-select 'always))
19221 (org-at-heading-p))
19222 (org-call-with-arg 'org-todo 'previousset))
19223 (org-support-shift-select
19224 (org-call-for-shift-select 'backward-word))
19225 (t (org-shiftselect-error))))
19227 (defun org-shiftcontrolup (&optional n)
19228 "Change timestamps synchronously up in CLOCK log lines.
19229 Optional argument N tells to change by that many units."
19230 (interactive "P")
19231 (cond ((and (not org-support-shift-select)
19232 (org-at-clock-log-p)
19233 (org-at-timestamp-p t))
19234 (org-clock-timestamps-up n))
19235 (t (org-shiftselect-error))))
19237 (defun org-shiftcontroldown (&optional n)
19238 "Change timestamps synchronously down in CLOCK log lines.
19239 Optional argument N tells to change by that many units."
19240 (interactive "P")
19241 (cond ((and (not org-support-shift-select)
19242 (org-at-clock-log-p)
19243 (org-at-timestamp-p t))
19244 (org-clock-timestamps-down n))
19245 (t (org-shiftselect-error))))
19247 (defun org-ctrl-c-ret ()
19248 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19249 (interactive)
19250 (cond
19251 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19252 (t (call-interactively 'org-insert-heading))))
19254 (defun org-find-visible ()
19255 (let ((s (point)))
19256 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19257 (get-char-property s 'invisible)))
19259 (defun org-find-invisible ()
19260 (let ((s (point)))
19261 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19262 (not (get-char-property s 'invisible))))
19265 (defun org-copy-visible (beg end)
19266 "Copy the visible parts of the region."
19267 (interactive "r")
19268 (let (snippets s)
19269 (save-excursion
19270 (save-restriction
19271 (narrow-to-region beg end)
19272 (setq s (goto-char (point-min)))
19273 (while (not (= (point) (point-max)))
19274 (goto-char (org-find-invisible))
19275 (push (buffer-substring s (point)) snippets)
19276 (setq s (goto-char (org-find-visible))))))
19277 (kill-new (apply 'concat (nreverse snippets)))))
19279 (defun org-copy-special ()
19280 "Copy region in table or copy current subtree.
19281 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19282 See the individual commands for more information."
19283 (interactive)
19284 (call-interactively
19285 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19287 (defun org-cut-special ()
19288 "Cut region in table or cut current subtree.
19289 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19290 See the individual commands for more information."
19291 (interactive)
19292 (call-interactively
19293 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19295 (defun org-paste-special (arg)
19296 "Paste rectangular region into table, or past subtree relative to level.
19297 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19298 See the individual commands for more information."
19299 (interactive "P")
19300 (if (org-at-table-p)
19301 (org-table-paste-rectangle)
19302 (org-paste-subtree arg)))
19304 (defun org-edit-special (&optional arg)
19305 "Call a special editor for the stuff at point.
19306 When at a table, call the formula editor with `org-table-edit-formulas'.
19307 When in a source code block, call `org-edit-src-code'.
19308 When in an #+include line, visit the included file.
19309 On a link, call `ffap' to visit the link at point.
19310 Otherwise, return a user error."
19311 (interactive)
19312 ;; possibly prep session before editing source
19313 (when (and (org-in-src-block-p) arg)
19314 (let* ((info (org-babel-get-src-block-info))
19315 (lang (nth 0 info))
19316 (params (nth 2 info))
19317 (session (cdr (assoc :session params))))
19318 (when (and info session) ;; we are in a source-code block with a session
19319 (funcall
19320 (intern (concat "org-babel-prep-session:" lang)) session params))))
19321 (cond ;; proceed with `org-edit-special'
19322 ((save-excursion
19323 (beginning-of-line 1)
19324 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19325 (find-file (org-trim (match-string 1))))
19326 ((or (org-at-table-p)
19327 (save-excursion
19328 (beginning-of-line 1)
19329 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19330 (call-interactively 'org-table-edit-formulas))
19331 ((or (org-in-src-block-p) (org-at-table.el-p)) (org-edit-src-code))
19332 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19333 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19334 (t (user-error "No special environment to edit here"))))
19336 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19337 (defun org-ctrl-c-ctrl-c (&optional arg)
19338 "Set tags in headline, or update according to changed information at point.
19340 This command does many different things, depending on context:
19342 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19343 this is what we do.
19345 - If the cursor is on a statistics cookie, update it.
19347 - If the cursor is in a headline, prompt for tags and insert them
19348 into the current line, aligned to `org-tags-column'. When called
19349 with prefix arg, realign all tags in the current buffer.
19351 - If the cursor is in one of the special #+KEYWORD lines, this
19352 triggers scanning the buffer for these lines and updating the
19353 information.
19355 - If the cursor is inside a table, realign the table. This command
19356 works even if the automatic table editor has been turned off.
19358 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19359 the entire table.
19361 - If the cursor is at a footnote reference or definition, jump to
19362 the corresponding definition or references, respectively.
19364 - If the cursor is a the beginning of a dynamic block, update it.
19366 - If the current buffer is a capture buffer, close note and file it.
19368 - If the cursor is on a <<<target>>>, update radio targets and
19369 corresponding links in this buffer.
19371 - If the cursor is on a numbered item in a plain list, renumber the
19372 ordered list.
19374 - If the cursor is on a checkbox, toggle it.
19376 - If the cursor is on a code block, evaluate it. The variable
19377 `org-confirm-babel-evaluate' can be used to control prompting
19378 before code block evaluation, by default every code block
19379 evaluation requires confirmation. Code block evaluation can be
19380 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19381 (interactive "P")
19382 (let ((org-enable-table-editor t))
19383 (cond
19384 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19385 org-occur-highlights
19386 org-latex-fragment-image-overlays)
19387 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19388 (org-remove-occur-highlights)
19389 (org-remove-latex-fragment-image-overlays)
19390 (message "Temporary highlights/overlays removed from current buffer"))
19391 ((and (local-variable-p 'org-finish-function (current-buffer))
19392 (fboundp org-finish-function))
19393 (funcall org-finish-function))
19394 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19395 ((org-in-regexp org-ts-regexp-both)
19396 (org-timestamp-change 0 'day))
19397 ((or (looking-at org-property-start-re)
19398 (org-at-property-p))
19399 (call-interactively 'org-property-action))
19400 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19401 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19402 (or (org-at-heading-p) (org-at-item-p)))
19403 (call-interactively 'org-update-statistics-cookies))
19404 ((org-at-heading-p) (call-interactively 'org-set-tags))
19405 ((org-at-table.el-p)
19406 (message "Use C-c ' to edit table.el tables"))
19407 ((org-at-table-p)
19408 (org-table-maybe-eval-formula)
19409 (if arg
19410 (call-interactively 'org-table-recalculate)
19411 (org-table-maybe-recalculate-line))
19412 (call-interactively 'org-table-align)
19413 (orgtbl-send-table 'maybe))
19414 ((or (org-footnote-at-reference-p)
19415 (org-footnote-at-definition-p))
19416 (call-interactively 'org-footnote-action))
19417 ((org-at-item-checkbox-p)
19418 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19419 ;; list only if at top item.
19420 (let* ((cbox (match-string 1))
19421 (struct (org-list-struct))
19422 (old-struct (copy-tree struct))
19423 (parents (org-list-parents-alist struct))
19424 (orderedp (org-entry-get nil "ORDERED"))
19425 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19426 block-item)
19427 ;; Use a light version of `org-toggle-checkbox' to avoid
19428 ;; computing list structure twice.
19429 (let ((new-box (cond
19430 ((equal arg '(16)) "[-]")
19431 ((equal arg '(4)) nil)
19432 ((equal "[X]" cbox) "[ ]")
19433 (t "[X]"))))
19434 (if (and firstp arg)
19435 ;; If at first item of sub-list, remove check-box from
19436 ;; every item at the same level.
19437 (mapc
19438 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19439 (org-list-get-all-items
19440 (point-at-bol) struct (org-list-prevs-alist struct)))
19441 (org-list-set-checkbox (point-at-bol) struct new-box)))
19442 ;; Replicate `org-list-write-struct', while grabbing a return
19443 ;; value from `org-list-struct-fix-box'.
19444 (org-list-struct-fix-ind struct parents 2)
19445 (org-list-struct-fix-item-end struct)
19446 (let ((prevs (org-list-prevs-alist struct)))
19447 (org-list-struct-fix-bul struct prevs)
19448 (org-list-struct-fix-ind struct parents)
19449 (setq block-item
19450 (org-list-struct-fix-box struct parents prevs orderedp)))
19451 (org-list-struct-apply-struct struct old-struct)
19452 (org-update-checkbox-count-maybe)
19453 (when block-item
19454 (message
19455 "Checkboxes were removed due to unchecked box at line %d"
19456 (org-current-line block-item)))
19457 (when firstp (org-list-send-list 'maybe))))
19458 ((org-at-item-p)
19459 ;; Cursor at an item: repair list. Do checkbox related actions
19460 ;; only if function was called with an argument. Send list only
19461 ;; if at top item.
19462 (let* ((struct (org-list-struct))
19463 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19464 old-struct)
19465 (when arg
19466 (setq old-struct (copy-tree struct))
19467 (if firstp
19468 ;; If at first item of sub-list, add check-box to every
19469 ;; item at the same level.
19470 (mapc
19471 (lambda (pos)
19472 (unless (org-list-get-checkbox pos struct)
19473 (org-list-set-checkbox pos struct "[ ]")))
19474 (org-list-get-all-items
19475 (point-at-bol) struct (org-list-prevs-alist struct)))
19476 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19477 (org-list-write-struct
19478 struct (org-list-parents-alist struct) old-struct)
19479 (when arg (org-update-checkbox-count-maybe))
19480 (when firstp (org-list-send-list 'maybe))))
19481 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19482 ;; Dynamic block
19483 (beginning-of-line 1)
19484 (save-excursion (org-update-dblock)))
19485 ((save-excursion
19486 (let ((case-fold-search t))
19487 (beginning-of-line 1)
19488 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19489 (cond
19490 ((or (equal (match-string 1) "TBLFM")
19491 (equal (match-string 1) "tblfm"))
19492 ;; Recalculate the table before this line
19493 (save-excursion
19494 (beginning-of-line 1)
19495 (skip-chars-backward " \r\n\t")
19496 (if (org-at-table-p)
19497 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19499 (let ((org-inhibit-startup-visibility-stuff t)
19500 (org-startup-align-all-tables nil))
19501 (when (boundp 'org-table-coordinate-overlays)
19502 (mapc 'delete-overlay org-table-coordinate-overlays)
19503 (setq org-table-coordinate-overlays nil))
19504 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19505 (message "Local setup has been refreshed"))))
19506 ((org-clock-update-time-maybe))
19508 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19509 (error "C-c C-c can do nothing useful at this location"))))))
19511 (defun org-mode-restart ()
19512 "Restart Org-mode, to scan again for special lines.
19513 Also updates the keyword regular expressions."
19514 (interactive)
19515 (org-mode)
19516 (message "Org-mode restarted"))
19518 (defun org-kill-note-or-show-branches ()
19519 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19520 (interactive)
19521 (if (not org-finish-function)
19522 (progn
19523 (hide-subtree)
19524 (call-interactively 'show-branches))
19525 (let ((org-note-abort t))
19526 (funcall org-finish-function))))
19528 (defun org-return (&optional indent)
19529 "Goto next table row or insert a newline.
19530 Calls `org-table-next-row' or `newline', depending on context.
19531 See the individual commands for more information."
19532 (interactive)
19533 (let (org-ts-what)
19534 (cond
19535 ((or (bobp) (org-in-src-block-p))
19536 (if indent (newline-and-indent) (newline)))
19537 ((org-at-table-p)
19538 (org-table-justify-field-maybe)
19539 (call-interactively 'org-table-next-row))
19540 ;; when `newline-and-indent' is called within a list, make sure
19541 ;; text moved stays inside the item.
19542 ((and (org-in-item-p) indent)
19543 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19544 (progn
19545 (save-match-data (newline))
19546 (org-indent-line-to (length (match-string 0))))
19547 (let ((ind (org-get-indentation)))
19548 (newline)
19549 (if (org-looking-back org-list-end-re)
19550 (org-indent-line)
19551 (org-indent-line-to ind)))))
19552 ((and org-return-follows-link
19553 (org-at-timestamp-p t)
19554 (not (eq org-ts-what 'after)))
19555 (org-follow-timestamp-link))
19556 ((and org-return-follows-link
19557 (let ((tprop (get-text-property (point) 'face)))
19558 (or (eq tprop 'org-link)
19559 (and (listp tprop) (memq 'org-link tprop)))))
19560 (call-interactively 'org-open-at-point))
19561 ((and (org-at-heading-p)
19562 (looking-at
19563 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19564 (org-show-entry)
19565 (end-of-line 1)
19566 (newline))
19567 (t (if indent (newline-and-indent) (newline))))))
19569 (defun org-return-indent ()
19570 "Goto next table row or insert a newline and indent.
19571 Calls `org-table-next-row' or `newline-and-indent', depending on
19572 context. See the individual commands for more information."
19573 (interactive)
19574 (org-return t))
19576 (defun org-ctrl-c-star ()
19577 "Compute table, or change heading status of lines.
19578 Calls `org-table-recalculate' or `org-toggle-heading',
19579 depending on context."
19580 (interactive)
19581 (cond
19582 ((org-at-table-p)
19583 (call-interactively 'org-table-recalculate))
19585 ;; Convert all lines in region to list items
19586 (call-interactively 'org-toggle-heading))))
19588 (defun org-ctrl-c-minus ()
19589 "Insert separator line in table or modify bullet status of line.
19590 Also turns a plain line or a region of lines into list items.
19591 Calls `org-table-insert-hline', `org-toggle-item', or
19592 `org-cycle-list-bullet', depending on context."
19593 (interactive)
19594 (cond
19595 ((org-at-table-p)
19596 (call-interactively 'org-table-insert-hline))
19597 ((org-region-active-p)
19598 (call-interactively 'org-toggle-item))
19599 ((org-in-item-p)
19600 (call-interactively 'org-cycle-list-bullet))
19602 (call-interactively 'org-toggle-item))))
19604 (defun org-toggle-item (arg)
19605 "Convert headings or normal lines to items, items to normal lines.
19606 If there is no active region, only the current line is considered.
19608 If the first non blank line in the region is an headline, convert
19609 all headlines to items, shifting text accordingly.
19611 If it is an item, convert all items to normal lines.
19613 If it is normal text, change region into an item. With a prefix
19614 argument ARG, change each line in region into an item."
19615 (interactive "P")
19616 (let ((shift-text
19617 (function
19618 ;; Shift text in current section to IND, from point to END.
19619 ;; The function leaves point to END line.
19620 (lambda (ind end)
19621 (let ((min-i 1000) (end (copy-marker end)))
19622 ;; First determine the minimum indentation (MIN-I) of
19623 ;; the text.
19624 (save-excursion
19625 (catch 'exit
19626 (while (< (point) end)
19627 (let ((i (org-get-indentation)))
19628 (cond
19629 ;; Skip blank lines and inline tasks.
19630 ((looking-at "^[ \t]*$"))
19631 ((looking-at org-outline-regexp-bol))
19632 ;; We can't find less than 0 indentation.
19633 ((zerop i) (throw 'exit (setq min-i 0)))
19634 ((< i min-i) (setq min-i i))))
19635 (forward-line))))
19636 ;; Then indent each line so that a line indented to
19637 ;; MIN-I becomes indented to IND. Ignore blank lines
19638 ;; and inline tasks in the process.
19639 (let ((delta (- ind min-i)))
19640 (while (< (point) end)
19641 (unless (or (looking-at "^[ \t]*$")
19642 (looking-at org-outline-regexp-bol))
19643 (org-indent-line-to (+ (org-get-indentation) delta)))
19644 (forward-line)))))))
19645 (skip-blanks
19646 (function
19647 ;; Return beginning of first non-blank line, starting from
19648 ;; line at POS.
19649 (lambda (pos)
19650 (save-excursion
19651 (goto-char pos)
19652 (skip-chars-forward " \r\t\n")
19653 (point-at-bol)))))
19654 beg end)
19655 ;; Determine boundaries of changes.
19656 (if (org-region-active-p)
19657 (setq beg (funcall skip-blanks (region-beginning))
19658 end (copy-marker (region-end)))
19659 (setq beg (funcall skip-blanks (point-at-bol))
19660 end (copy-marker (point-at-eol))))
19661 ;; Depending on the starting line, choose an action on the text
19662 ;; between BEG and END.
19663 (org-with-limited-levels
19664 (save-excursion
19665 (goto-char beg)
19666 (cond
19667 ;; Case 1. Start at an item: de-itemize. Note that it only
19668 ;; happens when a region is active: `org-ctrl-c-minus'
19669 ;; would call `org-cycle-list-bullet' otherwise.
19670 ((org-at-item-p)
19671 (while (< (point) end)
19672 (when (org-at-item-p)
19673 (skip-chars-forward " \t")
19674 (delete-region (point) (match-end 0)))
19675 (forward-line)))
19676 ;; Case 2. Start at an heading: convert to items.
19677 ((org-at-heading-p)
19678 (let* ((bul (org-list-bullet-string "-"))
19679 (bul-len (length bul))
19680 ;; Indentation of the first heading. It should be
19681 ;; relative to the indentation of its parent, if any.
19682 (start-ind (save-excursion
19683 (cond
19684 ((not org-adapt-indentation) 0)
19685 ((not (outline-previous-heading)) 0)
19686 (t (length (match-string 0))))))
19687 ;; Level of first heading. Further headings will be
19688 ;; compared to it to determine hierarchy in the list.
19689 (ref-level (org-reduced-level (org-outline-level))))
19690 (while (< (point) end)
19691 (let* ((level (org-reduced-level (org-outline-level)))
19692 (delta (max 0 (- level ref-level))))
19693 ;; If current headline is less indented than the first
19694 ;; one, set it as reference, in order to preserve
19695 ;; subtrees.
19696 (when (< level ref-level) (setq ref-level level))
19697 (replace-match bul t t)
19698 (org-indent-line-to (+ start-ind (* delta bul-len)))
19699 ;; Ensure all text down to END (or SECTION-END) belongs
19700 ;; to the newly created item.
19701 (let ((section-end (save-excursion
19702 (or (outline-next-heading) (point)))))
19703 (forward-line)
19704 (funcall shift-text
19705 (+ start-ind (* (1+ delta) bul-len))
19706 (min end section-end)))))))
19707 ;; Case 3. Normal line with ARG: turn each non-item line into
19708 ;; an item.
19709 (arg
19710 (while (< (point) end)
19711 (unless (or (org-at-heading-p) (org-at-item-p))
19712 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19713 (replace-match
19714 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19715 (forward-line)))
19716 ;; Case 4. Normal line without ARG: make the first line of
19717 ;; region an item, and shift indentation of others
19718 ;; lines to set them as item's body.
19719 (t (let* ((bul (org-list-bullet-string "-"))
19720 (bul-len (length bul))
19721 (ref-ind (org-get-indentation)))
19722 (skip-chars-forward " \t")
19723 (insert bul)
19724 (forward-line)
19725 (while (< (point) end)
19726 ;; Ensure that lines less indented than first one
19727 ;; still get included in item body.
19728 (funcall shift-text
19729 (+ ref-ind bul-len)
19730 (min end (save-excursion (or (outline-next-heading)
19731 (point)))))
19732 (forward-line)))))))))
19734 (defun org-toggle-heading (&optional nstars)
19735 "Convert headings to normal text, or items or text to headings.
19736 If there is no active region, only the current line is considered.
19738 With a \\[universal-argument] prefix, convert the whole list at
19739 point into heading.
19741 In a region:
19743 - If the first non blank line is an headline, remove the stars
19744 from all headlines in the region.
19746 - If it is a normal line turn each and every normal line (i.e. not an
19747 heading or an item) in the region into a heading.
19749 - If it is a plain list item, turn all plain list items into headings.
19751 When converting a line into a heading, the number of stars is chosen
19752 such that the lines become children of the current entry. However,
19753 when a prefix argument is given, its value determines the number of
19754 stars to add."
19755 (interactive "P")
19756 (let ((skip-blanks
19757 (function
19758 ;; Return beginning of first non-blank line, starting from
19759 ;; line at POS.
19760 (lambda (pos)
19761 (save-excursion
19762 (goto-char pos)
19763 (while (org-at-comment-p) (forward-line))
19764 (skip-chars-forward " \r\t\n")
19765 (point-at-bol)))))
19766 beg end toggled)
19767 ;; Determine boundaries of changes. If a universal prefix has
19768 ;; been given, put the list in a region. If region ends at a bol,
19769 ;; do not consider the last line to be in the region.
19771 (when (and current-prefix-arg (org-at-item-p))
19772 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19773 (org-mark-element))
19775 (if (org-region-active-p)
19776 (setq beg (funcall skip-blanks (region-beginning))
19777 end (copy-marker (save-excursion
19778 (goto-char (region-end))
19779 (if (bolp) (point) (point-at-eol)))))
19780 (setq beg (funcall skip-blanks (point-at-bol))
19781 end (copy-marker (point-at-eol))))
19782 ;; Ensure inline tasks don't count as headings.
19783 (org-with-limited-levels
19784 (save-excursion
19785 (goto-char beg)
19786 (cond
19787 ;; Case 1. Started at an heading: de-star headings.
19788 ((org-at-heading-p)
19789 (while (< (point) end)
19790 (when (org-at-heading-p t)
19791 (looking-at org-outline-regexp) (replace-match "")
19792 (setq toggled t))
19793 (forward-line)))
19794 ;; Case 2. Started at an item: change items into headlines.
19795 ;; One star will be added by `org-list-to-subtree'.
19796 ((org-at-item-p)
19797 (let* ((stars (make-string
19798 (if nstars
19799 ;; subtract the star that will be added again by
19800 ;; `org-list-to-subtree'
19801 (1- (prefix-numeric-value current-prefix-arg))
19802 (or (org-current-level) 0))
19803 ?*))
19804 (add-stars
19805 (cond (nstars "") ; stars from prefix only
19806 ((equal stars "") "") ; before first heading
19807 (org-odd-levels-only "*") ; inside heading, odd
19808 (t "")))) ; inside heading, oddeven
19809 (while (< (point) end)
19810 (when (org-at-item-p)
19811 ;; Pay attention to cases when region ends before list.
19812 (let* ((struct (org-list-struct))
19813 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19814 (save-restriction
19815 (narrow-to-region (point) list-end)
19816 (insert
19817 (org-list-to-subtree
19818 (org-list-parse-list t)
19819 '(:istart (concat stars add-stars (funcall get-stars depth))
19820 :icount (concat stars add-stars (funcall get-stars depth)))))))
19821 (setq toggled t))
19822 (forward-line))))
19823 ;; Case 3. Started at normal text: make every line an heading,
19824 ;; skipping headlines and items.
19825 (t (let* ((stars (make-string
19826 (if nstars
19827 (prefix-numeric-value current-prefix-arg)
19828 (or (org-current-level) 0))
19829 ?*))
19830 (add-stars
19831 (cond (nstars "") ; stars from prefix only
19832 ((equal stars "") "*") ; before first heading
19833 (org-odd-levels-only "**") ; inside heading, odd
19834 (t "*"))) ; inside heading, oddeven
19835 (rpl (concat stars add-stars " ")))
19836 (while (< (point) end)
19837 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19838 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19839 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19840 (forward-line)))))))
19841 (unless toggled (message "Cannot toggle heading from here"))))
19843 (defun org-meta-return (&optional arg)
19844 "Insert a new heading or wrap a region in a table.
19845 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19846 See the individual commands for more information."
19847 (interactive "P")
19848 (cond
19849 ((run-hook-with-args-until-success 'org-metareturn-hook))
19850 ((or (org-at-drawer-p) (org-at-property-p))
19851 (newline-and-indent))
19852 ((org-at-table-p)
19853 (call-interactively 'org-table-wrap-region))
19854 (t (call-interactively 'org-insert-heading))))
19856 ;;; Menu entries
19858 (defsubst org-in-subtree-not-table-p ()
19859 "Are we in a subtree and not in a table?"
19860 (and (not (org-before-first-heading-p))
19861 (not (org-at-table-p))))
19863 ;; Define the Org-mode menus
19864 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19865 '("Tbl"
19866 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19867 ["Next Field" org-cycle (org-at-table-p)]
19868 ["Previous Field" org-shifttab (org-at-table-p)]
19869 ["Next Row" org-return (org-at-table-p)]
19870 "--"
19871 ["Blank Field" org-table-blank-field (org-at-table-p)]
19872 ["Edit Field" org-table-edit-field (org-at-table-p)]
19873 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19874 "--"
19875 ("Column"
19876 ["Move Column Left" org-metaleft (org-at-table-p)]
19877 ["Move Column Right" org-metaright (org-at-table-p)]
19878 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19879 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19880 ("Row"
19881 ["Move Row Up" org-metaup (org-at-table-p)]
19882 ["Move Row Down" org-metadown (org-at-table-p)]
19883 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19884 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19885 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19886 "--"
19887 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19888 ("Rectangle"
19889 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19890 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19891 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19892 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19893 "--"
19894 ("Calculate"
19895 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19896 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19897 ["Edit Formulas" org-edit-special (org-at-table-p)]
19898 "--"
19899 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19900 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19901 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19902 "--"
19903 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19904 "--"
19905 ["Sum Column/Rectangle" org-table-sum
19906 (or (org-at-table-p) (org-region-active-p))]
19907 ["Which Column?" org-table-current-column (org-at-table-p)])
19908 ["Debug Formulas"
19909 org-table-toggle-formula-debugger
19910 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19911 ["Show Col/Row Numbers"
19912 org-table-toggle-coordinate-overlays
19913 :style toggle
19914 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19915 "--"
19916 ["Create" org-table-create (and (not (org-at-table-p))
19917 org-enable-table-editor)]
19918 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19919 ["Import from File" org-table-import (not (org-at-table-p))]
19920 ["Export to File" org-table-export (org-at-table-p)]
19921 "--"
19922 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19924 (easy-menu-define org-org-menu org-mode-map "Org menu"
19925 '("Org"
19926 ("Show/Hide"
19927 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19928 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19929 ["Sparse Tree..." org-sparse-tree t]
19930 ["Reveal Context" org-reveal t]
19931 ["Show All" show-all t]
19932 "--"
19933 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19934 "--"
19935 ["New Heading" org-insert-heading t]
19936 ("Navigate Headings"
19937 ["Up" outline-up-heading t]
19938 ["Next" outline-next-visible-heading t]
19939 ["Previous" outline-previous-visible-heading t]
19940 ["Next Same Level" outline-forward-same-level t]
19941 ["Previous Same Level" outline-backward-same-level t]
19942 "--"
19943 ["Jump" org-goto t])
19944 ("Edit Structure"
19945 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19946 "--"
19947 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19948 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19949 "--"
19950 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19951 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19952 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19953 "--"
19954 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19955 "--"
19956 ["Copy visible text" org-copy-visible t]
19957 "--"
19958 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19959 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19960 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19961 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19962 "--"
19963 ["Sort Region/Children" org-sort t]
19964 "--"
19965 ["Convert to odd levels" org-convert-to-odd-levels t]
19966 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19967 ("Editing"
19968 ["Emphasis..." org-emphasize t]
19969 ["Edit Source Example" org-edit-special t]
19970 "--"
19971 ["Footnote new/jump" org-footnote-action t]
19972 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19973 ("Archive"
19974 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19975 "--"
19976 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19977 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19978 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19980 "--"
19981 ("Hyperlinks"
19982 ["Store Link (Global)" org-store-link t]
19983 ["Find existing link to here" org-occur-link-in-agenda-files t]
19984 ["Insert Link" org-insert-link t]
19985 ["Follow Link" org-open-at-point t]
19986 "--"
19987 ["Next link" org-next-link t]
19988 ["Previous link" org-previous-link t]
19989 "--"
19990 ["Descriptive Links"
19991 org-toggle-link-display
19992 :style radio
19993 :selected org-descriptive-links
19995 ["Literal Links"
19996 org-toggle-link-display
19997 :style radio
19998 :selected (not org-descriptive-links)])
19999 "--"
20000 ("TODO Lists"
20001 ["TODO/DONE/-" org-todo t]
20002 ("Select keyword"
20003 ["Next keyword" org-shiftright (org-at-heading-p)]
20004 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20005 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20006 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20007 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20008 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20009 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20010 "--"
20011 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20012 :selected org-enforce-todo-dependencies :style toggle :active t]
20013 "Settings for tree at point"
20014 ["Do Children sequentially" org-toggle-ordered-property :style radio
20015 :selected (org-entry-get nil "ORDERED")
20016 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20017 ["Do Children parallel" org-toggle-ordered-property :style radio
20018 :selected (not (org-entry-get nil "ORDERED"))
20019 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20020 "--"
20021 ["Set Priority" org-priority t]
20022 ["Priority Up" org-shiftup t]
20023 ["Priority Down" org-shiftdown t]
20024 "--"
20025 ["Get news from all feeds" org-feed-update-all t]
20026 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20027 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20028 ("TAGS and Properties"
20029 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20030 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20031 "--"
20032 ["Set property" org-set-property (not (org-before-first-heading-p))]
20033 ["Column view of properties" org-columns t]
20034 ["Insert Column View DBlock" org-insert-columns-dblock t])
20035 ("Dates and Scheduling"
20036 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20037 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20038 ("Change Date"
20039 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20040 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20041 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20042 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20043 ["Compute Time Range" org-evaluate-time-range t]
20044 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20045 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20046 "--"
20047 ["Custom time format" org-toggle-time-stamp-overlays
20048 :style radio :selected org-display-custom-times]
20049 "--"
20050 ["Goto Calendar" org-goto-calendar t]
20051 ["Date from Calendar" org-date-from-calendar t]
20052 "--"
20053 ["Start/Restart Timer" org-timer-start t]
20054 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20055 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20056 ["Insert Timer String" org-timer t]
20057 ["Insert Timer Item" org-timer-item t])
20058 ("Logging work"
20059 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20060 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20061 ["Clock out" org-clock-out t]
20062 ["Clock cancel" org-clock-cancel t]
20063 "--"
20064 ["Mark as default task" org-clock-mark-default-task t]
20065 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20066 ["Goto running clock" org-clock-goto t]
20067 "--"
20068 ["Display times" org-clock-display t]
20069 ["Create clock table" org-clock-report t]
20070 "--"
20071 ["Record DONE time"
20072 (progn (setq org-log-done (not org-log-done))
20073 (message "Switching to %s will %s record a timestamp"
20074 (car org-done-keywords)
20075 (if org-log-done "automatically" "not")))
20076 :style toggle :selected org-log-done])
20077 "--"
20078 ["Agenda Command..." org-agenda t]
20079 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20080 ("File List for Agenda")
20081 ("Special views current file"
20082 ["TODO Tree" org-show-todo-tree t]
20083 ["Check Deadlines" org-check-deadlines t]
20084 ["Timeline" org-timeline t]
20085 ["Tags/Property tree" org-match-sparse-tree t])
20086 "--"
20087 ["Export/Publish..." org-export t]
20088 ("LaTeX"
20089 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20090 :selected org-cdlatex-mode]
20091 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20092 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20093 ["Modify math symbol" org-cdlatex-math-modify
20094 (org-inside-LaTeX-fragment-p)]
20095 ["Insert citation" org-reftex-citation t]
20096 "--"
20097 ["Template for BEAMER" (progn (require 'org-beamer)
20098 (org-insert-beamer-options-template)) t])
20099 "--"
20100 ("MobileOrg"
20101 ["Push Files and Views" org-mobile-push t]
20102 ["Get Captured and Flagged" org-mobile-pull t]
20103 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20104 "--"
20105 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20106 "--"
20107 ("Documentation"
20108 ["Show Version" org-version t]
20109 ["Info Documentation" org-info t])
20110 ("Customize"
20111 ["Browse Org Group" org-customize t]
20112 "--"
20113 ["Expand This Menu" org-create-customize-menu
20114 (fboundp 'customize-menu-create)])
20115 ["Send bug report" org-submit-bug-report t]
20116 "--"
20117 ("Refresh/Reload"
20118 ["Refresh setup current buffer" org-mode-restart t]
20119 ["Reload Org (after update)" org-reload t]
20120 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20123 (defun org-info (&optional node)
20124 "Read documentation for Org-mode in the info system.
20125 With optional NODE, go directly to that node."
20126 (interactive)
20127 (info (format "(org)%s" (or node ""))))
20129 ;;;###autoload
20130 (defun org-submit-bug-report ()
20131 "Submit a bug report on Org-mode via mail.
20133 Don't hesitate to report any problems or inaccurate documentation.
20135 If you don't have setup sending mail from (X)Emacs, please copy the
20136 output buffer into your mail program, as it gives us important
20137 information about your Org-mode version and configuration."
20138 (interactive)
20139 (require 'reporter)
20140 (org-load-modules-maybe)
20141 (org-require-autoloaded-modules)
20142 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20143 (reporter-submit-bug-report
20144 "emacs-orgmode@gnu.org"
20145 (org-version nil 'full)
20146 (let (list)
20147 (save-window-excursion
20148 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20149 (delete-other-windows)
20150 (erase-buffer)
20151 (insert "You are about to submit a bug report to the Org-mode mailing list.
20153 We would like to add your full Org-mode and Outline configuration to the
20154 bug report. This greatly simplifies the work of the maintainer and
20155 other experts on the mailing list.
20157 HOWEVER, some variables you have customized may contain private
20158 information. The names of customers, colleagues, or friends, might
20159 appear in the form of file names, tags, todo states, or search strings.
20160 If you answer yes to the prompt, you might want to check and remove
20161 such private information before sending the email.")
20162 (add-text-properties (point-min) (point-max) '(face org-warning))
20163 (when (yes-or-no-p "Include your Org-mode configuration ")
20164 (mapatoms
20165 (lambda (v)
20166 (and (boundp v)
20167 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20168 (or (and (symbol-value v)
20169 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20170 (and
20171 (get v 'custom-type) (get v 'standard-value)
20172 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20173 (push v list)))))
20174 (kill-buffer (get-buffer "*Warn about privacy*"))
20175 list))
20176 nil nil
20177 "Remember to cover the basics, that is, what you expected to happen and
20178 what in fact did happen. You don't know how to make a good report? See
20180 http://orgmode.org/manual/Feedback.html#Feedback
20182 Your bug report will be posted to the Org-mode mailing list.
20183 ------------------------------------------------------------------------")
20184 (save-excursion
20185 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20186 (replace-match "\\1Bug: \\3 [\\2]")))))
20189 (defun org-install-agenda-files-menu ()
20190 (let ((bl (buffer-list)))
20191 (save-excursion
20192 (while bl
20193 (set-buffer (pop bl))
20194 (if (derived-mode-p 'org-mode) (setq bl nil)))
20195 (when (derived-mode-p 'org-mode)
20196 (easy-menu-change
20197 '("Org") "File List for Agenda"
20198 (append
20199 (list
20200 ["Edit File List" (org-edit-agenda-file-list) t]
20201 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20202 ["Remove Current File from List" org-remove-file t]
20203 ["Cycle through agenda files" org-cycle-agenda-files t]
20204 ["Occur in all agenda files" org-occur-in-agenda-files t]
20205 "--")
20206 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20208 ;;;; Documentation
20210 (defun org-require-autoloaded-modules ()
20211 (interactive)
20212 (mapc 'require
20213 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20214 org-docbook org-exp org-html org-icalendar
20215 org-id org-latex
20216 org-publish org-remember org-table
20217 org-timer org-xoxo)))
20219 ;;;###autoload
20220 (defun org-reload (&optional uncompiled)
20221 "Reload all org lisp files.
20222 With prefix arg UNCOMPILED, load the uncompiled versions."
20223 (interactive "P")
20224 (require 'loadhist)
20225 (let* ((org-dir (org-find-library-dir "org"))
20226 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20227 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20228 (remove-re (mapconcat 'identity
20229 (mapcar (lambda (f) (concat "^" f "$"))
20230 (list (if (featurep 'xemacs)
20231 "org-colview"
20232 "org-colview-xemacs")
20233 "org" "org-loaddefs" "org-version"))
20234 "\\|"))
20235 (feats (delete-dups
20236 (mapcar 'file-name-sans-extension
20237 (mapcar 'file-name-nondirectory
20238 (delq nil
20239 (mapcar 'feature-file
20240 features))))))
20241 (lfeat (append
20242 (sort
20243 (setq feats
20244 (delq nil (mapcar
20245 (lambda (f)
20246 (if (and (string-match feature-re f)
20247 (not (string-match remove-re f)))
20248 f nil))
20249 feats)))
20250 'string-lessp)
20251 (list "org-version" "org")))
20252 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20253 load-uncore load-misses)
20254 (setq load-misses
20255 (delq 't
20256 (mapcar (lambda (f)
20257 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20258 (and (string= org-dir contrib-dir)
20259 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20260 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20261 (add-to-list 'load-uncore f 'append)
20264 lfeat)))
20265 (if load-uncore
20266 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20267 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20268 (if load-misses
20269 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20270 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20271 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20273 ;;;###autoload
20274 (defun org-customize ()
20275 "Call the customize function with org as argument."
20276 (interactive)
20277 (org-load-modules-maybe)
20278 (org-require-autoloaded-modules)
20279 (customize-browse 'org))
20281 (defun org-create-customize-menu ()
20282 "Create a full customization menu for Org-mode, insert it into the menu."
20283 (interactive)
20284 (org-load-modules-maybe)
20285 (org-require-autoloaded-modules)
20286 (if (fboundp 'customize-menu-create)
20287 (progn
20288 (easy-menu-change
20289 '("Org") "Customize"
20290 `(["Browse Org group" org-customize t]
20291 "--"
20292 ,(customize-menu-create 'org)
20293 ["Set" Custom-set t]
20294 ["Save" Custom-save t]
20295 ["Reset to Current" Custom-reset-current t]
20296 ["Reset to Saved" Custom-reset-saved t]
20297 ["Reset to Standard Settings" Custom-reset-standard t]))
20298 (message "\"Org\"-menu now contains full customization menu"))
20299 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20301 ;;;; Miscellaneous stuff
20303 ;;; Generally useful functions
20305 (defun org-get-at-bol (property)
20306 "Get text property PROPERTY at beginning of line."
20307 (get-text-property (point-at-bol) property))
20309 (defun org-find-text-property-in-string (prop s)
20310 "Return the first non-nil value of property PROP in string S."
20311 (or (get-text-property 0 prop s)
20312 (get-text-property (or (next-single-property-change 0 prop s) 0)
20313 prop s)))
20315 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20316 "Display the given MESSAGE as a warning."
20317 (if (fboundp 'display-warning)
20318 (display-warning 'org message
20319 (if (featurep 'xemacs) 'warning :warning))
20320 (let ((buf (get-buffer-create "*Org warnings*")))
20321 (with-current-buffer buf
20322 (goto-char (point-max))
20323 (insert "Warning (Org): " message)
20324 (unless (bolp)
20325 (newline)))
20326 (display-buffer buf)
20327 (sit-for 0))))
20329 (defun org-eval (form)
20330 "Eval FORM and return result."
20331 (condition-case error
20332 (eval form)
20333 (error (format "%%![Error: %s]" error))))
20335 (defun org-in-clocktable-p ()
20336 "Check if the cursor is in a clocktable."
20337 (let ((pos (point)) start)
20338 (save-excursion
20339 (end-of-line 1)
20340 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20341 (setq start (match-beginning 0))
20342 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20343 (>= (match-end 0) pos)
20344 start))))
20346 (defun org-in-commented-line ()
20347 "Is point in a line starting with `#'?"
20348 (equal (char-after (point-at-bol)) ?#))
20350 (defun org-in-indented-comment-line ()
20351 "Is point in a line starting with `#' after some white space?"
20352 (save-excursion
20353 (save-match-data
20354 (goto-char (point-at-bol))
20355 (looking-at "[ \t]*#"))))
20357 (defun org-in-verbatim-emphasis ()
20358 (save-match-data
20359 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20361 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20362 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20363 (if (and marker (marker-buffer marker)
20364 (buffer-live-p (marker-buffer marker)))
20365 (progn
20366 (org-pop-to-buffer-same-window (marker-buffer marker))
20367 (if (or (> marker (point-max)) (< marker (point-min)))
20368 (widen))
20369 (goto-char marker)
20370 (org-show-context 'org-goto))
20371 (if bookmark
20372 (bookmark-jump bookmark)
20373 (error "Cannot find location"))))
20375 (defun org-quote-csv-field (s)
20376 "Quote field for inclusion in CSV material."
20377 (if (string-match "[\",]" s)
20378 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20381 (defun org-force-self-insert (N)
20382 "Needed to enforce self-insert under remapping."
20383 (interactive "p")
20384 (self-insert-command N))
20386 (defun org-string-width (s)
20387 "Compute width of string, ignoring invisible characters.
20388 This ignores character with invisibility property `org-link', and also
20389 characters with property `org-cwidth', because these will become invisible
20390 upon the next fontification round."
20391 (let (b l)
20392 (when (or (eq t buffer-invisibility-spec)
20393 (assq 'org-link buffer-invisibility-spec))
20394 (while (setq b (text-property-any 0 (length s)
20395 'invisible 'org-link s))
20396 (setq s (concat (substring s 0 b)
20397 (substring s (or (next-single-property-change
20398 b 'invisible s) (length s)))))))
20399 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20400 (setq s (concat (substring s 0 b)
20401 (substring s (or (next-single-property-change
20402 b 'org-cwidth s) (length s))))))
20403 (setq l (string-width s) b -1)
20404 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20405 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20408 (defun org-shorten-string (s maxlength)
20409 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20410 If the string is shorter or has length MAXLENGTH, just return the
20411 original string. If it is longer, the functions finds a space in the
20412 string, breaks this string off at that locations and adds three dots
20413 as ellipsis. Including the ellipsis, the string will not be longer
20414 than MAXLENGTH. If finding a good breaking point in the string does
20415 not work, the string is just chopped off in the middle of a word
20416 if necessary."
20417 (if (<= (length s) maxlength)
20419 (let* ((n (max (- maxlength 4) 1))
20420 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20421 (if (string-match re s)
20422 (concat (match-string 1 s) "...")
20423 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20425 (defun org-get-indentation (&optional line)
20426 "Get the indentation of the current line, interpreting tabs.
20427 When LINE is given, assume it represents a line and compute its indentation."
20428 (if line
20429 (if (string-match "^ *" (org-remove-tabs line))
20430 (match-end 0))
20431 (save-excursion
20432 (beginning-of-line 1)
20433 (skip-chars-forward " \t")
20434 (current-column))))
20436 (defun org-get-string-indentation (s)
20437 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20438 (let ((n -1) (i 0) (w tab-width) c)
20439 (catch 'exit
20440 (while (< (setq n (1+ n)) (length s))
20441 (setq c (aref s n))
20442 (cond ((= c ?\ ) (setq i (1+ i)))
20443 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20444 (t (throw 'exit t)))))
20447 (defun org-remove-tabs (s &optional width)
20448 "Replace tabulators in S with spaces.
20449 Assumes that s is a single line, starting in column 0."
20450 (setq width (or width tab-width))
20451 (while (string-match "\t" s)
20452 (setq s (replace-match
20453 (make-string
20454 (- (* width (/ (+ (match-beginning 0) width) width))
20455 (match-beginning 0)) ?\ )
20456 t t s)))
20459 (defun org-fix-indentation (line ind)
20460 "Fix indentation in LINE.
20461 IND is a cons cell with target and minimum indentation.
20462 If the current indentation in LINE is smaller than the minimum,
20463 leave it alone. If it is larger than ind, set it to the target."
20464 (let* ((l (org-remove-tabs line))
20465 (i (org-get-indentation l))
20466 (i1 (car ind)) (i2 (cdr ind)))
20467 (if (>= i i2) (setq l (substring line i2)))
20468 (if (> i1 0)
20469 (concat (make-string i1 ?\ ) l)
20470 l)))
20472 (defun org-remove-indentation (code &optional n)
20473 "Remove the maximum common indentation from the lines in CODE.
20474 N may optionally be the number of spaces to remove."
20475 (with-temp-buffer
20476 (insert code)
20477 (org-do-remove-indentation n)
20478 (buffer-string)))
20480 (defun org-do-remove-indentation (&optional n)
20481 "Remove the maximum common indentation from the buffer."
20482 (untabify (point-min) (point-max))
20483 (let ((min 10000) re)
20484 (if n
20485 (setq min n)
20486 (goto-char (point-min))
20487 (while (re-search-forward "^ *[^ \n]" nil t)
20488 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20489 (unless (or (= min 0) (= min 10000))
20490 (setq re (format "^ \\{%d\\}" min))
20491 (goto-char (point-min))
20492 (while (re-search-forward re nil t)
20493 (replace-match "")
20494 (end-of-line 1))
20495 min)))
20497 (defun org-fill-template (template alist)
20498 "Find each %key of ALIST in TEMPLATE and replace it."
20499 (let ((case-fold-search nil)
20500 entry key value)
20501 (setq alist (sort (copy-sequence alist)
20502 (lambda (a b) (< (length (car a)) (length (car b))))))
20503 (while (setq entry (pop alist))
20504 (setq template
20505 (replace-regexp-in-string
20506 (concat "%" (regexp-quote (car entry)))
20507 (or (cdr entry) "") template t t)))
20508 template))
20510 (defun org-base-buffer (buffer)
20511 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20512 (if (not buffer)
20513 buffer
20514 (or (buffer-base-buffer buffer)
20515 buffer)))
20517 (defun org-trim (s)
20518 "Remove whitespace at beginning and end of string."
20519 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20520 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20523 (defun org-wrap (string &optional width lines)
20524 "Wrap string to either a number of lines, or a width in characters.
20525 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20526 that costs. If there is a word longer than WIDTH, the text is actually
20527 wrapped to the length of that word.
20528 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20529 many lines, whatever width that takes.
20530 The return value is a list of lines, without newlines at the end."
20531 (let* ((words (org-split-string string "[ \t\n]+"))
20532 (maxword (apply 'max (mapcar 'org-string-width words)))
20533 w ll)
20534 (cond (width
20535 (org-do-wrap words (max maxword width)))
20536 (lines
20537 (setq w maxword)
20538 (setq ll (org-do-wrap words maxword))
20539 (if (<= (length ll) lines)
20541 (setq ll words)
20542 (while (> (length ll) lines)
20543 (setq w (1+ w))
20544 (setq ll (org-do-wrap words w)))
20545 ll))
20546 (t (error "Cannot wrap this")))))
20548 (defun org-do-wrap (words width)
20549 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20550 (let (lines line)
20551 (while words
20552 (setq line (pop words))
20553 (while (and words (< (+ (length line) (length (car words))) width))
20554 (setq line (concat line " " (pop words))))
20555 (setq lines (push line lines)))
20556 (nreverse lines)))
20558 (defun org-split-string (string &optional separators)
20559 "Splits STRING into substrings at SEPARATORS.
20560 No empty strings are returned if there are matches at the beginning
20561 and end of string."
20562 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20563 (start 0)
20564 notfirst
20565 (list nil))
20566 (while (and (string-match rexp string
20567 (if (and notfirst
20568 (= start (match-beginning 0))
20569 (< start (length string)))
20570 (1+ start) start))
20571 (< (match-beginning 0) (length string)))
20572 (setq notfirst t)
20573 (or (eq (match-beginning 0) 0)
20574 (and (eq (match-beginning 0) (match-end 0))
20575 (eq (match-beginning 0) start))
20576 (setq list
20577 (cons (substring string start (match-beginning 0))
20578 list)))
20579 (setq start (match-end 0)))
20580 (or (eq start (length string))
20581 (setq list
20582 (cons (substring string start)
20583 list)))
20584 (nreverse list)))
20586 (defun org-quote-vert (s)
20587 "Replace \"|\" with \"\\vert\"."
20588 (while (string-match "|" s)
20589 (setq s (replace-match "\\vert" t t s)))
20592 (defun org-uuidgen-p (s)
20593 "Is S an ID created by UUIDGEN?"
20594 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20596 (defun org-in-src-block-p (&optional inside)
20597 "Whether point is in a code source block.
20598 When INSIDE is non-nil, don't consider we are within a src block
20599 when point is at #+BEGIN_SRC or #+END_SRC."
20600 (let (ov)
20601 (or (when (setq ov (overlays-at (point)))
20602 (memq 'org-block-background
20603 (overlay-properties
20604 (car ov))))
20605 (and (not inside)
20606 (save-match-data
20607 (save-excursion
20608 (move-beginning-of-line 1)
20609 (looking-at ".*#\\+\\(BEGIN\\|END\\)_SRC")))))))
20611 (defsubst org-in-fixed-width-region-p ()
20612 "Is point in a fixed-width region?"
20613 (eq 'fixed-width (org-element-type (org-element-at-point))))
20615 (defun org-context ()
20616 "Return a list of contexts of the current cursor position.
20617 If several contexts apply, all are returned.
20618 Each context entry is a list with a symbol naming the context, and
20619 two positions indicating start and end of the context. Possible
20620 contexts are:
20622 :headline anywhere in a headline
20623 :headline-stars on the leading stars in a headline
20624 :todo-keyword on a TODO keyword (including DONE) in a headline
20625 :tags on the TAGS in a headline
20626 :priority on the priority cookie in a headline
20627 :item on the first line of a plain list item
20628 :item-bullet on the bullet/number of a plain list item
20629 :checkbox on the checkbox in a plain list item
20630 :table in an org-mode table
20631 :table-special on a special filed in a table
20632 :table-table in a table.el table
20633 :clocktable in a clocktable
20634 :src-block in a source block
20635 :link on a hyperlink
20636 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20637 :target on a <<target>>
20638 :radio-target on a <<<radio-target>>>
20639 :latex-fragment on a LaTeX fragment
20640 :latex-preview on a LaTeX fragment with overlaid preview image
20642 This function expects the position to be visible because it uses font-lock
20643 faces as a help to recognize the following contexts: :table-special, :link,
20644 and :keyword."
20645 (let* ((f (get-text-property (point) 'face))
20646 (faces (if (listp f) f (list f)))
20647 (case-fold-search t)
20648 (p (point)) clist o)
20649 ;; First the large context
20650 (cond
20651 ((org-at-heading-p t)
20652 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20653 (when (progn
20654 (beginning-of-line 1)
20655 (looking-at org-todo-line-tags-regexp))
20656 (push (org-point-in-group p 1 :headline-stars) clist)
20657 (push (org-point-in-group p 2 :todo-keyword) clist)
20658 (push (org-point-in-group p 4 :tags) clist))
20659 (goto-char p)
20660 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20661 (if (looking-at "\\[#[A-Z0-9]\\]")
20662 (push (org-point-in-group p 0 :priority) clist)))
20664 ((org-at-item-p)
20665 (push (org-point-in-group p 2 :item-bullet) clist)
20666 (push (list :item (point-at-bol)
20667 (save-excursion (org-end-of-item) (point)))
20668 clist)
20669 (and (org-at-item-checkbox-p)
20670 (push (org-point-in-group p 0 :checkbox) clist)))
20672 ((org-at-table-p)
20673 (push (list :table (org-table-begin) (org-table-end)) clist)
20674 (if (memq 'org-formula faces)
20675 (push (list :table-special
20676 (previous-single-property-change p 'face)
20677 (next-single-property-change p 'face)) clist)))
20678 ((org-at-table-p 'any)
20679 (push (list :table-table) clist)))
20680 (goto-char p)
20682 (let ((case-fold-search t))
20683 ;; New the "medium" contexts: clocktables, source blocks
20684 (cond ((org-in-clocktable-p)
20685 (push (list :clocktable
20686 (and (or (looking-at "#\\+BEGIN: clocktable")
20687 (search-backward "#+BEGIN: clocktable" nil t))
20688 (match-beginning 0))
20689 (and (re-search-forward "#\\+END:?" nil t)
20690 (match-end 0))) clist))
20691 ((org-in-src-block-p)
20692 (push (list :src-block
20693 (and (or (looking-at "#\\+BEGIN_SRC")
20694 (search-backward "#+BEGIN_SRC" nil t))
20695 (match-beginning 0))
20696 (and (search-forward "#+END_SRC" nil t)
20697 (match-beginning 0))) clist))))
20698 (goto-char p)
20700 ;; Now the small context
20701 (cond
20702 ((org-at-timestamp-p)
20703 (push (org-point-in-group p 0 :timestamp) clist))
20704 ((memq 'org-link faces)
20705 (push (list :link
20706 (previous-single-property-change p 'face)
20707 (next-single-property-change p 'face)) clist))
20708 ((memq 'org-special-keyword faces)
20709 (push (list :keyword
20710 (previous-single-property-change p 'face)
20711 (next-single-property-change p 'face)) clist))
20712 ((org-at-target-p)
20713 (push (org-point-in-group p 0 :target) clist)
20714 (goto-char (1- (match-beginning 0)))
20715 (if (looking-at org-radio-target-regexp)
20716 (push (org-point-in-group p 0 :radio-target) clist))
20717 (goto-char p))
20718 ((setq o (car (delq nil
20719 (mapcar
20720 (lambda (x)
20721 (if (memq x org-latex-fragment-image-overlays) x))
20722 (overlays-at (point))))))
20723 (push (list :latex-fragment
20724 (overlay-start o) (overlay-end o)) clist)
20725 (push (list :latex-preview
20726 (overlay-start o) (overlay-end o)) clist))
20727 ((org-inside-LaTeX-fragment-p)
20728 ;; FIXME: positions wrong.
20729 (push (list :latex-fragment (point) (point)) clist)))
20731 (setq clist (nreverse (delq nil clist)))
20732 clist))
20734 ;; FIXME: Compare with at-regexp-p Do we need both?
20735 (defun org-in-regexp (re &optional nlines visually)
20736 "Check if point is inside a match of regexp.
20737 Normally only the current line is checked, but you can include NLINES extra
20738 lines both before and after point into the search.
20739 If VISUALLY is set, require that the cursor is not after the match but
20740 really on, so that the block visually is on the match."
20741 (catch 'exit
20742 (let ((pos (point))
20743 (eol (point-at-eol (+ 1 (or nlines 0))))
20744 (inc (if visually 1 0)))
20745 (save-excursion
20746 (beginning-of-line (- 1 (or nlines 0)))
20747 (while (re-search-forward re eol t)
20748 (if (and (<= (match-beginning 0) pos)
20749 (>= (+ inc (match-end 0)) pos))
20750 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20752 (defun org-at-regexp-p (regexp)
20753 "Is point inside a match of REGEXP in the current line?"
20754 (catch 'exit
20755 (save-excursion
20756 (let ((pos (point)) (end (point-at-eol)))
20757 (beginning-of-line 1)
20758 (while (re-search-forward regexp end t)
20759 (if (and (<= (match-beginning 0) pos)
20760 (>= (match-end 0) pos))
20761 (throw 'exit t)))
20762 nil))))
20764 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20765 "Non-nil when point is between matches of START-RE and END-RE.
20767 Also return a non-nil value when point is on one of the matches.
20769 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20770 buffer positions. Default values are the positions of headlines
20771 surrounding the point.
20773 The functions returns a cons cell whose car (resp. cdr) is the
20774 position before START-RE (resp. after END-RE)."
20775 (save-match-data
20776 (let ((pos (point))
20777 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20778 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20779 beg end)
20780 (save-excursion
20781 ;; Point is on a block when on START-RE or if START-RE can be
20782 ;; found before it...
20783 (and (or (org-at-regexp-p start-re)
20784 (re-search-backward start-re limit-up t))
20785 (setq beg (match-beginning 0))
20786 ;; ... and END-RE after it...
20787 (goto-char (match-end 0))
20788 (re-search-forward end-re limit-down t)
20789 (> (setq end (match-end 0)) pos)
20790 ;; ... without another START-RE in-between.
20791 (goto-char (match-beginning 0))
20792 (not (re-search-backward start-re (1+ beg) t))
20793 ;; Return value.
20794 (cons beg end))))))
20796 (defun org-in-block-p (names)
20797 "Non-nil when point belongs to a block whose name belongs to NAMES.
20799 NAMES is a list of strings containing names of blocks.
20801 Return first block name matched, or nil. Beware that in case of
20802 nested blocks, the returned name may not belong to the closest
20803 block from point."
20804 (save-match-data
20805 (catch 'exit
20806 (let ((case-fold-search t)
20807 (lim-up (save-excursion (outline-previous-heading)))
20808 (lim-down (save-excursion (outline-next-heading))))
20809 (mapc (lambda (name)
20810 (let ((n (regexp-quote name)))
20811 (when (org-between-regexps-p
20812 (concat "^[ \t]*#\\+begin_" n)
20813 (concat "^[ \t]*#\\+end_" n)
20814 lim-up lim-down)
20815 (throw 'exit n))))
20816 names))
20817 nil)))
20819 (defun org-occur-in-agenda-files (regexp &optional nlines)
20820 "Call `multi-occur' with buffers for all agenda files."
20821 (interactive "sOrg-files matching: \np")
20822 (let* ((files (org-agenda-files))
20823 (tnames (mapcar 'file-truename files))
20824 (extra org-agenda-text-search-extra-files)
20826 (when (eq (car extra) 'agenda-archives)
20827 (setq extra (cdr extra))
20828 (setq files (org-add-archive-files files)))
20829 (while (setq f (pop extra))
20830 (unless (member (file-truename f) tnames)
20831 (add-to-list 'files f 'append)
20832 (add-to-list 'tnames (file-truename f) 'append)))
20833 (multi-occur
20834 (mapcar (lambda (x)
20835 (with-current-buffer
20836 (or (get-file-buffer x) (find-file-noselect x))
20837 (widen)
20838 (current-buffer)))
20839 files)
20840 regexp)))
20842 (if (boundp 'occur-mode-find-occurrence-hook)
20843 ;; Emacs 23
20844 (add-hook 'occur-mode-find-occurrence-hook
20845 (lambda ()
20846 (when (derived-mode-p 'org-mode)
20847 (org-reveal))))
20848 ;; Emacs 22
20849 (defadvice occur-mode-goto-occurrence
20850 (after org-occur-reveal activate)
20851 (and (derived-mode-p 'org-mode) (org-reveal)))
20852 (defadvice occur-mode-goto-occurrence-other-window
20853 (after org-occur-reveal activate)
20854 (and (derived-mode-p 'org-mode) (org-reveal)))
20855 (defadvice occur-mode-display-occurrence
20856 (after org-occur-reveal activate)
20857 (when (derived-mode-p 'org-mode)
20858 (let ((pos (occur-mode-find-occurrence)))
20859 (with-current-buffer (marker-buffer pos)
20860 (save-excursion
20861 (goto-char pos)
20862 (org-reveal)))))))
20864 (defun org-occur-link-in-agenda-files ()
20865 "Create a link and search for it in the agendas.
20866 The link is not stored in `org-stored-links', it is just created
20867 for the search purpose."
20868 (interactive)
20869 (let ((link (condition-case nil
20870 (org-store-link nil)
20871 (error "Unable to create a link to here"))))
20872 (org-occur-in-agenda-files (regexp-quote link))))
20874 (defun org-uniquify (list)
20875 "Remove duplicate elements from LIST."
20876 (let (res)
20877 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20878 res))
20880 (defun org-delete-all (elts list)
20881 "Remove all elements in ELTS from LIST."
20882 (while elts
20883 (setq list (delete (pop elts) list)))
20884 list)
20886 (defun org-count (cl-item cl-seq)
20887 "Count the number of occurrences of ITEM in SEQ.
20888 Taken from `count' in cl-seq.el with all keyword arguments removed."
20889 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20890 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20891 (while (< cl-start cl-end)
20892 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20893 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20894 (setq cl-start (1+ cl-start)))
20895 cl-count))
20897 (defun org-remove-if (predicate seq)
20898 "Remove everything from SEQ that fulfills PREDICATE."
20899 (let (res e)
20900 (while seq
20901 (setq e (pop seq))
20902 (if (not (funcall predicate e)) (push e res)))
20903 (nreverse res)))
20905 (defun org-remove-if-not (predicate seq)
20906 "Remove everything from SEQ that does not fulfill PREDICATE."
20907 (let (res e)
20908 (while seq
20909 (setq e (pop seq))
20910 (if (funcall predicate e) (push e res)))
20911 (nreverse res)))
20913 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20914 "Reduce two-argument FUNCTION across SEQ.
20915 Taken from `reduce' in cl-seq.el with all keyword arguments but
20916 \":initial-value\" removed."
20917 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20918 (cadr (memq :initial-value cl-keys)))
20919 (cl-seq (pop cl-seq))
20920 (t (funcall cl-func)))))
20921 (while cl-seq
20922 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20923 cl-accum))
20925 (defun org-back-over-empty-lines ()
20926 "Move backwards over whitespace, to the beginning of the first empty line.
20927 Returns the number of empty lines passed."
20928 (let ((pos (point)))
20929 (if (cdr (assoc 'heading org-blank-before-new-entry))
20930 (skip-chars-backward " \t\n\r")
20931 (unless (eobp)
20932 (forward-line -1)))
20933 (beginning-of-line 2)
20934 (goto-char (min (point) pos))
20935 (count-lines (point) pos)))
20937 (defun org-skip-whitespace ()
20938 (skip-chars-forward " \t\n\r"))
20940 (defun org-point-in-group (point group &optional context)
20941 "Check if POINT is in match-group GROUP.
20942 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20943 match. If the match group does not exist or point is not inside it,
20944 return nil."
20945 (and (match-beginning group)
20946 (>= point (match-beginning group))
20947 (<= point (match-end group))
20948 (if context
20949 (list context (match-beginning group) (match-end group))
20950 t)))
20952 (defun org-switch-to-buffer-other-window (&rest args)
20953 "Switch to buffer in a second window on the current frame.
20954 In particular, do not allow pop-up frames.
20955 Returns the newly created buffer."
20956 (let (pop-up-frames special-display-buffer-names special-display-regexps
20957 special-display-function)
20958 (apply 'switch-to-buffer-other-window args)))
20960 (defun org-combine-plists (&rest plists)
20961 "Create a single property list from all plists in PLISTS.
20962 The process starts by copying the first list, and then setting properties
20963 from the other lists. Settings in the last list are the most significant
20964 ones and overrule settings in the other lists."
20965 (let ((rtn (copy-sequence (pop plists)))
20966 p v ls)
20967 (while plists
20968 (setq ls (pop plists))
20969 (while ls
20970 (setq p (pop ls) v (pop ls))
20971 (setq rtn (plist-put rtn p v))))
20972 rtn))
20974 (defun org-replace-escapes (string table)
20975 "Replace %-escapes in STRING with values in TABLE.
20976 TABLE is an association list with keys like \"%a\" and string values.
20977 The sequences in STRING may contain normal field width and padding information,
20978 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20979 so values can contain further %-escapes if they are define later in TABLE."
20980 (let ((tbl (copy-alist table))
20981 (case-fold-search nil)
20982 (pchg 0)
20983 e re rpl)
20984 (while (setq e (pop tbl))
20985 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20986 (when (and (cdr e) (string-match re (cdr e)))
20987 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20988 (safe "SREF"))
20989 (add-text-properties 0 3 (list 'sref sref) safe)
20990 (setcdr e (replace-match safe t t (cdr e)))))
20991 (while (string-match re string)
20992 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20993 (cdr e)))
20994 (setq string (replace-match rpl t t string))))
20995 (while (setq pchg (next-property-change pchg string))
20996 (let ((sref (get-text-property pchg 'sref string)))
20997 (when (and sref (string-match "SREF" string pchg))
20998 (setq string (replace-match sref t t string)))))
20999 string))
21001 (defun org-sublist (list start end)
21002 "Return a section of LIST, from START to END.
21003 Counting starts at 1."
21004 (let (rtn (c start))
21005 (setq list (nthcdr (1- start) list))
21006 (while (and list (<= c end))
21007 (push (pop list) rtn)
21008 (setq c (1+ c)))
21009 (nreverse rtn)))
21011 (defun org-find-base-buffer-visiting (file)
21012 "Like `find-buffer-visiting' but always return the base buffer and
21013 not an indirect buffer."
21014 (let ((buf (or (get-file-buffer file)
21015 (find-buffer-visiting file))))
21016 (if buf
21017 (or (buffer-base-buffer buf) buf)
21018 nil)))
21020 (defun org-image-file-name-regexp (&optional extensions)
21021 "Return regexp matching the file names of images.
21022 If EXTENSIONS is given, only match these."
21023 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21024 (image-file-name-regexp)
21025 (let ((image-file-name-extensions
21026 (or extensions
21027 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21028 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21029 (concat "\\."
21030 (regexp-opt (nconc (mapcar 'upcase
21031 image-file-name-extensions)
21032 image-file-name-extensions)
21034 "\\'"))))
21036 (defun org-file-image-p (file &optional extensions)
21037 "Return non-nil if FILE is an image."
21038 (save-match-data
21039 (string-match (org-image-file-name-regexp extensions) file)))
21041 (defun org-get-cursor-date (&optional with-time)
21042 "Return the date at cursor in as a time.
21043 This works in the calendar and in the agenda, anywhere else it just
21044 returns the current time.
21045 If WITH-TIME is non-nil, returns the time of the event at point (in
21046 the agenda) or the current time of the day."
21047 (let (date day defd tp tm hod mod)
21048 (when with-time
21049 (setq tp (get-text-property (point) 'time))
21050 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21051 (setq hod (string-to-number (match-string 1 tp))
21052 mod (string-to-number (match-string 2 tp))))
21053 (or tp (setq hod (nth 2 (decode-time (current-time)))
21054 mod (nth 1 (decode-time (current-time))))))
21055 (cond
21056 ((eq major-mode 'calendar-mode)
21057 (setq date (calendar-cursor-to-date)
21058 defd (encode-time 0 (or mod 0) (or hod 0)
21059 (nth 1 date) (nth 0 date) (nth 2 date))))
21060 ((eq major-mode 'org-agenda-mode)
21061 (setq day (get-text-property (point) 'day))
21062 (if day
21063 (setq date (calendar-gregorian-from-absolute day)
21064 defd (encode-time 0 (or mod 0) (or hod 0)
21065 (nth 1 date) (nth 0 date) (nth 2 date))))))
21066 (or defd (current-time))))
21068 (defun org-mark-subtree (&optional up)
21069 "Mark the current subtree.
21070 This puts point at the start of the current subtree, and mark at
21071 the end. If a numeric prefix UP is given, move up into the
21072 hierarchy of headlines by UP levels before marking the subtree."
21073 (interactive "P")
21074 (org-with-limited-levels
21075 (cond ((org-at-heading-p) (beginning-of-line))
21076 ((org-before-first-heading-p) (error "Not in a subtree"))
21077 (t (outline-previous-visible-heading 1))))
21078 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21079 (if (org-called-interactively-p 'any)
21080 (call-interactively 'org-mark-element)
21081 (org-mark-element)))
21084 ;;; Macros
21086 ;; Macros are expanded with `org-macro-replace-all', which relies
21087 ;; internally on `org-macro-expand'.
21089 ;; Default templates for expansion are stored in the buffer-local
21090 ;; variable `org-macro-templates'. This variable is updated by
21091 ;; `org-macro-initialize-templates'.
21093 ;; Along with macros defined through #+MACRO: keyword, default
21094 ;; templates include the following hard-coded macros:
21095 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21096 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21098 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21099 ;; {{{title}}} will also be provided.
21102 (defvar org-macro-templates nil
21103 "Alist containing all macro templates in current buffer.
21104 Associations are in the shape of (NAME . TEMPLATE) where NAME
21105 stands for macro's name and template for its replacement value,
21106 both as strings. This is an internal variable. Do not set it
21107 directly, use instead:
21109 #+MACRO: name template")
21110 (make-variable-buffer-local 'org-macro-templates)
21112 (defun org-macro-expand (macro templates)
21113 "Return expanded MACRO, as a string.
21114 MACRO is an object, obtained, for example, with
21115 `org-element-context'. TEMPLATES is an alist of templates used
21116 for expansion. See `org-macro-templates' for a buffer-local
21117 default value. Return nil if no template was found."
21118 (let ((template
21119 ;; Macro names are case-insensitive.
21120 (cdr (assoc-string (org-element-property :key macro) templates t))))
21121 (when template
21122 (let ((value (replace-regexp-in-string
21123 "\\$[0-9]+"
21124 (lambda (arg)
21125 (or (nth (1- (string-to-number (substring arg 1)))
21126 (org-element-property :args macro))
21127 ;; No argument provided: remove
21128 ;; place-holder.
21129 ""))
21130 template)))
21131 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21132 (when (string-match "\\`(eval\\>" value)
21133 (setq value (eval (read value))))
21134 ;; Return string.
21135 (format "%s" (or value ""))))))
21137 (defun org-macro-replace-all (templates)
21138 "Replace all macros in current buffer by their expansion.
21139 TEMPLATES is an alist of templates used for expansion. See
21140 `org-macro-templates' for a buffer-local default value."
21141 (save-excursion
21142 (goto-char (point-min))
21143 (let (record)
21144 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21145 (let ((object (org-element-context)))
21146 (when (eq (org-element-type object) 'macro)
21147 (let* ((value (org-macro-expand object templates))
21148 (begin (org-element-property :begin object))
21149 (signature (list begin
21150 object
21151 (org-element-property :args object))))
21152 ;; Avoid circular dependencies by checking if the same
21153 ;; macro with the same arguments is expanded at the same
21154 ;; position twice.
21155 (if (member signature record)
21156 (error "Circular macro expansion: %s"
21157 (org-element-property :key object))
21158 (when value
21159 (push signature record)
21160 (delete-region
21161 begin
21162 ;; Preserve white spaces after the macro.
21163 (progn (goto-char (org-element-property :end object))
21164 (skip-chars-backward " \t")
21165 (point)))
21166 ;; Leave point before replacement in case of recursive
21167 ;; expansions.
21168 (save-excursion (insert value)))))))))))
21170 (defun org-macro-initialize-templates ()
21171 "Collect macro templates defined in current buffer.
21172 Templates are stored in buffer-local variable
21173 `org-macro-templates'. In addition to buffer-defined macros, the
21174 function installs the following ones: \"property\",
21175 \"time\". and, if the buffer is associated to a file,
21176 \"input-file\" and \"modification-time\"."
21177 (let ((case-fold-search t)
21178 (set-template
21179 (lambda (cell)
21180 ;; Add CELL to `org-macro-templates' if there's no
21181 ;; association matching its name already. Otherwise,
21182 ;; replace old association with the new one in that
21183 ;; variable.
21184 (let ((old-template (assoc (car cell) org-macro-templates)))
21185 (if old-template (setcdr old-template (cdr cell))
21186 (push cell org-macro-templates))))))
21187 ;; Install buffer-local macros.
21188 (org-with-wide-buffer
21189 (goto-char (point-min))
21190 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21191 (let ((element (org-element-at-point)))
21192 (when (eq (org-element-type element) 'keyword)
21193 (let ((value (org-element-property :value element)))
21194 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21195 (funcall set-template
21196 (cons (match-string 1 value)
21197 (or (match-string 2 value) "")))))))))
21198 ;; Install hard-coded macros.
21199 (mapc (lambda (cell) (funcall set-template cell))
21200 (list
21201 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21202 (cons "time" "(eval (format-time-string \"$1\"))")))
21203 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21204 (when (and visited-file (file-exists-p visited-file))
21205 (mapc (lambda (cell) (funcall set-template cell))
21206 (list
21207 (cons "input-file" (file-name-nondirectory visited-file))
21208 (cons "modification-time"
21209 (format "(eval (format-time-string \"$1\" '%s))"
21210 (prin1-to-string
21211 (nth 5 (file-attributes visited-file)))))))))))
21214 ;;; Indentation
21216 (defun org-indent-line ()
21217 "Indent line depending on context."
21218 (interactive)
21219 (let* ((pos (point))
21220 (itemp (org-at-item-p))
21221 (case-fold-search t)
21222 (org-drawer-regexp (or org-drawer-regexp "\000"))
21223 (inline-task-p (and (featurep 'org-inlinetask)
21224 (org-inlinetask-in-task-p)))
21225 (inline-re (and inline-task-p
21226 (org-inlinetask-outline-regexp)))
21227 column)
21228 (if (and orgstruct-is-++ (eq pos (point)))
21229 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21230 (indent-according-to-mode))
21231 (beginning-of-line 1)
21232 (cond
21233 ;; Headings
21234 ((looking-at org-outline-regexp) (setq column 0))
21235 ;; Included files
21236 ((looking-at "#\\+include:") (setq column 0))
21237 ;; Footnote definition
21238 ((looking-at org-footnote-definition-re) (setq column 0))
21239 ;; Literal examples
21240 ((looking-at "[ \t]*:\\( \\|$\\)")
21241 (setq column (org-get-indentation))) ; do nothing
21242 ;; Lists
21243 ((ignore-errors (goto-char (org-in-item-p)))
21244 (setq column (if itemp
21245 (org-get-indentation)
21246 (org-list-item-body-column (point))))
21247 (goto-char pos))
21248 ;; Drawers
21249 ((and (looking-at "[ \t]*:END:")
21250 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21251 (save-excursion
21252 (goto-char (1- (match-beginning 1)))
21253 (setq column (current-column))))
21254 ;; Special blocks
21255 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21256 (save-excursion
21257 (re-search-backward
21258 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21259 (setq column (org-get-indentation (match-string 0))))
21260 ((and (not (looking-at "[ \t]*#\\+begin_"))
21261 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21262 (save-excursion
21263 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21264 (setq column
21265 (cond ((equal (downcase (match-string 1)) "src")
21266 ;; src blocks: let `org-edit-src-exit' handle them
21267 (org-get-indentation))
21268 ((equal (downcase (match-string 1)) "example")
21269 (max (org-get-indentation)
21270 (org-get-indentation (match-string 0))))
21272 (org-get-indentation (match-string 0))))))
21273 ;; This line has nothing special, look at the previous relevant
21274 ;; line to compute indentation
21276 (beginning-of-line 0)
21277 (while (and (not (bobp))
21278 (not (looking-at org-drawer-regexp))
21279 ;; When point started in an inline task, do not move
21280 ;; above task starting line.
21281 (not (and inline-task-p (looking-at inline-re)))
21282 ;; Skip drawers, blocks, empty lines, verbatim,
21283 ;; comments, tables, footnotes definitions, lists,
21284 ;; inline tasks.
21285 (or (and (looking-at "[ \t]*:END:")
21286 (re-search-backward org-drawer-regexp nil t))
21287 (and (looking-at "[ \t]*#\\+end_")
21288 (re-search-backward "[ \t]*#\\+begin_"nil t))
21289 (looking-at "[ \t]*[\n:#|]")
21290 (looking-at org-footnote-definition-re)
21291 (and (ignore-errors (goto-char (org-in-item-p)))
21292 (goto-char
21293 (org-list-get-top-point (org-list-struct))))
21294 (and (not inline-task-p)
21295 (featurep 'org-inlinetask)
21296 (org-inlinetask-in-task-p)
21297 (or (org-inlinetask-goto-beginning) t))))
21298 (beginning-of-line 0))
21299 (cond
21300 ;; There was an heading above.
21301 ((looking-at "\\*+[ \t]+")
21302 (if (not org-adapt-indentation)
21303 (setq column 0)
21304 (goto-char (match-end 0))
21305 (setq column (current-column))))
21306 ;; A drawer had started and is unfinished
21307 ((looking-at org-drawer-regexp)
21308 (goto-char (1- (match-beginning 1)))
21309 (setq column (current-column)))
21310 ;; Else, nothing noticeable found: get indentation and go on.
21311 (t (setq column (org-get-indentation))))))
21312 ;; Now apply indentation and move cursor accordingly
21313 (goto-char pos)
21314 (if (<= (current-column) (current-indentation))
21315 (org-indent-line-to column)
21316 (save-excursion (org-indent-line-to column)))
21317 ;; Special polishing for properties, see `org-property-format'
21318 (setq column (current-column))
21319 (beginning-of-line 1)
21320 (if (looking-at
21321 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21322 (replace-match (concat (match-string 1)
21323 (format org-property-format
21324 (match-string 2) (match-string 3)))
21325 t t))
21326 (org-move-to-column column))))
21328 (defun org-indent-drawer ()
21329 "Indent the drawer at point."
21330 (interactive)
21331 (let ((p (point))
21332 (e (and (save-excursion (re-search-forward ":END:" nil t))
21333 (match-end 0)))
21334 (folded
21335 (save-excursion
21336 (end-of-line)
21337 (when (overlays-at (point))
21338 (member 'invisible (overlay-properties
21339 (car (overlays-at (point)))))))))
21340 (when folded (org-cycle))
21341 (indent-for-tab-command)
21342 (while (and (move-beginning-of-line 2) (< (point) e))
21343 (indent-for-tab-command))
21344 (goto-char p)
21345 (when folded (org-cycle)))
21346 (message "Drawer at point indented"))
21348 (defun org-indent-block ()
21349 "Indent the block at point."
21350 (interactive)
21351 (let ((p (point))
21352 (case-fold-search t)
21353 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21354 (match-end 0)))
21355 (folded
21356 (save-excursion
21357 (end-of-line)
21358 (when (overlays-at (point))
21359 (member 'invisible (overlay-properties
21360 (car (overlays-at (point)))))))))
21361 (when folded (org-cycle))
21362 (indent-for-tab-command)
21363 (while (and (move-beginning-of-line 2) (< (point) e))
21364 (indent-for-tab-command))
21365 (goto-char p)
21366 (when folded (org-cycle)))
21367 (message "Block at point indented"))
21369 (defun org-indent-region (start end)
21370 "Indent region."
21371 (interactive "r")
21372 (save-excursion
21373 (let ((line-end (org-current-line end)))
21374 (goto-char start)
21375 (while (< (org-current-line) line-end)
21376 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21377 (t (call-interactively 'org-indent-line)))
21378 (move-beginning-of-line 2)))))
21381 ;;; Filling
21383 ;; We use our own fill-paragraph and auto-fill functions.
21385 ;; `org-fill-paragraph' relies on adaptive filling and context
21386 ;; checking. Appropriate `fill-prefix' is computed with
21387 ;; `org-adaptive-fill-function'.
21389 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21390 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21391 ;; `org-adaptive-fill-function' value. Internally,
21392 ;; `org-comment-line-break-function' breaks the line.
21394 ;; `org-setup-filling' installs filling and auto-filling related
21395 ;; variables during `org-mode' initialization.
21397 (defun org-setup-filling ()
21398 (interactive)
21399 ;; Prevent auto-fill from inserting unwanted new items.
21400 (when (boundp 'fill-nobreak-predicate)
21401 (org-set-local
21402 'fill-nobreak-predicate
21403 (org-uniquify
21404 (append fill-nobreak-predicate
21405 '(org-fill-paragraph-separate-nobreak-p
21406 org-fill-line-break-nobreak-p)))))
21407 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21408 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21409 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21410 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21412 (defvar org-element-paragraph-separate) ; org-element.el
21413 (defun org-fill-paragraph-separate-nobreak-p ()
21414 "Non-nil when a line break at point would insert a new item."
21415 (looking-at (substring org-element-paragraph-separate 1)))
21417 (defun org-fill-line-break-nobreak-p ()
21418 "Non-nil when a line break at point would create an Org line break."
21419 (save-excursion
21420 (skip-chars-backward "[ \t]")
21421 (skip-chars-backward "\\\\")
21422 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21424 (declare-function message-in-body-p "message" ())
21425 (defun org-adaptive-fill-function ()
21426 "Compute a fill prefix for the current line.
21427 Return fill prefix, as a string, or nil if current line isn't
21428 meant to be filled."
21429 (org-with-wide-buffer
21430 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21431 ;; FIXME: This is really the job of orgstruct++-mode
21432 (let* ((p (line-beginning-position))
21433 (element (save-excursion (beginning-of-line)
21434 (org-element-at-point)))
21435 (type (org-element-type element))
21436 (post-affiliated (org-element-property :post-affiliated element)))
21437 (unless (and post-affiliated (< p post-affiliated))
21438 (case type
21439 (comment (looking-at "[ \t]*# ?") (match-string 0))
21440 (footnote-definition "")
21441 ((item plain-list)
21442 (make-string (org-list-item-body-column
21443 (or post-affiliated
21444 (org-element-property :begin element)))
21445 ? ))
21446 (paragraph
21447 ;; Fill prefix is usually the same as the current line,
21448 ;; except if the paragraph is at the beginning of an item.
21449 (let ((parent (org-element-property :parent element)))
21450 (cond ((eq (org-element-type parent) 'item)
21451 (make-string (org-list-item-body-column
21452 (org-element-property :begin parent))
21453 ? ))
21454 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21455 (match-string 0))
21456 (t ""))))
21457 (comment-block
21458 ;; Only fill contents if P is within block boundaries.
21459 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21460 (forward-line)
21461 (point)))
21462 (cend (save-excursion
21463 (goto-char (org-element-property :end element))
21464 (skip-chars-backward " \r\t\n")
21465 (line-beginning-position))))
21466 (when (and (>= p cbeg) (< p cend))
21467 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21468 (match-string 0)
21469 ""))))))))))
21471 (declare-function message-goto-body "message" ())
21472 (defvar message-cite-prefix-regexp) ; From message.el
21473 (defvar org-element-all-objects) ; From org-element.el
21474 (defun org-fill-paragraph (&optional justify)
21475 "Fill element at point, when applicable.
21477 This function only applies to comment blocks, comments, example
21478 blocks and paragraphs. Also, as a special case, re-align table
21479 when point is at one.
21481 If JUSTIFY is non-nil (interactively, with prefix argument),
21482 justify as well. If `sentence-end-double-space' is non-nil, then
21483 period followed by one space does not end a sentence, so don't
21484 break a line there. The variable `fill-column' controls the
21485 width for filling.
21487 For convenience, when point is at a plain list, an item or
21488 a footnote definition, try to fill the first paragraph within."
21489 (interactive)
21490 (if (and (derived-mode-p 'message-mode)
21491 (or (not (message-in-body-p))
21492 (save-excursion (move-beginning-of-line 1)
21493 (looking-at message-cite-prefix-regexp))))
21494 ;; First ensure filling is correct in message-mode.
21495 (let ((fill-paragraph-function
21496 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21497 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21498 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21499 (paragraph-separate
21500 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21501 (fill-paragraph nil))
21502 (save-excursion
21503 ;; Move to end of line in order to get the first paragraph
21504 ;; within a plain list or a footnote definition.
21505 (end-of-line)
21506 (let ((element (org-element-at-point)))
21507 ;; First check if point is in a blank line at the beginning of
21508 ;; the buffer. In that case, ignore filling.
21509 (if (< (point) (org-element-property :begin element)) t
21510 (case (org-element-type element)
21511 ;; Use major mode filling function is src blocks.
21512 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21513 ;; Align Org tables, leave table.el tables as-is.
21514 (table-row (org-table-align) t)
21515 (table
21516 (when (eq (org-element-property :type element) 'org)
21517 (org-table-align))
21519 (paragraph
21520 ;; Paragraphs may contain `line-break' type objects.
21521 (let ((beg (max (point-min)
21522 (org-element-property :contents-begin element)))
21523 (end (min (point-max)
21524 (org-element-property :contents-end element))))
21525 ;; Do nothing if point is at an affiliated keyword.
21526 (if (< (point) beg) t
21527 (when (derived-mode-p 'message-mode)
21528 ;; In `message-mode', do not fill following
21529 ;; citation in current paragraph nor text before
21530 ;; message body.
21531 (let ((body-start (save-excursion (message-goto-body))))
21532 (when body-start (setq beg (max body-start beg))))
21533 (when (save-excursion
21534 (re-search-forward
21535 (concat "^" message-cite-prefix-regexp) end t))
21536 (setq end (match-beginning 0))))
21537 ;; Fill paragraph, taking line breaks into
21538 ;; consideration. For that, slice the paragraph
21539 ;; using line breaks as separators, and fill the
21540 ;; parts in reverse order to avoid messing with
21541 ;; markers.
21542 (save-excursion
21543 (goto-char end)
21544 (mapc
21545 (lambda (pos)
21546 (fill-region-as-paragraph pos (point) justify)
21547 (goto-char pos))
21548 ;; Find the list of ending positions for line
21549 ;; breaks in the current paragraph. Add paragraph
21550 ;; beginning to include first slice.
21551 (nreverse
21552 (cons
21554 (org-element-map
21555 (org-element--parse-objects
21556 beg end nil org-element-all-objects)
21557 'line-break
21558 (lambda (lb) (org-element-property :end lb)))))))
21559 t)))
21560 ;; Contents of `comment-block' type elements should be
21561 ;; filled as plain text, but only if point is within block
21562 ;; markers.
21563 (comment-block
21564 (let* ((case-fold-search t)
21565 (beg (save-excursion
21566 (goto-char (org-element-property :begin element))
21567 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21568 (forward-line)
21569 (point)))
21570 (end (save-excursion
21571 (goto-char (org-element-property :end element))
21572 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21573 (line-beginning-position))))
21574 (when (and (>= (point) beg) (< (point) end))
21575 (fill-region-as-paragraph
21576 (save-excursion
21577 (end-of-line)
21578 (re-search-backward "^[ \t]*$" beg 'move)
21579 (line-beginning-position))
21580 (save-excursion
21581 (beginning-of-line)
21582 (re-search-forward "^[ \t]*$" end 'move)
21583 (line-beginning-position))
21584 justify)))
21586 ;; Fill comments.
21587 (comment (fill-comment-paragraph justify))
21588 ;; Ignore every other element.
21589 (otherwise t)))))))
21591 (defun org-auto-fill-function ()
21592 "Auto-fill function."
21593 ;; Check if auto-filling is meaningful.
21594 (let ((fc (current-fill-column)))
21595 (when (and fc (> (current-column) fc))
21596 (let* ((fill-prefix (org-adaptive-fill-function))
21597 ;; Enforce empty fill prefix, if required. Otherwise, it
21598 ;; will be computed again.
21599 (adaptive-fill-mode (not (equal fill-prefix ""))))
21600 (when fill-prefix (do-auto-fill))))))
21602 (defun org-comment-line-break-function (&optional soft)
21603 "Break line at point and indent, continuing comment if within one.
21604 The inserted newline is marked hard if variable
21605 `use-hard-newlines' is true, unless optional argument SOFT is
21606 non-nil."
21607 (if soft (insert-and-inherit ?\n) (newline 1))
21608 (save-excursion (forward-char -1) (delete-horizontal-space))
21609 (delete-horizontal-space)
21610 (indent-to-left-margin)
21611 (insert-before-markers-and-inherit fill-prefix))
21614 ;;; Comments
21616 ;; Org comments syntax is quite complex. It requires the entire line
21617 ;; to be just a comment. Also, even with the right syntax at the
21618 ;; beginning of line, some some elements (i.e. verse-block or
21619 ;; example-block) don't accept comments. Usual Emacs comment commands
21620 ;; cannot cope with those requirements. Therefore, Org replaces them.
21622 ;; Org still relies on `comment-dwim', but cannot trust
21623 ;; `comment-only-p'. So, `comment-region-function' and
21624 ;; `uncomment-region-function' both point
21625 ;; to`org-comment-or-uncomment-region'. Eventually,
21626 ;; `org-insert-comment' takes care of insertion of comments at the
21627 ;; beginning of line.
21629 ;; `org-setup-comments-handling' install comments related variables
21630 ;; during `org-mode' initialization.
21632 (defun org-setup-comments-handling ()
21633 (interactive)
21634 (org-set-local 'comment-use-syntax nil)
21635 (org-set-local 'comment-start "# ")
21636 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21637 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21638 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21639 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21641 (defun org-insert-comment ()
21642 "Insert an empty comment above current line.
21643 If the line is empty, insert comment at its beginning."
21644 (beginning-of-line)
21645 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21646 (org-indent-line)
21647 (insert "# "))
21649 (defvar comment-empty-lines) ; From newcomment.el.
21650 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21651 "Comment or uncomment each non-blank line in the region.
21652 Uncomment each non-blank line between BEG and END if it only
21653 contains commented lines. Otherwise, comment them."
21654 (save-restriction
21655 ;; Restrict region
21656 (narrow-to-region (save-excursion (goto-char beg)
21657 (skip-chars-forward " \r\t\n" end)
21658 (line-beginning-position))
21659 (save-excursion (goto-char end)
21660 (skip-chars-backward " \r\t\n" beg)
21661 (line-end-position)))
21662 (let ((uncommentp
21663 ;; UNCOMMENTP is non-nil when every non blank line between
21664 ;; BEG and END is a comment.
21665 (save-excursion
21666 (goto-char (point-min))
21667 (while (and (not (eobp))
21668 (let ((element (org-element-at-point)))
21669 (and (eq (org-element-type element) 'comment)
21670 (goto-char (min (point-max)
21671 (org-element-property
21672 :end element)))))))
21673 (eobp))))
21674 (if uncommentp
21675 ;; Only blank lines and comments in region: uncomment it.
21676 (save-excursion
21677 (goto-char (point-min))
21678 (while (not (eobp))
21679 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21680 (replace-match "" nil nil nil 1))
21681 (forward-line)))
21682 ;; Comment each line in region.
21683 (let ((min-indent (point-max)))
21684 ;; First find the minimum indentation across all lines.
21685 (save-excursion
21686 (goto-char (point-min))
21687 (while (and (not (eobp)) (not (zerop min-indent)))
21688 (unless (looking-at "[ \t]*$")
21689 (setq min-indent (min min-indent (current-indentation))))
21690 (forward-line)))
21691 ;; Then loop over all lines.
21692 (save-excursion
21693 (goto-char (point-min))
21694 (while (not (eobp))
21695 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21696 (org-move-to-column min-indent t)
21697 (insert comment-start))
21698 (forward-line))))))))
21701 ;;; Other stuff.
21703 (defun org-toggle-fixed-width-section (arg)
21704 "Toggle the fixed-width export.
21705 If there is no active region, the QUOTE keyword at the current headline is
21706 inserted or removed. When present, it causes the text between this headline
21707 and the next to be exported as fixed-width text, and unmodified.
21708 If there is an active region, this command adds or removes a colon as the
21709 first character of this line. If the first character of a line is a colon,
21710 this line is also exported in fixed-width font."
21711 (interactive "P")
21712 (let* ((cc 0)
21713 (regionp (org-region-active-p))
21714 (beg (if regionp (region-beginning) (point)))
21715 (end (if regionp (region-end)))
21716 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21717 (case-fold-search nil)
21718 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21719 off)
21720 (if regionp
21721 (save-excursion
21722 (goto-char beg)
21723 (setq cc (current-column))
21724 (beginning-of-line 1)
21725 (setq off (looking-at re))
21726 (while (> nlines 0)
21727 (setq nlines (1- nlines))
21728 (beginning-of-line 1)
21729 (cond
21730 (arg
21731 (org-move-to-column cc t)
21732 (insert ": \n")
21733 (forward-line -1))
21734 ((and off (looking-at re))
21735 (replace-match "" t t nil 1))
21736 ((not off) (org-move-to-column cc t) (insert ": ")))
21737 (forward-line 1)))
21738 (save-excursion
21739 (org-back-to-heading)
21740 (cond
21741 ((looking-at (format org-heading-keyword-regexp-format
21742 org-quote-string))
21743 (goto-char (match-end 1))
21744 (looking-at (concat " +" org-quote-string))
21745 (replace-match "" t t)
21746 (when (eolp) (insert " ")))
21747 ((looking-at org-outline-regexp)
21748 (goto-char (match-end 0))
21749 (insert org-quote-string " ")))))))
21751 (defun org-reftex-citation ()
21752 "Use reftex-citation to insert a citation into the buffer.
21753 This looks for a line like
21755 #+BIBLIOGRAPHY: foo plain option:-d
21757 and derives from it that foo.bib is the bibliography file relevant
21758 for this document. It then installs the necessary environment for RefTeX
21759 to work in this buffer and calls `reftex-citation' to insert a citation
21760 into the buffer.
21762 Export of such citations to both LaTeX and HTML is handled by the contributed
21763 package org-exp-bibtex by Taru Karttunen."
21764 (interactive)
21765 (let ((reftex-docstruct-symbol 'rds)
21766 (reftex-cite-format "\\cite{%l}")
21767 rds bib)
21768 (save-excursion
21769 (save-restriction
21770 (widen)
21771 (let ((case-fold-search t)
21772 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21773 (if (not (save-excursion
21774 (or (re-search-forward re nil t)
21775 (re-search-backward re nil t))))
21776 (error "No bibliography defined in file")
21777 (setq bib (concat (match-string 1) ".bib")
21778 rds (list (list 'bib bib)))))))
21779 (call-interactively 'reftex-citation)))
21781 ;;;; Functions extending outline functionality
21783 (defun org-beginning-of-line (&optional arg)
21784 "Go to the beginning of the current line. If that is invisible, continue
21785 to a visible line beginning. This makes the function of C-a more intuitive.
21786 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21787 first attempt, and only move to after the tags when the cursor is already
21788 beyond the end of the headline."
21789 (interactive "P")
21790 (let ((pos (point))
21791 (special (if (consp org-special-ctrl-a/e)
21792 (car org-special-ctrl-a/e)
21793 org-special-ctrl-a/e))
21794 refpos)
21795 (if (org-bound-and-true-p visual-line-mode)
21796 (beginning-of-visual-line 1)
21797 (beginning-of-line 1))
21798 (if (and arg (fboundp 'move-beginning-of-line))
21799 (call-interactively 'move-beginning-of-line)
21800 (if (bobp)
21802 (backward-char 1)
21803 (if (org-truely-invisible-p)
21804 (while (and (not (bobp)) (org-truely-invisible-p))
21805 (backward-char 1)
21806 (beginning-of-line 1))
21807 (forward-char 1))))
21808 (when special
21809 (cond
21810 ((and (looking-at org-complex-heading-regexp)
21811 (= (char-after (match-end 1)) ?\ ))
21812 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21813 (point-at-eol)))
21814 (goto-char
21815 (if (eq special t)
21816 (cond ((> pos refpos) refpos)
21817 ((= pos (point)) refpos)
21818 (t (point)))
21819 (cond ((> pos (point)) (point))
21820 ((not (eq last-command this-command)) (point))
21821 (t refpos)))))
21822 ((org-at-item-p)
21823 ;; Being at an item and not looking at an the item means point
21824 ;; was previously moved to beginning of a visual line, which
21825 ;; doesn't contain the item. Therefore, do nothing special,
21826 ;; just stay here.
21827 (when (looking-at org-list-full-item-re)
21828 ;; Set special position at first white space character after
21829 ;; bullet, and check-box, if any.
21830 (let ((after-bullet
21831 (let ((box (match-end 3)))
21832 (if (not box) (match-end 1)
21833 (let ((after (char-after box)))
21834 (if (and after (= after ? )) (1+ box) box))))))
21835 ;; Special case: Move point to special position when
21836 ;; currently after it or at beginning of line.
21837 (if (eq special t)
21838 (when (or (> pos after-bullet) (= (point) pos))
21839 (goto-char after-bullet))
21840 ;; Reversed case: Move point to special position when
21841 ;; point was already at beginning of line and command is
21842 ;; repeated.
21843 (when (and (= (point) pos) (eq last-command this-command))
21844 (goto-char after-bullet))))))))
21845 (org-no-warnings
21846 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21848 (defun org-end-of-line (&optional arg)
21849 "Go to the end of the line.
21850 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21851 tags on the first attempt, and only move to after the tags when
21852 the cursor is already beyond the end of the headline."
21853 (interactive "P")
21854 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21855 org-special-ctrl-a/e))
21856 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21857 'end-of-visual-line)
21858 ((fboundp 'move-end-of-line) 'move-end-of-line)
21859 (t 'end-of-line))))
21860 (if (or (not special) arg) (call-interactively move-fun)
21861 (let* ((element (save-excursion (beginning-of-line)
21862 (org-element-at-point)))
21863 (type (org-element-type element)))
21864 (cond
21865 ((memq type '(headline inlinetask))
21866 (let ((pos (point)))
21867 (beginning-of-line 1)
21868 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21869 (if (eq special t)
21870 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21871 (goto-char (match-beginning 1))
21872 (goto-char (match-end 0)))
21873 (if (or (< pos (match-end 0))
21874 (not (eq this-command last-command)))
21875 (goto-char (match-end 0))
21876 (goto-char (match-beginning 1))))
21877 (call-interactively move-fun))))
21878 ((org-element-property :hiddenp element)
21879 ;; If element is hidden, `move-end-of-line' would put point
21880 ;; after it. Use `end-of-line' to stay on current line.
21881 (call-interactively 'end-of-line))
21882 (t (call-interactively move-fun)))))
21883 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21885 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21886 (define-key org-mode-map "\C-e" 'org-end-of-line)
21888 (defun org-backward-sentence (&optional arg)
21889 "Go to beginning of sentence, or beginning of table field.
21890 This will call `backward-sentence' or `org-table-beginning-of-field',
21891 depending on context."
21892 (interactive "P")
21893 (cond
21894 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21895 (t (call-interactively 'backward-sentence))))
21897 (defun org-forward-sentence (&optional arg)
21898 "Go to end of sentence, or end of table field.
21899 This will call `forward-sentence' or `org-table-end-of-field',
21900 depending on context."
21901 (interactive "P")
21902 (cond
21903 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21904 (t (call-interactively 'forward-sentence))))
21906 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21907 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21909 (defun org-kill-line (&optional arg)
21910 "Kill line, to tags or end of line."
21911 (interactive "P")
21912 (cond
21913 ((or (not org-special-ctrl-k)
21914 (bolp)
21915 (not (org-at-heading-p)))
21916 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21917 org-ctrl-k-protect-subtree)
21918 (if (or (eq org-ctrl-k-protect-subtree 'error)
21919 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21920 (error "C-k aborted - would kill hidden subtree")))
21921 (call-interactively
21922 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21923 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21924 (kill-region (point) (match-beginning 1))
21925 (org-set-tags nil t))
21926 (t (kill-region (point) (point-at-eol)))))
21928 (define-key org-mode-map "\C-k" 'org-kill-line)
21930 (defun org-yank (&optional arg)
21931 "Yank. If the kill is a subtree, treat it specially.
21932 This command will look at the current kill and check if is a single
21933 subtree, or a series of subtrees[1]. If it passes the test, and if the
21934 cursor is at the beginning of a line or after the stars of a currently
21935 empty headline, then the yank is handled specially. How exactly depends
21936 on the value of the following variables, both set by default.
21938 org-yank-folded-subtrees
21939 When set, the subtree(s) will be folded after insertion, but only
21940 if doing so would now swallow text after the yanked text.
21942 org-yank-adjusted-subtrees
21943 When set, the subtree will be promoted or demoted in order to
21944 fit into the local outline tree structure, which means that the level
21945 will be adjusted so that it becomes the smaller one of the two
21946 *visible* surrounding headings.
21948 Any prefix to this command will cause `yank' to be called directly with
21949 no special treatment. In particular, a simple \\[universal-argument] prefix \
21950 will just
21951 plainly yank the text as it is.
21953 \[1] The test checks if the first non-white line is a heading
21954 and if there are no other headings with fewer stars."
21955 (interactive "P")
21956 (org-yank-generic 'yank arg))
21958 (defun org-yank-generic (command arg)
21959 "Perform some yank-like command.
21961 This function implements the behavior described in the `org-yank'
21962 documentation. However, it has been generalized to work for any
21963 interactive command with similar behavior."
21965 ;; pretend to be command COMMAND
21966 (setq this-command command)
21968 (if arg
21969 (call-interactively command)
21971 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21972 (and (org-kill-is-subtree-p)
21973 (or (bolp)
21974 (and (looking-at "[ \t]*$")
21975 (string-match
21976 "\\`\\*+\\'"
21977 (buffer-substring (point-at-bol) (point)))))))
21978 swallowp)
21979 (cond
21980 ((and subtreep org-yank-folded-subtrees)
21981 (let ((beg (point))
21982 end)
21983 (if (and subtreep org-yank-adjusted-subtrees)
21984 (org-paste-subtree nil nil 'for-yank)
21985 (call-interactively command))
21987 (setq end (point))
21988 (goto-char beg)
21989 (when (and (bolp) subtreep
21990 (not (setq swallowp
21991 (org-yank-folding-would-swallow-text beg end))))
21992 (org-with-limited-levels
21993 (or (looking-at org-outline-regexp)
21994 (re-search-forward org-outline-regexp-bol end t))
21995 (while (and (< (point) end) (looking-at org-outline-regexp))
21996 (hide-subtree)
21997 (org-cycle-show-empty-lines 'folded)
21998 (condition-case nil
21999 (outline-forward-same-level 1)
22000 (error (goto-char end))))))
22001 (when swallowp
22002 (message
22003 "Inserted text not folded because that would swallow text"))
22005 (goto-char end)
22006 (skip-chars-forward " \t\n\r")
22007 (beginning-of-line 1)
22008 (push-mark beg 'nomsg)))
22009 ((and subtreep org-yank-adjusted-subtrees)
22010 (let ((beg (point-at-bol)))
22011 (org-paste-subtree nil nil 'for-yank)
22012 (push-mark beg 'nomsg)))
22014 (call-interactively command))))))
22016 (defun org-yank-folding-would-swallow-text (beg end)
22017 "Would hide-subtree at BEG swallow any text after END?"
22018 (let (level)
22019 (org-with-limited-levels
22020 (save-excursion
22021 (goto-char beg)
22022 (when (or (looking-at org-outline-regexp)
22023 (re-search-forward org-outline-regexp-bol end t))
22024 (setq level (org-outline-level)))
22025 (goto-char end)
22026 (skip-chars-forward " \t\r\n\v\f")
22027 (if (or (eobp)
22028 (and (bolp) (looking-at org-outline-regexp)
22029 (<= (org-outline-level) level)))
22030 nil ; Nothing would be swallowed
22031 t))))) ; something would swallow
22033 (define-key org-mode-map "\C-y" 'org-yank)
22035 (defun org-truely-invisible-p ()
22036 "Check if point is at a character currently not visible.
22037 This version does not only check the character property, but also
22038 `visible-mode'."
22039 ;; Early versions of noutline don't have `outline-invisible-p'.
22040 (if (org-bound-and-true-p visible-mode)
22042 (outline-invisible-p)))
22044 (defun org-invisible-p2 ()
22045 "Check if point is at a character currently not visible."
22046 (save-excursion
22047 (if (and (eolp) (not (bobp))) (backward-char 1))
22048 ;; Early versions of noutline don't have `outline-invisible-p'.
22049 (outline-invisible-p)))
22051 (defun org-back-to-heading (&optional invisible-ok)
22052 "Call `outline-back-to-heading', but provide a better error message."
22053 (condition-case nil
22054 (outline-back-to-heading invisible-ok)
22055 (error (error "Before first headline at position %d in buffer %s"
22056 (point) (current-buffer)))))
22058 (defun org-before-first-heading-p ()
22059 "Before first heading?"
22060 (save-excursion
22061 (end-of-line)
22062 (null (re-search-backward org-outline-regexp-bol nil t))))
22064 (defun org-at-heading-p (&optional ignored)
22065 (outline-on-heading-p t))
22066 ;; Compatibility alias with Org versions < 7.8.03
22067 (defalias 'org-on-heading-p 'org-at-heading-p)
22069 (defun org-at-comment-p nil
22070 "Is cursor in a line starting with a # character?"
22071 (save-excursion
22072 (beginning-of-line)
22073 (looking-at "^#")))
22075 (defun org-at-drawer-p nil
22076 "Is cursor at a drawer keyword?"
22077 (save-excursion
22078 (move-beginning-of-line 1)
22079 (looking-at org-drawer-regexp)))
22081 (defun org-at-block-p nil
22082 "Is cursor at a block keyword?"
22083 (save-excursion
22084 (move-beginning-of-line 1)
22085 (looking-at org-block-regexp)))
22087 (defun org-point-at-end-of-empty-headline ()
22088 "If point is at the end of an empty headline, return t, else nil.
22089 If the heading only contains a TODO keyword, it is still still considered
22090 empty."
22091 (and (looking-at "[ \t]*$")
22092 (when org-todo-line-regexp
22093 (save-excursion
22094 (beginning-of-line 1)
22095 (let ((case-fold-search nil))
22096 (looking-at org-todo-line-regexp)
22097 (string= (match-string 3) ""))))))
22099 (defun org-at-heading-or-item-p ()
22100 (or (org-at-heading-p) (org-at-item-p)))
22102 (defun org-at-target-p ()
22103 (or (org-in-regexp org-radio-target-regexp)
22104 (org-in-regexp org-target-regexp)))
22105 ;; Compatibility alias with Org versions < 7.8.03
22106 (defalias 'org-on-target-p 'org-at-target-p)
22108 (defun org-up-heading-all (arg)
22109 "Move to the heading line of which the present line is a subheading.
22110 This function considers both visible and invisible heading lines.
22111 With argument, move up ARG levels."
22112 (if (fboundp 'outline-up-heading-all)
22113 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22114 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22116 (defun org-up-heading-safe ()
22117 "Move to the heading line of which the present line is a subheading.
22118 This version will not throw an error. It will return the level of the
22119 headline found, or nil if no higher level is found.
22121 Also, this function will be a lot faster than `outline-up-heading',
22122 because it relies on stars being the outline starters. This can really
22123 make a significant difference in outlines with very many siblings."
22124 (let (start-level re)
22125 (org-back-to-heading t)
22126 (setq start-level (funcall outline-level))
22127 (if (equal start-level 1)
22129 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22130 (if (re-search-backward re nil t)
22131 (funcall outline-level)))))
22133 (defun org-first-sibling-p ()
22134 "Is this heading the first child of its parents?"
22135 (interactive)
22136 (let ((re org-outline-regexp-bol)
22137 level l)
22138 (unless (org-at-heading-p t)
22139 (error "Not at a heading"))
22140 (setq level (funcall outline-level))
22141 (save-excursion
22142 (if (not (re-search-backward re nil t))
22144 (setq l (funcall outline-level))
22145 (< l level)))))
22147 (defun org-goto-sibling (&optional previous)
22148 "Goto the next sibling, even if it is invisible.
22149 When PREVIOUS is set, go to the previous sibling instead. Returns t
22150 when a sibling was found. When none is found, return nil and don't
22151 move point."
22152 (let ((fun (if previous 're-search-backward 're-search-forward))
22153 (pos (point))
22154 (re org-outline-regexp-bol)
22155 level l)
22156 (when (condition-case nil (org-back-to-heading t) (error nil))
22157 (setq level (funcall outline-level))
22158 (catch 'exit
22159 (or previous (forward-char 1))
22160 (while (funcall fun re nil t)
22161 (setq l (funcall outline-level))
22162 (when (< l level) (goto-char pos) (throw 'exit nil))
22163 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22164 (goto-char pos)
22165 nil))))
22167 (defun org-show-siblings ()
22168 "Show all siblings of the current headline."
22169 (save-excursion
22170 (while (org-goto-sibling) (org-flag-heading nil)))
22171 (save-excursion
22172 (while (org-goto-sibling 'previous)
22173 (org-flag-heading nil))))
22175 (defun org-goto-first-child ()
22176 "Goto the first child, even if it is invisible.
22177 Return t when a child was found. Otherwise don't move point and
22178 return nil."
22179 (let (level (pos (point)) (re org-outline-regexp-bol))
22180 (when (condition-case nil (org-back-to-heading t) (error nil))
22181 (setq level (outline-level))
22182 (forward-char 1)
22183 (if (and (re-search-forward re nil t) (> (outline-level) level))
22184 (progn (goto-char (match-beginning 0)) t)
22185 (goto-char pos) nil))))
22187 (defun org-show-hidden-entry ()
22188 "Show an entry where even the heading is hidden."
22189 (save-excursion
22190 (org-show-entry)))
22192 (defun org-flag-heading (flag &optional entry)
22193 "Flag the current heading. FLAG non-nil means make invisible.
22194 When ENTRY is non-nil, show the entire entry."
22195 (save-excursion
22196 (org-back-to-heading t)
22197 ;; Check if we should show the entire entry
22198 (if entry
22199 (progn
22200 (org-show-entry)
22201 (save-excursion
22202 (and (outline-next-heading)
22203 (org-flag-heading nil))))
22204 (outline-flag-region (max (point-min) (1- (point)))
22205 (save-excursion (outline-end-of-heading) (point))
22206 flag))))
22208 (defun org-get-next-sibling ()
22209 "Move to next heading of the same level, and return point.
22210 If there is no such heading, return nil.
22211 This is like outline-next-sibling, but invisible headings are ok."
22212 (let ((level (funcall outline-level)))
22213 (outline-next-heading)
22214 (while (and (not (eobp)) (> (funcall outline-level) level))
22215 (outline-next-heading))
22216 (if (or (eobp) (< (funcall outline-level) level))
22218 (point))))
22220 (defun org-get-last-sibling ()
22221 "Move to previous heading of the same level, and return point.
22222 If there is no such heading, return nil."
22223 (let ((opoint (point))
22224 (level (funcall outline-level)))
22225 (outline-previous-heading)
22226 (when (and (/= (point) opoint) (outline-on-heading-p t))
22227 (while (and (> (funcall outline-level) level)
22228 (not (bobp)))
22229 (outline-previous-heading))
22230 (if (< (funcall outline-level) level)
22232 (point)))))
22234 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22235 "Goto to the end of a subtree."
22236 ;; This contains an exact copy of the original function, but it uses
22237 ;; `org-back-to-heading', to make it work also in invisible
22238 ;; trees. And is uses an invisible-ok argument.
22239 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22240 ;; Furthermore, when used inside Org, finding the end of a large subtree
22241 ;; with many children and grandchildren etc, this can be much faster
22242 ;; than the outline version.
22243 (org-back-to-heading invisible-ok)
22244 (let ((first t)
22245 (level (funcall outline-level)))
22246 (if (and (derived-mode-p 'org-mode) (< level 1000))
22247 ;; A true heading (not a plain list item), in Org-mode
22248 ;; This means we can easily find the end by looking
22249 ;; only for the right number of stars. Using a regexp to do
22250 ;; this is so much faster than using a Lisp loop.
22251 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22252 (forward-char 1)
22253 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22254 ;; something else, do it the slow way
22255 (while (and (not (eobp))
22256 (or first (> (funcall outline-level) level)))
22257 (setq first nil)
22258 (outline-next-heading)))
22259 (unless to-heading
22260 (if (memq (preceding-char) '(?\n ?\^M))
22261 (progn
22262 ;; Go to end of line before heading
22263 (forward-char -1)
22264 (if (memq (preceding-char) '(?\n ?\^M))
22265 ;; leave blank line before heading
22266 (forward-char -1))))))
22267 (point))
22269 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22270 "Use Org version in org-mode, for dramatic speed-up."
22271 (if (derived-mode-p 'org-mode)
22272 (progn
22273 (org-end-of-subtree nil t)
22274 (unless (eobp) (backward-char 1)))
22275 ad-do-it))
22277 (defun org-end-of-meta-data-and-drawers ()
22278 "Jump to the first text after meta data and drawers in the current entry.
22279 This will move over empty lines, lines with planning time stamps,
22280 clocking lines, and drawers."
22281 (org-back-to-heading t)
22282 (let ((end (save-excursion (outline-next-heading) (point)))
22283 (re (concat "\\(" org-drawer-regexp "\\)"
22284 "\\|" "[ \t]*" org-keyword-time-regexp)))
22285 (forward-line 1)
22286 (while (re-search-forward re end t)
22287 (if (not (match-end 1))
22288 ;; empty or planning line
22289 (forward-line 1)
22290 ;; a drawer, find the end
22291 (re-search-forward "^[ \t]*:END:" end 'move)
22292 (forward-line 1)))
22293 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22294 (point)))
22296 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22297 "Move forward to the arg'th subheading at same level as this one.
22298 Stop at the first and last subheadings of a superior heading.
22299 Normally this only looks at visible headings, but when INVISIBLE-OK is
22300 non-nil it will also look at invisible ones."
22301 (interactive "p")
22302 (org-back-to-heading invisible-ok)
22303 (org-at-heading-p)
22304 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22305 (re (format "^\\*\\{1,%d\\} " level))
22307 (forward-char 1)
22308 (while (> arg 0)
22309 (while (and (re-search-forward re nil 'move)
22310 (setq l (- (match-end 0) (match-beginning 0) 1))
22311 (= l level)
22312 (not invisible-ok)
22313 (progn (backward-char 1) (outline-invisible-p)))
22314 (if (< l level) (setq arg 1)))
22315 (setq arg (1- arg)))
22316 (beginning-of-line 1)))
22318 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22319 "Move backward to the arg'th subheading at same level as this one.
22320 Stop at the first and last subheadings of a superior heading."
22321 (interactive "p")
22322 (org-back-to-heading)
22323 (org-at-heading-p)
22324 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22325 (re (format "^\\*\\{1,%d\\} " level))
22327 (while (> arg 0)
22328 (while (and (re-search-backward re nil 'move)
22329 (setq l (- (match-end 0) (match-beginning 0) 1))
22330 (= l level)
22331 (not invisible-ok)
22332 (outline-invisible-p))
22333 (if (< l level) (setq arg 1)))
22334 (setq arg (1- arg)))))
22336 (defun org-forward-element ()
22337 "Move forward by one element.
22338 Move to the next element at the same level, when possible."
22339 (interactive)
22340 (cond ((eobp) (error "Cannot move further down"))
22341 ((org-with-limited-levels (org-at-heading-p))
22342 (let ((origin (point)))
22343 (org-forward-heading-same-level 1)
22344 (unless (org-with-limited-levels (org-at-heading-p))
22345 (goto-char origin)
22346 (error "Cannot move further down"))))
22348 (let* ((elem (org-element-at-point))
22349 (end (org-element-property :end elem))
22350 (parent (org-element-property :parent elem)))
22351 (if (and parent (= (org-element-property :contents-end parent) end))
22352 (goto-char (org-element-property :end parent))
22353 (goto-char end))))))
22355 (defun org-backward-element ()
22356 "Move backward by one element.
22357 Move to the previous element at the same level, when possible."
22358 (interactive)
22359 (cond ((bobp) (error "Cannot move further up"))
22360 ((org-with-limited-levels (org-at-heading-p))
22361 ;; At an headline, move to the previous one, if any, or stay
22362 ;; here.
22363 (let ((origin (point)))
22364 (org-backward-heading-same-level 1)
22365 (unless (org-with-limited-levels (org-at-heading-p))
22366 (goto-char origin)
22367 (error "Cannot move further up"))))
22369 (let* ((trail (org-element-at-point 'keep-trail))
22370 (elem (car trail))
22371 (prev-elem (nth 1 trail))
22372 (beg (org-element-property :begin elem)))
22373 (cond
22374 ;; Move to beginning of current element if point isn't
22375 ;; there already.
22376 ((/= (point) beg) (goto-char beg))
22377 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22378 ((org-before-first-heading-p) (goto-char (point-min)))
22379 (t (org-back-to-heading)))))))
22381 (defun org-up-element ()
22382 "Move to upper element."
22383 (interactive)
22384 (if (org-with-limited-levels (org-at-heading-p))
22385 (unless (org-up-heading-safe) (error "No surrounding element"))
22386 (let* ((elem (org-element-at-point))
22387 (parent (org-element-property :parent elem)))
22388 (if parent (goto-char (org-element-property :begin parent))
22389 (if (org-with-limited-levels (org-before-first-heading-p))
22390 (error "No surrounding element")
22391 (org-with-limited-levels (org-back-to-heading)))))))
22393 (defvar org-element-greater-elements)
22394 (defun org-down-element ()
22395 "Move to inner element."
22396 (interactive)
22397 (let ((element (org-element-at-point)))
22398 (cond
22399 ((memq (org-element-type element) '(plain-list table))
22400 (goto-char (org-element-property :contents-begin element))
22401 (forward-char))
22402 ((memq (org-element-type element) org-element-greater-elements)
22403 ;; If contents are hidden, first disclose them.
22404 (when (org-element-property :hiddenp element) (org-cycle))
22405 (goto-char (or (org-element-property :contents-begin element)
22406 (error "No content for this element"))))
22407 (t (error "No inner element")))))
22409 (defun org-drag-element-backward ()
22410 "Move backward element at point."
22411 (interactive)
22412 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22413 (let* ((trail (org-element-at-point 'keep-trail))
22414 (elem (car trail))
22415 (prev-elem (nth 1 trail)))
22416 ;; Error out if no previous element or previous element is
22417 ;; a parent of the current one.
22418 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22419 (error "Cannot drag element backward")
22420 (let ((pos (point)))
22421 (org-element-swap-A-B prev-elem elem)
22422 (goto-char (+ (org-element-property :begin prev-elem)
22423 (- pos (org-element-property :begin elem)))))))))
22425 (defun org-drag-element-forward ()
22426 "Move forward element at point."
22427 (interactive)
22428 (let* ((pos (point))
22429 (elem (org-element-at-point)))
22430 (when (= (point-max) (org-element-property :end elem))
22431 (error "Cannot drag element forward"))
22432 (goto-char (org-element-property :end elem))
22433 (let ((next-elem (org-element-at-point)))
22434 (when (or (org-element-nested-p elem next-elem)
22435 (and (eq (org-element-type next-elem) 'headline)
22436 (not (eq (org-element-type elem) 'headline))))
22437 (goto-char pos)
22438 (error "Cannot drag element forward"))
22439 ;; Compute new position of point: it's shifted by NEXT-ELEM
22440 ;; body's length (without final blanks) and by the length of
22441 ;; blanks between ELEM and NEXT-ELEM.
22442 (let ((size-next (- (save-excursion
22443 (goto-char (org-element-property :end next-elem))
22444 (skip-chars-backward " \r\t\n")
22445 (forward-line)
22446 ;; Small correction if buffer doesn't end
22447 ;; with a newline character.
22448 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22449 (org-element-property :begin next-elem)))
22450 (size-blank (- (org-element-property :end elem)
22451 (save-excursion
22452 (goto-char (org-element-property :end elem))
22453 (skip-chars-backward " \r\t\n")
22454 (forward-line)
22455 (point)))))
22456 (org-element-swap-A-B elem next-elem)
22457 (goto-char (+ pos size-next size-blank))))))
22459 (defun org-mark-element ()
22460 "Put point at beginning of this element, mark at end.
22462 Interactively, if this command is repeated or (in Transient Mark
22463 mode) if the mark is active, it marks the next element after the
22464 ones already marked."
22465 (interactive)
22466 (let (deactivate-mark)
22467 (if (and (org-called-interactively-p 'any)
22468 (or (and (eq last-command this-command) (mark t))
22469 (and transient-mark-mode mark-active)))
22470 (set-mark
22471 (save-excursion
22472 (goto-char (mark))
22473 (goto-char (org-element-property :end (org-element-at-point)))))
22474 (let ((element (org-element-at-point)))
22475 (end-of-line)
22476 (push-mark (org-element-property :end element) t t)
22477 (goto-char (org-element-property :begin element))))))
22479 (defun org-narrow-to-element ()
22480 "Narrow buffer to current element."
22481 (interactive)
22482 (let ((elem (org-element-at-point)))
22483 (cond
22484 ((eq (car elem) 'headline)
22485 (narrow-to-region
22486 (org-element-property :begin elem)
22487 (org-element-property :end elem)))
22488 ((memq (car elem) org-element-greater-elements)
22489 (narrow-to-region
22490 (org-element-property :contents-begin elem)
22491 (org-element-property :contents-end elem)))
22493 (narrow-to-region
22494 (org-element-property :begin elem)
22495 (org-element-property :end elem))))))
22497 (defun org-transpose-element ()
22498 "Transpose current and previous elements, keeping blank lines between.
22499 Point is moved after both elements."
22500 (interactive)
22501 (org-skip-whitespace)
22502 (let ((end (org-element-property :end (org-element-at-point))))
22503 (org-drag-element-backward)
22504 (goto-char end)))
22506 (defun org-unindent-buffer ()
22507 "Un-indent the visible part of the buffer.
22508 Relative indentation (between items, inside blocks, etc.) isn't
22509 modified."
22510 (interactive)
22511 (unless (eq major-mode 'org-mode)
22512 (error "Cannot un-indent a buffer not in Org mode"))
22513 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22514 unindent-tree ; For byte-compiler.
22515 (unindent-tree
22516 (function
22517 (lambda (contents)
22518 (mapc
22519 (lambda (element)
22520 (if (memq (org-element-type element) '(headline section))
22521 (funcall unindent-tree (org-element-contents element))
22522 (save-excursion
22523 (save-restriction
22524 (narrow-to-region
22525 (org-element-property :begin element)
22526 (org-element-property :end element))
22527 (org-do-remove-indentation)))))
22528 (reverse contents))))))
22529 (funcall unindent-tree (org-element-contents parse-tree))))
22531 (defun org-show-subtree ()
22532 "Show everything after this heading at deeper levels."
22533 (interactive)
22534 (outline-flag-region
22535 (point)
22536 (save-excursion
22537 (org-end-of-subtree t t))
22538 nil))
22540 (defun org-show-entry ()
22541 "Show the body directly following this heading.
22542 Show the heading too, if it is currently invisible."
22543 (interactive)
22544 (save-excursion
22545 (condition-case nil
22546 (progn
22547 (org-back-to-heading t)
22548 (outline-flag-region
22549 (max (point-min) (1- (point)))
22550 (save-excursion
22551 (if (re-search-forward
22552 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22553 (match-beginning 1)
22554 (point-max)))
22555 nil)
22556 (org-cycle-hide-drawers 'children))
22557 (error nil))))
22559 (defun org-make-options-regexp (kwds &optional extra)
22560 "Make a regular expression for keyword lines."
22561 (concat
22562 "^#\\+\\("
22563 (mapconcat 'regexp-quote kwds "\\|")
22564 (if extra (concat "\\|" extra))
22565 "\\):[ \t]*\\(.*\\)"))
22567 ;; Make isearch reveal the necessary context
22568 (defun org-isearch-end ()
22569 "Reveal context after isearch exits."
22570 (when isearch-success ; only if search was successful
22571 (if (featurep 'xemacs)
22572 ;; Under XEmacs, the hook is run in the correct place,
22573 ;; we directly show the context.
22574 (org-show-context 'isearch)
22575 ;; In Emacs the hook runs *before* restoring the overlays.
22576 ;; So we have to use a one-time post-command-hook to do this.
22577 ;; (Emacs 22 has a special variable, see function `org-mode')
22578 (unless (and (boundp 'isearch-mode-end-hook-quit)
22579 isearch-mode-end-hook-quit)
22580 ;; Only when the isearch was not quitted.
22581 (org-add-hook 'post-command-hook 'org-isearch-post-command
22582 'append 'local)))))
22584 (defun org-isearch-post-command ()
22585 "Remove self from hook, and show context."
22586 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22587 (org-show-context 'isearch))
22590 ;;;; Integration with and fixes for other packages
22592 ;;; Imenu support
22594 (defvar org-imenu-markers nil
22595 "All markers currently used by Imenu.")
22596 (make-variable-buffer-local 'org-imenu-markers)
22598 (defun org-imenu-new-marker (&optional pos)
22599 "Return a new marker for use by Imenu, and remember the marker."
22600 (let ((m (make-marker)))
22601 (move-marker m (or pos (point)))
22602 (push m org-imenu-markers)
22605 (defun org-imenu-get-tree ()
22606 "Produce the index for Imenu."
22607 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22608 (setq org-imenu-markers nil)
22609 (let* ((n org-imenu-depth)
22610 (re (concat "^" (org-get-limited-outline-regexp)))
22611 (subs (make-vector (1+ n) nil))
22612 (last-level 0)
22613 m level head)
22614 (save-excursion
22615 (save-restriction
22616 (widen)
22617 (goto-char (point-max))
22618 (while (re-search-backward re nil t)
22619 (setq level (org-reduced-level (funcall outline-level)))
22620 (when (and (<= level n)
22621 (looking-at org-complex-heading-regexp))
22622 (setq head (org-link-display-format
22623 (org-match-string-no-properties 4))
22624 m (org-imenu-new-marker))
22625 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22626 (if (>= level last-level)
22627 (push (cons head m) (aref subs level))
22628 (push (cons head (aref subs (1+ level))) (aref subs level))
22629 (loop for i from (1+ level) to n do (aset subs i nil)))
22630 (setq last-level level)))))
22631 (aref subs 1)))
22633 (eval-after-load "imenu"
22634 '(progn
22635 (add-hook 'imenu-after-jump-hook
22636 (lambda ()
22637 (if (derived-mode-p 'org-mode)
22638 (org-show-context 'org-goto))))))
22640 (defun org-link-display-format (link)
22641 "Replace a link with either the description, or the link target
22642 if no description is present"
22643 (save-match-data
22644 (if (string-match org-bracket-link-analytic-regexp link)
22645 (replace-match (if (match-end 5)
22646 (match-string 5 link)
22647 (concat (match-string 1 link)
22648 (match-string 3 link)))
22649 nil t link)
22650 link)))
22652 (defun org-toggle-link-display ()
22653 "Toggle the literal or descriptive display of links."
22654 (interactive)
22655 (if org-descriptive-links
22656 (progn (org-remove-from-invisibility-spec '(org-link))
22657 (org-restart-font-lock)
22658 (setq org-descriptive-links nil))
22659 (progn (add-to-invisibility-spec '(org-link))
22660 (org-restart-font-lock)
22661 (setq org-descriptive-links t))))
22663 ;; Speedbar support
22665 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22666 "Overlay marking the agenda restriction line in speedbar.")
22667 (overlay-put org-speedbar-restriction-lock-overlay
22668 'face 'org-agenda-restriction-lock)
22669 (overlay-put org-speedbar-restriction-lock-overlay
22670 'help-echo "Agendas are currently limited to this item.")
22671 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22673 (defun org-speedbar-set-agenda-restriction ()
22674 "Restrict future agenda commands to the location at point in speedbar.
22675 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22676 (interactive)
22677 (require 'org-agenda)
22678 (let (p m tp np dir txt)
22679 (cond
22680 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22681 'org-imenu t))
22682 (setq m (get-text-property p 'org-imenu-marker))
22683 (with-current-buffer (marker-buffer m)
22684 (goto-char m)
22685 (org-agenda-set-restriction-lock 'subtree)))
22686 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22687 'speedbar-function 'speedbar-find-file))
22688 (setq tp (previous-single-property-change
22689 (1+ p) 'speedbar-function)
22690 np (next-single-property-change
22691 tp 'speedbar-function)
22692 dir (speedbar-line-directory)
22693 txt (buffer-substring-no-properties (or tp (point-min))
22694 (or np (point-max))))
22695 (with-current-buffer (find-file-noselect
22696 (let ((default-directory dir))
22697 (expand-file-name txt)))
22698 (unless (derived-mode-p 'org-mode)
22699 (error "Cannot restrict to non-Org-mode file"))
22700 (org-agenda-set-restriction-lock 'file)))
22701 (t (error "Don't know how to restrict Org-mode's agenda")))
22702 (move-overlay org-speedbar-restriction-lock-overlay
22703 (point-at-bol) (point-at-eol))
22704 (setq current-prefix-arg nil)
22705 (org-agenda-maybe-redo)))
22707 (eval-after-load "speedbar"
22708 '(progn
22709 (speedbar-add-supported-extension ".org")
22710 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22711 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22712 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22713 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22714 (add-hook 'speedbar-visiting-tag-hook
22715 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22717 ;;; Fixes and Hacks for problems with other packages
22719 ;; Make flyspell not check words in links, to not mess up our keymap
22720 (defun org-mode-flyspell-verify ()
22721 "Don't let flyspell put overlays at active buttons, or on
22722 {todo,all-time,additional-option-like}-keywords."
22723 (let ((pos (max (1- (point)) (point-min)))
22724 (word (thing-at-point 'word)))
22725 (and (not (get-text-property pos 'keymap))
22726 (not (get-text-property pos 'org-no-flyspell))
22727 (not (member word org-todo-keywords-1))
22728 (not (member word org-all-time-keywords))
22729 (not (member word org-options-keywords))
22730 (not (member word (mapcar 'car org-startup-options)))
22731 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22733 (defun org-remove-flyspell-overlays-in (beg end)
22734 "Remove flyspell overlays in region."
22735 (and (org-bound-and-true-p flyspell-mode)
22736 (fboundp 'flyspell-delete-region-overlays)
22737 (flyspell-delete-region-overlays beg end))
22738 (add-text-properties beg end '(org-no-flyspell t)))
22740 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22741 (eval-after-load "bookmark"
22742 '(if (boundp 'bookmark-after-jump-hook)
22743 ;; We can use the hook
22744 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22745 ;; Hook not available, use advice
22746 (defadvice bookmark-jump (after org-make-visible activate)
22747 "Make the position visible."
22748 (org-bookmark-jump-unhide))))
22750 ;; Make sure saveplace shows the location if it was hidden
22751 (eval-after-load "saveplace"
22752 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22753 "Make the position visible."
22754 (org-bookmark-jump-unhide)))
22756 ;; Make sure ecb shows the location if it was hidden
22757 (eval-after-load "ecb"
22758 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22759 "Make hierarchy visible when jumping into location from ECB tree buffer."
22760 (if (derived-mode-p 'org-mode)
22761 (org-show-context))))
22763 (defun org-bookmark-jump-unhide ()
22764 "Unhide the current position, to show the bookmark location."
22765 (and (derived-mode-p 'org-mode)
22766 (or (outline-invisible-p)
22767 (save-excursion (goto-char (max (point-min) (1- (point))))
22768 (outline-invisible-p)))
22769 (org-show-context 'bookmark-jump)))
22771 ;; Make session.el ignore our circular variable
22772 (eval-after-load "session"
22773 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22775 ;;;; Experimental code
22777 (defun org-closed-in-range ()
22778 "Sparse tree of items closed in a certain time range.
22779 Still experimental, may disappear in the future."
22780 (interactive)
22781 ;; Get the time interval from the user.
22782 (let* ((time1 (org-float-time
22783 (org-read-date nil 'to-time nil "Starting date: ")))
22784 (time2 (org-float-time
22785 (org-read-date nil 'to-time nil "End date:")))
22786 ;; callback function
22787 (callback (lambda ()
22788 (let ((time
22789 (org-float-time
22790 (apply 'encode-time
22791 (org-parse-time-string
22792 (match-string 1))))))
22793 ;; check if time in interval
22794 (and (>= time time1) (<= time time2))))))
22795 ;; make tree, check each match with the callback
22796 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22798 ;;;; Finish up
22800 (provide 'org)
22802 (run-hooks 'org-load-hook)
22804 ;;; org.el ends here