Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobb537ff43ba281d50cb11a565b40a7c282448f82f
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 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
117 (declare-function org-clock-timestamps-up "org-clock" ())
118 (declare-function org-clock-timestamps-down "org-clock" ())
119 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
121 ;; load languages based on value of `org-babel-load-languages'
122 (defvar org-babel-load-languages)
123 ;;;###autoload
124 (defun org-babel-do-load-languages (sym value)
125 "Load the languages defined in `org-babel-load-languages'."
126 (set-default sym value)
127 (mapc (lambda (pair)
128 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
129 (if active
130 (progn
131 (require (intern (concat "ob-" lang))))
132 (progn
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-execute:" lang)))
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-expand-body:" lang)))))))
137 org-babel-load-languages))
139 (defcustom org-babel-load-languages '((emacs-lisp . t))
140 "Languages which can be evaluated in Org-mode buffers.
141 This list can be used to load support for any of the languages
142 below, note that each language will depend on a different set of
143 system executables and/or Emacs modes. When a language is
144 \"loaded\", then code blocks in that language can be evaluated
145 with `org-babel-execute-src-block' bound by default to C-c
146 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
147 be set to remove code block evaluation from the C-c C-c
148 keybinding. By default only Emacs Lisp (which has no
149 requirements) is loaded."
150 :group 'org-babel
151 :set 'org-babel-do-load-languages
152 :version "24.1"
153 :type '(alist :tag "Babel Languages"
154 :key-type
155 (choice
156 (const :tag "Awk" awk)
157 (const :tag "C" C)
158 (const :tag "R" R)
159 (const :tag "Asymptote" asymptote)
160 (const :tag "Calc" calc)
161 (const :tag "Clojure" clojure)
162 (const :tag "CSS" css)
163 (const :tag "Ditaa" ditaa)
164 (const :tag "Dot" dot)
165 (const :tag "Emacs Lisp" emacs-lisp)
166 (const :tag "Fortran" fortran)
167 (const :tag "Gnuplot" gnuplot)
168 (const :tag "Haskell" haskell)
169 (const :tag "IO" io)
170 (const :tag "Java" java)
171 (const :tag "Javascript" js)
172 (const :tag "LaTeX" latex)
173 (const :tag "Ledger" ledger)
174 (const :tag "Lilypond" lilypond)
175 (const :tag "Lisp" lisp)
176 (const :tag "Maxima" maxima)
177 (const :tag "Matlab" matlab)
178 (const :tag "Mscgen" mscgen)
179 (const :tag "Ocaml" ocaml)
180 (const :tag "Octave" octave)
181 (const :tag "Org" org)
182 (const :tag "Perl" perl)
183 (const :tag "Pico Lisp" picolisp)
184 (const :tag "PlantUML" plantuml)
185 (const :tag "Python" python)
186 (const :tag "Ruby" ruby)
187 (const :tag "Sass" sass)
188 (const :tag "Scala" scala)
189 (const :tag "Scheme" scheme)
190 (const :tag "Screen" screen)
191 (const :tag "Shell Script" sh)
192 (const :tag "Shen" shen)
193 (const :tag "Sql" sql)
194 (const :tag "Sqlite" sqlite))
195 :value-type (boolean :tag "Activate" :value t)))
197 ;;;; Customization variables
198 (defcustom org-clone-delete-id nil
199 "Remove ID property of clones of a subtree.
200 When non-nil, clones of a subtree don't inherit the ID property.
201 Otherwise they inherit the ID property with a new unique
202 identifier."
203 :type 'boolean
204 :version "24.1"
205 :group 'org-id)
207 ;;; Version
208 (require 'org-compat)
209 (org-check-version)
210 ;;;###autoload
211 (defun org-version (&optional here full message)
212 "Show the org-mode version in the echo area.
213 With prefix argument HERE, insert it at point.
214 When FULL is non-nil, use a verbose version string.
215 When MESSAGE is non-nil, display a message with the version."
216 (interactive "P")
217 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
218 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
219 (org-trash (or
220 (and (fboundp 'org-release) (fboundp 'org-git-version))
221 (load (concat org-dir "org-version.el")
222 'noerror 'nomessage 'nosuffix)))
223 (org-version (org-release))
224 (git-version (org-git-version))
225 (version (format "Org-mode version %s (%s @ %s)"
226 org-version
227 git-version
228 (if org-install-dir
229 (if (string= org-dir org-install-dir)
230 org-install-dir
231 (concat "mixed installation! " org-install-dir " and " org-dir))
232 "org-install.el can not be found!")))
233 (_version (if full version org-version)))
234 (if (org-called-interactively-p 'interactive)
235 (if here
236 (insert version)
237 (message version))
238 (if message (message _version))
239 _version)))
241 (defconst org-version (org-version))
243 ;;; Compatibility constants
245 ;;; The custom variables
247 (defgroup org nil
248 "Outline-based notes management and organizer."
249 :tag "Org"
250 :group 'outlines
251 :group 'calendar)
253 (defcustom org-mode-hook nil
254 "Mode hook for Org-mode, run after the mode was turned on."
255 :group 'org
256 :type 'hook)
258 (defcustom org-load-hook nil
259 "Hook that is run after org.el has been loaded."
260 :group 'org
261 :type 'hook)
263 (defcustom org-log-buffer-setup-hook nil
264 "Hook that is run after an Org log buffer is created."
265 :group 'org
266 :version "24.1"
267 :type 'hook)
269 (defvar org-modules) ; defined below
270 (defvar org-modules-loaded nil
271 "Have the modules been loaded already?")
273 (defun org-load-modules-maybe (&optional force)
274 "Load all extensions listed in `org-modules'."
275 (when (or force (not org-modules-loaded))
276 (mapc (lambda (ext)
277 (condition-case nil (require ext)
278 (error (message "Problems while trying to load feature `%s'" ext))))
279 org-modules)
280 (setq org-modules-loaded t)))
282 (defun org-set-modules (var value)
283 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
284 (set var value)
285 (when (featurep 'org)
286 (org-load-modules-maybe 'force)))
288 (when (org-bound-and-true-p org-modules)
289 (let ((a (member 'org-infojs org-modules)))
290 (and a (setcar a 'org-jsinfo))))
292 (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)
293 "Modules that should always be loaded together with org.el.
294 If a description starts with <C>, the file is not part of Emacs
295 and loading it will require that you have downloaded and properly installed
296 the org-mode distribution.
298 You can also use this system to load external packages (i.e. neither Org
299 core modules, nor modules from the CONTRIB directory). Just add symbols
300 to the end of the list. If the package is called org-xyz.el, then you need
301 to add the symbol `xyz', and the package must have a call to
303 (provide 'org-xyz)"
304 :group 'org
305 :set 'org-set-modules
306 :type
307 '(set :greedy t
308 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
309 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
310 (const :tag " crypt: Encryption of subtrees" org-crypt)
311 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
312 (const :tag " docview: Links to doc-view buffers" org-docview)
313 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
314 (const :tag " id: Global IDs for identifying entries" org-id)
315 (const :tag " info: Links to Info nodes" org-info)
316 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
317 (const :tag " habit: Track your consistency with habits" org-habit)
318 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
319 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
320 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
321 (const :tag " mew Links to Mew folders/messages" org-mew)
322 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
323 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
324 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
325 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
326 (const :tag " vm: Links to VM folders/messages" org-vm)
327 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
328 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
329 (const :tag " mouse: Additional mouse support" org-mouse)
330 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
332 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
333 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
334 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
335 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
336 (const :tag "C collector: Collect properties into tables" org-collector)
337 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
338 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
339 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
340 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
341 (const :tag "C eval: Include command output as text" org-eval)
342 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
343 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
344 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
345 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
346 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
348 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
350 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
351 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
352 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
353 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
354 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
355 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
356 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
357 (const :tag "C mtags: Support for muse-like tags" org-mtags)
358 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
359 (const :tag "C registry: A registry for Org-mode links" org-registry)
360 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
361 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
362 (const :tag "C secretary: Team management with org-mode" org-secretary)
363 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
364 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
365 (const :tag "C track: Keep up with Org-mode development" org-track)
366 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
367 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
368 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
370 (defcustom org-support-shift-select nil
371 "Non-nil means make shift-cursor commands select text when possible.
373 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
374 start selecting a region, or enlarge regions started in this way.
375 In Org-mode, in special contexts, these same keys are used for
376 other purposes, important enough to compete with shift selection.
377 Org tries to balance these needs by supporting `shift-select-mode'
378 outside these special contexts, under control of this variable.
380 The default of this variable is nil, to avoid confusing behavior. Shifted
381 cursor keys will then execute Org commands in the following contexts:
382 - on a headline, changing TODO state (left/right) and priority (up/down)
383 - on a time stamp, changing the time
384 - in a plain list item, changing the bullet type
385 - in a property definition line, switching between allowed values
386 - in the BEGIN line of a clock table (changing the time block).
387 Outside these contexts, the commands will throw an error.
389 When this variable is t and the cursor is not in a special
390 context, Org-mode will support shift-selection for making and
391 enlarging regions. To make this more effective, the bullet
392 cycling will no longer happen anywhere in an item line, but only
393 if the cursor is exactly on the bullet.
395 If you set this variable to the symbol `always', then the keys
396 will not be special in headlines, property lines, and item lines,
397 to make shift selection work there as well. If this is what you
398 want, you can use the following alternative commands: `C-c C-t'
399 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
400 can be used to switch TODO sets, `C-c -' to cycle item bullet
401 types, and properties can be edited by hand or in column view.
403 However, when the cursor is on a timestamp, shift-cursor commands
404 will still edit the time stamp - this is just too good to give up.
406 XEmacs user should have this variable set to nil, because
407 `shift-select-mode' is in Emacs 23 or later only."
408 :group 'org
409 :type '(choice
410 (const :tag "Never" nil)
411 (const :tag "When outside special context" t)
412 (const :tag "Everywhere except timestamps" always)))
414 (defcustom org-loop-over-headlines-in-active-region nil
415 "Shall some commands act upon headlines in the active region?
417 When set to `t', some commands will be performed in all headlines
418 within the active region.
420 When set to `start-level', some commands will be performed in all
421 headlines within the active region, provided that these headlines
422 are of the same level than the first one.
424 When set to a string, those commands will be performed on the
425 matching headlines within the active region. Such string must be
426 a tags/property/todo match as it is used in the agenda tags view.
428 The list of commands is: `org-schedule', `org-deadline',
429 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
430 `org-archive-to-archive-sibling'. The archiving commands skip
431 already archived entries."
432 :type '(choice (const :tag "Don't loop" nil)
433 (const :tag "All headlines in active region" t)
434 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
435 (string :tag "Tags/Property/Todo matcher"))
436 :version "24.1"
437 :group 'org-todo
438 :group 'org-archive)
440 (defgroup org-startup nil
441 "Options concerning startup of Org-mode."
442 :tag "Org Startup"
443 :group 'org)
445 (defcustom org-startup-folded t
446 "Non-nil means entering Org-mode will switch to OVERVIEW.
447 This can also be configured on a per-file basis by adding one of
448 the following lines anywhere in the buffer:
450 #+STARTUP: fold (or `overview', this is equivalent)
451 #+STARTUP: nofold (or `showall', this is equivalent)
452 #+STARTUP: content
453 #+STARTUP: showeverything"
454 :group 'org-startup
455 :type '(choice
456 (const :tag "nofold: show all" nil)
457 (const :tag "fold: overview" t)
458 (const :tag "content: all headlines" content)
459 (const :tag "show everything, even drawers" showeverything)))
461 (defcustom org-startup-truncated t
462 "Non-nil means entering Org-mode will set `truncate-lines'.
463 This is useful since some lines containing links can be very long and
464 uninteresting. Also tables look terrible when wrapped."
465 :group 'org-startup
466 :type 'boolean)
468 (defcustom org-startup-indented nil
469 "Non-nil means turn on `org-indent-mode' on startup.
470 This can also be configured on a per-file basis by adding one of
471 the following lines anywhere in the buffer:
473 #+STARTUP: indent
474 #+STARTUP: noindent"
475 :group 'org-structure
476 :type '(choice
477 (const :tag "Not" nil)
478 (const :tag "Globally (slow on startup in large files)" t)))
480 (defcustom org-use-sub-superscripts t
481 "Non-nil means interpret \"_\" and \"^\" for export.
482 When this option is turned on, you can use TeX-like syntax for sub- and
483 superscripts. Several characters after \"_\" or \"^\" will be
484 considered as a single item - so grouping with {} is normally not
485 needed. For example, the following things will be parsed as single
486 sub- or superscripts.
488 10^24 or 10^tau several digits will be considered 1 item.
489 10^-12 or 10^-tau a leading sign with digits or a word
490 x^2-y^3 will be read as x^2 - y^3, because items are
491 terminated by almost any nonword/nondigit char.
492 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
494 Still, ambiguity is possible - so when in doubt use {} to enclose the
495 sub/superscript. If you set this variable to the symbol `{}',
496 the braces are *required* in order to trigger interpretations as
497 sub/superscript. This can be helpful in documents that need \"_\"
498 frequently in plain text.
500 Not all export backends support this, but HTML does.
502 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
503 :group 'org-startup
504 :group 'org-export-translation
505 :version "24.1"
506 :type '(choice
507 (const :tag "Always interpret" t)
508 (const :tag "Only with braces" {})
509 (const :tag "Never interpret" nil)))
511 (if (fboundp 'defvaralias)
512 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
515 (defcustom org-startup-with-beamer-mode nil
516 "Non-nil means turn on `org-beamer-mode' on startup.
517 This can also be configured on a per-file basis by adding one of
518 the following lines anywhere in the buffer:
520 #+STARTUP: beamer"
521 :group 'org-startup
522 :version "24.1"
523 :type 'boolean)
525 (defcustom org-startup-align-all-tables nil
526 "Non-nil means align all tables when visiting a file.
527 This is useful when the column width in tables is forced with <N> cookies
528 in table fields. Such tables will look correct only after the first re-align.
529 This can also be configured on a per-file basis by adding one of
530 the following lines anywhere in the buffer:
531 #+STARTUP: align
532 #+STARTUP: noalign"
533 :group 'org-startup
534 :type 'boolean)
536 (defcustom org-startup-with-inline-images nil
537 "Non-nil means show inline images when loading a new Org file.
538 This can also be configured on a per-file basis by adding one of
539 the following lines anywhere in the buffer:
540 #+STARTUP: inlineimages
541 #+STARTUP: noinlineimages"
542 :group 'org-startup
543 :version "24.1"
544 :type 'boolean)
546 (defcustom org-insert-mode-line-in-empty-file nil
547 "Non-nil means insert the first line setting Org-mode in empty files.
548 When the function `org-mode' is called interactively in an empty file, this
549 normally means that the file name does not automatically trigger Org-mode.
550 To ensure that the file will always be in Org-mode in the future, a
551 line enforcing Org-mode will be inserted into the buffer, if this option
552 has been set."
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-replace-disputed-keys nil
557 "Non-nil means use alternative key bindings for some keys.
558 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
559 These keys are also used by other packages like shift-selection-mode'
560 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
561 If you want to use Org-mode together with one of these other modes,
562 or more generally if you would like to move some Org-mode commands to
563 other keys, set this variable and configure the keys with the variable
564 `org-disputed-keys'.
566 This option is only relevant at load-time of Org-mode, and must be set
567 *before* org.el is loaded. Changing it requires a restart of Emacs to
568 become effective."
569 :group 'org-startup
570 :type 'boolean)
572 (defcustom org-use-extra-keys nil
573 "Non-nil means use extra key sequence definitions for certain commands.
574 This happens automatically if you run XEmacs or if `window-system'
575 is nil. This variable lets you do the same manually. You must
576 set it before loading org.
578 Example: on Carbon Emacs 22 running graphically, with an external
579 keyboard on a Powerbook, the default way of setting M-left might
580 not work for either Alt or ESC. Setting this variable will make
581 it work for ESC."
582 :group 'org-startup
583 :type 'boolean)
585 (if (fboundp 'defvaralias)
586 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
588 (defcustom org-disputed-keys
589 '(([(shift up)] . [(meta p)])
590 ([(shift down)] . [(meta n)])
591 ([(shift left)] . [(meta -)])
592 ([(shift right)] . [(meta +)])
593 ([(control shift right)] . [(meta shift +)])
594 ([(control shift left)] . [(meta shift -)]))
595 "Keys for which Org-mode and other modes compete.
596 This is an alist, cars are the default keys, second element specifies
597 the alternative to use when `org-replace-disputed-keys' is t.
599 Keys can be specified in any syntax supported by `define-key'.
600 The value of this option takes effect only at Org-mode's startup,
601 therefore you'll have to restart Emacs to apply it after changing."
602 :group 'org-startup
603 :type 'alist)
605 (defun org-key (key)
606 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
607 Or return the original if not disputed.
608 Also apply the translations defined in `org-xemacs-key-equivalents'."
609 (when org-replace-disputed-keys
610 (let* ((nkey (key-description key))
611 (x (org-find-if (lambda (x)
612 (equal (key-description (car x)) nkey))
613 org-disputed-keys)))
614 (setq key (if x (cdr x) key))))
615 (when (featurep 'xemacs)
616 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
617 key)
619 (defun org-find-if (predicate seq)
620 (catch 'exit
621 (while seq
622 (if (funcall predicate (car seq))
623 (throw 'exit (car seq))
624 (pop seq)))))
626 (defun org-defkey (keymap key def)
627 "Define a key, possibly translated, as returned by `org-key'."
628 (define-key keymap (org-key key) def))
630 (defcustom org-ellipsis nil
631 "The ellipsis to use in the Org-mode outline.
632 When nil, just use the standard three dots. When a string, use that instead,
633 When a face, use the standard 3 dots, but with the specified face.
634 The change affects only Org-mode (which will then use its own display table).
635 Changing this requires executing `M-x org-mode' in a buffer to become
636 effective."
637 :group 'org-startup
638 :type '(choice (const :tag "Default" nil)
639 (face :tag "Face" :value org-warning)
640 (string :tag "String" :value "...#")))
642 (defvar org-display-table nil
643 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
645 (defgroup org-keywords nil
646 "Keywords in Org-mode."
647 :tag "Org Keywords"
648 :group 'org)
650 (defcustom org-deadline-string "DEADLINE:"
651 "String to mark deadline entries.
652 A deadline is this string, followed by a time stamp. Should be a word,
653 terminated by a colon. You can insert a schedule keyword and
654 a timestamp with \\[org-deadline].
655 Changes become only effective after restarting Emacs."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-scheduled-string "SCHEDULED:"
660 "String to mark scheduled TODO entries.
661 A schedule is this string, followed by a time stamp. Should be a word,
662 terminated by a colon. You can insert a schedule keyword and
663 a timestamp with \\[org-schedule].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-closed-string "CLOSED:"
669 "String used as the prefix for timestamps logging closing a TODO entry."
670 :group 'org-keywords
671 :type 'string)
673 (defcustom org-clock-string "CLOCK:"
674 "String used as prefix for timestamps clocking work hours on an item."
675 :group 'org-keywords
676 :type 'string)
678 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
679 org-scheduled-string "\\|"
680 org-deadline-string "\\|"
681 org-closed-string "\\|"
682 org-clock-string "\\)")
683 "Matches a line with planning or clock info.")
685 (defcustom org-comment-string "COMMENT"
686 "Entries starting with this keyword will never be exported.
687 An entry can be toggled between COMMENT and normal with
688 \\[org-toggle-comment].
689 Changes become only effective after restarting Emacs."
690 :group 'org-keywords
691 :type 'string)
693 (defcustom org-quote-string "QUOTE"
694 "Entries starting with this keyword will be exported in fixed-width font.
695 Quoting applies only to the text in the entry following the headline, and does
696 not extend beyond the next headline, even if that is lower level.
697 An entry can be toggled between QUOTE and normal with
698 \\[org-toggle-fixed-width-section]."
699 :group 'org-keywords
700 :type 'string)
702 (defconst org-repeat-re
703 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
704 "Regular expression for specifying repeated events.
705 After a match, group 1 contains the repeat expression.")
707 (defgroup org-structure nil
708 "Options concerning the general structure of Org-mode files."
709 :tag "Org Structure"
710 :group 'org)
712 (defgroup org-reveal-location nil
713 "Options about how to make context of a location visible."
714 :tag "Org Reveal Location"
715 :group 'org-structure)
717 (defconst org-context-choice
718 '(choice
719 (const :tag "Always" t)
720 (const :tag "Never" nil)
721 (repeat :greedy t :tag "Individual contexts"
722 (cons
723 (choice :tag "Context"
724 (const agenda)
725 (const org-goto)
726 (const occur-tree)
727 (const tags-tree)
728 (const link-search)
729 (const mark-goto)
730 (const bookmark-jump)
731 (const isearch)
732 (const default))
733 (boolean))))
734 "Contexts for the reveal options.")
736 (defcustom org-show-hierarchy-above '((default . t))
737 "Non-nil means show full hierarchy when revealing a location.
738 Org-mode often shows locations in an org-mode file which might have
739 been invisible before. When this is set, the hierarchy of headings
740 above the exposed location is shown.
741 Turning this off for example for sparse trees makes them very compact.
742 Instead of t, this can also be an alist specifying this option for different
743 contexts. Valid contexts are
744 agenda when exposing an entry from the agenda
745 org-goto when using the command `org-goto' on key C-c C-j
746 occur-tree when using the command `org-occur' on key C-c /
747 tags-tree when constructing a sparse tree based on tags matches
748 link-search when exposing search matches associated with a link
749 mark-goto when exposing the jump goal of a mark
750 bookmark-jump when exposing a bookmark location
751 isearch when exiting from an incremental search
752 default default for all contexts not set explicitly"
753 :group 'org-reveal-location
754 :type org-context-choice)
756 (defcustom org-show-following-heading '((default . nil))
757 "Non-nil means show following heading when revealing a location.
758 Org-mode often shows locations in an org-mode file which might have
759 been invisible before. When this is set, the heading following the
760 match is shown.
761 Turning this off for example for sparse trees makes them very compact,
762 but makes it harder to edit the location of the match. In such a case,
763 use the command \\[org-reveal] to show more context.
764 Instead of t, this can also be an alist specifying this option for different
765 contexts. See `org-show-hierarchy-above' for valid contexts."
766 :group 'org-reveal-location
767 :type org-context-choice)
769 (defcustom org-show-siblings '((default . nil) (isearch t))
770 "Non-nil means show all sibling heading when revealing a location.
771 Org-mode often shows locations in an org-mode file which might have
772 been invisible before. When this is set, the sibling of the current entry
773 heading are all made visible. If `org-show-hierarchy-above' is t,
774 the same happens on each level of the hierarchy above the current entry.
776 By default this is on for the isearch context, off for all other contexts.
777 Turning this off for example for sparse trees makes them very compact,
778 but makes it harder to edit the location of the match. In such a case,
779 use the command \\[org-reveal] to show more context.
780 Instead of t, this can also be an alist specifying this option for different
781 contexts. See `org-show-hierarchy-above' for valid contexts."
782 :group 'org-reveal-location
783 :type org-context-choice)
785 (defcustom org-show-entry-below '((default . nil))
786 "Non-nil means show the entry below a headline when revealing a location.
787 Org-mode often shows locations in an org-mode file which might have
788 been invisible before. When this is set, the text below the headline that is
789 exposed is also shown.
791 By default this is off for all contexts.
792 Instead of t, this can also be an alist specifying this option for different
793 contexts. See `org-show-hierarchy-above' for valid contexts."
794 :group 'org-reveal-location
795 :type org-context-choice)
797 (defcustom org-indirect-buffer-display 'other-window
798 "How should indirect tree buffers be displayed?
799 This applies to indirect buffers created with the commands
800 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
801 Valid values are:
802 current-window Display in the current window
803 other-window Just display in another window.
804 dedicated-frame Create one new frame, and re-use it each time.
805 new-frame Make a new frame each time. Note that in this case
806 previously-made indirect buffers are kept, and you need to
807 kill these buffers yourself."
808 :group 'org-structure
809 :group 'org-agenda-windows
810 :type '(choice
811 (const :tag "In current window" current-window)
812 (const :tag "In current frame, other window" other-window)
813 (const :tag "Each time a new frame" new-frame)
814 (const :tag "One dedicated frame" dedicated-frame)))
816 (defcustom org-use-speed-commands nil
817 "Non-nil means activate single letter commands at beginning of a headline.
818 This may also be a function to test for appropriate locations where speed
819 commands should be active."
820 :group 'org-structure
821 :type '(choice
822 (const :tag "Never" nil)
823 (const :tag "At beginning of headline stars" t)
824 (function)))
826 (defcustom org-speed-commands-user nil
827 "Alist of additional speed commands.
828 This list will be checked before `org-speed-commands-default'
829 when the variable `org-use-speed-commands' is non-nil
830 and when the cursor is at the beginning of a headline.
831 The car if each entry is a string with a single letter, which must
832 be assigned to `self-insert-command' in the global map.
833 The cdr is either a command to be called interactively, a function
834 to be called, or a form to be evaluated.
835 An entry that is just a list with a single string will be interpreted
836 as a descriptive headline that will be added when listing the speed
837 commands in the Help buffer using the `?' speed command."
838 :group 'org-structure
839 :type '(repeat :value ("k" . ignore)
840 (choice :value ("k" . ignore)
841 (list :tag "Descriptive Headline" (string :tag "Headline"))
842 (cons :tag "Letter and Command"
843 (string :tag "Command letter")
844 (choice
845 (function)
846 (sexp))))))
848 (defgroup org-cycle nil
849 "Options concerning visibility cycling in Org-mode."
850 :tag "Org Cycle"
851 :group 'org-structure)
853 (defcustom org-cycle-skip-children-state-if-no-children t
854 "Non-nil means skip CHILDREN state in entries that don't have any."
855 :group 'org-cycle
856 :type 'boolean)
858 (defcustom org-cycle-max-level nil
859 "Maximum level which should still be subject to visibility cycling.
860 Levels higher than this will, for cycling, be treated as text, not a headline.
861 When `org-odd-levels-only' is set, a value of N in this variable actually
862 means 2N-1 stars as the limiting headline.
863 When nil, cycle all levels.
864 Note that the limiting level of cycling is also influenced by
865 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
866 `org-inlinetask-min-level' is, cycling will be limited to levels one less
867 than its value."
868 :group 'org-cycle
869 :type '(choice
870 (const :tag "No limit" nil)
871 (integer :tag "Maximum level")))
873 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
874 "Names of drawers. Drawers are not opened by cycling on the headline above.
875 Drawers only open with a TAB on the drawer line itself. A drawer looks like
876 this:
877 :DRAWERNAME:
878 .....
879 :END:
880 The drawer \"PROPERTIES\" is special for capturing properties through
881 the property API.
883 Drawers can be defined on the per-file basis with a line like:
885 #+DRAWERS: HIDDEN STATE PROPERTIES"
886 :group 'org-structure
887 :group 'org-cycle
888 :type '(repeat (string :tag "Drawer Name")))
890 (defcustom org-hide-block-startup nil
891 "Non-nil means entering Org-mode will fold all blocks.
892 This can also be set in on a per-file basis with
894 #+STARTUP: hideblocks
895 #+STARTUP: showblocks"
896 :group 'org-startup
897 :group 'org-cycle
898 :type 'boolean)
900 (defcustom org-cycle-global-at-bob nil
901 "Cycle globally if cursor is at beginning of buffer and not at a headline.
902 This makes it possible to do global cycling without having to use S-TAB or
903 \\[universal-argument] TAB. For this special case to work, the first line
904 of the buffer must not be a headline -- it may be empty or some other text.
905 When used in this way, `org-cycle-hook' is disabled temporarily to make
906 sure the cursor stays at the beginning of the buffer. When this option is
907 nil, don't do anything special at the beginning of the buffer."
908 :group 'org-cycle
909 :type 'boolean)
911 (defcustom org-cycle-level-after-item/entry-creation t
912 "Non-nil means cycle entry level or item indentation in new empty entries.
914 When the cursor is at the end of an empty headline, i.e with only stars
915 and maybe a TODO keyword, TAB will then switch the entry to become a child,
916 and then all possible ancestor states, before returning to the original state.
917 This makes data entry extremely fast: M-RET to create a new headline,
918 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
920 When the cursor is at the end of an empty plain list item, one TAB will
921 make it a subitem, two or more tabs will back up to make this an item
922 higher up in the item hierarchy."
923 :group 'org-cycle
924 :type 'boolean)
926 (defcustom org-cycle-emulate-tab t
927 "Where should `org-cycle' emulate TAB.
928 nil Never
929 white Only in completely white lines
930 whitestart Only at the beginning of lines, before the first non-white char
931 t Everywhere except in headlines
932 exc-hl-bol Everywhere except at the start of a headline
933 If TAB is used in a place where it does not emulate TAB, the current subtree
934 visibility is cycled."
935 :group 'org-cycle
936 :type '(choice (const :tag "Never" nil)
937 (const :tag "Only in completely white lines" white)
938 (const :tag "Before first char in a line" whitestart)
939 (const :tag "Everywhere except in headlines" t)
940 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
943 (defcustom org-cycle-separator-lines 2
944 "Number of empty lines needed to keep an empty line between collapsed trees.
945 If you leave an empty line between the end of a subtree and the following
946 headline, this empty line is hidden when the subtree is folded.
947 Org-mode will leave (exactly) one empty line visible if the number of
948 empty lines is equal or larger to the number given in this variable.
949 So the default 2 means at least 2 empty lines after the end of a subtree
950 are needed to produce free space between a collapsed subtree and the
951 following headline.
953 If the number is negative, and the number of empty lines is at least -N,
954 all empty lines are shown.
956 Special case: when 0, never leave empty lines in collapsed view."
957 :group 'org-cycle
958 :type 'integer)
959 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
961 (defcustom org-pre-cycle-hook nil
962 "Hook that is run before visibility cycling is happening.
963 The function(s) in this hook must accept a single argument which indicates
964 the new state that will be set right after running this hook. The
965 argument is a symbol. Before a global state change, it can have the values
966 `overview', `content', or `all'. Before a local state change, it can have
967 the values `folded', `children', or `subtree'."
968 :group 'org-cycle
969 :type 'hook)
971 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
972 org-cycle-hide-drawers
973 org-cycle-hide-inline-tasks
974 org-cycle-show-empty-lines
975 org-optimize-window-after-visibility-change)
976 "Hook that is run after `org-cycle' has changed the buffer visibility.
977 The function(s) in this hook must accept a single argument which indicates
978 the new state that was set by the most recent `org-cycle' command. The
979 argument is a symbol. After a global state change, it can have the values
980 `overview', `contents', or `all'. After a local state change, it can have
981 the values `folded', `children', or `subtree'."
982 :group 'org-cycle
983 :type 'hook)
985 (defgroup org-edit-structure nil
986 "Options concerning structure editing in Org-mode."
987 :tag "Org Edit Structure"
988 :group 'org-structure)
990 (defcustom org-odd-levels-only nil
991 "Non-nil means skip even levels and only use odd levels for the outline.
992 This has the effect that two stars are being added/taken away in
993 promotion/demotion commands. It also influences how levels are
994 handled by the exporters.
995 Changing it requires restart of `font-lock-mode' to become effective
996 for fontification also in regions already fontified.
997 You may also set this on a per-file basis by adding one of the following
998 lines to the buffer:
1000 #+STARTUP: odd
1001 #+STARTUP: oddeven"
1002 :group 'org-edit-structure
1003 :group 'org-appearance
1004 :type 'boolean)
1006 (defcustom org-adapt-indentation t
1007 "Non-nil means adapt indentation to outline node level.
1009 When this variable is set, Org assumes that you write outlines by
1010 indenting text in each node to align with the headline (after the stars).
1011 The following issues are influenced by this variable:
1013 - When this is set and the *entire* text in an entry is indented, the
1014 indentation is increased by one space in a demotion command, and
1015 decreased by one in a promotion command. If any line in the entry
1016 body starts with text at column 0, indentation is not changed at all.
1018 - Property drawers and planning information is inserted indented when
1019 this variable s set. When nil, they will not be indented.
1021 - TAB indents a line relative to context. The lines below a headline
1022 will be indented when this variable is set.
1024 Note that this is all about true indentation, by adding and removing
1025 space characters. See also `org-indent.el' which does level-dependent
1026 indentation in a virtual way, i.e. at display time in Emacs."
1027 :group 'org-edit-structure
1028 :type 'boolean)
1030 (defcustom org-special-ctrl-a/e nil
1031 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1033 When t, `C-a' will bring back the cursor to the beginning of the
1034 headline text, i.e. after the stars and after a possible TODO
1035 keyword. In an item, this will be the position after bullet and
1036 check-box, if any. When the cursor is already at that position,
1037 another `C-a' will bring it to the beginning of the line.
1039 `C-e' will jump to the end of the headline, ignoring the presence
1040 of tags in the headline. A second `C-e' will then jump to the
1041 true end of the line, after any tags. This also means that, when
1042 this variable is non-nil, `C-e' also will never jump beyond the
1043 end of the heading of a folded section, i.e. not after the
1044 ellipses.
1046 When set to the symbol `reversed', the first `C-a' or `C-e' works
1047 normally, going to the true line boundary first. Only a directly
1048 following, identical keypress will bring the cursor to the
1049 special positions.
1051 This may also be a cons cell where the behavior for `C-a' and
1052 `C-e' is set separately."
1053 :group 'org-edit-structure
1054 :type '(choice
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet and before tags first" t)
1057 (const :tag "reversed: true line boundary first" reversed)
1058 (cons :tag "Set C-a and C-e separately"
1059 (choice :tag "Special C-a"
1060 (const :tag "off" nil)
1061 (const :tag "on: after stars/bullet first" t)
1062 (const :tag "reversed: before stars/bullet first" reversed))
1063 (choice :tag "Special C-e"
1064 (const :tag "off" nil)
1065 (const :tag "on: before tags first" t)
1066 (const :tag "reversed: after tags first" reversed)))))
1067 (if (fboundp 'defvaralias)
1068 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1070 (defcustom org-special-ctrl-k nil
1071 "Non-nil means `C-k' will behave specially in headlines.
1072 When nil, `C-k' will call the default `kill-line' command.
1073 When t, the following will happen while the cursor is in the headline:
1075 - When the cursor is at the beginning of a headline, kill the entire
1076 line and possible the folded subtree below the line.
1077 - When in the middle of the headline text, kill the headline up to the tags.
1078 - When after the headline text, kill the tags."
1079 :group 'org-edit-structure
1080 :type 'boolean)
1082 (defcustom org-ctrl-k-protect-subtree nil
1083 "Non-nil means, do not delete a hidden subtree with C-k.
1084 When set to the symbol `error', simply throw an error when C-k is
1085 used to kill (part-of) a headline that has hidden text behind it.
1086 Any other non-nil value will result in a query to the user, if it is
1087 OK to kill that hidden subtree. When nil, kill without remorse."
1088 :group 'org-edit-structure
1089 :version "24.1"
1090 :type '(choice
1091 (const :tag "Do not protect hidden subtrees" nil)
1092 (const :tag "Protect hidden subtrees with a security query" t)
1093 (const :tag "Never kill a hidden subtree with C-k" error)))
1095 (defcustom org-catch-invisible-edits nil
1096 "Check if in invisible region before inserting or deleting a character.
1097 Valid values are:
1099 nil Do not check, so just do invisible edits.
1100 error Throw an error and do nothing.
1101 show Make point visible, and do the requested edit.
1102 show-and-error Make point visible, then throw an error and abort the edit.
1103 smart Make point visible, and do insertion/deletion if it is
1104 adjacent to visible text and the change feels predictable.
1105 Never delete a previously invisible character or add in the
1106 middle or right after an invisible region. Basically, this
1107 allows insertion and backward-delete right before ellipses.
1108 FIXME: maybe in this case we should not even show?"
1109 :group 'org-edit-structure
1110 :version "24.1"
1111 :type '(choice
1112 (const :tag "Do not check" nil)
1113 (const :tag "Throw error when trying to edit" error)
1114 (const :tag "Unhide, but do not do the edit" show-and-error)
1115 (const :tag "Show invisible part and do the edit" show)
1116 (const :tag "Be smart and do the right thing" smart)))
1118 (defcustom org-yank-folded-subtrees t
1119 "Non-nil means when yanking subtrees, fold them.
1120 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1121 it starts with a heading and all other headings in it are either children
1122 or siblings, then fold all the subtrees. However, do this only if no
1123 text after the yank would be swallowed into a folded tree by this action."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-yank-adjusted-subtrees nil
1128 "Non-nil means when yanking subtrees, adjust the level.
1129 With this setting, `org-paste-subtree' is used to insert the subtree, see
1130 this function for details."
1131 :group 'org-edit-structure
1132 :type 'boolean)
1134 (defcustom org-M-RET-may-split-line '((default . t))
1135 "Non-nil means M-RET will split the line at the cursor position.
1136 When nil, it will go to the end of the line before making a
1137 new line.
1138 You may also set this option in a different way for different
1139 contexts. Valid contexts are:
1141 headline when creating a new headline
1142 item when creating a new item
1143 table in a table field
1144 default the value to be used for all contexts not explicitly
1145 customized"
1146 :group 'org-structure
1147 :group 'org-table
1148 :type '(choice
1149 (const :tag "Always" t)
1150 (const :tag "Never" nil)
1151 (repeat :greedy t :tag "Individual contexts"
1152 (cons
1153 (choice :tag "Context"
1154 (const headline)
1155 (const item)
1156 (const table)
1157 (const default))
1158 (boolean)))))
1161 (defcustom org-insert-heading-respect-content nil
1162 "Non-nil means insert new headings after the current subtree.
1163 When nil, the new heading is created directly after the current line.
1164 The commands \\[org-insert-heading-respect-content] and
1165 \\[org-insert-todo-heading-respect-content] turn this variable on
1166 for the duration of the command."
1167 :group 'org-structure
1168 :type 'boolean)
1170 (defcustom org-blank-before-new-entry '((heading . auto)
1171 (plain-list-item . auto))
1172 "Should `org-insert-heading' leave a blank line before new heading/item?
1173 The value is an alist, with `heading' and `plain-list-item' as CAR,
1174 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1175 which case Org will look at the surrounding headings/items and try to
1176 make an intelligent decision whether to insert a blank line or not.
1178 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1179 set, the setting here is ignored and no empty line is inserted, to avoid
1180 breaking the list structure."
1181 :group 'org-edit-structure
1182 :type '(list
1183 (cons (const heading)
1184 (choice (const :tag "Never" nil)
1185 (const :tag "Always" t)
1186 (const :tag "Auto" auto)))
1187 (cons (const plain-list-item)
1188 (choice (const :tag "Never" nil)
1189 (const :tag "Always" t)
1190 (const :tag "Auto" auto)))))
1192 (defcustom org-insert-heading-hook nil
1193 "Hook being run after inserting a new heading."
1194 :group 'org-edit-structure
1195 :type 'hook)
1197 (defcustom org-enable-fixed-width-editor t
1198 "Non-nil means lines starting with \":\" are treated as fixed-width.
1199 This currently only means they are never auto-wrapped.
1200 When nil, such lines will be treated like ordinary lines.
1201 See also the QUOTE keyword."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defcustom org-goto-auto-isearch t
1206 "Non-nil means typing characters in `org-goto' starts incremental search."
1207 :group 'org-edit-structure
1208 :type 'boolean)
1210 (defgroup org-sparse-trees nil
1211 "Options concerning sparse trees in Org-mode."
1212 :tag "Org Sparse Trees"
1213 :group 'org-structure)
1215 (defcustom org-highlight-sparse-tree-matches t
1216 "Non-nil means highlight all matches that define a sparse tree.
1217 The highlights will automatically disappear the next time the buffer is
1218 changed by an edit command."
1219 :group 'org-sparse-trees
1220 :type 'boolean)
1222 (defcustom org-remove-highlights-with-change t
1223 "Non-nil means any change to the buffer will remove temporary highlights.
1224 Such highlights are created by `org-occur' and `org-clock-display'.
1225 When nil, `C-c C-c needs to be used to get rid of the highlights.
1226 The highlights created by `org-preview-latex-fragment' always need
1227 `C-c C-c' to be removed."
1228 :group 'org-sparse-trees
1229 :group 'org-time
1230 :type 'boolean)
1233 (defcustom org-occur-hook '(org-first-headline-recenter)
1234 "Hook that is run after `org-occur' has constructed a sparse tree.
1235 This can be used to recenter the window to show as much of the structure
1236 as possible."
1237 :group 'org-sparse-trees
1238 :type 'hook)
1240 (defgroup org-imenu-and-speedbar nil
1241 "Options concerning imenu and speedbar in Org-mode."
1242 :tag "Org Imenu and Speedbar"
1243 :group 'org-structure)
1245 (defcustom org-imenu-depth 2
1246 "The maximum level for Imenu access to Org-mode headlines.
1247 This also applied for speedbar access."
1248 :group 'org-imenu-and-speedbar
1249 :type 'integer)
1251 (defgroup org-table nil
1252 "Options concerning tables in Org-mode."
1253 :tag "Org Table"
1254 :group 'org)
1256 (defcustom org-enable-table-editor 'optimized
1257 "Non-nil means lines starting with \"|\" are handled by the table editor.
1258 When nil, such lines will be treated like ordinary lines.
1260 When equal to the symbol `optimized', the table editor will be optimized to
1261 do the following:
1262 - Automatic overwrite mode in front of whitespace in table fields.
1263 This makes the structure of the table stay in tact as long as the edited
1264 field does not exceed the column width.
1265 - Minimize the number of realigns. Normally, the table is aligned each time
1266 TAB or RET are pressed to move to another field. With optimization this
1267 happens only if changes to a field might have changed the column width.
1268 Optimization requires replacing the functions `self-insert-command',
1269 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1270 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1271 very good at guessing when a re-align will be necessary, but you can always
1272 force one with \\[org-ctrl-c-ctrl-c].
1274 If you would like to use the optimized version in Org-mode, but the
1275 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1277 This variable can be used to turn on and off the table editor during a session,
1278 but in order to toggle optimization, a restart is required.
1280 See also the variable `org-table-auto-blank-field'."
1281 :group 'org-table
1282 :type '(choice
1283 (const :tag "off" nil)
1284 (const :tag "on" t)
1285 (const :tag "on, optimized" optimized)))
1287 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1288 (version<= emacs-version "24.1"))
1289 "Non-nil means cluster self-insert commands for undo when possible.
1290 If this is set, then, like in the Emacs command loop, 20 consecutive
1291 characters will be undone together.
1292 This is configurable, because there is some impact on typing performance."
1293 :group 'org-table
1294 :type 'boolean)
1296 (defcustom org-table-tab-recognizes-table.el t
1297 "Non-nil means TAB will automatically notice a table.el table.
1298 When it sees such a table, it moves point into it and - if necessary -
1299 calls `table-recognize-table'."
1300 :group 'org-table-editing
1301 :type 'boolean)
1303 (defgroup org-link nil
1304 "Options concerning links in Org-mode."
1305 :tag "Org Link"
1306 :group 'org)
1308 (defvar org-link-abbrev-alist-local nil
1309 "Buffer-local version of `org-link-abbrev-alist', which see.
1310 The value of this is taken from the #+LINK lines.")
1311 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1313 (defcustom org-link-abbrev-alist nil
1314 "Alist of link abbreviations.
1315 The car of each element is a string, to be replaced at the start of a link.
1316 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1317 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1319 [[linkkey:tag][description]]
1321 The 'linkkey' must be a word word, starting with a letter, followed
1322 by letters, numbers, '-' or '_'.
1324 If REPLACE is a string, the tag will simply be appended to create the link.
1325 If the string contains \"%s\", the tag will be inserted there. If the string
1326 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1327 at that point (see the function `url-hexify-string'). If the string contains
1328 the specifier \"%(my-function)\", then the custom function `my-function' will
1329 be invoked: this function takes the tag as its only argument and must return
1330 a string.
1332 REPLACE may also be a function that will be called with the tag as the
1333 only argument to create the link, which should be returned as a string.
1335 See the manual for examples."
1336 :group 'org-link
1337 :type '(repeat
1338 (cons
1339 (string :tag "Protocol")
1340 (choice
1341 (string :tag "Format")
1342 (function)))))
1344 (defcustom org-descriptive-links t
1345 "Non-nil means Org will display descriptive links.
1346 E.g. [[http://orgmode.org][Org website]] will be displayed as
1347 \"Org Website\", hiding the link itself and just displaying its
1348 description. When set to `nil', Org will display the full links
1349 literally.
1351 You can interactively set the value of this variable by calling
1352 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1353 :group 'org-link
1354 :type 'boolean)
1356 (defcustom org-link-file-path-type 'adaptive
1357 "How the path name in file links should be stored.
1358 Valid values are:
1360 relative Relative to the current directory, i.e. the directory of the file
1361 into which the link is being inserted.
1362 absolute Absolute path, if possible with ~ for home directory.
1363 noabbrev Absolute path, no abbreviation of home directory.
1364 adaptive Use relative path for files in the current directory and sub-
1365 directories of it. For other files, use an absolute path."
1366 :group 'org-link
1367 :type '(choice
1368 (const relative)
1369 (const absolute)
1370 (const noabbrev)
1371 (const adaptive)))
1373 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1374 "Types of links that should be activated in Org-mode files.
1375 This is a list of symbols, each leading to the activation of a certain link
1376 type. In principle, it does not hurt to turn on most link types - there may
1377 be a small gain when turning off unused link types. The types are:
1379 bracket The recommended [[link][description]] or [[link]] links with hiding.
1380 angle Links in angular brackets that may contain whitespace like
1381 <bbdb:Carsten Dominik>.
1382 plain Plain links in normal text, no whitespace, like http://google.com.
1383 radio Text that is matched by a radio target, see manual for details.
1384 tag Tag settings in a headline (link to tag search).
1385 date Time stamps (link to calendar).
1386 footnote Footnote labels.
1388 Changing this variable requires a restart of Emacs to become effective."
1389 :group 'org-link
1390 :type '(set :greedy t
1391 (const :tag "Double bracket links" bracket)
1392 (const :tag "Angular bracket links" angle)
1393 (const :tag "Plain text links" plain)
1394 (const :tag "Radio target matches" radio)
1395 (const :tag "Tags" tag)
1396 (const :tag "Timestamps" date)
1397 (const :tag "Footnotes" footnote)))
1399 (defcustom org-make-link-description-function nil
1400 "Function to use for generating link descriptions from links.
1401 When nil, the link location will be used. This function must take
1402 two parameters: the first one is the link, the second one is the
1403 description generated by `org-insert-link'. The function should
1404 return the description to use."
1405 :group 'org-link
1406 :type 'function)
1408 (defgroup org-link-store nil
1409 "Options concerning storing links in Org-mode."
1410 :tag "Org Store Link"
1411 :group 'org-link)
1413 (defcustom org-url-hexify-p t
1414 "When non-nil, hexify URL when creating a link."
1415 :type 'boolean
1416 :version "24.3"
1417 :group 'org-link-store)
1419 (defcustom org-email-link-description-format "Email %c: %.30s"
1420 "Format of the description part of a link to an email or usenet message.
1421 The following %-escapes will be replaced by corresponding information:
1423 %F full \"From\" field
1424 %f name, taken from \"From\" field, address if no name
1425 %T full \"To\" field
1426 %t first name in \"To\" field, address if no name
1427 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1428 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1429 %s subject
1430 %d date
1431 %m message-id.
1433 You may use normal field width specification between the % and the letter.
1434 This is for example useful to limit the length of the subject.
1436 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1437 :group 'org-link-store
1438 :type 'string)
1440 (defcustom org-from-is-user-regexp
1441 (let (r1 r2)
1442 (when (and user-mail-address (not (string= user-mail-address "")))
1443 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1444 (when (and user-full-name (not (string= user-full-name "")))
1445 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1446 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1447 "Regexp matched against the \"From:\" header of an email or usenet message.
1448 It should match if the message is from the user him/herself."
1449 :group 'org-link-store
1450 :type 'regexp)
1452 (defcustom org-context-in-file-links t
1453 "Non-nil means file links from `org-store-link' contain context.
1454 A search string will be added to the file name with :: as separator and
1455 used to find the context when the link is activated by the command
1456 `org-open-at-point'. When this option is t, the entire active region
1457 will be placed in the search string of the file link. If set to a
1458 positive integer, only the first n lines of context will be stored.
1460 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1461 negates this setting for the duration of the command."
1462 :group 'org-link-store
1463 :type '(choice boolean integer))
1465 (defcustom org-keep-stored-link-after-insertion nil
1466 "Non-nil means keep link in list for entire session.
1468 The command `org-store-link' adds a link pointing to the current
1469 location to an internal list. These links accumulate during a session.
1470 The command `org-insert-link' can be used to insert links into any
1471 Org-mode file (offering completion for all stored links). When this
1472 option is nil, every link which has been inserted once using \\[org-insert-link]
1473 will be removed from the list, to make completing the unused links
1474 more efficient."
1475 :group 'org-link-store
1476 :type 'boolean)
1478 (defgroup org-link-follow nil
1479 "Options concerning following links in Org-mode."
1480 :tag "Org Follow Link"
1481 :group 'org-link)
1483 (defcustom org-link-translation-function nil
1484 "Function to translate links with different syntax to Org syntax.
1485 This can be used to translate links created for example by the Planner
1486 or emacs-wiki packages to Org syntax.
1487 The function must accept two parameters, a TYPE containing the link
1488 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1489 which is everything after the link protocol. It should return a cons
1490 with possibly modified values of type and path.
1491 Org contains a function for this, so if you set this variable to
1492 `org-translate-link-from-planner', you should be able follow many
1493 links created by planner."
1494 :group 'org-link-follow
1495 :type 'function)
1497 (defcustom org-follow-link-hook nil
1498 "Hook that is run after a link has been followed."
1499 :group 'org-link-follow
1500 :type 'hook)
1502 (defcustom org-tab-follows-link nil
1503 "Non-nil means on links TAB will follow the link.
1504 Needs to be set before org.el is loaded.
1505 This really should not be used, it does not make sense, and the
1506 implementation is bad."
1507 :group 'org-link-follow
1508 :type 'boolean)
1510 (defcustom org-return-follows-link nil
1511 "Non-nil means on links RET will follow the link."
1512 :group 'org-link-follow
1513 :type 'boolean)
1515 (defcustom org-mouse-1-follows-link
1516 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1517 "Non-nil means mouse-1 on a link will follow the link.
1518 A longer mouse click will still set point. Does not work on XEmacs.
1519 Needs to be set before org.el is loaded."
1520 :group 'org-link-follow
1521 :type 'boolean)
1523 (defcustom org-mark-ring-length 4
1524 "Number of different positions to be recorded in the ring.
1525 Changing this requires a restart of Emacs to work correctly."
1526 :group 'org-link-follow
1527 :type 'integer)
1529 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1530 "Non-nil means internal links in Org files must exactly match a headline.
1531 When nil, the link search tries to match a phrase with all words
1532 in the search text."
1533 :group 'org-link-follow
1534 :version "24.1"
1535 :type '(choice
1536 (const :tag "Use fuzzy text search" nil)
1537 (const :tag "Match only exact headline" t)
1538 (const :tag "Match exact headline or query to create it"
1539 query-to-create)))
1541 (defcustom org-link-frame-setup
1542 '((vm . vm-visit-folder-other-frame)
1543 (vm-imap . vm-visit-imap-folder-other-frame)
1544 (gnus . org-gnus-no-new-news)
1545 (file . find-file-other-window)
1546 (wl . wl-other-frame))
1547 "Setup the frame configuration for following links.
1548 When following a link with Emacs, it may often be useful to display
1549 this link in another window or frame. This variable can be used to
1550 set this up for the different types of links.
1551 For VM, use any of
1552 `vm-visit-folder'
1553 `vm-visit-folder-other-window'
1554 `vm-visit-folder-other-frame'
1555 For Gnus, use any of
1556 `gnus'
1557 `gnus-other-frame'
1558 `org-gnus-no-new-news'
1559 For FILE, use any of
1560 `find-file'
1561 `find-file-other-window'
1562 `find-file-other-frame'
1563 For Wanderlust use any of
1564 `wl'
1565 `wl-other-frame'
1566 For the calendar, use the variable `calendar-setup'.
1567 For BBDB, it is currently only possible to display the matches in
1568 another window."
1569 :group 'org-link-follow
1570 :type '(list
1571 (cons (const vm)
1572 (choice
1573 (const vm-visit-folder)
1574 (const vm-visit-folder-other-window)
1575 (const vm-visit-folder-other-frame)))
1576 (cons (const gnus)
1577 (choice
1578 (const gnus)
1579 (const gnus-other-frame)
1580 (const org-gnus-no-new-news)))
1581 (cons (const file)
1582 (choice
1583 (const find-file)
1584 (const find-file-other-window)
1585 (const find-file-other-frame)))
1586 (cons (const wl)
1587 (choice
1588 (const wl)
1589 (const wl-other-frame)))))
1591 (defcustom org-display-internal-link-with-indirect-buffer nil
1592 "Non-nil means use indirect buffer to display infile links.
1593 Activating internal links (from one location in a file to another location
1594 in the same file) normally just jumps to the location. When the link is
1595 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1596 is displayed in
1597 another window. When this option is set, the other window actually displays
1598 an indirect buffer clone of the current buffer, to avoid any visibility
1599 changes to the current buffer."
1600 :group 'org-link-follow
1601 :type 'boolean)
1603 (defcustom org-open-non-existing-files nil
1604 "Non-nil means `org-open-file' will open non-existing files.
1605 When nil, an error will be generated.
1606 This variable applies only to external applications because they
1607 might choke on non-existing files. If the link is to a file that
1608 will be opened in Emacs, the variable is ignored."
1609 :group 'org-link-follow
1610 :type 'boolean)
1612 (defcustom org-open-directory-means-index-dot-org nil
1613 "Non-nil means a link to a directory really means to index.org.
1614 When nil, following a directory link will run dired or open a finder/explorer
1615 window on that directory."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1620 "Function and arguments to call for following mailto links.
1621 This is a list with the first element being a Lisp function, and the
1622 remaining elements being arguments to the function. In string arguments,
1623 %a will be replaced by the address, and %s will be replaced by the subject
1624 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1625 :group 'org-link-follow
1626 :type '(choice
1627 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1628 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1629 (const :tag "message-mail" (message-mail "%a" "%s"))
1630 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1632 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1633 "Non-nil means ask for confirmation before executing shell links.
1634 Shell links can be dangerous: just think about a link
1636 [[shell:rm -rf ~/*][Google Search]]
1638 This link would show up in your Org-mode document as \"Google Search\",
1639 but really it would remove your entire home directory.
1640 Therefore we advise against setting this variable to nil.
1641 Just change it to `y-or-n-p' if you want to confirm with a
1642 single keystroke rather than having to type \"yes\"."
1643 :group 'org-link-follow
1644 :type '(choice
1645 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1646 (const :tag "with y-or-n (faster)" y-or-n-p)
1647 (const :tag "no confirmation (dangerous)" nil)))
1648 (put 'org-confirm-shell-link-function
1649 'safe-local-variable
1650 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1652 (defcustom org-confirm-shell-link-not-regexp ""
1653 "A regexp to skip confirmation for shell links."
1654 :group 'org-link-follow
1655 :version "24.1"
1656 :type 'regexp)
1658 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1660 Elisp links can be dangerous: just think about a link
1662 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-elisp-link-not-regexp ""
1679 "A regexp to skip confirmation for Elisp links."
1680 :group 'org-link-follow
1681 :version "24.1"
1682 :type 'regexp)
1684 (defconst org-file-apps-defaults-gnu
1685 '((remote . emacs)
1686 (system . mailcap)
1687 (t . mailcap))
1688 "Default file applications on a UNIX or GNU/Linux system.
1689 See `org-file-apps'.")
1691 (defconst org-file-apps-defaults-macosx
1692 '((remote . emacs)
1693 (t . "open %s")
1694 (system . "open %s")
1695 ("ps.gz" . "gv %s")
1696 ("eps.gz" . "gv %s")
1697 ("dvi" . "xdvi %s")
1698 ("fig" . "xfig %s"))
1699 "Default file applications on a MacOS X system.
1700 The system \"open\" is known as a default, but we use X11 applications
1701 for some files for which the OS does not have a good default.
1702 See `org-file-apps'.")
1704 (defconst org-file-apps-defaults-windowsnt
1705 (list
1706 '(remote . emacs)
1707 (cons t
1708 (list (if (featurep 'xemacs)
1709 'mswindows-shell-execute
1710 'w32-shell-execute)
1711 "open" 'file))
1712 (cons 'system
1713 (list (if (featurep 'xemacs)
1714 'mswindows-shell-execute
1715 'w32-shell-execute)
1716 "open" 'file)))
1717 "Default file applications on a Windows NT system.
1718 The system \"open\" is used for most files.
1719 See `org-file-apps'.")
1721 (defcustom org-file-apps
1723 (auto-mode . emacs)
1724 ("\\.mm\\'" . default)
1725 ("\\.x?html?\\'" . default)
1726 ("\\.pdf\\'" . default)
1728 "External applications for opening `file:path' items in a document.
1729 Org-mode uses system defaults for different file types, but
1730 you can use this variable to set the application for a given file
1731 extension. The entries in this list are cons cells where the car identifies
1732 files and the cdr the corresponding command. Possible values for the
1733 file identifier are
1734 \"string\" A string as a file identifier can be interpreted in different
1735 ways, depending on its contents:
1737 - Alphanumeric characters only:
1738 Match links with this file extension.
1739 Example: (\"pdf\" . \"evince %s\")
1740 to open PDFs with evince.
1742 - Regular expression: Match links where the
1743 filename matches the regexp. If you want to
1744 use groups here, use shy groups.
1746 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1747 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1748 to open *.html and *.xhtml with firefox.
1750 - Regular expression which contains (non-shy) groups:
1751 Match links where the whole link, including \"::\", and
1752 anything after that, matches the regexp.
1753 In a custom command string, %1, %2, etc. are replaced with
1754 the parts of the link that were matched by the groups.
1755 For backwards compatibility, if a command string is given
1756 that does not use any of the group matches, this case is
1757 handled identically to the second one (i.e. match against
1758 file name only).
1759 In a custom lisp form, you can access the group matches with
1760 (match-string n link).
1762 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1763 to open [[file:document.pdf::5]] with evince at page 5.
1765 `directory' Matches a directory
1766 `remote' Matches a remote file, accessible through tramp or efs.
1767 Remote files most likely should be visited through Emacs
1768 because external applications cannot handle such paths.
1769 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1770 so all files Emacs knows how to handle. Using this with
1771 command `emacs' will open most files in Emacs. Beware that this
1772 will also open html files inside Emacs, unless you add
1773 (\"html\" . default) to the list as well.
1774 t Default for files not matched by any of the other options.
1775 `system' The system command to open files, like `open' on Windows
1776 and Mac OS X, and mailcap under GNU/Linux. This is the command
1777 that will be selected if you call `C-c C-o' with a double
1778 \\[universal-argument] \\[universal-argument] prefix.
1780 Possible values for the command are:
1781 `emacs' The file will be visited by the current Emacs process.
1782 `default' Use the default application for this file type, which is the
1783 association for t in the list, most likely in the system-specific
1784 part.
1785 This can be used to overrule an unwanted setting in the
1786 system-specific variable.
1787 `system' Use the system command for opening files, like \"open\".
1788 This command is specified by the entry whose car is `system'.
1789 Most likely, the system-specific version of this variable
1790 does define this command, but you can overrule/replace it
1791 here.
1792 string A command to be executed by a shell; %s will be replaced
1793 by the path to the file.
1794 sexp A Lisp form which will be evaluated. The file path will
1795 be available in the Lisp variable `file'.
1796 For more examples, see the system specific constants
1797 `org-file-apps-defaults-macosx'
1798 `org-file-apps-defaults-windowsnt'
1799 `org-file-apps-defaults-gnu'."
1800 :group 'org-link-follow
1801 :type '(repeat
1802 (cons (choice :value ""
1803 (string :tag "Extension")
1804 (const :tag "System command to open files" system)
1805 (const :tag "Default for unrecognized files" t)
1806 (const :tag "Remote file" remote)
1807 (const :tag "Links to a directory" directory)
1808 (const :tag "Any files that have Emacs modes"
1809 auto-mode))
1810 (choice :value ""
1811 (const :tag "Visit with Emacs" emacs)
1812 (const :tag "Use default" default)
1813 (const :tag "Use the system command" system)
1814 (string :tag "Command")
1815 (sexp :tag "Lisp form")))))
1817 (defcustom org-doi-server-url "http://dx.doi.org/"
1818 "The URL of the DOI server."
1819 :type 'string
1820 :version "24.3"
1821 :group 'org-link-follow)
1823 (defgroup org-refile nil
1824 "Options concerning refiling entries in Org-mode."
1825 :tag "Org Refile"
1826 :group 'org)
1828 (defcustom org-directory "~/org"
1829 "Directory with org files.
1830 This is just a default location to look for Org files. There is no need
1831 at all to put your files into this directory. It is only used in the
1832 following situations:
1834 1. When a capture template specifies a target file that is not an
1835 absolute path. The path will then be interpreted relative to
1836 `org-directory'
1837 2. When a capture note is filed away in an interactive way (when exiting the
1838 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1839 with `org-directory' as the default path."
1840 :group 'org-refile
1841 :group 'org-remember
1842 :group 'org-capture
1843 :type 'directory)
1845 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1846 "Default target for storing notes.
1847 Used as a fall back file for org-remember.el and org-capture.el, for
1848 templates that do not specify a target file."
1849 :group 'org-refile
1850 :group 'org-remember
1851 :group 'org-capture
1852 :type '(choice
1853 (const :tag "Default from remember-data-file" nil)
1854 file))
1856 (defcustom org-goto-interface 'outline
1857 "The default interface to be used for `org-goto'.
1858 Allowed values are:
1859 outline The interface shows an outline of the relevant file
1860 and the correct heading is found by moving through
1861 the outline or by searching with incremental search.
1862 outline-path-completion Headlines in the current buffer are offered via
1863 completion. This is the interface also used by
1864 the refile command."
1865 :group 'org-refile
1866 :type '(choice
1867 (const :tag "Outline" outline)
1868 (const :tag "Outline-path-completion" outline-path-completion)))
1870 (defcustom org-goto-max-level 5
1871 "Maximum target level when running `org-goto' with refile interface."
1872 :group 'org-refile
1873 :type 'integer)
1875 (defcustom org-reverse-note-order nil
1876 "Non-nil means store new notes at the beginning of a file or entry.
1877 When nil, new notes will be filed to the end of a file or entry.
1878 This can also be a list with cons cells of regular expressions that
1879 are matched against file names, and values."
1880 :group 'org-remember
1881 :group 'org-capture
1882 :group 'org-refile
1883 :type '(choice
1884 (const :tag "Reverse always" t)
1885 (const :tag "Reverse never" nil)
1886 (repeat :tag "By file name regexp"
1887 (cons regexp boolean))))
1889 (defcustom org-log-refile nil
1890 "Information to record when a task is refiled.
1892 Possible values are:
1894 nil Don't add anything
1895 time Add a time stamp to the task
1896 note Prompt for a note and add it with template `org-log-note-headings'
1898 This option can also be set with on a per-file-basis with
1900 #+STARTUP: nologrefile
1901 #+STARTUP: logrefile
1902 #+STARTUP: lognoterefile
1904 You can have local logging settings for a subtree by setting the LOGGING
1905 property to one or more of these keywords.
1907 When bulk-refiling from the agenda, the value `note' is forbidden and
1908 will temporarily be changed to `time'."
1909 :group 'org-refile
1910 :group 'org-progress
1911 :version "24.1"
1912 :type '(choice
1913 (const :tag "No logging" nil)
1914 (const :tag "Record timestamp" time)
1915 (const :tag "Record timestamp with note." note)))
1917 (defcustom org-refile-targets nil
1918 "Targets for refiling entries with \\[org-refile].
1919 This is a list of cons cells. Each cell contains:
1920 - a specification of the files to be considered, either a list of files,
1921 or a symbol whose function or variable value will be used to retrieve
1922 a file name or a list of file names. If you use `org-agenda-files' for
1923 that, all agenda files will be scanned for targets. Nil means consider
1924 headings in the current buffer.
1925 - A specification of how to find candidate refile targets. This may be
1926 any of:
1927 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1928 This tag has to be present in all target headlines, inheritance will
1929 not be considered.
1930 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1931 todo keyword.
1932 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1933 headlines that are refiling targets.
1934 - a cons cell (:level . N). Any headline of level N is considered a target.
1935 Note that, when `org-odd-levels-only' is set, level corresponds to
1936 order in hierarchy, not to the number of stars.
1937 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1938 Note that, when `org-odd-levels-only' is set, level corresponds to
1939 order in hierarchy, not to the number of stars.
1941 Each element of this list generates a set of possible targets.
1942 The union of these sets is presented (with completion) to
1943 the user by `org-refile'.
1945 You can set the variable `org-refile-target-verify-function' to a function
1946 to verify each headline found by the simple criteria above.
1948 When this variable is nil, all top-level headlines in the current buffer
1949 are used, equivalent to the value `((nil . (:level . 1))'."
1950 :group 'org-refile
1951 :type '(repeat
1952 (cons
1953 (choice :value org-agenda-files
1954 (const :tag "All agenda files" org-agenda-files)
1955 (const :tag "Current buffer" nil)
1956 (function) (variable) (file))
1957 (choice :tag "Identify target headline by"
1958 (cons :tag "Specific tag" (const :value :tag) (string))
1959 (cons :tag "TODO keyword" (const :value :todo) (string))
1960 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1961 (cons :tag "Level number" (const :value :level) (integer))
1962 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1964 (defcustom org-refile-target-verify-function nil
1965 "Function to verify if the headline at point should be a refile target.
1966 The function will be called without arguments, with point at the
1967 beginning of the headline. It should return t and leave point
1968 where it is if the headline is a valid target for refiling.
1970 If the target should not be selected, the function must return nil.
1971 In addition to this, it may move point to a place from where the search
1972 should be continued. For example, the function may decide that the entire
1973 subtree of the current entry should be excluded and move point to the end
1974 of the subtree."
1975 :group 'org-refile
1976 :type 'function)
1978 (defcustom org-refile-use-cache nil
1979 "Non-nil means cache refile targets to speed up the process.
1980 The cache for a particular file will be updated automatically when
1981 the buffer has been killed, or when any of the marker used for flagging
1982 refile targets no longer points at a live buffer.
1983 If you have added new entries to a buffer that might themselves be targets,
1984 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1985 find that easier, `C-u C-u C-u C-c C-w'."
1986 :group 'org-refile
1987 :version "24.1"
1988 :type 'boolean)
1990 (defcustom org-refile-use-outline-path nil
1991 "Non-nil means provide refile targets as paths.
1992 So a level 3 headline will be available as level1/level2/level3.
1994 When the value is `file', also include the file name (without directory)
1995 into the path. In this case, you can also stop the completion after
1996 the file name, to get entries inserted as top level in the file.
1998 When `full-file-path', include the full file path."
1999 :group 'org-refile
2000 :type '(choice
2001 (const :tag "Not" nil)
2002 (const :tag "Yes" t)
2003 (const :tag "Start with file name" file)
2004 (const :tag "Start with full file path" full-file-path)))
2006 (defcustom org-outline-path-complete-in-steps t
2007 "Non-nil means complete the outline path in hierarchical steps.
2008 When Org-mode uses the refile interface to select an outline path
2009 \(see variable `org-refile-use-outline-path'), the completion of
2010 the path can be done is a single go, or if can be done in steps down
2011 the headline hierarchy. Going in steps is probably the best if you
2012 do not use a special completion package like `ido' or `icicles'.
2013 However, when using these packages, going in one step can be very
2014 fast, while still showing the whole path to the entry."
2015 :group 'org-refile
2016 :type 'boolean)
2018 (defcustom org-refile-allow-creating-parent-nodes nil
2019 "Non-nil means allow to create new nodes as refile targets.
2020 New nodes are then created by adding \"/new node name\" to the completion
2021 of an existing node. When the value of this variable is `confirm',
2022 new node creation must be confirmed by the user (recommended)
2023 When nil, the completion must match an existing entry.
2025 Note that, if the new heading is not seen by the criteria
2026 listed in `org-refile-targets', multiple instances of the same
2027 heading would be created by trying again to file under the new
2028 heading."
2029 :group 'org-refile
2030 :type '(choice
2031 (const :tag "Never" nil)
2032 (const :tag "Always" t)
2033 (const :tag "Prompt for confirmation" confirm)))
2035 (defcustom org-refile-active-region-within-subtree nil
2036 "Non-nil means also refile active region within a subtree.
2038 By default `org-refile' doesn't allow refiling regions if they
2039 don't contain a set of subtrees, but it might be convenient to
2040 do so sometimes: in that case, the first line of the region is
2041 converted to a headline before refiling."
2042 :group 'org-refile
2043 :version "24.1"
2044 :type 'boolean)
2046 (defgroup org-todo nil
2047 "Options concerning TODO items in Org-mode."
2048 :tag "Org TODO"
2049 :group 'org)
2051 (defgroup org-progress nil
2052 "Options concerning Progress logging in Org-mode."
2053 :tag "Org Progress"
2054 :group 'org-time)
2056 (defvar org-todo-interpretation-widgets
2057 '((:tag "Sequence (cycling hits every state)" sequence)
2058 (:tag "Type (cycling directly to DONE)" type))
2059 "The available interpretation symbols for customizing `org-todo-keywords'.
2060 Interested libraries should add to this list.")
2062 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2063 "List of TODO entry keyword sequences and their interpretation.
2064 \\<org-mode-map>This is a list of sequences.
2066 Each sequence starts with a symbol, either `sequence' or `type',
2067 indicating if the keywords should be interpreted as a sequence of
2068 action steps, or as different types of TODO items. The first
2069 keywords are states requiring action - these states will select a headline
2070 for inclusion into the global TODO list Org-mode produces. If one of
2071 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2072 signify that no further action is necessary. If \"|\" is not found,
2073 the last keyword is treated as the only DONE state of the sequence.
2075 The command \\[org-todo] cycles an entry through these states, and one
2076 additional state where no keyword is present. For details about this
2077 cycling, see the manual.
2079 TODO keywords and interpretation can also be set on a per-file basis with
2080 the special #+SEQ_TODO and #+TYP_TODO lines.
2082 Each keyword can optionally specify a character for fast state selection
2083 \(in combination with the variable `org-use-fast-todo-selection')
2084 and specifiers for state change logging, using the same syntax that
2085 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2086 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2087 indicates to record a time stamp each time this state is selected.
2089 Each keyword may also specify if a timestamp or a note should be
2090 recorded when entering or leaving the state, by adding additional
2091 characters in the parenthesis after the keyword. This looks like this:
2092 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2093 record only the time of the state change. With X and Y being either
2094 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2095 Y when leaving the state if and only if the *target* state does not
2096 define X. You may omit any of the fast-selection key or X or /Y,
2097 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2099 For backward compatibility, this variable may also be just a list
2100 of keywords. In this case the interpretation (sequence or type) will be
2101 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2102 :group 'org-todo
2103 :group 'org-keywords
2104 :type '(choice
2105 (repeat :tag "Old syntax, just keywords"
2106 (string :tag "Keyword"))
2107 (repeat :tag "New syntax"
2108 (cons
2109 (choice
2110 :tag "Interpretation"
2111 ;;Quick and dirty way to see
2112 ;;`org-todo-interpretations'. This takes the
2113 ;;place of item arguments
2114 :convert-widget
2115 (lambda (widget)
2116 (widget-put widget
2117 :args (mapcar
2118 #'(lambda (x)
2119 (widget-convert
2120 (cons 'const x)))
2121 org-todo-interpretation-widgets))
2122 widget))
2123 (repeat
2124 (string :tag "Keyword"))))))
2126 (defvar org-todo-keywords-1 nil
2127 "All TODO and DONE keywords active in a buffer.")
2128 (make-variable-buffer-local 'org-todo-keywords-1)
2129 (defvar org-todo-keywords-for-agenda nil)
2130 (defvar org-done-keywords-for-agenda nil)
2131 (defvar org-drawers-for-agenda nil)
2132 (defvar org-todo-keyword-alist-for-agenda nil)
2133 (defvar org-tag-alist-for-agenda nil)
2134 (defvar org-agenda-contributing-files nil)
2135 (defvar org-not-done-keywords nil)
2136 (make-variable-buffer-local 'org-not-done-keywords)
2137 (defvar org-done-keywords nil)
2138 (make-variable-buffer-local 'org-done-keywords)
2139 (defvar org-todo-heads nil)
2140 (make-variable-buffer-local 'org-todo-heads)
2141 (defvar org-todo-sets nil)
2142 (make-variable-buffer-local 'org-todo-sets)
2143 (defvar org-todo-log-states nil)
2144 (make-variable-buffer-local 'org-todo-log-states)
2145 (defvar org-todo-kwd-alist nil)
2146 (make-variable-buffer-local 'org-todo-kwd-alist)
2147 (defvar org-todo-key-alist nil)
2148 (make-variable-buffer-local 'org-todo-key-alist)
2149 (defvar org-todo-key-trigger nil)
2150 (make-variable-buffer-local 'org-todo-key-trigger)
2152 (defcustom org-todo-interpretation 'sequence
2153 "Controls how TODO keywords are interpreted.
2154 This variable is in principle obsolete and is only used for
2155 backward compatibility, if the interpretation of todo keywords is
2156 not given already in `org-todo-keywords'. See that variable for
2157 more information."
2158 :group 'org-todo
2159 :group 'org-keywords
2160 :type '(choice (const sequence)
2161 (const type)))
2163 (defcustom org-use-fast-todo-selection t
2164 "Non-nil means use the fast todo selection scheme with C-c C-t.
2165 This variable describes if and under what circumstances the cycling
2166 mechanism for TODO keywords will be replaced by a single-key, direct
2167 selection scheme.
2169 When nil, fast selection is never used.
2171 When the symbol `prefix', it will be used when `org-todo' is called
2172 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2173 `C-u t' in an agenda buffer.
2175 When t, fast selection is used by default. In this case, the prefix
2176 argument forces cycling instead.
2178 In all cases, the special interface is only used if access keys have
2179 actually been assigned by the user, i.e. if keywords in the configuration
2180 are followed by a letter in parenthesis, like TODO(t)."
2181 :group 'org-todo
2182 :type '(choice
2183 (const :tag "Never" nil)
2184 (const :tag "By default" t)
2185 (const :tag "Only with C-u C-c C-t" prefix)))
2187 (defcustom org-provide-todo-statistics t
2188 "Non-nil means update todo statistics after insert and toggle.
2189 ALL-HEADLINES means update todo statistics by including headlines
2190 with no TODO keyword as well, counting them as not done.
2191 A list of TODO keywords means the same, but skip keywords that are
2192 not in this list.
2194 When this is set, todo statistics is updated in the parent of the
2195 current entry each time a todo state is changed."
2196 :group 'org-todo
2197 :type '(choice
2198 (const :tag "Yes, only for TODO entries" t)
2199 (const :tag "Yes, including all entries" 'all-headlines)
2200 (repeat :tag "Yes, for TODOs in this list"
2201 (string :tag "TODO keyword"))
2202 (other :tag "No TODO statistics" nil)))
2204 (defcustom org-hierarchical-todo-statistics t
2205 "Non-nil means TODO statistics covers just direct children.
2206 When nil, all entries in the subtree are considered.
2207 This has only an effect if `org-provide-todo-statistics' is set.
2208 To set this to nil for only a single subtree, use a COOKIE_DATA
2209 property and include the word \"recursive\" into the value."
2210 :group 'org-todo
2211 :type 'boolean)
2213 (defcustom org-after-todo-state-change-hook nil
2214 "Hook which is run after the state of a TODO item was changed.
2215 The new state (a string with a TODO keyword, or nil) is available in the
2216 Lisp variable `org-state'."
2217 :group 'org-todo
2218 :type 'hook)
2220 (defvar org-blocker-hook nil
2221 "Hook for functions that are allowed to block a state change.
2223 Each function gets as its single argument a property list, see
2224 `org-trigger-hook' for more information about this list.
2226 If any of the functions in this hook returns nil, the state change
2227 is blocked.")
2229 (defvar org-trigger-hook nil
2230 "Hook for functions that are triggered by a state change.
2232 Each function gets as its single argument a property list with at least
2233 the following elements:
2235 (:type type-of-change :position pos-at-entry-start
2236 :from old-state :to new-state)
2238 Depending on the type, more properties may be present.
2240 This mechanism is currently implemented for:
2242 TODO state changes
2243 ------------------
2244 :type todo-state-change
2245 :from previous state (keyword as a string), or nil, or a symbol
2246 'todo' or 'done', to indicate the general type of state.
2247 :to new state, like in :from")
2249 (defcustom org-enforce-todo-dependencies nil
2250 "Non-nil means undone TODO entries will block switching the parent to DONE.
2251 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2252 be blocked if any prior sibling is not yet done.
2253 Finally, if the parent is blocked because of ordered siblings of its own,
2254 the child will also be blocked."
2255 :set (lambda (var val)
2256 (set var val)
2257 (if val
2258 (add-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent)
2260 (remove-hook 'org-blocker-hook
2261 'org-block-todo-from-children-or-siblings-or-parent)))
2262 :group 'org-todo
2263 :type 'boolean)
2265 (defcustom org-enforce-todo-checkbox-dependencies nil
2266 "Non-nil means unchecked boxes will block switching the parent to DONE.
2267 When this is nil, checkboxes have no influence on switching TODO states.
2268 When non-nil, you first need to check off all check boxes before the TODO
2269 entry can be switched to DONE.
2270 This variable needs to be set before org.el is loaded, and you need to
2271 restart Emacs after a change to make the change effective. The only way
2272 to change is while Emacs is running is through the customize interface."
2273 :set (lambda (var val)
2274 (set var val)
2275 (if val
2276 (add-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes)
2278 (remove-hook 'org-blocker-hook
2279 'org-block-todo-from-checkboxes)))
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-treat-insert-todo-heading-as-state-change nil
2284 "Non-nil means inserting a TODO heading is treated as state change.
2285 So when the command \\[org-insert-todo-heading] is used, state change
2286 logging will apply if appropriate. When nil, the new TODO item will
2287 be inserted directly, and no logging will take place."
2288 :group 'org-todo
2289 :type 'boolean)
2291 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2292 "Non-nil means switching TODO states with S-cursor counts as state change.
2293 This is the default behavior. However, setting this to nil allows a
2294 convenient way to select a TODO state and bypass any logging associated
2295 with that."
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-todo-state-tags-triggers nil
2300 "Tag changes that should be triggered by TODO state changes.
2301 This is a list. Each entry is
2303 (state-change (tag . flag) .......)
2305 State-change can be a string with a state, and empty string to indicate the
2306 state that has no TODO keyword, or it can be one of the symbols `todo'
2307 or `done', meaning any not-done or done state, respectively."
2308 :group 'org-todo
2309 :group 'org-tags
2310 :type '(repeat
2311 (cons (choice :tag "When changing to"
2312 (const :tag "Not-done state" todo)
2313 (const :tag "Done state" done)
2314 (string :tag "State"))
2315 (repeat
2316 (cons :tag "Tag action"
2317 (string :tag "Tag")
2318 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2320 (defcustom org-log-done nil
2321 "Information to record when a task moves to the DONE state.
2323 Possible values are:
2325 nil Don't add anything, just change the keyword
2326 time Add a time stamp to the task
2327 note Prompt for a note and add it with template `org-log-note-headings'
2329 This option can also be set with on a per-file-basis with
2331 #+STARTUP: nologdone
2332 #+STARTUP: logdone
2333 #+STARTUP: lognotedone
2335 You can have local logging settings for a subtree by setting the LOGGING
2336 property to one or more of these keywords."
2337 :group 'org-todo
2338 :group 'org-progress
2339 :type '(choice
2340 (const :tag "No logging" nil)
2341 (const :tag "Record CLOSED timestamp" time)
2342 (const :tag "Record CLOSED timestamp with note." note)))
2344 ;; Normalize old uses of org-log-done.
2345 (cond
2346 ((eq org-log-done t) (setq org-log-done 'time))
2347 ((and (listp org-log-done) (memq 'done org-log-done))
2348 (setq org-log-done 'note)))
2350 (defcustom org-log-reschedule nil
2351 "Information to record when the scheduling date of a tasks is modified.
2353 Possible values are:
2355 nil Don't add anything, just change the date
2356 time Add a time stamp to the task
2357 note Prompt for a note and add it with template `org-log-note-headings'
2359 This option can also be set with on a per-file-basis with
2361 #+STARTUP: nologreschedule
2362 #+STARTUP: logreschedule
2363 #+STARTUP: lognotereschedule"
2364 :group 'org-todo
2365 :group 'org-progress
2366 :type '(choice
2367 (const :tag "No logging" nil)
2368 (const :tag "Record timestamp" time)
2369 (const :tag "Record timestamp with note." note)))
2371 (defcustom org-log-redeadline nil
2372 "Information to record when the deadline date of a tasks is modified.
2374 Possible values are:
2376 nil Don't add anything, just change the date
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologredeadline
2383 #+STARTUP: logredeadline
2384 #+STARTUP: lognoteredeadline
2386 You can have local logging settings for a subtree by setting the LOGGING
2387 property to one or more of these keywords."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "No logging" nil)
2392 (const :tag "Record timestamp" time)
2393 (const :tag "Record timestamp with note." note)))
2395 (defcustom org-log-note-clock-out nil
2396 "Non-nil means record a note when clocking out of an item.
2397 This can also be configured on a per-file basis by adding one of
2398 the following lines anywhere in the buffer:
2400 #+STARTUP: lognoteclock-out
2401 #+STARTUP: nolognoteclock-out"
2402 :group 'org-todo
2403 :group 'org-progress
2404 :type 'boolean)
2406 (defcustom org-log-done-with-time t
2407 "Non-nil means the CLOSED time stamp will contain date and time.
2408 When nil, only the date will be recorded."
2409 :group 'org-progress
2410 :type 'boolean)
2412 (defcustom org-log-note-headings
2413 '((done . "CLOSING NOTE %t")
2414 (state . "State %-12s from %-12S %t")
2415 (note . "Note taken on %t")
2416 (reschedule . "Rescheduled from %S on %t")
2417 (delschedule . "Not scheduled, was %S on %t")
2418 (redeadline . "New deadline from %S on %t")
2419 (deldeadline . "Removed deadline, was %S on %t")
2420 (refile . "Refiled on %t")
2421 (clock-out . ""))
2422 "Headings for notes added to entries.
2423 The value is an alist, with the car being a symbol indicating the note
2424 context, and the cdr is the heading to be used. The heading may also be the
2425 empty string.
2426 %t in the heading will be replaced by a time stamp.
2427 %T will be an active time stamp instead the default inactive one
2428 %d will be replaced by a short-format time stamp.
2429 %D will be replaced by an active short-format time stamp.
2430 %s will be replaced by the new TODO state, in double quotes.
2431 %S will be replaced by the old TODO state, in double quotes.
2432 %u will be replaced by the user name.
2433 %U will be replaced by the full user name.
2435 In fact, it is not a good idea to change the `state' entry, because
2436 agenda log mode depends on the format of these entries."
2437 :group 'org-todo
2438 :group 'org-progress
2439 :type '(list :greedy t
2440 (cons (const :tag "Heading when closing an item" done) string)
2441 (cons (const :tag
2442 "Heading when changing todo state (todo sequence only)"
2443 state) string)
2444 (cons (const :tag "Heading when just taking a note" note) string)
2445 (cons (const :tag "Heading when clocking out" clock-out) string)
2446 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2447 (cons (const :tag "Heading when rescheduling" reschedule) string)
2448 (cons (const :tag "Heading when changing deadline" redeadline) string)
2449 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2450 (cons (const :tag "Heading when refiling" refile) string)))
2452 (unless (assq 'note org-log-note-headings)
2453 (push '(note . "%t") org-log-note-headings))
2455 (defcustom org-log-into-drawer nil
2456 "Non-nil means insert state change notes and time stamps into a drawer.
2457 When nil, state changes notes will be inserted after the headline and
2458 any scheduling and clock lines, but not inside a drawer.
2460 The value of this variable should be the name of the drawer to use.
2461 LOGBOOK is proposed as the default drawer for this purpose, you can
2462 also set this to a string to define the drawer of your choice.
2464 A value of t is also allowed, representing \"LOGBOOK\".
2466 If this variable is set, `org-log-state-notes-insert-after-drawers'
2467 will be ignored.
2469 You can set the property LOG_INTO_DRAWER to overrule this setting for
2470 a subtree."
2471 :group 'org-todo
2472 :group 'org-progress
2473 :type '(choice
2474 (const :tag "Not into a drawer" nil)
2475 (const :tag "LOGBOOK" t)
2476 (string :tag "Other")))
2478 (if (fboundp 'defvaralias)
2479 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2481 (defun org-log-into-drawer ()
2482 "Return the value of `org-log-into-drawer', but let properties overrule.
2483 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2484 used instead of the default value."
2485 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2486 (cond
2487 ((or (not p) (equal p "nil")) org-log-into-drawer)
2488 ((equal p "t") "LOGBOOK")
2489 (t p))))
2491 (defcustom org-log-state-notes-insert-after-drawers nil
2492 "Non-nil means insert state change notes after any drawers in entry.
2493 Only the drawers that *immediately* follow the headline and the
2494 deadline/scheduled line are skipped.
2495 When nil, insert notes right after the heading and perhaps the line
2496 with deadline/scheduling if present.
2498 This variable will have no effect if `org-log-into-drawer' is
2499 set."
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type 'boolean)
2504 (defcustom org-log-states-order-reversed t
2505 "Non-nil means the latest state note will be directly after heading.
2506 When nil, the state change notes will be ordered according to time."
2507 :group 'org-todo
2508 :group 'org-progress
2509 :type 'boolean)
2511 (defcustom org-todo-repeat-to-state nil
2512 "The TODO state to which a repeater should return the repeating task.
2513 By default this is the first task in a TODO sequence, or the previous state
2514 in a TODO_TYP set. But you can specify another task here.
2515 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2516 :group 'org-todo
2517 :version "24.1"
2518 :type '(choice (const :tag "Head of sequence" nil)
2519 (string :tag "Specific state")))
2521 (defcustom org-log-repeat 'time
2522 "Non-nil means record moving through the DONE state when triggering repeat.
2523 An auto-repeating task is immediately switched back to TODO when
2524 marked DONE. If you are not logging state changes (by adding \"@\"
2525 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2526 record a closing note, there will be no record of the task moving
2527 through DONE. This variable forces taking a note anyway.
2529 nil Don't force a record
2530 time Record a time stamp
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologrepeat
2536 #+STARTUP: logrepeat
2537 #+STARTUP: lognoterepeat
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "Don't force a record" nil)
2545 (const :tag "Force recording the DONE state" time)
2546 (const :tag "Force recording a note with the DONE state" note)))
2549 (defgroup org-priorities nil
2550 "Priorities in Org-mode."
2551 :tag "Org Priorities"
2552 :group 'org-todo)
2554 (defcustom org-enable-priority-commands t
2555 "Non-nil means priority commands are active.
2556 When nil, these commands will be disabled, so that you never accidentally
2557 set a priority."
2558 :group 'org-priorities
2559 :type 'boolean)
2561 (defcustom org-highest-priority ?A
2562 "The highest priority of TODO items. A character like ?A, ?B etc.
2563 Must have a smaller ASCII number than `org-lowest-priority'."
2564 :group 'org-priorities
2565 :type 'character)
2567 (defcustom org-lowest-priority ?C
2568 "The lowest priority of TODO items. A character like ?A, ?B etc.
2569 Must have a larger ASCII number than `org-highest-priority'."
2570 :group 'org-priorities
2571 :type 'character)
2573 (defcustom org-default-priority ?B
2574 "The default priority of TODO items.
2575 This is the priority an item gets if no explicit priority is given.
2576 When starting to cycle on an empty priority the first step in the cycle
2577 depends on `org-priority-start-cycle-with-default'. The resulting first
2578 step priority must not exceed the range from `org-highest-priority' to
2579 `org-lowest-priority' which means that `org-default-priority' has to be
2580 in this range exclusive or inclusive the range boundaries. Else the
2581 first step refuses to set the default and the second will fall back
2582 to (depending on the command used) the highest or lowest priority."
2583 :group 'org-priorities
2584 :type 'character)
2586 (defcustom org-priority-start-cycle-with-default t
2587 "Non-nil means start with default priority when starting to cycle.
2588 When this is nil, the first step in the cycle will be (depending on the
2589 command used) one higher or lower than the default priority.
2590 See also `org-default-priority'."
2591 :group 'org-priorities
2592 :type 'boolean)
2594 (defcustom org-get-priority-function nil
2595 "Function to extract the priority from a string.
2596 The string is normally the headline. If this is nil Org computes the
2597 priority from the priority cookie like [#A] in the headline. It returns
2598 an integer, increasing by 1000 for each priority level.
2599 The user can set a different function here, which should take a string
2600 as an argument and return the numeric priority."
2601 :group 'org-priorities
2602 :version "24.1"
2603 :type 'function)
2605 (defgroup org-time nil
2606 "Options concerning time stamps and deadlines in Org-mode."
2607 :tag "Org Time"
2608 :group 'org)
2610 (defcustom org-insert-labeled-timestamps-at-point nil
2611 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2612 When nil, these labeled time stamps are forces into the second line of an
2613 entry, just after the headline. When scheduling from the global TODO list,
2614 the time stamp will always be forced into the second line."
2615 :group 'org-time
2616 :type 'boolean)
2618 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2619 "Formats for `format-time-string' which are used for time stamps.
2620 It is not recommended to change this constant.")
2622 (defcustom org-time-stamp-rounding-minutes '(0 5)
2623 "Number of minutes to round time stamps to.
2624 These are two values, the first applies when first creating a time stamp.
2625 The second applies when changing it with the commands `S-up' and `S-down'.
2626 When changing the time stamp, this means that it will change in steps
2627 of N minutes, as given by the second value.
2629 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2630 numbers should be factors of 60, so for example 5, 10, 15.
2632 When this is larger than 1, you can still force an exact time stamp by using
2633 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2634 and by using a prefix arg to `S-up/down' to specify the exact number
2635 of minutes to shift."
2636 :group 'org-time
2637 :get #'(lambda (var) ; Make sure both elements are there
2638 (if (integerp (default-value var))
2639 (list (default-value var) 5)
2640 (default-value var)))
2641 :type '(list
2642 (integer :tag "when inserting times")
2643 (integer :tag "when modifying times")))
2645 ;; Normalize old customizations of this variable.
2646 (when (integerp org-time-stamp-rounding-minutes)
2647 (setq org-time-stamp-rounding-minutes
2648 (list org-time-stamp-rounding-minutes
2649 org-time-stamp-rounding-minutes)))
2651 (defcustom org-display-custom-times nil
2652 "Non-nil means overlay custom formats over all time stamps.
2653 The formats are defined through the variable `org-time-stamp-custom-formats'.
2654 To turn this on on a per-file basis, insert anywhere in the file:
2655 #+STARTUP: customtime"
2656 :group 'org-time
2657 :set 'set-default
2658 :type 'sexp)
2659 (make-variable-buffer-local 'org-display-custom-times)
2661 (defcustom org-time-stamp-custom-formats
2662 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2663 "Custom formats for time stamps. See `format-time-string' for the syntax.
2664 These are overlaid over the default ISO format if the variable
2665 `org-display-custom-times' is set. Time like %H:%M should be at the
2666 end of the second format. The custom formats are also honored by export
2667 commands, if custom time display is turned on at the time of export."
2668 :group 'org-time
2669 :type 'sexp)
2671 (defun org-time-stamp-format (&optional long inactive)
2672 "Get the right format for a time string."
2673 (let ((f (if long (cdr org-time-stamp-formats)
2674 (car org-time-stamp-formats))))
2675 (if inactive
2676 (concat "[" (substring f 1 -1) "]")
2677 f)))
2679 (defcustom org-time-clocksum-format "%d:%02d"
2680 "The format string used when creating CLOCKSUM lines.
2681 This is also used when org-mode generates a time duration."
2682 :group 'org-time
2683 :type 'string)
2685 (defcustom org-time-clocksum-use-fractional nil
2686 "If non-nil, \\[org-clock-display] uses fractional times.
2687 org-mode generates a time duration."
2688 :group 'org-time
2689 :type 'boolean)
2691 (defcustom org-time-clocksum-fractional-format "%.2f"
2692 "The format string used when creating CLOCKSUM lines, or when
2693 org-mode generates a time duration."
2694 :group 'org-time
2695 :type 'string)
2697 (defcustom org-deadline-warning-days 14
2698 "No. of days before expiration during which a deadline becomes active.
2699 This variable governs the display in sparse trees and in the agenda.
2700 When 0 or negative, it means use this number (the absolute value of it)
2701 even if a deadline has a different individual lead time specified.
2703 Custom commands can set this variable in the options section."
2704 :group 'org-time
2705 :group 'org-agenda-daily/weekly
2706 :type 'integer)
2708 (defcustom org-read-date-prefer-future t
2709 "Non-nil means assume future for incomplete date input from user.
2710 This affects the following situations:
2711 1. The user gives a month but not a year.
2712 For example, if it is April and you enter \"feb 2\", this will be read
2713 as Feb 2, *next* year. \"May 5\", however, will be this year.
2714 2. The user gives a day, but no month.
2715 For example, if today is the 15th, and you enter \"3\", Org-mode will
2716 read this as the third of *next* month. However, if you enter \"17\",
2717 it will be considered as *this* month.
2719 If you set this variable to the symbol `time', then also the following
2720 will work:
2722 3. If the user gives a time.
2723 If the time is before now, it will be interpreted as tomorrow.
2725 Currently none of this works for ISO week specifications.
2727 When this option is nil, the current day, month and year will always be
2728 used as defaults.
2730 See also `org-agenda-jump-prefer-future'."
2731 :group 'org-time
2732 :type '(choice
2733 (const :tag "Never" nil)
2734 (const :tag "Check month and day" t)
2735 (const :tag "Check month, day, and time" time)))
2737 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2738 "Should the agenda jump command prefer the future for incomplete dates?
2739 The default is to do the same as configured in `org-read-date-prefer-future'.
2740 But you can also set a deviating value here.
2741 This may t or nil, or the symbol `org-read-date-prefer-future'."
2742 :group 'org-agenda
2743 :group 'org-time
2744 :version "24.1"
2745 :type '(choice
2746 (const :tag "Use org-read-date-prefer-future"
2747 org-read-date-prefer-future)
2748 (const :tag "Never" nil)
2749 (const :tag "Always" t)))
2751 (defcustom org-read-date-force-compatible-dates t
2752 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2754 Depending on the system Emacs is running on, certain dates cannot
2755 be represented with the type used internally to represent time.
2756 Dates between 1970-1-1 and 2038-1-1 can always be represented
2757 correctly. Some systems allow for earlier dates, some for later,
2758 some for both. One way to find out it to insert any date into an
2759 Org buffer, putting the cursor on the year and hitting S-up and
2760 S-down to test the range.
2762 When this variable is set to t, the date/time prompt will not let
2763 you specify dates outside the 1970-2037 range, so it is certain that
2764 these dates will work in whatever version of Emacs you are
2765 running, and also that you can move a file from one Emacs implementation
2766 to another. WHenever Org is forcing the year for you, it will display
2767 a message and beep.
2769 When this variable is nil, Org will check if the date is
2770 representable in the specific Emacs implementation you are using.
2771 If not, it will force a year, usually the current year, and beep
2772 to remind you. Currently this setting is not recommended because
2773 the likelihood that you will open your Org files in an Emacs that
2774 has limited date range is not negligible.
2776 A workaround for this problem is to use diary sexp dates for time
2777 stamps outside of this range."
2778 :group 'org-time
2779 :version "24.1"
2780 :type 'boolean)
2782 (defcustom org-read-date-display-live t
2783 "Non-nil means display current interpretation of date prompt live.
2784 This display will be in an overlay, in the minibuffer."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defcustom org-read-date-popup-calendar t
2789 "Non-nil means pop up a calendar when prompting for a date.
2790 In the calendar, the date can be selected with mouse-1. However, the
2791 minibuffer will also be active, and you can simply enter the date as well.
2792 When nil, only the minibuffer will be available."
2793 :group 'org-time
2794 :type 'boolean)
2795 (if (fboundp 'defvaralias)
2796 (defvaralias 'org-popup-calendar-for-date-prompt
2797 'org-read-date-popup-calendar))
2799 (defcustom org-read-date-minibuffer-setup-hook nil
2800 "Hook to be used to set up keys for the date/time interface.
2801 Add key definitions to `minibuffer-local-map', which will be a temporary
2802 copy."
2803 :group 'org-time
2804 :type 'hook)
2806 (defcustom org-extend-today-until 0
2807 "The hour when your day really ends. Must be an integer.
2808 This has influence for the following applications:
2809 - When switching the agenda to \"today\". It it is still earlier than
2810 the time given here, the day recognized as TODAY is actually yesterday.
2811 - When a date is read from the user and it is still before the time given
2812 here, the current date and time will be assumed to be yesterday, 23:59.
2813 Also, timestamps inserted in capture templates follow this rule.
2815 IMPORTANT: This is a feature whose implementation is and likely will
2816 remain incomplete. Really, it is only here because past midnight seems to
2817 be the favorite working time of John Wiegley :-)"
2818 :group 'org-time
2819 :type 'integer)
2821 (defcustom org-use-effective-time nil
2822 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2823 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2824 \"effective time\" of any timestamps between midnight and 8am will be
2825 23:59 of the previous day."
2826 :group 'org-time
2827 :version "24.1"
2828 :type 'boolean)
2830 (defcustom org-use-last-clock-out-time-as-effective-time nil
2831 "When non-nil, use the last clock out time for `org-todo'.
2832 Note that this option has precedence over the combined use of
2833 `org-use-effective-time' and `org-extend-today-until'."
2834 :group 'org-time
2835 ;; :version "24.3"
2836 :type 'boolean)
2838 (defcustom org-edit-timestamp-down-means-later nil
2839 "Non-nil means S-down will increase the time in a time stamp.
2840 When nil, S-up will increase."
2841 :group 'org-time
2842 :type 'boolean)
2844 (defcustom org-calendar-follow-timestamp-change t
2845 "Non-nil means make the calendar window follow timestamp changes.
2846 When a timestamp is modified and the calendar window is visible, it will be
2847 moved to the new date."
2848 :group 'org-time
2849 :type 'boolean)
2851 (defgroup org-tags nil
2852 "Options concerning tags in Org-mode."
2853 :tag "Org Tags"
2854 :group 'org)
2856 (defcustom org-tag-alist nil
2857 "List of tags allowed in Org-mode files.
2858 When this list is nil, Org-mode will base TAG input on what is already in the
2859 buffer.
2860 The value of this variable is an alist, the car of each entry must be a
2861 keyword as a string, the cdr may be a character that is used to select
2862 that tag through the fast-tag-selection interface.
2863 See the manual for details."
2864 :group 'org-tags
2865 :type '(repeat
2866 (choice
2867 (cons (string :tag "Tag name")
2868 (character :tag "Access char"))
2869 (list :tag "Start radio group"
2870 (const :startgroup)
2871 (option (string :tag "Group description")))
2872 (list :tag "End radio group"
2873 (const :endgroup)
2874 (option (string :tag "Group description")))
2875 (const :tag "New line" (:newline)))))
2877 (defcustom org-tag-persistent-alist nil
2878 "List of tags that will always appear in all Org-mode files.
2879 This is in addition to any in buffer settings or customizations
2880 of `org-tag-alist'.
2881 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2882 The value of this variable is an alist, the car of each entry must be a
2883 keyword as a string, the cdr may be a character that is used to select
2884 that tag through the fast-tag-selection interface.
2885 See the manual for details.
2886 To disable these tags on a per-file basis, insert anywhere in the file:
2887 #+STARTUP: noptag"
2888 :group 'org-tags
2889 :type '(repeat
2890 (choice
2891 (cons (string :tag "Tag name")
2892 (character :tag "Access char"))
2893 (const :tag "Start radio group" (:startgroup))
2894 (const :tag "End radio group" (:endgroup))
2895 (const :tag "New line" (:newline)))))
2897 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2898 "If non-nil, always offer completion for all tags of all agenda files.
2899 Instead of customizing this variable directly, you might want to
2900 set it locally for capture buffers, because there no list of
2901 tags in that file can be created dynamically (there are none).
2903 (add-hook 'org-capture-mode-hook
2904 (lambda ()
2905 (set (make-local-variable
2906 'org-complete-tags-always-offer-all-agenda-tags)
2907 t)))"
2908 :group 'org-tags
2909 :version "24.1"
2910 :type 'boolean)
2912 (defvar org-file-tags nil
2913 "List of tags that can be inherited by all entries in the file.
2914 The tags will be inherited if the variable `org-use-tag-inheritance'
2915 says they should be.
2916 This variable is populated from #+FILETAGS lines.")
2918 (defcustom org-use-fast-tag-selection 'auto
2919 "Non-nil means use fast tag selection scheme.
2920 This is a special interface to select and deselect tags with single keys.
2921 When nil, fast selection is never used.
2922 When the symbol `auto', fast selection is used if and only if selection
2923 characters for tags have been configured, either through the variable
2924 `org-tag-alist' or through a #+TAGS line in the buffer.
2925 When t, fast selection is always used and selection keys are assigned
2926 automatically if necessary."
2927 :group 'org-tags
2928 :type '(choice
2929 (const :tag "Always" t)
2930 (const :tag "Never" nil)
2931 (const :tag "When selection characters are configured" 'auto)))
2933 (defcustom org-fast-tag-selection-single-key nil
2934 "Non-nil means fast tag selection exits after first change.
2935 When nil, you have to press RET to exit it.
2936 During fast tag selection, you can toggle this flag with `C-c'.
2937 This variable can also have the value `expert'. In this case, the window
2938 displaying the tags menu is not even shown, until you press C-c again."
2939 :group 'org-tags
2940 :type '(choice
2941 (const :tag "No" nil)
2942 (const :tag "Yes" t)
2943 (const :tag "Expert" expert)))
2945 (defvar org-fast-tag-selection-include-todo nil
2946 "Non-nil means fast tags selection interface will also offer TODO states.
2947 This is an undocumented feature, you should not rely on it.")
2949 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2950 "The column to which tags should be indented in a headline.
2951 If this number is positive, it specifies the column. If it is negative,
2952 it means that the tags should be flushright to that column. For example,
2953 -80 works well for a normal 80 character screen.
2954 When 0, place tags directly after headline text, with only one space in
2955 between."
2956 :group 'org-tags
2957 :type 'integer)
2959 (defcustom org-auto-align-tags t
2960 "Non-nil keeps tags aligned when modifying headlines.
2961 Some operations (i.e. demoting) change the length of a headline and
2962 therefore shift the tags around. With this option turned on, after
2963 each such operation the tags are again aligned to `org-tags-column'."
2964 :group 'org-tags
2965 :type 'boolean)
2967 (defcustom org-use-tag-inheritance t
2968 "Non-nil means tags in levels apply also for sublevels.
2969 When nil, only the tags directly given in a specific line apply there.
2970 This may also be a list of tags that should be inherited, or a regexp that
2971 matches tags that should be inherited. Additional control is possible
2972 with the variable `org-tags-exclude-from-inheritance' which gives an
2973 explicit list of tags to be excluded from inheritance., even if the value of
2974 `org-use-tag-inheritance' would select it for inheritance.
2976 If this option is t, a match early-on in a tree can lead to a large
2977 number of matches in the subtree when constructing the agenda or creating
2978 a sparse tree. If you only want to see the first match in a tree during
2979 a search, check out the variable `org-tags-match-list-sublevels'."
2980 :group 'org-tags
2981 :type '(choice
2982 (const :tag "Not" nil)
2983 (const :tag "Always" t)
2984 (repeat :tag "Specific tags" (string :tag "Tag"))
2985 (regexp :tag "Tags matched by regexp")))
2987 (defcustom org-tags-exclude-from-inheritance nil
2988 "List of tags that should never be inherited.
2989 This is a way to exclude a few tags from inheritance. For way to do
2990 the opposite, to actively allow inheritance for selected tags,
2991 see the variable `org-use-tag-inheritance'."
2992 :group 'org-tags
2993 :type '(repeat (string :tag "Tag")))
2995 (defun org-tag-inherit-p (tag)
2996 "Check if TAG is one that should be inherited."
2997 (cond
2998 ((member tag org-tags-exclude-from-inheritance) nil)
2999 ((eq org-use-tag-inheritance t) t)
3000 ((not org-use-tag-inheritance) nil)
3001 ((stringp org-use-tag-inheritance)
3002 (string-match org-use-tag-inheritance tag))
3003 ((listp org-use-tag-inheritance)
3004 (member tag org-use-tag-inheritance))
3005 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3007 (defcustom org-tags-match-list-sublevels t
3008 "Non-nil means list also sublevels of headlines matching a search.
3009 This variable applies to tags/property searches, and also to stuck
3010 projects because this search is based on a tags match as well.
3012 When set to the symbol `indented', sublevels are indented with
3013 leading dots.
3015 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3016 the sublevels of a headline matching a tag search often also match
3017 the same search. Listing all of them can create very long lists.
3018 Setting this variable to nil causes subtrees of a match to be skipped.
3020 This variable is semi-obsolete and probably should always be true. It
3021 is better to limit inheritance to certain tags using the variables
3022 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3023 :group 'org-tags
3024 :type '(choice
3025 (const :tag "No, don't list them" nil)
3026 (const :tag "Yes, do list them" t)
3027 (const :tag "List them, indented with leading dots" indented)))
3029 (defcustom org-tags-sort-function nil
3030 "When set, tags are sorted using this function as a comparator."
3031 :group 'org-tags
3032 :type '(choice
3033 (const :tag "No sorting" nil)
3034 (const :tag "Alphabetical" string<)
3035 (const :tag "Reverse alphabetical" string>)
3036 (function :tag "Custom function" nil)))
3038 (defvar org-tags-history nil
3039 "History of minibuffer reads for tags.")
3040 (defvar org-last-tags-completion-table nil
3041 "The last used completion table for tags.")
3042 (defvar org-after-tags-change-hook nil
3043 "Hook that is run after the tags in a line have changed.")
3045 (defgroup org-properties nil
3046 "Options concerning properties in Org-mode."
3047 :tag "Org Properties"
3048 :group 'org)
3050 (defcustom org-property-format "%-10s %s"
3051 "How property key/value pairs should be formatted by `indent-line'.
3052 When `indent-line' hits a property definition, it will format the line
3053 according to this format, mainly to make sure that the values are
3054 lined-up with respect to each other."
3055 :group 'org-properties
3056 :type 'string)
3058 (defcustom org-properties-postprocess-alist nil
3059 "Alist of properties and functions to adjust inserted values.
3060 Elements of this alist must be of the form
3062 ([string] [function])
3064 where [string] must be a property name and [function] must be a
3065 lambda expression: this lambda expression must take one argument,
3066 the value to adjust, and return the new value as a string.
3068 For example, this element will allow the property \"Remaining\"
3069 to be updated wrt the relation between the \"Effort\" property
3070 and the clock summary:
3072 ((\"Remaining\" (lambda(value)
3073 (let ((clocksum (org-clock-sum-current-item))
3074 (effort (org-duration-string-to-minutes
3075 (org-entry-get (point) \"Effort\"))))
3076 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3077 :group 'org-properties
3078 :version "24.1"
3079 :type '(alist :key-type (string :tag "Property")
3080 :value-type (function :tag "Function")))
3082 (defcustom org-use-property-inheritance nil
3083 "Non-nil means properties apply also for sublevels.
3085 This setting is chiefly used during property searches. Turning it on can
3086 cause significant overhead when doing a search, which is why it is not
3087 on by default.
3089 When nil, only the properties directly given in the current entry count.
3090 When t, every property is inherited. The value may also be a list of
3091 properties that should have inheritance, or a regular expression matching
3092 properties that should be inherited.
3094 However, note that some special properties use inheritance under special
3095 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3096 and the properties ending in \"_ALL\" when they are used as descriptor
3097 for valid values of a property.
3099 Note for programmers:
3100 When querying an entry with `org-entry-get', you can control if inheritance
3101 should be used. By default, `org-entry-get' looks only at the local
3102 properties. You can request inheritance by setting the inherit argument
3103 to t (to force inheritance) or to `selective' (to respect the setting
3104 in this variable)."
3105 :group 'org-properties
3106 :type '(choice
3107 (const :tag "Not" nil)
3108 (const :tag "Always" t)
3109 (repeat :tag "Specific properties" (string :tag "Property"))
3110 (regexp :tag "Properties matched by regexp")))
3112 (defun org-property-inherit-p (property)
3113 "Check if PROPERTY is one that should be inherited."
3114 (cond
3115 ((eq org-use-property-inheritance t) t)
3116 ((not org-use-property-inheritance) nil)
3117 ((stringp org-use-property-inheritance)
3118 (string-match org-use-property-inheritance property))
3119 ((listp org-use-property-inheritance)
3120 (member property org-use-property-inheritance))
3121 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3123 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3124 "The default column format, if no other format has been defined.
3125 This variable can be set on the per-file basis by inserting a line
3127 #+COLUMNS: %25ITEM ....."
3128 :group 'org-properties
3129 :type 'string)
3131 (defcustom org-columns-ellipses ".."
3132 "The ellipses to be used when a field in column view is truncated.
3133 When this is the empty string, as many characters as possible are shown,
3134 but then there will be no visual indication that the field has been truncated.
3135 When this is a string of length N, the last N characters of a truncated
3136 field are replaced by this string. If the column is narrower than the
3137 ellipses string, only part of the ellipses string will be shown."
3138 :group 'org-properties
3139 :type 'string)
3141 (defcustom org-columns-modify-value-for-display-function nil
3142 "Function that modifies values for display in column view.
3143 For example, it can be used to cut out a certain part from a time stamp.
3144 The function must take 2 arguments:
3146 column-title The title of the column (*not* the property name)
3147 value The value that should be modified.
3149 The function should return the value that should be displayed,
3150 or nil if the normal value should be used."
3151 :group 'org-properties
3152 :type 'function)
3154 (defcustom org-effort-property "Effort"
3155 "The property that is being used to keep track of effort estimates.
3156 Effort estimates given in this property need to have the format H:MM."
3157 :group 'org-properties
3158 :group 'org-progress
3159 :type '(string :tag "Property"))
3161 (defconst org-global-properties-fixed
3162 '(("VISIBILITY_ALL" . "folded children content all")
3163 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3164 "List of property/value pairs that can be inherited by any entry.
3166 These are fixed values, for the preset properties. The user variable
3167 that can be used to add to this list is `org-global-properties'.
3169 The entries in this list are cons cells where the car is a property
3170 name and cdr is a string with the value. If the value represents
3171 multiple items like an \"_ALL\" property, separate the items by
3172 spaces.")
3174 (defcustom org-global-properties nil
3175 "List of property/value pairs that can be inherited by any entry.
3177 This list will be combined with the constant `org-global-properties-fixed'.
3179 The entries in this list are cons cells where the car is a property
3180 name and cdr is a string with the value.
3182 You can set buffer-local values for the same purpose in the variable
3183 `org-file-properties' this by adding lines like
3185 #+PROPERTY: NAME VALUE"
3186 :group 'org-properties
3187 :type '(repeat
3188 (cons (string :tag "Property")
3189 (string :tag "Value"))))
3191 (defvar org-file-properties nil
3192 "List of property/value pairs that can be inherited by any entry.
3193 Valid for the current buffer.
3194 This variable is populated from #+PROPERTY lines.")
3195 (make-variable-buffer-local 'org-file-properties)
3197 (defgroup org-agenda nil
3198 "Options concerning agenda views in Org-mode."
3199 :tag "Org Agenda"
3200 :group 'org)
3202 (defvar org-category nil
3203 "Variable used by org files to set a category for agenda display.
3204 Such files should use a file variable to set it, for example
3206 # -*- mode: org; org-category: \"ELisp\"
3208 or contain a special line
3210 #+CATEGORY: ELisp
3212 If the file does not specify a category, then file's base name
3213 is used instead.")
3214 (make-variable-buffer-local 'org-category)
3215 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3217 (defcustom org-agenda-files nil
3218 "The files to be used for agenda display.
3219 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3220 \\[org-remove-file]. You can also use customize to edit the list.
3222 If an entry is a directory, all files in that directory that are matched by
3223 `org-agenda-file-regexp' will be part of the file list.
3225 If the value of the variable is not a list but a single file name, then
3226 the list of agenda files is actually stored and maintained in that file, one
3227 agenda file per line. In this file paths can be given relative to
3228 `org-directory'. Tilde expansion and environment variable substitution
3229 are also made."
3230 :group 'org-agenda
3231 :type '(choice
3232 (repeat :tag "List of files and directories" file)
3233 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3235 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3236 "Regular expression to match files for `org-agenda-files'.
3237 If any element in the list in that variable contains a directory instead
3238 of a normal file, all files in that directory that are matched by this
3239 regular expression will be included."
3240 :group 'org-agenda
3241 :type 'regexp)
3243 (defcustom org-agenda-text-search-extra-files nil
3244 "List of extra files to be searched by text search commands.
3245 These files will be search in addition to the agenda files by the
3246 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3247 Note that these files will only be searched for text search commands,
3248 not for the other agenda views like todo lists, tag searches or the weekly
3249 agenda. This variable is intended to list notes and possibly archive files
3250 that should also be searched by these two commands.
3251 In fact, if the first element in the list is the symbol `agenda-archives',
3252 than all archive files of all agenda files will be added to the search
3253 scope."
3254 :group 'org-agenda
3255 :type '(set :greedy t
3256 (const :tag "Agenda Archives" agenda-archives)
3257 (repeat :inline t (file))))
3259 (if (fboundp 'defvaralias)
3260 (defvaralias 'org-agenda-multi-occur-extra-files
3261 'org-agenda-text-search-extra-files))
3263 (defcustom org-agenda-skip-unavailable-files nil
3264 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3265 A nil value means to remove them, after a query, from the list."
3266 :group 'org-agenda
3267 :type 'boolean)
3269 (defcustom org-calendar-to-agenda-key [?c]
3270 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3271 The command `org-calendar-goto-agenda' will be bound to this key. The
3272 default is the character `c' because then `c' can be used to switch back and
3273 forth between agenda and calendar."
3274 :group 'org-agenda
3275 :type 'sexp)
3277 (defcustom org-calendar-agenda-action-key [?k]
3278 "The key to be installed in `calendar-mode-map' for agenda-action.
3279 The command `org-agenda-action' will be bound to this key. The
3280 default is the character `k' because we use the same key in the agenda."
3281 :group 'org-agenda
3282 :type 'sexp)
3284 (defcustom org-calendar-insert-diary-entry-key [?i]
3285 "The key to be installed in `calendar-mode-map' for adding diary entries.
3286 This option is irrelevant until `org-agenda-diary-file' has been configured
3287 to point to an Org-mode file. When that is the case, the command
3288 `org-agenda-diary-entry' will be bound to the key given here, by default
3289 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3290 if you want to continue doing this, you need to change this to a different
3291 key."
3292 :group 'org-agenda
3293 :type 'sexp)
3295 (defcustom org-agenda-diary-file 'diary-file
3296 "File to which to add new entries with the `i' key in agenda and calendar.
3297 When this is the symbol `diary-file', the functionality in the Emacs
3298 calendar will be used to add entries to the `diary-file'. But when this
3299 points to a file, `org-agenda-diary-entry' will be used instead."
3300 :group 'org-agenda
3301 :type '(choice
3302 (const :tag "The standard Emacs diary file" diary-file)
3303 (file :tag "Special Org file diary entries")))
3305 (eval-after-load "calendar"
3306 '(progn
3307 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3308 'org-calendar-goto-agenda)
3309 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3310 'org-agenda-action)
3311 (add-hook 'calendar-mode-hook
3312 (lambda ()
3313 (unless (eq org-agenda-diary-file 'diary-file)
3314 (define-key calendar-mode-map
3315 org-calendar-insert-diary-entry-key
3316 'org-agenda-diary-entry))))))
3318 (defgroup org-latex nil
3319 "Options for embedding LaTeX code into Org-mode."
3320 :tag "Org LaTeX"
3321 :group 'org)
3323 (defcustom org-format-latex-options
3324 '(:foreground default :background default :scale 1.0
3325 :html-foreground "Black" :html-background "Transparent"
3326 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3327 "Options for creating images from LaTeX fragments.
3328 This is a property list with the following properties:
3329 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3330 `default' means use the foreground of the default face.
3331 `auto' means use the foreground from the text face.
3332 :background the background color, or \"Transparent\".
3333 `default' means use the background of the default face.
3334 `auto' means use the background from the text face.
3335 :scale a scaling factor for the size of the images, to get more pixels
3336 :html-foreground, :html-background, :html-scale
3337 the same numbers for HTML export.
3338 :matchers a list indicating which matchers should be used to
3339 find LaTeX fragments. Valid members of this list are:
3340 \"begin\" find environments
3341 \"$1\" find single characters surrounded by $.$
3342 \"$\" find math expressions surrounded by $...$
3343 \"$$\" find math expressions surrounded by $$....$$
3344 \"\\(\" find math expressions surrounded by \\(...\\)
3345 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3346 :group 'org-latex
3347 :type 'plist)
3349 (defcustom org-format-latex-signal-error t
3350 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3351 When nil, just push out a message."
3352 :group 'org-latex
3353 :version "24.1"
3354 :type 'boolean)
3356 (defcustom org-latex-to-mathml-jar-file nil
3357 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3358 Use this to specify additional executable file say a jar file.
3360 When using MathToWeb as the converter, specify the full-path to
3361 your mathtoweb.jar file."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type '(choice
3365 (const :tag "None" nil)
3366 (file :tag "JAR file" :must-match t)))
3368 (defcustom org-latex-to-mathml-convert-command nil
3369 "Command to convert LaTeX fragments to MathML.
3370 Replace format-specifiers in the command as noted below and use
3371 `shell-command' to convert LaTeX to MathML.
3372 %j: Executable file in fully expanded form as specified by
3373 `org-latex-to-mathml-jar-file'.
3374 %I: Input LaTeX file in fully expanded form
3375 %o: Output MathML file
3376 This command is used by `org-create-math-formula'.
3378 When using MathToWeb as the converter, set this to
3379 \"java -jar %j -unicode -force -df %o %I\"."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type '(choice
3383 (const :tag "None" nil)
3384 (string :tag "\nShell command")))
3386 (defcustom org-latex-create-formula-image-program 'dvipng
3387 "Program to convert LaTeX fragments with.
3389 dvipng Process the LaTeX fragments to dvi file, then convert
3390 dvi files to png files using dvipng.
3391 This will also include processing of non-math environments.
3392 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3393 to convert pdf files to png files"
3394 :group 'org-latex
3395 :version "24.1"
3396 :type '(choice
3397 (const :tag "dvipng" dvipng)
3398 (const :tag "imagemagick" imagemagick)))
3400 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3401 "Path to store latex preview images. A relative path here creates many
3402 directories relative to the processed org files paths. An absolute path
3403 puts all preview images at the same place."
3404 :group 'org-latex
3405 :version "24.3"
3406 :type 'string)
3408 (defun org-format-latex-mathml-available-p ()
3409 "Return t if `org-latex-to-mathml-convert-command' is usable."
3410 (save-match-data
3411 (when (and (boundp 'org-latex-to-mathml-convert-command)
3412 org-latex-to-mathml-convert-command)
3413 (let ((executable (car (split-string
3414 org-latex-to-mathml-convert-command))))
3415 (when (executable-find executable)
3416 (if (string-match
3417 "%j" org-latex-to-mathml-convert-command)
3418 (file-readable-p org-latex-to-mathml-jar-file)
3419 t))))))
3421 (defcustom org-format-latex-header "\\documentclass{article}
3422 \\usepackage[usenames]{color}
3423 \\usepackage{amsmath}
3424 \\usepackage[mathscr]{eucal}
3425 \\pagestyle{empty} % do not remove
3426 \[PACKAGES]
3427 \[DEFAULT-PACKAGES]
3428 % The settings below are copied from fullpage.sty
3429 \\setlength{\\textwidth}{\\paperwidth}
3430 \\addtolength{\\textwidth}{-3cm}
3431 \\setlength{\\oddsidemargin}{1.5cm}
3432 \\addtolength{\\oddsidemargin}{-2.54cm}
3433 \\setlength{\\evensidemargin}{\\oddsidemargin}
3434 \\setlength{\\textheight}{\\paperheight}
3435 \\addtolength{\\textheight}{-\\headheight}
3436 \\addtolength{\\textheight}{-\\headsep}
3437 \\addtolength{\\textheight}{-\\footskip}
3438 \\addtolength{\\textheight}{-3cm}
3439 \\setlength{\\topmargin}{1.5cm}
3440 \\addtolength{\\topmargin}{-2.54cm}"
3441 "The document header used for processing LaTeX fragments.
3442 It is imperative that this header make sure that no page number
3443 appears on the page. The package defined in the variables
3444 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3445 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3446 will be appended."
3447 :group 'org-latex
3448 :type 'string)
3450 (defvar org-format-latex-header-extra nil)
3452 (defun org-set-packages-alist (var val)
3453 "Set the packages alist and make sure it has 3 elements per entry."
3454 (set var (mapcar (lambda (x)
3455 (if (and (consp x) (= (length x) 2))
3456 (list (car x) (nth 1 x) t)
3458 val)))
3460 (defun org-get-packages-alist (var)
3462 "Get the packages alist and make sure it has 3 elements per entry."
3463 (mapcar (lambda (x)
3464 (if (and (consp x) (= (length x) 2))
3465 (list (car x) (nth 1 x) t)
3467 (default-value var)))
3469 ;; The following variables are defined here because is it also used
3470 ;; when formatting latex fragments. Originally it was part of the
3471 ;; LaTeX exporter, which is why the name includes "export".
3472 (defcustom org-export-latex-default-packages-alist
3473 '(("AUTO" "inputenc" t)
3474 ("T1" "fontenc" t)
3475 ("" "fixltx2e" nil)
3476 ("" "graphicx" t)
3477 ("" "longtable" nil)
3478 ("" "float" nil)
3479 ("" "wrapfig" nil)
3480 ("" "soul" t)
3481 ("" "textcomp" t)
3482 ("" "marvosym" t)
3483 ("" "wasysym" t)
3484 ("" "latexsym" t)
3485 ("" "amssymb" t)
3486 ("" "hyperref" nil)
3487 "\\tolerance=1000"
3489 "Alist of default packages to be inserted in the header.
3490 Change this only if one of the packages here causes an incompatibility
3491 with another package you are using.
3492 The packages in this list are needed by one part or another of Org-mode
3493 to function properly.
3495 - inputenc, fontenc: for basic font and character selection
3496 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3497 for interpreting the entities in `org-entities'. You can skip some of these
3498 packages if you don't use any of the symbols in it.
3499 - graphicx: for including images
3500 - float, wrapfig: for figure placement
3501 - longtable: for long tables
3502 - hyperref: for cross references
3504 Therefore you should not modify this variable unless you know what you
3505 are doing. The one reason to change it anyway is that you might be loading
3506 some other package that conflicts with one of the default packages.
3507 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3508 If SNIPPET-FLAG is t, the package also needs to be included when
3509 compiling LaTeX snippets into images for inclusion into HTML."
3510 :group 'org-export-latex
3511 :set 'org-set-packages-alist
3512 :get 'org-get-packages-alist
3513 :version "24.1"
3514 :type '(repeat
3515 (choice
3516 (list :tag "options/package pair"
3517 (string :tag "options")
3518 (string :tag "package")
3519 (boolean :tag "Snippet"))
3520 (string :tag "A line of LaTeX"))))
3522 (defcustom org-export-latex-packages-alist nil
3523 "Alist of packages to be inserted in every LaTeX header.
3524 These will be inserted after `org-export-latex-default-packages-alist'.
3525 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3526 SNIPPET-FLAG, when t, indicates that this package is also needed when
3527 turning LaTeX snippets into images for inclusion into HTML.
3528 Make sure that you only list packages here which:
3529 - you want in every file
3530 - do not conflict with the default packages in
3531 `org-export-latex-default-packages-alist'
3532 - do not conflict with the setup in `org-format-latex-header'."
3533 :group 'org-export-latex
3534 :set 'org-set-packages-alist
3535 :get 'org-get-packages-alist
3536 :type '(repeat
3537 (choice
3538 (list :tag "options/package pair"
3539 (string :tag "options")
3540 (string :tag "package")
3541 (boolean :tag "Snippet"))
3542 (string :tag "A line of LaTeX"))))
3545 (defgroup org-appearance nil
3546 "Settings for Org-mode appearance."
3547 :tag "Org Appearance"
3548 :group 'org)
3550 (defcustom org-level-color-stars-only nil
3551 "Non-nil means fontify only the stars in each headline.
3552 When nil, the entire headline is fontified.
3553 Changing it requires restart of `font-lock-mode' to become effective
3554 also in regions already fontified."
3555 :group 'org-appearance
3556 :type 'boolean)
3558 (defcustom org-hide-leading-stars nil
3559 "Non-nil means hide the first N-1 stars in a headline.
3560 This works by using the face `org-hide' for these stars. This
3561 face is white for a light background, and black for a dark
3562 background. You may have to customize the face `org-hide' to
3563 make this work.
3564 Changing it requires restart of `font-lock-mode' to become effective
3565 also in regions already fontified.
3566 You may also set this on a per-file basis by adding one of the following
3567 lines to the buffer:
3569 #+STARTUP: hidestars
3570 #+STARTUP: showstars"
3571 :group 'org-appearance
3572 :type 'boolean)
3574 (defcustom org-hidden-keywords nil
3575 "List of symbols corresponding to keywords to be hidden the org buffer.
3576 For example, a value '(title) for this list will make the document's title
3577 appear in the buffer without the initial #+TITLE: keyword."
3578 :group 'org-appearance
3579 :version "24.1"
3580 :type '(set (const :tag "#+AUTHOR" author)
3581 (const :tag "#+DATE" date)
3582 (const :tag "#+EMAIL" email)
3583 (const :tag "#+TITLE" title)))
3585 (defcustom org-custom-properties nil
3586 "List of properties (as strings) with a special meaning.
3587 The default use of these custom properties is to let the user
3588 hide them with `org-toggle-custom-properties-visibility'."
3589 :group 'org-properties
3590 :group 'org-appearance
3591 :version "24.3"
3592 :type '(repeat (string :tag "Property Name")))
3594 (defcustom org-fontify-done-headline nil
3595 "Non-nil means change the face of a headline if it is marked DONE.
3596 Normally, only the TODO/DONE keyword indicates the state of a headline.
3597 When this is non-nil, the headline after the keyword is set to the
3598 `org-headline-done' as an additional indication."
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-fontify-emphasized-text t
3603 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3604 Changing this variable requires a restart of Emacs to take effect."
3605 :group 'org-appearance
3606 :type 'boolean)
3608 (defcustom org-fontify-whole-heading-line nil
3609 "Non-nil means fontify the whole line for headings.
3610 This is useful when setting a background color for the
3611 org-level-* faces."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-highlight-latex-fragments-and-specials nil
3616 "Non-nil means fontify what is treated specially by the exporters."
3617 :group 'org-appearance
3618 :type 'boolean)
3620 (defcustom org-hide-emphasis-markers nil
3621 "Non-nil mean font-lock should hide the emphasis marker characters."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-pretty-entities nil
3626 "Non-nil means show entities as UTF8 characters.
3627 When nil, the \\name form remains in the buffer."
3628 :group 'org-appearance
3629 :version "24.1"
3630 :type 'boolean)
3632 (defcustom org-pretty-entities-include-sub-superscripts t
3633 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3634 :group 'org-appearance
3635 :version "24.1"
3636 :type 'boolean)
3638 (defvar org-emph-re nil
3639 "Regular expression for matching emphasis.
3640 After a match, the match groups contain these elements:
3641 0 The match of the full regular expression, including the characters
3642 before and after the proper match
3643 1 The character before the proper match, or empty at beginning of line
3644 2 The proper match, including the leading and trailing markers
3645 3 The leading marker like * or /, indicating the type of highlighting
3646 4 The text between the emphasis markers, not including the markers
3647 5 The character after the match, empty at the end of a line")
3648 (defvar org-verbatim-re nil
3649 "Regular expression for matching verbatim text.")
3650 (defvar org-emphasis-regexp-components) ; defined just below
3651 (defvar org-emphasis-alist) ; defined just below
3652 (defun org-set-emph-re (var val)
3653 "Set variable and compute the emphasis regular expression."
3654 (set var val)
3655 (when (and (boundp 'org-emphasis-alist)
3656 (boundp 'org-emphasis-regexp-components)
3657 org-emphasis-alist org-emphasis-regexp-components)
3658 (let* ((e org-emphasis-regexp-components)
3659 (pre (car e))
3660 (post (nth 1 e))
3661 (border (nth 2 e))
3662 (body (nth 3 e))
3663 (nl (nth 4 e))
3664 (body1 (concat body "*?"))
3665 (markers (mapconcat 'car org-emphasis-alist ""))
3666 (vmarkers (mapconcat
3667 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3668 org-emphasis-alist "")))
3669 ;; make sure special characters appear at the right position in the class
3670 (if (string-match "\\^" markers)
3671 (setq markers (concat (replace-match "" t t markers) "^")))
3672 (if (string-match "-" markers)
3673 (setq markers (concat (replace-match "" t t markers) "-")))
3674 (if (string-match "\\^" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3676 (if (string-match "-" vmarkers)
3677 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3678 (if (> nl 0)
3679 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3680 (int-to-string nl) "\\}")))
3681 ;; Make the regexp
3682 (setq org-emph-re
3683 (concat "\\([" pre "]\\|^\\)"
3684 "\\("
3685 "\\([" markers "]\\)"
3686 "\\("
3687 "[^" border "]\\|"
3688 "[^" border "]"
3689 body1
3690 "[^" border "]"
3691 "\\)"
3692 "\\3\\)"
3693 "\\([" post "]\\|$\\)"))
3694 (setq org-verbatim-re
3695 (concat "\\([" pre "]\\|^\\)"
3696 "\\("
3697 "\\([" vmarkers "]\\)"
3698 "\\("
3699 "[^" border "]\\|"
3700 "[^" border "]"
3701 body1
3702 "[^" border "]"
3703 "\\)"
3704 "\\3\\)"
3705 "\\([" post "]\\|$\\)")))))
3707 (defcustom org-emphasis-regexp-components
3708 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3709 "Components used to build the regular expression for emphasis.
3710 This is a list with five entries. Terminology: In an emphasis string
3711 like \" *strong word* \", we call the initial space PREMATCH, the final
3712 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3713 and \"trong wor\" is the body. The different components in this variable
3714 specify what is allowed/forbidden in each part:
3716 pre Chars allowed as prematch. Beginning of line will be allowed too.
3717 post Chars allowed as postmatch. End of line will be allowed too.
3718 border The chars *forbidden* as border characters.
3719 body-regexp A regexp like \".\" to match a body character. Don't use
3720 non-shy groups here, and don't allow newline here.
3721 newline The maximum number of newlines allowed in an emphasis exp.
3723 Use customize to modify this, or restart Emacs after changing it."
3724 :group 'org-appearance
3725 :set 'org-set-emph-re
3726 :type '(list
3727 (sexp :tag "Allowed chars in pre ")
3728 (sexp :tag "Allowed chars in post ")
3729 (sexp :tag "Forbidden chars in border ")
3730 (sexp :tag "Regexp for body ")
3731 (integer :tag "number of newlines allowed")
3732 (option (boolean :tag "Please ignore this button"))))
3734 (defcustom org-emphasis-alist
3735 `(("*" bold "<b>" "</b>")
3736 ("/" italic "<i>" "</i>")
3737 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3738 ("=" org-code "<code>" "</code>" verbatim)
3739 ("~" org-verbatim "<code>" "</code>" verbatim)
3740 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3741 "<del>" "</del>")
3743 "Special syntax for emphasized text.
3744 Text starting and ending with a special character will be emphasized, for
3745 example *bold*, _underlined_ and /italic/. This variable sets the marker
3746 characters, the face to be used by font-lock for highlighting in Org-mode
3747 Emacs buffers, and the HTML tags to be used for this.
3748 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3749 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3750 Use customize to modify this, or restart Emacs after changing it."
3751 :group 'org-appearance
3752 :set 'org-set-emph-re
3753 :type '(repeat
3754 (list
3755 (string :tag "Marker character")
3756 (choice
3757 (face :tag "Font-lock-face")
3758 (plist :tag "Face property list"))
3759 (string :tag "HTML start tag")
3760 (string :tag "HTML end tag")
3761 (option (const verbatim)))))
3763 (defvar org-protecting-blocks
3764 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3765 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3766 This is needed for font-lock setup.")
3768 ;;; Miscellaneous options
3770 (defgroup org-completion nil
3771 "Completion in Org-mode."
3772 :tag "Org Completion"
3773 :group 'org)
3775 (defcustom org-completion-use-ido nil
3776 "Non-nil means use ido completion wherever possible.
3777 Note that `ido-mode' must be active for this variable to be relevant.
3778 If you decide to turn this variable on, you might well want to turn off
3779 `org-outline-path-complete-in-steps'.
3780 See also `org-completion-use-iswitchb'."
3781 :group 'org-completion
3782 :type 'boolean)
3784 (defcustom org-completion-use-iswitchb nil
3785 "Non-nil means use iswitchb completion wherever possible.
3786 Note that `iswitchb-mode' must be active for this variable to be relevant.
3787 If you decide to turn this variable on, you might well want to turn off
3788 `org-outline-path-complete-in-steps'.
3789 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3790 :group 'org-completion
3791 :type 'boolean)
3793 (defcustom org-completion-fallback-command 'hippie-expand
3794 "The expansion command called by \\[pcomplete] in normal context.
3795 Normal means, no org-mode-specific context."
3796 :group 'org-completion
3797 :type 'function)
3799 ;;; Functions and variables from their packages
3800 ;; Declared here to avoid compiler warnings
3802 ;; XEmacs only
3803 (defvar outline-mode-menu-heading)
3804 (defvar outline-mode-menu-show)
3805 (defvar outline-mode-menu-hide)
3806 (defvar zmacs-regions) ; XEmacs regions
3808 ;; Emacs only
3809 (defvar mark-active)
3811 ;; Various packages
3812 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3813 (declare-function calendar-forward-day "cal-move" (arg))
3814 (declare-function calendar-goto-date "cal-move" (date))
3815 (declare-function calendar-goto-today "cal-move" ())
3816 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3817 (defvar calc-embedded-close-formula)
3818 (defvar calc-embedded-open-formula)
3819 (declare-function cdlatex-tab "ext:cdlatex" ())
3820 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3821 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3822 (defvar font-lock-unfontify-region-function)
3823 (declare-function iswitchb-read-buffer "iswitchb"
3824 (prompt &optional default require-match start matches-set))
3825 (defvar iswitchb-temp-buflist)
3826 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3827 (defvar org-agenda-tags-todo-honor-ignore-options)
3828 (declare-function org-agenda-skip "org-agenda" ())
3829 (declare-function
3830 org-agenda-format-item "org-agenda"
3831 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3832 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3833 (declare-function org-agenda-change-all-lines "org-agenda"
3834 (newhead hdmarker &optional fixface just-this))
3835 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3836 (declare-function org-agenda-maybe-redo "org-agenda" ())
3837 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3838 (beg end))
3839 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3840 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3841 "org-agenda" (&optional end))
3842 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3843 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3844 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3845 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3846 (declare-function org-indent-mode "org-indent" (&optional arg))
3847 (declare-function parse-time-string "parse-time" (string))
3848 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3849 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3850 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3851 (defvar remember-data-file)
3852 (defvar texmathp-why)
3853 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3854 (declare-function table--at-cell-p "table" (position &optional object at-column))
3856 (defvar w3m-current-url)
3857 (defvar w3m-current-title)
3859 (defvar org-latex-regexps)
3861 ;;; Autoload and prepare some org modules
3863 ;; Some table stuff that needs to be defined here, because it is used
3864 ;; by the functions setting up org-mode or checking for table context.
3866 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3867 "Detect an org-type or table-type table.")
3868 (defconst org-table-line-regexp "^[ \t]*|"
3869 "Detect an org-type table line.")
3870 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3871 "Detect an org-type table line.")
3872 (defconst org-table-hline-regexp "^[ \t]*|-"
3873 "Detect an org-type table hline.")
3874 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3875 "Detect a table-type table hline.")
3876 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3877 "Detect the first line outside a table when searching from within it.
3878 This works for both table types.")
3880 ;; Autoload the functions in org-table.el that are needed by functions here.
3882 (eval-and-compile
3883 (org-autoload "org-table"
3884 '(org-table-align org-table-begin org-table-blank-field
3885 org-table-convert org-table-convert-region org-table-copy-down
3886 org-table-copy-region org-table-create
3887 org-table-create-or-convert-from-region
3888 org-table-create-with-table.el org-table-current-dline
3889 org-table-cut-region org-table-delete-column org-table-edit-field
3890 org-table-edit-formulas org-table-end org-table-eval-formula
3891 org-table-export org-table-field-info
3892 org-table-get-stored-formulas org-table-goto-column
3893 org-table-hline-and-move org-table-import org-table-insert-column
3894 org-table-insert-hline org-table-insert-row org-table-iterate
3895 org-table-justify-field-maybe org-table-kill-row
3896 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3897 org-table-move-column org-table-move-column-left
3898 org-table-move-column-right org-table-move-row
3899 org-table-move-row-down org-table-move-row-up
3900 org-table-next-field org-table-next-row org-table-paste-rectangle
3901 org-table-previous-field org-table-recalculate
3902 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3903 org-table-toggle-coordinate-overlays
3904 org-table-toggle-formula-debugger org-table-wrap-region
3905 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3906 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3907 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3909 (defun org-at-table-p (&optional table-type)
3910 "Return t if the cursor is inside an org-type table.
3911 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3912 (if org-enable-table-editor
3913 (save-excursion
3914 (beginning-of-line 1)
3915 (looking-at (if table-type org-table-any-line-regexp
3916 org-table-line-regexp)))
3917 nil))
3918 (defsubst org-table-p () (org-at-table-p))
3920 (defun org-at-table.el-p ()
3921 "Return t if and only if we are at a table.el table."
3922 (and (org-at-table-p 'any)
3923 (save-excursion
3924 (goto-char (org-table-begin 'any))
3925 (looking-at org-table1-hline-regexp))))
3926 (defun org-table-recognize-table.el ()
3927 "If there is a table.el table nearby, recognize it and move into it."
3928 (if org-table-tab-recognizes-table.el
3929 (if (org-at-table.el-p)
3930 (progn
3931 (beginning-of-line 1)
3932 (if (looking-at org-table-dataline-regexp)
3934 (if (looking-at org-table1-hline-regexp)
3935 (progn
3936 (beginning-of-line 2)
3937 (if (looking-at org-table-any-border-regexp)
3938 (beginning-of-line -1)))))
3939 (if (re-search-forward "|" (org-table-end t) t)
3940 (progn
3941 (require 'table)
3942 (if (table--at-cell-p (point))
3944 (message "recognizing table.el table...")
3945 (table-recognize-table)
3946 (message "recognizing table.el table...done")))
3947 (error "This should not happen"))
3949 nil)
3950 nil))
3952 (defun org-at-table-hline-p ()
3953 "Return t if the cursor is inside a hline in a table."
3954 (if org-enable-table-editor
3955 (save-excursion
3956 (beginning-of-line 1)
3957 (looking-at org-table-hline-regexp))
3958 nil))
3960 (defvar org-table-clean-did-remove-column nil)
3962 (defun org-table-map-tables (function &optional quietly)
3963 "Apply FUNCTION to the start of all tables in the buffer."
3964 (save-excursion
3965 (save-restriction
3966 (widen)
3967 (goto-char (point-min))
3968 (while (re-search-forward org-table-any-line-regexp nil t)
3969 (unless quietly
3970 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3971 (beginning-of-line 1)
3972 (when (and (looking-at org-table-line-regexp)
3973 ;; Exclude tables in src/example/verbatim/clocktable blocks
3974 (not (org-in-block-p '("src" "example"))))
3975 (save-excursion (funcall function))
3976 (or (looking-at org-table-line-regexp)
3977 (forward-char 1)))
3978 (re-search-forward org-table-any-border-regexp nil 1))))
3979 (unless quietly (message "Mapping tables: done")))
3981 ;; Declare and autoload functions from org-exp.el & Co
3983 (declare-function org-default-export-plist "org-exp")
3984 (declare-function org-infile-export-plist "org-exp")
3985 (declare-function org-get-current-options "org-exp")
3986 (eval-and-compile
3987 (org-autoload "org-exp"
3988 '(org-export org-export-visible
3989 org-insert-export-options-template
3990 org-table-clean-before-export))
3991 (org-autoload "org-ascii"
3992 '(org-export-as-ascii org-export-ascii-preprocess
3993 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3994 org-export-region-as-ascii))
3995 (org-autoload "org-latex"
3996 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3997 org-replace-region-by-latex org-export-region-as-latex
3998 org-export-as-latex org-export-as-pdf
3999 org-export-as-pdf-and-open))
4000 (org-autoload "org-html"
4001 '(org-export-as-html-and-open
4002 org-export-as-html-batch org-export-as-html-to-buffer
4003 org-replace-region-by-html org-export-region-as-html
4004 org-export-as-html))
4005 (org-autoload "org-docbook"
4006 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4007 org-replace-region-by-docbook org-export-region-as-docbook
4008 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4009 org-export-as-docbook))
4010 (org-autoload "org-icalendar"
4011 '(org-export-icalendar-this-file
4012 org-export-icalendar-all-agenda-files
4013 org-export-icalendar-combine-agenda-files))
4014 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4015 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4017 ;; Declare and autoload functions from org-agenda.el
4019 (eval-and-compile
4020 (org-autoload "org-agenda"
4021 '(org-agenda org-agenda-list org-search-view
4022 org-todo-list org-tags-view org-agenda-list-stuck-projects
4023 org-diary org-agenda-to-appt
4024 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4026 ;; Autoload org-remember
4028 (eval-and-compile
4029 (org-autoload "org-remember"
4030 '(org-remember-insinuate org-remember-annotation
4031 org-remember-apply-template org-remember org-remember-handler)))
4033 (eval-and-compile
4034 (org-autoload "org-capture"
4035 '(org-capture org-capture-insert-template-here
4036 org-capture-import-remember-templates)))
4038 ;; Autoload org-clock.el
4040 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4041 (beg end))
4042 (declare-function org-clock-update-mode-line "org-clock" ())
4043 (declare-function org-resolve-clocks "org-clock"
4044 (&optional also-non-dangling-p prompt last-valid))
4045 (defvar org-clock-start-time)
4046 (defvar org-clock-marker (make-marker)
4047 "Marker recording the last clock-in.")
4048 (defvar org-clock-hd-marker (make-marker)
4049 "Marker recording the last clock-in, but the headline position.")
4050 (defvar org-clock-heading ""
4051 "The heading of the current clock entry.")
4052 (defun org-clock-is-active ()
4053 "Return non-nil if clock is currently running.
4054 The return value is actually the clock marker."
4055 (marker-buffer org-clock-marker))
4057 (eval-and-compile
4058 (org-autoload
4059 "org-clock"
4060 '(org-clock-in org-clock-out org-clock-cancel
4061 org-clock-goto org-clock-sum org-clock-display
4062 org-clock-remove-overlays org-clock-report
4063 org-clocktable-shift org-dblock-write:clocktable
4064 org-get-clocktable org-resolve-clocks)))
4066 (defun org-clock-update-time-maybe ()
4067 "If this is a CLOCK line, update it and return t.
4068 Otherwise, return nil."
4069 (interactive)
4070 (save-excursion
4071 (beginning-of-line 1)
4072 (skip-chars-forward " \t")
4073 (when (looking-at org-clock-string)
4074 (let ((re (concat "[ \t]*" org-clock-string
4075 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4076 "\\([ \t]*=>.*\\)?\\)?"))
4077 ts te h m s neg)
4078 (cond
4079 ((not (looking-at re))
4080 nil)
4081 ((not (match-end 2))
4082 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4083 (> org-clock-marker (point))
4084 (<= org-clock-marker (point-at-eol)))
4085 ;; The clock is running here
4086 (setq org-clock-start-time
4087 (apply 'encode-time
4088 (org-parse-time-string (match-string 1))))
4089 (org-clock-update-mode-line)))
4091 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4092 (end-of-line 1)
4093 (setq ts (match-string 1)
4094 te (match-string 3))
4095 (setq s (- (org-float-time
4096 (apply 'encode-time (org-parse-time-string te)))
4097 (org-float-time
4098 (apply 'encode-time (org-parse-time-string ts))))
4099 neg (< s 0)
4100 s (abs s)
4101 h (floor (/ s 3600))
4102 s (- s (* 3600 h))
4103 m (floor (/ s 60))
4104 s (- s (* 60 s)))
4105 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4106 t))))))
4108 (defun org-check-running-clock ()
4109 "Check if the current buffer contains the running clock.
4110 If yes, offer to stop it and to save the buffer with the changes."
4111 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4112 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4113 (buffer-name))))
4114 (org-clock-out)
4115 (when (y-or-n-p "Save changed buffer?")
4116 (save-buffer))))
4118 (defun org-clocktable-try-shift (dir n)
4119 "Check if this line starts a clock table, if yes, shift the time block."
4120 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4121 (org-clocktable-shift dir n)))
4123 ;; Autoload org-timer.el
4125 (eval-and-compile
4126 (org-autoload
4127 "org-timer"
4128 '(org-timer-start org-timer org-timer-item
4129 org-timer-change-times-in-region
4130 org-timer-set-timer
4131 org-timer-reset-timers
4132 org-timer-show-remaining-time)))
4134 ;; Autoload org-feed.el
4136 (eval-and-compile
4137 (org-autoload
4138 "org-feed"
4139 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4142 ;; Autoload org-indent.el
4144 ;; Define the variable already here, to make sure we have it.
4145 (defvar org-indent-mode nil
4146 "Non-nil if Org-Indent mode is enabled.
4147 Use the command `org-indent-mode' to change this variable.")
4149 (eval-and-compile
4150 (org-autoload
4151 "org-indent"
4152 '(org-indent-mode)))
4154 ;; Autoload org-mobile.el
4156 (eval-and-compile
4157 (org-autoload
4158 "org-mobile"
4159 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4161 ;; Autoload archiving code
4162 ;; The stuff that is needed for cycling and tags has to be defined here.
4164 (defgroup org-archive nil
4165 "Options concerning archiving in Org-mode."
4166 :tag "Org Archive"
4167 :group 'org-structure)
4169 (defcustom org-archive-location "%s_archive::"
4170 "The location where subtrees should be archived.
4172 The value of this variable is a string, consisting of two parts,
4173 separated by a double-colon. The first part is a filename and
4174 the second part is a headline.
4176 When the filename is omitted, archiving happens in the same file.
4177 %s in the filename will be replaced by the current file
4178 name (without the directory part). Archiving to a different file
4179 is useful to keep archived entries from contributing to the
4180 Org-mode Agenda.
4182 The archived entries will be filed as subtrees of the specified
4183 headline. When the headline is omitted, the subtrees are simply
4184 filed away at the end of the file, as top-level entries. Also in
4185 the heading you can use %s to represent the file name, this can be
4186 useful when using the same archive for a number of different files.
4188 Here are a few examples:
4189 \"%s_archive::\"
4190 If the current file is Projects.org, archive in file
4191 Projects.org_archive, as top-level trees. This is the default.
4193 \"::* Archived Tasks\"
4194 Archive in the current file, under the top-level headline
4195 \"* Archived Tasks\".
4197 \"~/org/archive.org::\"
4198 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4200 \"~/org/archive.org::* From %s\"
4201 Archive in file ~/org/archive.org (absolute path), under headlines
4202 \"From FILENAME\" where file name is the current file name.
4204 \"~/org/datetree.org::datetree/* Finished Tasks\"
4205 The \"datetree/\" string is special, signifying to archive
4206 items to the datetree. Items are placed in either the CLOSED
4207 date of the item, or the current date if there is no CLOSED date.
4208 The heading will be a subentry to the current date. There doesn't
4209 need to be a heading, but there always needs to be a slash after
4210 datetree. For example, to store archived items directly in the
4211 datetree, use \"~/org/datetree.org::datetree/\".
4213 \"basement::** Finished Tasks\"
4214 Archive in file ./basement (relative path), as level 3 trees
4215 below the level 2 heading \"** Finished Tasks\".
4217 You may set this option on a per-file basis by adding to the buffer a
4218 line like
4220 #+ARCHIVE: basement::** Finished Tasks
4222 You may also define it locally for a subtree by setting an ARCHIVE property
4223 in the entry. If such a property is found in an entry, or anywhere up
4224 the hierarchy, it will be used."
4225 :group 'org-archive
4226 :type 'string)
4228 (defcustom org-archive-tag "ARCHIVE"
4229 "The tag that marks a subtree as archived.
4230 An archived subtree does not open during visibility cycling, and does
4231 not contribute to the agenda listings.
4232 After changing this, font-lock must be restarted in the relevant buffers to
4233 get the proper fontification."
4234 :group 'org-archive
4235 :group 'org-keywords
4236 :type 'string)
4238 (defcustom org-agenda-skip-archived-trees t
4239 "Non-nil means the agenda will skip any items located in archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4241 variable is no longer recommended, you should leave it at the value t.
4242 Instead, use the key `v' to cycle the archives-mode in the agenda."
4243 :group 'org-archive
4244 :group 'org-agenda-skip
4245 :type 'boolean)
4247 (defcustom org-columns-skip-archived-trees t
4248 "Non-nil means ignore archived trees when creating column view."
4249 :group 'org-archive
4250 :group 'org-properties
4251 :type 'boolean)
4253 (defcustom org-cycle-open-archived-trees nil
4254 "Non-nil means `org-cycle' will open archived trees.
4255 An archived tree is a tree marked with the tag ARCHIVE.
4256 When nil, archived trees will stay folded. You can still open them with
4257 normal outline commands like `show-all', but not with the cycling commands."
4258 :group 'org-archive
4259 :group 'org-cycle
4260 :type 'boolean)
4262 (defcustom org-sparse-tree-open-archived-trees nil
4263 "Non-nil means sparse tree construction shows matches in archived trees.
4264 When nil, matches in these trees are highlighted, but the trees are kept in
4265 collapsed state."
4266 :group 'org-archive
4267 :group 'org-sparse-trees
4268 :type 'boolean)
4270 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4271 "The default date type when building a sparse tree.
4272 When this is nil, a date is a scheduled or a deadline timestamp.
4273 Otherwise, these types are allowed:
4275 all: all timestamps
4276 active: only active timestamps (<...>)
4277 inactive: only inactive timestamps (<...)
4278 scheduled: only scheduled timestamps
4279 deadline: only deadline timestamps"
4280 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4281 (const :tag "All timestamps" all)
4282 (const :tag "Only active timestamps" active)
4283 (const :tag "Only inactive timestamps" inactive)
4284 (const :tag "Only scheduled timestamps" scheduled)
4285 (const :tag "Only deadline timestamps" deadline))
4286 :version "24.3"
4287 :group 'org-sparse-trees)
4289 (defun org-cycle-hide-archived-subtrees (state)
4290 "Re-hide all archived subtrees after a visibility state change."
4291 (when (and (not org-cycle-open-archived-trees)
4292 (not (memq state '(overview folded))))
4293 (save-excursion
4294 (let* ((globalp (memq state '(contents all)))
4295 (beg (if globalp (point-min) (point)))
4296 (end (if globalp (point-max) (org-end-of-subtree t))))
4297 (org-hide-archived-subtrees beg end)
4298 (goto-char beg)
4299 (if (looking-at (concat ".*:" org-archive-tag ":"))
4300 (message "%s" (substitute-command-keys
4301 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4303 (defun org-force-cycle-archived ()
4304 "Cycle subtree even if it is archived."
4305 (interactive)
4306 (setq this-command 'org-cycle)
4307 (let ((org-cycle-open-archived-trees t))
4308 (call-interactively 'org-cycle)))
4310 (defun org-hide-archived-subtrees (beg end)
4311 "Re-hide all archived subtrees after a visibility state change."
4312 (save-excursion
4313 (let* ((re (concat ":" org-archive-tag ":")))
4314 (goto-char beg)
4315 (while (re-search-forward re end t)
4316 (when (org-at-heading-p)
4317 (org-flag-subtree t)
4318 (org-end-of-subtree t))))))
4320 (declare-function outline-end-of-heading "outline" ())
4321 (declare-function outline-flag-region "outline" (from to flag))
4322 (defun org-flag-subtree (flag)
4323 (save-excursion
4324 (org-back-to-heading t)
4325 (outline-end-of-heading)
4326 (outline-flag-region (point)
4327 (progn (org-end-of-subtree t) (point))
4328 flag)))
4330 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4332 (eval-and-compile
4333 (org-autoload "org-archive"
4334 '(org-add-archive-files org-archive-subtree
4335 org-archive-to-archive-sibling org-toggle-archive-tag
4336 org-archive-subtree-default
4337 org-archive-subtree-default-with-confirmation)))
4339 ;; Autoload Column View Code
4341 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4342 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4343 (declare-function org-columns-compute "org-colview" (property))
4345 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4346 '(org-columns-number-to-string org-columns-get-format-and-top-level
4347 org-columns-compute org-agenda-columns org-columns-remove-overlays
4348 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4350 ;; Autoload ID code
4352 (declare-function org-id-store-link "org-id")
4353 (declare-function org-id-locations-load "org-id")
4354 (declare-function org-id-locations-save "org-id")
4355 (defvar org-id-track-globally)
4356 (org-autoload "org-id"
4357 '(org-id-get-create org-id-new org-id-copy org-id-get
4358 org-id-get-with-outline-path-completion
4359 org-id-get-with-outline-drilling org-id-store-link
4360 org-id-goto org-id-find org-id-store-link))
4362 ;; Autoload Plotting Code
4364 (org-autoload "org-plot"
4365 '(org-plot/gnuplot))
4367 ;;; Variables for pre-computed regular expressions, all buffer local
4369 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4370 "Matches first line of a hidden block.")
4371 (make-variable-buffer-local 'org-drawer-regexp)
4372 (defvar org-todo-regexp nil
4373 "Matches any of the TODO state keywords.")
4374 (make-variable-buffer-local 'org-todo-regexp)
4375 (defvar org-not-done-regexp nil
4376 "Matches any of the TODO state keywords except the last one.")
4377 (make-variable-buffer-local 'org-not-done-regexp)
4378 (defvar org-not-done-heading-regexp nil
4379 "Matches a TODO headline that is not done.")
4380 (make-variable-buffer-local 'org-not-done-regexp)
4381 (defvar org-todo-line-regexp nil
4382 "Matches a headline and puts TODO state into group 2 if present.")
4383 (make-variable-buffer-local 'org-todo-line-regexp)
4384 (defvar org-complex-heading-regexp nil
4385 "Matches a headline and puts everything into groups:
4386 group 1: the stars
4387 group 2: The todo keyword, maybe
4388 group 3: Priority cookie
4389 group 4: True headline
4390 group 5: Tags")
4391 (make-variable-buffer-local 'org-complex-heading-regexp)
4392 (defvar org-complex-heading-regexp-format nil
4393 "Printf format to make regexp to match an exact headline.
4394 This regexp will match the headline of any node which has the
4395 exact headline text that is put into the format, but may have any
4396 TODO state, priority and tags.")
4397 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4398 (defvar org-todo-line-tags-regexp nil
4399 "Matches a headline and puts TODO state into group 2 if present.
4400 Also put tags into group 4 if tags are present.")
4401 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4402 (defvar org-ds-keyword-length 12
4403 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4404 (make-variable-buffer-local 'org-ds-keyword-length)
4405 (defvar org-deadline-regexp nil
4406 "Matches the DEADLINE keyword.")
4407 (make-variable-buffer-local 'org-deadline-regexp)
4408 (defvar org-deadline-time-regexp nil
4409 "Matches the DEADLINE keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-deadline-time-regexp)
4411 (defvar org-deadline-line-regexp nil
4412 "Matches the DEADLINE keyword and the rest of the line.")
4413 (make-variable-buffer-local 'org-deadline-line-regexp)
4414 (defvar org-scheduled-regexp nil
4415 "Matches the SCHEDULED keyword.")
4416 (make-variable-buffer-local 'org-scheduled-regexp)
4417 (defvar org-scheduled-time-regexp nil
4418 "Matches the SCHEDULED keyword together with a time stamp.")
4419 (make-variable-buffer-local 'org-scheduled-time-regexp)
4420 (defvar org-closed-time-regexp nil
4421 "Matches the CLOSED keyword together with a time stamp.")
4422 (make-variable-buffer-local 'org-closed-time-regexp)
4424 (defvar org-keyword-time-regexp nil
4425 "Matches any of the 4 keywords, together with the time stamp.")
4426 (make-variable-buffer-local 'org-keyword-time-regexp)
4427 (defvar org-keyword-time-not-clock-regexp nil
4428 "Matches any of the 3 keywords, together with the time stamp.")
4429 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4430 (defvar org-maybe-keyword-time-regexp nil
4431 "Matches a timestamp, possibly preceded by a keyword.")
4432 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4433 (defvar org-all-time-keywords nil
4434 "List of time keywords.")
4435 (make-variable-buffer-local 'org-all-time-keywords)
4437 (defconst org-plain-time-of-day-regexp
4438 (concat
4439 "\\(\\<[012]?[0-9]"
4440 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4441 "\\(--?"
4442 "\\(\\<[012]?[0-9]"
4443 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4444 "\\)?")
4445 "Regular expression to match a plain time or time range.
4446 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4447 groups carry important information:
4448 0 the full match
4449 1 the first time, range or not
4450 8 the second time, if it is a range.")
4452 (defconst org-plain-time-extension-regexp
4453 (concat
4454 "\\(\\<[012]?[0-9]"
4455 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4456 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4457 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4458 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4459 groups carry important information:
4460 0 the full match
4461 7 hours of duration
4462 9 minutes of duration")
4464 (defconst org-stamp-time-of-day-regexp
4465 (concat
4466 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4467 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4468 "\\(--?"
4469 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4470 "Regular expression to match a timestamp time or time range.
4471 After a match, the following groups carry important information:
4472 0 the full match
4473 1 date plus weekday, for back referencing to make sure both times are on the same day
4474 2 the first time, range or not
4475 4 the second time, if it is a range.")
4477 (defconst org-startup-options
4478 '(("fold" org-startup-folded t)
4479 ("overview" org-startup-folded t)
4480 ("nofold" org-startup-folded nil)
4481 ("showall" org-startup-folded nil)
4482 ("showeverything" org-startup-folded showeverything)
4483 ("content" org-startup-folded content)
4484 ("indent" org-startup-indented t)
4485 ("noindent" org-startup-indented nil)
4486 ("hidestars" org-hide-leading-stars t)
4487 ("showstars" org-hide-leading-stars nil)
4488 ("odd" org-odd-levels-only t)
4489 ("oddeven" org-odd-levels-only nil)
4490 ("align" org-startup-align-all-tables t)
4491 ("noalign" org-startup-align-all-tables nil)
4492 ("inlineimages" org-startup-with-inline-images t)
4493 ("noinlineimages" org-startup-with-inline-images nil)
4494 ("customtime" org-display-custom-times t)
4495 ("logdone" org-log-done time)
4496 ("lognotedone" org-log-done note)
4497 ("nologdone" org-log-done nil)
4498 ("lognoteclock-out" org-log-note-clock-out t)
4499 ("nolognoteclock-out" org-log-note-clock-out nil)
4500 ("logrepeat" org-log-repeat state)
4501 ("lognoterepeat" org-log-repeat note)
4502 ("nologrepeat" org-log-repeat nil)
4503 ("logreschedule" org-log-reschedule time)
4504 ("lognotereschedule" org-log-reschedule note)
4505 ("nologreschedule" org-log-reschedule nil)
4506 ("logredeadline" org-log-redeadline time)
4507 ("lognoteredeadline" org-log-redeadline note)
4508 ("nologredeadline" org-log-redeadline nil)
4509 ("logrefile" org-log-refile time)
4510 ("lognoterefile" org-log-refile note)
4511 ("nologrefile" org-log-refile nil)
4512 ("fninline" org-footnote-define-inline t)
4513 ("nofninline" org-footnote-define-inline nil)
4514 ("fnlocal" org-footnote-section nil)
4515 ("fnauto" org-footnote-auto-label t)
4516 ("fnprompt" org-footnote-auto-label nil)
4517 ("fnconfirm" org-footnote-auto-label confirm)
4518 ("fnplain" org-footnote-auto-label plain)
4519 ("fnadjust" org-footnote-auto-adjust t)
4520 ("nofnadjust" org-footnote-auto-adjust nil)
4521 ("constcgs" constants-unit-system cgs)
4522 ("constSI" constants-unit-system SI)
4523 ("noptag" org-tag-persistent-alist nil)
4524 ("hideblocks" org-hide-block-startup t)
4525 ("nohideblocks" org-hide-block-startup nil)
4526 ("beamer" org-startup-with-beamer-mode t)
4527 ("entitiespretty" org-pretty-entities t)
4528 ("entitiesplain" org-pretty-entities nil))
4529 "Variable associated with STARTUP options for org-mode.
4530 Each element is a list of three items: the startup options (as written
4531 in the #+STARTUP line), the corresponding variable, and the value to set
4532 this variable to if the option is found. An optional forth element PUSH
4533 means to push this value onto the list in the variable.")
4535 (defun org-update-property-plist (key val props)
4536 "Update PROPS with KEY and VAL."
4537 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4538 (key (if appending (substring key 0 (- (length key) 1)) key))
4539 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4540 (previous (cdr (assoc key props))))
4541 (if appending
4542 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4543 (cons (cons key val) remainder))))
4545 (defconst org-block-regexp
4546 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4547 "Regular expression for hiding blocks.")
4548 (defconst org-heading-keyword-regexp-format
4549 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4550 "Printf format for a regexp matching an headline with some keyword.
4551 This regexp will match the headline of any node which has the
4552 exact keyword that is put into the format. The keyword isn't in
4553 any group by default, but the stars and the body are.")
4554 (defconst org-heading-keyword-maybe-regexp-format
4555 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4556 "Printf format for a regexp matching an headline, possibly with some keyword.
4557 This regexp can match any headline with the specified keyword, or
4558 without a keyword. The keyword isn't in any group by default,
4559 but the stars and the body are.")
4561 (defun org-set-regexps-and-options ()
4562 "Precompute regular expressions for current buffer."
4563 (when (derived-mode-p 'org-mode)
4564 (org-set-local 'org-todo-kwd-alist nil)
4565 (org-set-local 'org-todo-key-alist nil)
4566 (org-set-local 'org-todo-key-trigger nil)
4567 (org-set-local 'org-todo-keywords-1 nil)
4568 (org-set-local 'org-done-keywords nil)
4569 (org-set-local 'org-todo-heads nil)
4570 (org-set-local 'org-todo-sets nil)
4571 (org-set-local 'org-todo-log-states nil)
4572 (org-set-local 'org-file-properties nil)
4573 (org-set-local 'org-file-tags nil)
4574 (let ((re (org-make-options-regexp
4575 '("CATEGORY" "TODO" "COLUMNS"
4576 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4577 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4578 "OPTIONS")
4579 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4580 (splitre "[ \t]+")
4581 (scripts org-use-sub-superscripts)
4582 kwds kws0 kwsa key log value cat arch tags const links hw dws
4583 tail sep kws1 prio props ftags drawers beamer-p
4584 ext-setup-or-nil setup-contents (start 0))
4585 (save-excursion
4586 (save-restriction
4587 (widen)
4588 (goto-char (point-min))
4589 (while (or (and ext-setup-or-nil
4590 (string-match re ext-setup-or-nil start)
4591 (setq start (match-end 0)))
4592 (and (setq ext-setup-or-nil nil start 0)
4593 (re-search-forward re nil t)))
4594 (setq key (upcase (match-string 1 ext-setup-or-nil))
4595 value (org-match-string-no-properties 2 ext-setup-or-nil))
4596 (if (stringp value) (setq value (org-trim value)))
4597 (cond
4598 ((equal key "CATEGORY")
4599 (setq cat value))
4600 ((member key '("SEQ_TODO" "TODO"))
4601 (push (cons 'sequence (org-split-string value splitre)) kwds))
4602 ((equal key "TYP_TODO")
4603 (push (cons 'type (org-split-string value splitre)) kwds))
4604 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4605 ;; general TODO-like setup
4606 (push (cons (intern (downcase (match-string 1 key)))
4607 (org-split-string value splitre)) kwds))
4608 ((equal key "TAGS")
4609 (setq tags (append tags (if tags '("\\n") nil)
4610 (org-split-string value splitre))))
4611 ((equal key "COLUMNS")
4612 (org-set-local 'org-columns-default-format value))
4613 ((equal key "LINK")
4614 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4615 (push (cons (match-string 1 value)
4616 (org-trim (match-string 2 value)))
4617 links)))
4618 ((equal key "PRIORITIES")
4619 (setq prio (org-split-string value " +")))
4620 ((equal key "PROPERTY")
4621 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4622 (setq props (org-update-property-plist (match-string 1 value)
4623 (match-string 2 value)
4624 props))))
4625 ((equal key "FILETAGS")
4626 (when (string-match "\\S-" value)
4627 (setq ftags
4628 (append
4629 ftags
4630 (apply 'append
4631 (mapcar (lambda (x) (org-split-string x ":"))
4632 (org-split-string value)))))))
4633 ((equal key "DRAWERS")
4634 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4635 ((equal key "CONSTANTS")
4636 (setq const (append const (org-split-string value splitre))))
4637 ((equal key "STARTUP")
4638 (let ((opts (org-split-string value splitre))
4639 l var val)
4640 (while (setq l (pop opts))
4641 (when (setq l (assoc l org-startup-options))
4642 (setq var (nth 1 l) val (nth 2 l))
4643 (if (not (nth 3 l))
4644 (set (make-local-variable var) val)
4645 (if (not (listp (symbol-value var)))
4646 (set (make-local-variable var) nil))
4647 (set (make-local-variable var) (symbol-value var))
4648 (add-to-list var val))))))
4649 ((equal key "ARCHIVE")
4650 (setq arch value)
4651 (remove-text-properties 0 (length arch)
4652 '(face t fontified t) arch))
4653 ((equal key "LATEX_CLASS")
4654 (setq beamer-p (equal value "beamer")))
4655 ((equal key "OPTIONS")
4656 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4657 (setq scripts (read (match-string 2 value)))))
4658 ((equal key "SETUPFILE")
4659 (setq setup-contents (org-file-contents
4660 (expand-file-name
4661 (org-remove-double-quotes value))
4662 'noerror))
4663 (if (not ext-setup-or-nil)
4664 (setq ext-setup-or-nil setup-contents start 0)
4665 (setq ext-setup-or-nil
4666 (concat (substring ext-setup-or-nil 0 start)
4667 "\n" setup-contents "\n"
4668 (substring ext-setup-or-nil start)))))))
4669 ;; search for property blocks
4670 (goto-char (point-min))
4671 (while (re-search-forward org-block-regexp nil t)
4672 (when (equal "PROPERTY" (upcase (match-string 1)))
4673 (setq value (replace-regexp-in-string
4674 "[\n\r]" " " (match-string 4)))
4675 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4676 (setq props (org-update-property-plist (match-string 1 value)
4677 (match-string 2 value)
4678 props)))))))
4679 (org-set-local 'org-use-sub-superscripts scripts)
4680 (when cat
4681 (org-set-local 'org-category (intern cat))
4682 (push (cons "CATEGORY" cat) props))
4683 (when prio
4684 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4685 (setq prio (mapcar 'string-to-char prio))
4686 (org-set-local 'org-highest-priority (nth 0 prio))
4687 (org-set-local 'org-lowest-priority (nth 1 prio))
4688 (org-set-local 'org-default-priority (nth 2 prio)))
4689 (and props (org-set-local 'org-file-properties (nreverse props)))
4690 (and ftags (org-set-local 'org-file-tags
4691 (mapcar 'org-add-prop-inherited ftags)))
4692 (and drawers (org-set-local 'org-drawers drawers))
4693 (and arch (org-set-local 'org-archive-location arch))
4694 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4695 ;; Process the TODO keywords
4696 (unless kwds
4697 ;; Use the global values as if they had been given locally.
4698 (setq kwds (default-value 'org-todo-keywords))
4699 (if (stringp (car kwds))
4700 (setq kwds (list (cons org-todo-interpretation
4701 (default-value 'org-todo-keywords)))))
4702 (setq kwds (reverse kwds)))
4703 (setq kwds (nreverse kwds))
4704 (let (inter kws kw)
4705 (while (setq kws (pop kwds))
4706 (let ((kws (or
4707 (run-hook-with-args-until-success
4708 'org-todo-setup-filter-hook kws)
4709 kws)))
4710 (setq inter (pop kws) sep (member "|" kws)
4711 kws0 (delete "|" (copy-sequence kws))
4712 kwsa nil
4713 kws1 (mapcar
4714 (lambda (x)
4715 ;; 1 2
4716 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4717 (progn
4718 (setq kw (match-string 1 x)
4719 key (and (match-end 2) (match-string 2 x))
4720 log (org-extract-log-state-settings x))
4721 (push (cons kw (and key (string-to-char key))) kwsa)
4722 (and log (push log org-todo-log-states))
4724 (error "Invalid TODO keyword %s" x)))
4725 kws0)
4726 kwsa (if kwsa (append '((:startgroup))
4727 (nreverse kwsa)
4728 '((:endgroup))))
4729 hw (car kws1)
4730 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4731 tail (list inter hw (car dws) (org-last dws))))
4732 (add-to-list 'org-todo-heads hw 'append)
4733 (push kws1 org-todo-sets)
4734 (setq org-done-keywords (append org-done-keywords dws nil))
4735 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4736 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4737 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4738 (setq org-todo-sets (nreverse org-todo-sets)
4739 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4740 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4741 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4742 ;; Process the constants
4743 (when const
4744 (let (e cst)
4745 (while (setq e (pop const))
4746 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4747 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4748 (setq org-table-formula-constants-local cst)))
4750 ;; Process the tags.
4751 (when tags
4752 (let (e tgs)
4753 (while (setq e (pop tags))
4754 (cond
4755 ((equal e "{") (push '(:startgroup) tgs))
4756 ((equal e "}") (push '(:endgroup) tgs))
4757 ((equal e "\\n") (push '(:newline) tgs))
4758 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4759 (push (cons (match-string 1 e)
4760 (string-to-char (match-string 2 e)))
4761 tgs))
4762 (t (push (list e) tgs))))
4763 (org-set-local 'org-tag-alist nil)
4764 (while (setq e (pop tgs))
4765 (or (and (stringp (car e))
4766 (assoc (car e) org-tag-alist))
4767 (push e org-tag-alist)))))
4769 ;; Compute the regular expressions and other local variables.
4770 ;; Using `org-outline-regexp-bol' would complicate them much,
4771 ;; because of the fixed white space at the end of that string.
4772 (if (not org-done-keywords)
4773 (setq org-done-keywords (and org-todo-keywords-1
4774 (list (org-last org-todo-keywords-1)))))
4775 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4776 (length org-scheduled-string)
4777 (length org-clock-string)
4778 (length org-closed-string)))
4779 org-drawer-regexp
4780 (concat "^[ \t]*:\\("
4781 (mapconcat 'regexp-quote org-drawers "\\|")
4782 "\\):[ \t]*$")
4783 org-not-done-keywords
4784 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4785 org-todo-regexp
4786 (concat "\\("
4787 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4788 "\\)")
4789 org-not-done-regexp
4790 (concat "\\("
4791 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4792 "\\)")
4793 org-not-done-heading-regexp
4794 (format org-heading-keyword-regexp-format org-not-done-regexp)
4795 org-todo-line-regexp
4796 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4797 org-complex-heading-regexp
4798 (concat "^\\(\\*+\\)"
4799 "\\(?: +" org-todo-regexp "\\)?"
4800 "\\(?: +\\(\\[#.\\]\\)\\)?"
4801 "\\(?: +\\(.*?\\)\\)??"
4802 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4803 "[ \t]*$")
4804 org-complex-heading-regexp-format
4805 (concat "^\\(\\*+\\)"
4806 "\\(?: +" org-todo-regexp "\\)?"
4807 "\\(?: +\\(\\[#.\\]\\)\\)?"
4808 "\\(?: +"
4809 ;; Stats cookies can be stuck to body.
4810 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4811 "\\(%s\\)"
4812 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4813 "\\)"
4814 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4815 "[ \t]*$")
4816 org-todo-line-tags-regexp
4817 (concat "^\\(\\*+\\)"
4818 "\\(?: +" org-todo-regexp "\\)?"
4819 "\\(?: +\\(.*?\\)\\)??"
4820 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4821 "[ \t]*$")
4822 org-deadline-regexp (concat "\\<" org-deadline-string)
4823 org-deadline-time-regexp
4824 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4825 org-deadline-line-regexp
4826 (concat "\\<\\(" org-deadline-string "\\).*")
4827 org-scheduled-regexp
4828 (concat "\\<" org-scheduled-string)
4829 org-scheduled-time-regexp
4830 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4831 org-closed-time-regexp
4832 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4833 org-keyword-time-regexp
4834 (concat "\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\|" org-clock-string "\\)"
4838 " *[[<]\\([^]>]+\\)[]>]")
4839 org-keyword-time-not-clock-regexp
4840 (concat "\\<\\(" org-scheduled-string
4841 "\\|" org-deadline-string
4842 "\\|" org-closed-string
4843 "\\)"
4844 " *[[<]\\([^]>]+\\)[]>]")
4845 org-maybe-keyword-time-regexp
4846 (concat "\\(\\<\\(" org-scheduled-string
4847 "\\|" org-deadline-string
4848 "\\|" org-closed-string
4849 "\\|" org-clock-string "\\)\\)?"
4850 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4851 org-all-time-keywords
4852 (mapcar (lambda (w) (substring w 0 -1))
4853 (list org-scheduled-string org-deadline-string
4854 org-clock-string org-closed-string))
4856 (org-compute-latex-and-specials-regexp)
4857 (org-set-font-lock-defaults))))
4859 (defun org-file-contents (file &optional noerror)
4860 "Return the contents of FILE, as a string."
4861 (if (or (not file)
4862 (not (file-readable-p file)))
4863 (if noerror
4864 (progn
4865 (message "Cannot read file \"%s\"" file)
4866 (ding) (sit-for 2)
4868 (error "Cannot read file \"%s\"" file))
4869 (with-temp-buffer
4870 (insert-file-contents file)
4871 (buffer-string))))
4873 (defun org-extract-log-state-settings (x)
4874 "Extract the log state setting from a TODO keyword string.
4875 This will extract info from a string like \"WAIT(w@/!)\"."
4876 (let (kw key log1 log2)
4877 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4878 (setq kw (match-string 1 x)
4879 key (and (match-end 2) (match-string 2 x))
4880 log1 (and (match-end 3) (match-string 3 x))
4881 log2 (and (match-end 4) (match-string 4 x)))
4882 (and (or log1 log2)
4883 (list kw
4884 (and log1 (if (equal log1 "!") 'time 'note))
4885 (and log2 (if (equal log2 "!") 'time 'note)))))))
4887 (defun org-remove-keyword-keys (list)
4888 "Remove a pair of parenthesis at the end of each string in LIST."
4889 (mapcar (lambda (x)
4890 (if (string-match "(.*)$" x)
4891 (substring x 0 (match-beginning 0))
4893 list))
4895 (defun org-assign-fast-keys (alist)
4896 "Assign fast keys to a keyword-key alist.
4897 Respect keys that are already there."
4898 (let (new e (alt ?0))
4899 (while (setq e (pop alist))
4900 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4901 (cdr e)) ;; Key already assigned.
4902 (push e new)
4903 (let ((clist (string-to-list (downcase (car e))))
4904 (used (append new alist)))
4905 (when (= (car clist) ?@)
4906 (pop clist))
4907 (while (and clist (rassoc (car clist) used))
4908 (pop clist))
4909 (unless clist
4910 (while (rassoc alt used)
4911 (incf alt)))
4912 (push (cons (car e) (or (car clist) alt)) new))))
4913 (nreverse new)))
4915 ;;; Some variables used in various places
4917 (defvar org-window-configuration nil
4918 "Used in various places to store a window configuration.")
4919 (defvar org-selected-window nil
4920 "Used in various places to store a window configuration.")
4921 (defvar org-finish-function nil
4922 "Function to be called when `C-c C-c' is used.
4923 This is for getting out of special buffers like capture.")
4926 ;; FIXME: Occasionally check by commenting these, to make sure
4927 ;; no other functions uses these, forgetting to let-bind them.
4928 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4929 (defvar org-last-state)
4930 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4932 ;; Defined somewhere in this file, but used before definition.
4933 (defvar org-entities) ;; defined in org-entities.el
4934 (defvar org-struct-menu)
4935 (defvar org-org-menu)
4936 (defvar org-tbl-menu)
4938 ;;;; Define the Org-mode
4940 ;; We use a before-change function to check if a table might need
4941 ;; an update.
4942 (defvar org-table-may-need-update t
4943 "Indicates that a table might need an update.
4944 This variable is set by `org-before-change-function'.
4945 `org-table-align' sets it back to nil.")
4946 (defun org-before-change-function (beg end)
4947 "Every change indicates that a table might need an update."
4948 (setq org-table-may-need-update t))
4949 (defvar org-mode-map)
4950 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4951 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4952 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4953 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4954 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4955 (defvar org-table-buffer-is-an nil)
4957 (defvar bidi-paragraph-direction)
4958 (defvar buffer-face-mode-face)
4960 (require 'outline)
4961 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4962 (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"))
4963 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4965 ;; Other stuff we need.
4966 (require 'time-date)
4967 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4968 (require 'easymenu)
4969 (require 'overlay)
4971 (require 'org-macs)
4972 (require 'org-entities)
4973 ;; (require 'org-compat) moved higher up in the file before it is first used
4974 (require 'org-faces)
4975 (require 'org-list)
4976 (require 'org-pcomplete)
4977 (require 'org-src)
4978 (require 'org-footnote)
4980 ;; babel
4981 (require 'ob)
4982 (require 'ob-table)
4983 (require 'ob-lob)
4984 (require 'ob-ref)
4985 (require 'ob-tangle)
4986 (require 'ob-comint)
4987 (require 'ob-keys)
4989 ;;;###autoload
4990 (define-derived-mode org-mode outline-mode "Org"
4991 "Outline-based notes management and organizer, alias
4992 \"Carsten's outline-mode for keeping track of everything.\"
4994 Org-mode develops organizational tasks around a NOTES file which
4995 contains information about projects as plain text. Org-mode is
4996 implemented on top of outline-mode, which is ideal to keep the content
4997 of large files well structured. It supports ToDo items, deadlines and
4998 time stamps, which magically appear in the diary listing of the Emacs
4999 calendar. Tables are easily created with a built-in table editor.
5000 Plain text URL-like links connect to websites, emails (VM), Usenet
5001 messages (Gnus), BBDB entries, and any files related to the project.
5002 For printing and sharing of notes, an Org-mode file (or a part of it)
5003 can be exported as a structured ASCII or HTML file.
5005 The following commands are available:
5007 \\{org-mode-map}"
5009 ;; Get rid of Outline menus, they are not needed
5010 ;; Need to do this here because define-derived-mode sets up
5011 ;; the keymap so late. Still, it is a waste to call this each time
5012 ;; we switch another buffer into org-mode.
5013 (if (featurep 'xemacs)
5014 (when (boundp 'outline-mode-menu-heading)
5015 ;; Assume this is Greg's port, it uses easymenu
5016 (easy-menu-remove outline-mode-menu-heading)
5017 (easy-menu-remove outline-mode-menu-show)
5018 (easy-menu-remove outline-mode-menu-hide))
5019 (define-key org-mode-map [menu-bar headings] 'undefined)
5020 (define-key org-mode-map [menu-bar hide] 'undefined)
5021 (define-key org-mode-map [menu-bar show] 'undefined))
5023 (org-load-modules-maybe)
5024 (easy-menu-add org-org-menu)
5025 (easy-menu-add org-tbl-menu)
5026 (org-install-agenda-files-menu)
5027 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5028 (add-to-invisibility-spec '(org-cwidth))
5029 (add-to-invisibility-spec '(org-hide-block . t))
5030 (when (featurep 'xemacs)
5031 (org-set-local 'line-move-ignore-invisible t))
5032 (org-set-local 'outline-regexp org-outline-regexp)
5033 (org-set-local 'outline-level 'org-outline-level)
5034 (setq bidi-paragraph-direction 'left-to-right)
5035 (when (and org-ellipsis
5036 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5037 (fboundp 'make-glyph-code))
5038 (unless org-display-table
5039 (setq org-display-table (make-display-table)))
5040 (set-display-table-slot
5041 org-display-table 4
5042 (vconcat (mapcar
5043 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5044 org-ellipsis)))
5045 (if (stringp org-ellipsis) org-ellipsis "..."))))
5046 (setq buffer-display-table org-display-table))
5047 (org-set-regexps-and-options)
5048 (when (and org-tag-faces (not org-tags-special-faces-re))
5049 ;; tag faces set outside customize.... force initialization.
5050 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5051 ;; Calc embedded
5052 (org-set-local 'calc-embedded-open-mode "# ")
5053 (modify-syntax-entry ?@ "w")
5054 (modify-syntax-entry ?\" "\"")
5055 (if org-startup-truncated (setq truncate-lines t))
5056 (org-set-local 'font-lock-unfontify-region-function
5057 'org-unfontify-region)
5058 ;; Activate before-change-function
5059 (org-set-local 'org-table-may-need-update t)
5060 (org-add-hook 'before-change-functions 'org-before-change-function nil
5061 'local)
5062 ;; Check for running clock before killing a buffer
5063 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5064 ;; Initialize macros templates.
5065 (org-macro-initialize-templates)
5066 ;; Initialize radio targets.
5067 (org-update-radio-target-regexp)
5068 ;; Indentation.
5069 (org-set-local 'indent-line-function 'org-indent-line)
5070 (org-set-local 'indent-region-function 'org-indent-region)
5071 ;; Filling and auto-filling.
5072 (org-setup-filling)
5073 ;; Comments.
5074 (org-setup-comments-handling)
5075 ;; Beginning/end of defun
5076 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5077 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5078 ;; Next error for sparse trees
5079 (org-set-local 'next-error-function 'org-occur-next-match)
5080 ;; Make sure dependence stuff works reliably, even for users who set it
5081 ;; too late :-(
5082 (if org-enforce-todo-dependencies
5083 (add-hook 'org-blocker-hook
5084 'org-block-todo-from-children-or-siblings-or-parent)
5085 (remove-hook 'org-blocker-hook
5086 'org-block-todo-from-children-or-siblings-or-parent))
5087 (if org-enforce-todo-checkbox-dependencies
5088 (add-hook 'org-blocker-hook
5089 'org-block-todo-from-checkboxes)
5090 (remove-hook 'org-blocker-hook
5091 'org-block-todo-from-checkboxes))
5093 ;; Align options lines
5094 (org-set-local
5095 'align-mode-rules-list
5096 '((org-in-buffer-settings
5097 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5098 (modes . '(org-mode)))))
5100 ;; Imenu
5101 (org-set-local 'imenu-create-index-function
5102 'org-imenu-get-tree)
5104 ;; Make isearch reveal context
5105 (if (or (featurep 'xemacs)
5106 (not (boundp 'outline-isearch-open-invisible-function)))
5107 ;; Emacs 21 and XEmacs make use of the hook
5108 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5109 ;; Emacs 22 deals with this through a special variable
5110 (org-set-local 'outline-isearch-open-invisible-function
5111 (lambda (&rest ignore) (org-show-context 'isearch))))
5113 ;; Turn on org-beamer-mode?
5114 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5116 ;; Setup the pcomplete hooks
5117 (set (make-local-variable 'pcomplete-command-completion-function)
5118 'org-pcomplete-initial)
5119 (set (make-local-variable 'pcomplete-command-name-function)
5120 'org-command-at-point)
5121 (set (make-local-variable 'pcomplete-default-completion-function)
5122 'ignore)
5123 (set (make-local-variable 'pcomplete-parse-arguments-function)
5124 'org-parse-arguments)
5125 (set (make-local-variable 'pcomplete-termination-string) "")
5126 (when (>= emacs-major-version 23)
5127 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5129 ;; If empty file that did not turn on org-mode automatically, make it to.
5130 (if (and org-insert-mode-line-in-empty-file
5131 (org-called-interactively-p 'any)
5132 (= (point-min) (point-max)))
5133 (insert "# -*- mode: org -*-\n\n"))
5134 (unless org-inhibit-startup
5135 (when org-startup-align-all-tables
5136 (let ((bmp (buffer-modified-p)))
5137 (org-table-map-tables 'org-table-align 'quietly)
5138 (set-buffer-modified-p bmp)))
5139 (when org-startup-with-inline-images
5140 (org-display-inline-images))
5141 (when org-startup-indented
5142 (require 'org-indent)
5143 (org-indent-mode 1))
5144 (unless org-inhibit-startup-visibility-stuff
5145 (org-set-startup-visibility)))
5146 ;; Try to set org-hide correctly
5147 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5149 (when (fboundp 'abbrev-table-put)
5150 (abbrev-table-put org-mode-abbrev-table
5151 :parents (list text-mode-abbrev-table)))
5153 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5156 (defun org-find-invisible-foreground ()
5157 (let ((candidates (remove
5158 "unspecified-bg"
5159 (list
5160 (face-background 'default)
5161 (face-background 'org-default)
5162 (cdr (assoc 'background-color default-frame-alist))
5163 (cdr (assoc 'background-color initial-frame-alist))
5164 (cdr (assoc 'background-color window-system-default-frame-alist))
5165 (face-foreground 'org-hide)))))
5166 (car (remove nil candidates))))
5168 (defun org-current-time ()
5169 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5170 (if (> (car org-time-stamp-rounding-minutes) 1)
5171 (let ((r (car org-time-stamp-rounding-minutes))
5172 (time (decode-time)))
5173 (apply 'encode-time
5174 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5175 (nthcdr 2 time))))
5176 (current-time)))
5178 (defun org-today ()
5179 "Return today date, considering `org-extend-today-until'."
5180 (time-to-days
5181 (time-subtract (current-time)
5182 (list 0 (* 3600 org-extend-today-until) 0))))
5184 ;;;; Font-Lock stuff, including the activators
5186 (defvar org-mouse-map (make-sparse-keymap))
5187 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5188 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5189 (when org-mouse-1-follows-link
5190 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5191 (when org-tab-follows-link
5192 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5193 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5195 (require 'font-lock)
5197 (defconst org-non-link-chars "]\t\n\r<>")
5198 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5199 "shell" "elisp" "doi" "message"))
5200 (defvar org-link-types-re nil
5201 "Matches a link that has a url-like prefix like \"http:\"")
5202 (defvar org-link-re-with-space nil
5203 "Matches a link with spaces, optional angular brackets around it.")
5204 (defvar org-link-re-with-space2 nil
5205 "Matches a link with spaces, optional angular brackets around it.")
5206 (defvar org-link-re-with-space3 nil
5207 "Matches a link with spaces, only for internal part in bracket links.")
5208 (defvar org-angle-link-re nil
5209 "Matches link with angular brackets, spaces are allowed.")
5210 (defvar org-plain-link-re nil
5211 "Matches plain link, without spaces.")
5212 (defvar org-bracket-link-regexp nil
5213 "Matches a link in double brackets.")
5214 (defvar org-bracket-link-analytic-regexp nil
5215 "Regular expression used to analyze links.
5216 Here is what the match groups contain after a match:
5217 1: http:
5218 2: http
5219 3: path
5220 4: [desc]
5221 5: desc")
5222 (defvar org-bracket-link-analytic-regexp++ nil
5223 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5224 (defvar org-any-link-re nil
5225 "Regular expression matching any link.")
5227 (defcustom org-match-sexp-depth 3
5228 "Number of stacked braces for sub/superscript matching.
5229 This has to be set before loading org.el to be effective."
5230 :group 'org-export-translation ; ??????????????????????????/
5231 :type 'integer)
5233 (defun org-create-multibrace-regexp (left right n)
5234 "Create a regular expression which will match a balanced sexp.
5235 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5236 as single character strings.
5237 The regexp returned will match the entire expression including the
5238 delimiters. It will also define a single group which contains the
5239 match except for the outermost delimiters. The maximum depth of
5240 stacked delimiters is N. Escaping delimiters is not possible."
5241 (let* ((nothing (concat "[^" left right "]*?"))
5242 (or "\\|")
5243 (re nothing)
5244 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5245 (while (> n 1)
5246 (setq n (1- n)
5247 re (concat re or next)
5248 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5249 (concat left "\\(" re "\\)" right)))
5251 (defvar org-match-substring-regexp
5252 (concat
5253 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5254 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5255 "\\|"
5256 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5257 "\\|"
5258 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5259 "The regular expression matching a sub- or superscript.")
5261 (defvar org-match-substring-with-braces-regexp
5262 (concat
5263 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5264 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5265 "\\)")
5266 "The regular expression matching a sub- or superscript, forcing braces.")
5268 (defun org-make-link-regexps ()
5269 "Update the link regular expressions.
5270 This should be called after the variable `org-link-types' has changed."
5271 (setq org-link-types-re
5272 (concat
5273 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5274 org-link-re-with-space
5275 (concat
5276 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5277 "\\([^" org-non-link-chars " ]"
5278 "[^" org-non-link-chars "]*"
5279 "[^" org-non-link-chars " ]\\)>?")
5280 org-link-re-with-space2
5281 (concat
5282 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5283 "\\([^" org-non-link-chars " ]"
5284 "[^\t\n\r]*"
5285 "[^" org-non-link-chars " ]\\)>?")
5286 org-link-re-with-space3
5287 (concat
5288 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5289 "\\([^" org-non-link-chars " ]"
5290 "[^\t\n\r]*\\)")
5291 org-angle-link-re
5292 (concat
5293 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5294 "\\([^" org-non-link-chars " ]"
5295 "[^" org-non-link-chars "]*"
5296 "\\)>")
5297 org-plain-link-re
5298 (concat
5299 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5300 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5301 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5302 org-bracket-link-regexp
5303 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5304 org-bracket-link-analytic-regexp
5305 (concat
5306 "\\[\\["
5307 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5308 "\\([^]]+\\)"
5309 "\\]"
5310 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5311 "\\]")
5312 org-bracket-link-analytic-regexp++
5313 (concat
5314 "\\[\\["
5315 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5316 "\\([^]]+\\)"
5317 "\\]"
5318 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5319 "\\]")
5320 org-any-link-re
5321 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5322 org-angle-link-re "\\)\\|\\("
5323 org-plain-link-re "\\)")))
5325 (org-make-link-regexps)
5327 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5328 "Regular expression for fast time stamp matching.")
5329 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5330 "Regular expression for fast time stamp matching.")
5331 (defconst org-ts-regexp0
5332 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5333 "Regular expression matching time strings for analysis.
5334 This one does not require the space after the date, so it can be used
5335 on a string that terminates immediately after the date.")
5336 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5337 "Regular expression matching time strings for analysis.")
5338 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5339 "Regular expression matching time stamps, with groups.")
5340 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5341 "Regular expression matching time stamps (also [..]), with groups.")
5342 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5343 "Regular expression matching a time stamp range.")
5344 (defconst org-tr-regexp-both
5345 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5346 "Regular expression matching a time stamp range.")
5347 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5348 org-ts-regexp "\\)?")
5349 "Regular expression matching a time stamp or time stamp range.")
5350 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5351 org-ts-regexp-both "\\)?")
5352 "Regular expression matching a time stamp or time stamp range.
5353 The time stamps may be either active or inactive.")
5355 (defvar org-emph-face nil)
5357 (defun org-do-emphasis-faces (limit)
5358 "Run through the buffer and add overlays to emphasized strings."
5359 (let (rtn a)
5360 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5361 (if (not (= (char-after (match-beginning 3))
5362 (char-after (match-beginning 4))))
5363 (progn
5364 (setq rtn t)
5365 (setq a (assoc (match-string 3) org-emphasis-alist))
5366 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5367 'face
5368 (nth 1 a))
5369 (and (nth 4 a)
5370 (org-remove-flyspell-overlays-in
5371 (match-beginning 0) (match-end 0)))
5372 (add-text-properties (match-beginning 2) (match-end 2)
5373 '(font-lock-multiline t org-emphasis t))
5374 (when org-hide-emphasis-markers
5375 (add-text-properties (match-end 4) (match-beginning 5)
5376 '(invisible org-link))
5377 (add-text-properties (match-beginning 3) (match-end 3)
5378 '(invisible org-link)))))
5379 (backward-char 1))
5380 rtn))
5382 (defun org-emphasize (&optional char)
5383 "Insert or change an emphasis, i.e. a font like bold or italic.
5384 If there is an active region, change that region to a new emphasis.
5385 If there is no region, just insert the marker characters and position
5386 the cursor between them.
5387 CHAR should be either the marker character, or the first character of the
5388 HTML tag associated with that emphasis. If CHAR is a space, the means
5389 to remove the emphasis of the selected region.
5390 If char is not given (for example in an interactive call) it
5391 will be prompted for."
5392 (interactive)
5393 (let ((eal org-emphasis-alist) e det
5394 (erc org-emphasis-regexp-components)
5395 (prompt "")
5396 (string "") beg end move tag c s)
5397 (if (org-region-active-p)
5398 (setq beg (region-beginning) end (region-end)
5399 string (buffer-substring beg end))
5400 (setq move t))
5402 (while (setq e (pop eal))
5403 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5404 c (aref tag 0))
5405 (push (cons c (string-to-char (car e))) det)
5406 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5407 (substring tag 1)))))
5408 (setq det (nreverse det))
5409 (unless char
5410 (message "%s" (concat "Emphasis marker or tag:" prompt))
5411 (setq char (read-char-exclusive)))
5412 (setq char (or (cdr (assoc char det)) char))
5413 (if (equal char ?\ )
5414 (setq s "" move nil)
5415 (unless (assoc (char-to-string char) org-emphasis-alist)
5416 (error "No such emphasis marker: \"%c\"" char))
5417 (setq s (char-to-string char)))
5418 (while (and (> (length string) 1)
5419 (equal (substring string 0 1) (substring string -1))
5420 (assoc (substring string 0 1) org-emphasis-alist))
5421 (setq string (substring string 1 -1)))
5422 (setq string (concat s string s))
5423 (if beg (delete-region beg end))
5424 (unless (or (bolp)
5425 (string-match (concat "[" (nth 0 erc) "\n]")
5426 (char-to-string (char-before (point)))))
5427 (insert " "))
5428 (unless (or (eobp)
5429 (string-match (concat "[" (nth 1 erc) "\n]")
5430 (char-to-string (char-after (point)))))
5431 (insert " ") (backward-char 1))
5432 (insert string)
5433 (and move (backward-char 1))))
5435 (defconst org-nonsticky-props
5436 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5438 (defsubst org-rear-nonsticky-at (pos)
5439 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5441 (defun org-activate-plain-links (limit)
5442 "Run through the buffer and add overlays to links."
5443 (catch 'exit
5444 (let (f hl)
5445 (when (re-search-forward (concat org-plain-link-re) limit t)
5446 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5447 (setq f (get-text-property (match-beginning 0) 'face))
5448 (setq hl (org-match-string-no-properties 0))
5449 (if (or (eq f 'org-tag)
5450 (and (listp f) (memq 'org-tag f)))
5452 (add-text-properties (match-beginning 0) (match-end 0)
5453 (list 'mouse-face 'highlight
5454 'face 'org-link
5455 'htmlize-link `(:uri ,hl)
5456 'keymap org-mouse-map))
5457 (org-rear-nonsticky-at (match-end 0)))
5458 t))))
5460 (defun org-activate-code (limit)
5461 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5462 (progn
5463 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5464 (remove-text-properties (match-beginning 0) (match-end 0)
5465 '(display t invisible t intangible t))
5466 t)))
5468 (defcustom org-src-fontify-natively nil
5469 "When non-nil, fontify code in code blocks."
5470 :type 'boolean
5471 :version "24.1"
5472 :group 'org-appearance
5473 :group 'org-babel)
5475 (defcustom org-allow-promoting-top-level-subtree nil
5476 "When non-nil, allow promoting a top level subtree.
5477 The leading star of the top level headline will be replaced
5478 by a #."
5479 :type 'boolean
5480 :version "24.1"
5481 :group 'org-appearance)
5483 (defun org-fontify-meta-lines-and-blocks (limit)
5484 (condition-case nil
5485 (org-fontify-meta-lines-and-blocks-1 limit)
5486 (error (message "org-mode fontification error"))))
5488 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5489 "Fontify #+ lines and blocks, in the correct ways."
5490 (let ((case-fold-search t))
5491 (if (re-search-forward
5492 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5493 limit t)
5494 (let ((beg (match-beginning 0))
5495 (block-start (match-end 0))
5496 (block-end nil)
5497 (lang (match-string 7))
5498 (beg1 (line-beginning-position 2))
5499 (dc1 (downcase (match-string 2)))
5500 (dc3 (downcase (match-string 3)))
5501 end end1 quoting block-type ovl)
5502 (cond
5503 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5504 ;; a single line of backend-specific content
5505 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5506 (remove-text-properties (match-beginning 0) (match-end 0)
5507 '(display t invisible t intangible t))
5508 (add-text-properties (match-beginning 1) (match-end 3)
5509 '(font-lock-fontified t face org-meta-line))
5510 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5511 '(font-lock-fontified t face org-block))
5512 ; for backend-specific code
5514 ((and (match-end 4) (equal dc3 "+begin"))
5515 ;; Truly a block
5516 (setq block-type (downcase (match-string 5))
5517 quoting (member block-type org-protecting-blocks))
5518 (when (re-search-forward
5519 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5520 nil t) ;; on purpose, we look further than LIMIT
5521 (setq end (min (point-max) (match-end 0))
5522 end1 (min (point-max) (1- (match-beginning 0))))
5523 (setq block-end (match-beginning 0))
5524 (when quoting
5525 (remove-text-properties beg end
5526 '(display t invisible t intangible t)))
5527 (add-text-properties
5528 beg end
5529 '(font-lock-fontified t font-lock-multiline t))
5530 (add-text-properties beg beg1 '(face org-meta-line))
5531 (add-text-properties end1 (min (point-max) (1+ end))
5532 '(face org-meta-line)) ; for end_src
5533 (cond
5534 ((and lang (not (string= lang "")) org-src-fontify-natively)
5535 (org-src-font-lock-fontify-block lang block-start block-end)
5536 ;; remove old background overlays
5537 (mapc (lambda (ov)
5538 (if (eq (overlay-get ov 'face) 'org-block-background)
5539 (delete-overlay ov)))
5540 (overlays-at (/ (+ beg1 block-end) 2)))
5541 ;; add a background overlay
5542 (setq ovl (make-overlay beg1 block-end))
5543 (overlay-put ovl 'face 'org-block-background)
5544 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5545 (quoting
5546 (add-text-properties beg1 (min (point-max) (1+ end1))
5547 '(face org-block))) ; end of source block
5548 ((not org-fontify-quote-and-verse-blocks))
5549 ((string= block-type "quote")
5550 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5551 ((string= block-type "verse")
5552 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5553 (add-text-properties beg beg1 '(face org-block-begin-line))
5554 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5555 '(face org-block-end-line))
5557 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5558 (add-text-properties
5559 beg (match-end 3)
5560 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5561 '(font-lock-fontified t invisible t)
5562 '(font-lock-fontified t face org-document-info-keyword)))
5563 (add-text-properties
5564 (match-beginning 6) (match-end 6)
5565 (if (string-equal dc1 "+title:")
5566 '(font-lock-fontified t face org-document-title)
5567 '(font-lock-fontified t face org-document-info))))
5568 ((or (equal dc1 "+results")
5569 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5570 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5571 "+call:" "+header:" "+headers:" "+name:"))
5572 (and (match-end 4) (equal dc3 "+attr")))
5573 (add-text-properties
5574 beg (match-end 0)
5575 '(font-lock-fontified t face org-meta-line))
5577 ((member dc3 '(" " ""))
5578 (add-text-properties
5579 beg (match-end 0)
5580 '(font-lock-fontified t face font-lock-comment-face)))
5581 ((not (member (char-after beg) '(?\ ?\t)))
5582 ;; just any other in-buffer setting, but not indented
5583 (add-text-properties
5584 beg (match-end 0)
5585 '(font-lock-fontified t face org-meta-line))
5587 (t nil))))))
5589 (defun org-strip-protective-commas (beg end)
5590 "Strip protective commas between BEG and END in the current buffer."
5591 (interactive "r")
5592 (save-excursion
5593 (save-match-data
5594 (goto-char beg)
5595 (let ((front-line (save-excursion
5596 (re-search-forward
5597 "[^[:space:]]" end t)
5598 (goto-char (match-beginning 0))
5599 (current-column))))
5600 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5601 (goto-char (match-beginning 1))
5602 (when (= (current-column) front-line)
5603 (replace-match "" nil nil nil 1)))))))
5605 (defun org-activate-angle-links (limit)
5606 "Run through the buffer and add overlays to links."
5607 (if (re-search-forward org-angle-link-re limit t)
5608 (progn
5609 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5610 (add-text-properties (match-beginning 0) (match-end 0)
5611 (list 'mouse-face 'highlight
5612 'keymap org-mouse-map))
5613 (org-rear-nonsticky-at (match-end 0))
5614 t)))
5616 (defun org-activate-footnote-links (limit)
5617 "Run through the buffer and add overlays to footnotes."
5618 (let ((fn (org-footnote-next-reference-or-definition limit)))
5619 (when fn
5620 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5621 (org-remove-flyspell-overlays-in beg end)
5622 (add-text-properties beg end
5623 (list 'mouse-face 'highlight
5624 'keymap org-mouse-map
5625 'help-echo
5626 (if (= (point-at-bol) beg)
5627 "Footnote definition"
5628 "Footnote reference")
5629 'font-lock-fontified t
5630 'font-lock-multiline t
5631 'face 'org-footnote))))))
5633 (defun org-activate-bracket-links (limit)
5634 "Run through the buffer and add overlays to bracketed links."
5635 (if (re-search-forward org-bracket-link-regexp limit t)
5636 (let* ((hl (org-match-string-no-properties 1))
5637 (help (concat "LINK: " hl))
5638 ;; FIXME: Above we should remove the escapes. But that
5639 ;; requires another match, protecting match data, a lot
5640 ;; of overhead for font-lock.
5641 (ip (org-maybe-intangible
5642 (list 'invisible 'org-link
5643 'keymap org-mouse-map 'mouse-face 'highlight
5644 'font-lock-multiline t 'help-echo help
5645 'htmlize-link `(:uri ,hl))))
5646 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5647 'font-lock-multiline t 'help-echo help
5648 'htmlize-link `(:uri ,hl))))
5649 ;; We need to remove the invisible property here. Table narrowing
5650 ;; may have made some of this invisible.
5651 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5652 (remove-text-properties (match-beginning 0) (match-end 0)
5653 '(invisible nil))
5654 (if (match-end 3)
5655 (progn
5656 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5657 (org-rear-nonsticky-at (match-beginning 3))
5658 (add-text-properties (match-beginning 3) (match-end 3) vp)
5659 (org-rear-nonsticky-at (match-end 3))
5660 (add-text-properties (match-end 3) (match-end 0) ip)
5661 (org-rear-nonsticky-at (match-end 0)))
5662 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5663 (org-rear-nonsticky-at (match-beginning 1))
5664 (add-text-properties (match-beginning 1) (match-end 1) vp)
5665 (org-rear-nonsticky-at (match-end 1))
5666 (add-text-properties (match-end 1) (match-end 0) ip)
5667 (org-rear-nonsticky-at (match-end 0)))
5668 t)))
5670 (defun org-activate-dates (limit)
5671 "Run through the buffer and add overlays to dates."
5672 (if (re-search-forward org-tsr-regexp-both limit t)
5673 (progn
5674 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5675 (add-text-properties (match-beginning 0) (match-end 0)
5676 (list 'mouse-face 'highlight
5677 'keymap org-mouse-map))
5678 (org-rear-nonsticky-at (match-end 0))
5679 (when org-display-custom-times
5680 (if (match-end 3)
5681 (org-display-custom-time (match-beginning 3) (match-end 3)))
5682 (org-display-custom-time (match-beginning 1) (match-end 1)))
5683 t)))
5685 (defvar org-target-link-regexp nil
5686 "Regular expression matching radio targets in plain text.")
5687 (make-variable-buffer-local 'org-target-link-regexp)
5688 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5689 "Regular expression matching a link target.")
5690 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5691 "Regular expression matching a radio target.")
5692 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5693 "Regular expression matching any target.")
5695 (defun org-activate-target-links (limit)
5696 "Run through the buffer and add overlays to target matches."
5697 (when org-target-link-regexp
5698 (let ((case-fold-search t))
5699 (if (re-search-forward org-target-link-regexp limit t)
5700 (progn
5701 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5702 (add-text-properties (match-beginning 0) (match-end 0)
5703 (list 'mouse-face 'highlight
5704 'keymap org-mouse-map
5705 'help-echo "Radio target link"
5706 'org-linked-text t))
5707 (org-rear-nonsticky-at (match-end 0))
5708 t)))))
5710 (defun org-update-radio-target-regexp ()
5711 "Find all radio targets in this file and update the regular expression."
5712 (interactive)
5713 (when (memq 'radio org-activate-links)
5714 (setq org-target-link-regexp
5715 (org-make-target-link-regexp (org-all-targets 'radio)))
5716 (org-restart-font-lock)))
5718 (defun org-hide-wide-columns (limit)
5719 (let (s e)
5720 (setq s (text-property-any (point) (or limit (point-max))
5721 'org-cwidth t))
5722 (when s
5723 (setq e (next-single-property-change s 'org-cwidth))
5724 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5725 (goto-char e)
5726 t)))
5728 (defvar org-latex-and-specials-regexp nil
5729 "Regular expression for highlighting export special stuff.")
5730 (defvar org-match-substring-regexp)
5731 (defvar org-match-substring-with-braces-regexp)
5733 ;; This should be with the exporter code, but we also use if for font-locking
5734 (defconst org-export-html-special-string-regexps
5735 '(("\\\\-" . "&shy;")
5736 ("---\\([^-]\\)" . "&mdash;\\1")
5737 ("--\\([^-]\\)" . "&ndash;\\1")
5738 ("\\.\\.\\." . "&hellip;"))
5739 "Regular expressions for special string conversion.")
5742 (defun org-compute-latex-and-specials-regexp ()
5743 "Compute regular expression for stuff treated specially by exporters."
5744 (if (not org-highlight-latex-fragments-and-specials)
5745 (org-set-local 'org-latex-and-specials-regexp nil)
5746 (require 'org-exp)
5747 (let*
5748 ((matchers (plist-get org-format-latex-options :matchers))
5749 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5750 org-latex-regexps)))
5751 (org-export-allow-BIND nil)
5752 (options (org-combine-plists (org-default-export-plist)
5753 (org-infile-export-plist)))
5754 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5755 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5756 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5757 (org-export-html-expand (plist-get options :expand-quoted-html))
5758 (org-export-with-special-strings (plist-get options :special-strings))
5759 (re-sub
5760 (cond
5761 ((equal org-export-with-sub-superscripts '{})
5762 (list org-match-substring-with-braces-regexp))
5763 (org-export-with-sub-superscripts
5764 (list org-match-substring-regexp))))
5765 (re-latex
5766 (if org-export-with-LaTeX-fragments
5767 (mapcar (lambda (x) (nth 1 x)) latexs)))
5768 (re-macros
5769 (if org-export-with-TeX-macros
5770 (list (concat "\\\\"
5771 (regexp-opt
5772 (append
5774 (delq nil
5775 (mapcar 'car-safe
5776 (append org-entities-user
5777 org-entities)))
5778 (if (boundp 'org-latex-entities)
5779 (mapcar (lambda (x)
5780 (or (car-safe x) x))
5781 org-latex-entities)
5782 nil))
5783 'words))) ; FIXME
5785 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5786 (re-special (if org-export-with-special-strings
5787 (mapcar (lambda (x) (car x))
5788 org-export-html-special-string-regexps)))
5789 (re-rest
5790 (delq nil
5791 (list
5792 (if org-export-html-expand "@<[^>\n]+>")
5793 ))))
5794 (org-set-local
5795 'org-latex-and-specials-regexp
5796 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5797 re-rest) "\\|")))))
5799 (defun org-do-latex-and-special-faces (limit)
5800 "Run through the buffer and add overlays to links."
5801 (when org-latex-and-specials-regexp
5802 (let (rtn d)
5803 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5804 limit t))
5805 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5806 'face))
5807 '(org-code org-verbatim underline)))
5808 (progn
5809 (setq rtn t
5810 d (cond ((member (char-after (1+ (match-beginning 0)))
5811 '(?_ ?^)) 1)
5812 (t 0)))
5813 (font-lock-prepend-text-property
5814 (+ d (match-beginning 0)) (match-end 0)
5815 'face 'org-latex-and-export-specials)
5816 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5817 '(font-lock-multiline t)))))
5818 rtn)))
5820 (defun org-restart-font-lock ()
5821 "Restart `font-lock-mode', to force refontification."
5822 (when (and (boundp 'font-lock-mode) font-lock-mode)
5823 (font-lock-mode -1)
5824 (font-lock-mode 1)))
5826 (defun org-all-targets (&optional radio)
5827 "Return a list of all targets in this file.
5828 With optional argument RADIO, only find radio targets."
5829 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5830 rtn)
5831 (save-excursion
5832 (goto-char (point-min))
5833 (while (re-search-forward re nil t)
5834 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5835 rtn)))
5837 (defun org-make-target-link-regexp (targets)
5838 "Make regular expression matching all strings in TARGETS.
5839 The regular expression finds the targets also if there is a line break
5840 between words."
5841 (and targets
5842 (concat
5843 "\\<\\("
5844 (mapconcat
5845 (lambda (x)
5846 (setq x (regexp-quote x))
5847 (while (string-match " +" x)
5848 (setq x (replace-match "\\s-+" t t x)))
5850 targets
5851 "\\|")
5852 "\\)\\>")))
5854 (defun org-activate-tags (limit)
5855 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5856 (progn
5857 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5858 (add-text-properties (match-beginning 1) (match-end 1)
5859 (list 'mouse-face 'highlight
5860 'keymap org-mouse-map))
5861 (org-rear-nonsticky-at (match-end 1))
5862 t)))
5864 (defun org-outline-level ()
5865 "Compute the outline level of the heading at point.
5866 If this is called at a normal headline, the level is the number of stars.
5867 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5868 (save-excursion
5869 (if (not (condition-case nil
5870 (org-back-to-heading t)
5871 (error nil)))
5873 (looking-at org-outline-regexp)
5874 (1- (- (match-end 0) (match-beginning 0))))))
5876 (defvar org-font-lock-keywords nil)
5878 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5879 "Regular expression matching a property line.")
5881 (defvar org-font-lock-hook nil
5882 "Functions to be called for special font lock stuff.")
5884 (defvar org-font-lock-set-keywords-hook nil
5885 "Functions that can manipulate `org-font-lock-extra-keywords'.
5886 This is called after `org-font-lock-extra-keywords' is defined, but before
5887 it is installed to be used by font lock. This can be useful if something
5888 needs to be inserted at a specific position in the font-lock sequence.")
5890 (defun org-font-lock-hook (limit)
5891 "Run `org-font-lock-hook' within LIMIT."
5892 (run-hook-with-args 'org-font-lock-hook limit))
5894 (defun org-set-font-lock-defaults ()
5895 "Set font lock defaults for the current buffer."
5896 (let* ((em org-fontify-emphasized-text)
5897 (lk org-activate-links)
5898 (org-font-lock-extra-keywords
5899 (list
5900 ;; Call the hook
5901 '(org-font-lock-hook)
5902 ;; Headlines
5903 `(,(if org-fontify-whole-heading-line
5904 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5905 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5906 (1 (org-get-level-face 1))
5907 (2 (org-get-level-face 2))
5908 (3 (org-get-level-face 3)))
5909 ;; Table lines
5910 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5911 (1 'org-table t))
5912 ;; Table internals
5913 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5914 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5915 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5916 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5917 ;; Drawers
5918 (list org-drawer-regexp '(0 'org-special-keyword t))
5919 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5920 ;; Properties
5921 (list org-property-re
5922 '(1 'org-special-keyword t)
5923 '(3 'org-property-value t))
5924 ;; Links
5925 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5926 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5927 (if (memq 'plain lk) '(org-activate-plain-links))
5928 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5929 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5930 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5931 (if (memq 'footnote lk) '(org-activate-footnote-links))
5932 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5933 '(org-hide-wide-columns (0 nil append))
5934 ;; TODO keyword
5935 (list (format org-heading-keyword-regexp-format
5936 org-todo-regexp)
5937 '(2 (org-get-todo-face 2) t))
5938 ;; DONE
5939 (if org-fontify-done-headline
5940 (list (format org-heading-keyword-regexp-format
5941 (concat
5942 "\\(?:"
5943 (mapconcat 'regexp-quote org-done-keywords "\\|")
5944 "\\)"))
5945 '(2 'org-headline-done t))
5946 nil)
5947 ;; Priorities
5948 '(org-font-lock-add-priority-faces)
5949 ;; Tags
5950 '(org-font-lock-add-tag-faces)
5951 ;; Special keywords
5952 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5953 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5954 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5955 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5956 ;; Emphasis
5957 (if em
5958 (if (featurep 'xemacs)
5959 '(org-do-emphasis-faces (0 nil append))
5960 '(org-do-emphasis-faces)))
5961 ;; Checkboxes
5962 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5963 1 'org-checkbox prepend)
5964 (if (cdr (assq 'checkbox org-list-automatic-rules))
5965 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5966 (0 (org-get-checkbox-statistics-face) t)))
5967 ;; Description list items
5968 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5969 1 'org-list-dt prepend)
5970 ;; ARCHIVEd headings
5971 (list (concat
5972 org-outline-regexp-bol
5973 "\\(.*:" org-archive-tag ":.*\\)")
5974 '(1 'org-archived prepend))
5975 ;; Specials
5976 '(org-do-latex-and-special-faces)
5977 '(org-fontify-entities)
5978 '(org-raise-scripts)
5979 ;; Code
5980 '(org-activate-code (1 'org-code t))
5981 ;; COMMENT
5982 (list (format org-heading-keyword-regexp-format
5983 (concat "\\("
5984 org-comment-string "\\|" org-quote-string
5985 "\\)"))
5986 '(2 'org-special-keyword t))
5987 ;; Blocks and meta lines
5988 '(org-fontify-meta-lines-and-blocks)
5990 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5991 (run-hooks 'org-font-lock-set-keywords-hook)
5992 ;; Now set the full font-lock-keywords
5993 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5994 (org-set-local 'font-lock-defaults
5995 '(org-font-lock-keywords t nil nil backward-paragraph))
5996 (kill-local-variable 'font-lock-keywords) nil))
5998 (defun org-toggle-pretty-entities ()
5999 "Toggle the composition display of entities as UTF8 characters."
6000 (interactive)
6001 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6002 (org-restart-font-lock)
6003 (if org-pretty-entities
6004 (message "Entities are displayed as UTF8 characters")
6005 (save-restriction
6006 (widen)
6007 (org-decompose-region (point-min) (point-max))
6008 (message "Entities are displayed plain"))))
6010 (defvar org-custom-properties-overlays nil
6011 "List of overlays used for custom properties.")
6012 (make-variable-buffer-local 'org-custom-properties-overlays)
6014 (defun org-toggle-custom-properties-visibility ()
6015 "Display or hide properties in `org-custom-properties'."
6016 (interactive)
6017 (if org-custom-properties-overlays
6018 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6019 (setq org-custom-properties-overlays nil))
6020 (unless (not org-custom-properties)
6021 (save-excursion
6022 (save-restriction
6023 (widen)
6024 (goto-char (point-min))
6025 (while (re-search-forward org-property-re nil t)
6026 (mapc (lambda(p)
6027 (when (equal p (substring (match-string 1) 1 -1))
6028 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6029 (overlay-put o 'invisible t)
6030 (overlay-put o 'org-custom-property t)
6031 (push o org-custom-properties-overlays))))
6032 org-custom-properties)))))))
6034 (defun org-fontify-entities (limit)
6035 "Find an entity to fontify."
6036 (let (ee)
6037 (when org-pretty-entities
6038 (catch 'match
6039 (while (re-search-forward
6040 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6041 limit t)
6042 (if (and (not (org-in-indented-comment-line))
6043 (setq ee (org-entity-get (match-string 1)))
6044 (= (length (nth 6 ee)) 1))
6045 (let*
6046 ((end (if (equal (match-string 2) "{}")
6047 (match-end 2)
6048 (match-end 1))))
6049 (add-text-properties
6050 (match-beginning 0) end
6051 (list 'font-lock-fontified t))
6052 (compose-region (match-beginning 0) end
6053 (nth 6 ee) nil)
6054 (backward-char 1)
6055 (throw 'match t))))
6056 nil))))
6058 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6059 "Fontify string S like in Org-mode."
6060 (with-temp-buffer
6061 (insert s)
6062 (let ((org-odd-levels-only odd-levels))
6063 (org-mode)
6064 (font-lock-fontify-buffer)
6065 (buffer-string))))
6067 (defvar org-m nil)
6068 (defvar org-l nil)
6069 (defvar org-f nil)
6070 (defun org-get-level-face (n)
6071 "Get the right face for match N in font-lock matching of headlines."
6072 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6073 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6074 (if org-cycle-level-faces
6075 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6076 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6077 (cond
6078 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6079 ((eq n 2) org-f)
6080 (t (if org-level-color-stars-only nil org-f))))
6083 (defun org-get-todo-face (kwd)
6084 "Get the right face for a TODO keyword KWD.
6085 If KWD is a number, get the corresponding match group."
6086 (if (numberp kwd) (setq kwd (match-string kwd)))
6087 (or (org-face-from-face-or-color
6088 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6089 (and (member kwd org-done-keywords) 'org-done)
6090 'org-todo))
6092 (defun org-face-from-face-or-color (context inherit face-or-color)
6093 "Create a face list that inherits INHERIT, but sets the foreground color.
6094 When FACE-OR-COLOR is not a string, just return it."
6095 (if (stringp face-or-color)
6096 (list :inherit inherit
6097 (cdr (assoc context org-faces-easy-properties))
6098 face-or-color)
6099 face-or-color))
6101 (defun org-font-lock-add-tag-faces (limit)
6102 "Add the special tag faces."
6103 (when (and org-tag-faces org-tags-special-faces-re)
6104 (while (re-search-forward org-tags-special-faces-re limit t)
6105 (add-text-properties (match-beginning 1) (match-end 1)
6106 (list 'face (org-get-tag-face 1)
6107 'font-lock-fontified t))
6108 (backward-char 1))))
6110 (defun org-font-lock-add-priority-faces (limit)
6111 "Add the special priority faces."
6112 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6113 (when (save-match-data (org-at-heading-p))
6114 (add-text-properties
6115 (match-beginning 0) (match-end 0)
6116 (list 'face (or (org-face-from-face-or-color
6117 'priority 'org-special-keyword
6118 (cdr (assoc (char-after (match-beginning 1))
6119 org-priority-faces)))
6120 'org-special-keyword)
6121 'font-lock-fontified t)))))
6123 (defun org-get-tag-face (kwd)
6124 "Get the right face for a TODO keyword KWD.
6125 If KWD is a number, get the corresponding match group."
6126 (if (numberp kwd) (setq kwd (match-string kwd)))
6127 (or (org-face-from-face-or-color
6128 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6129 'org-tag))
6131 (defun org-unfontify-region (beg end &optional maybe_loudly)
6132 "Remove fontification and activation overlays from links."
6133 (font-lock-default-unfontify-region beg end)
6134 (let* ((buffer-undo-list t)
6135 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6136 (inhibit-modification-hooks t)
6137 deactivate-mark buffer-file-name buffer-file-truename)
6138 (org-decompose-region beg end)
6139 (remove-text-properties beg end
6140 '(mouse-face t keymap t org-linked-text t
6141 invisible t intangible t
6142 org-no-flyspell t org-emphasis t))
6143 (org-remove-font-lock-display-properties beg end)))
6145 (defconst org-script-display '(((raise -0.3) (height 0.7))
6146 ((raise 0.3) (height 0.7))
6147 ((raise -0.5))
6148 ((raise 0.5)))
6149 "Display properties for showing superscripts and subscripts.")
6151 (defun org-remove-font-lock-display-properties (beg end)
6152 "Remove specific display properties that have been added by font lock.
6153 The will remove the raise properties that are used to show superscripts
6154 and subscripts."
6155 (let (next prop)
6156 (while (< beg end)
6157 (setq next (next-single-property-change beg 'display nil end)
6158 prop (get-text-property beg 'display))
6159 (if (member prop org-script-display)
6160 (put-text-property beg next 'display nil))
6161 (setq beg next))))
6163 (defun org-raise-scripts (limit)
6164 "Add raise properties to sub/superscripts."
6165 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6166 (if (re-search-forward
6167 (if (eq org-use-sub-superscripts t)
6168 org-match-substring-regexp
6169 org-match-substring-with-braces-regexp)
6170 limit t)
6171 (let* ((pos (point)) table-p comment-p
6172 (mpos (match-beginning 3))
6173 (emph-p (get-text-property mpos 'org-emphasis))
6174 (link-p (get-text-property mpos 'mouse-face))
6175 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6176 (goto-char (point-at-bol))
6177 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6178 comment-p (org-looking-at-p "[ \t]*#"))
6179 (goto-char pos)
6180 ;; FIXME: Should we go back one character here, for a_b^c
6181 ;; (goto-char (1- pos)) ;????????????????????
6182 (if (or comment-p emph-p link-p keyw-p)
6184 (put-text-property (match-beginning 3) (match-end 0)
6185 'display
6186 (if (equal (char-after (match-beginning 2)) ?^)
6187 (nth (if table-p 3 1) org-script-display)
6188 (nth (if table-p 2 0) org-script-display)))
6189 (add-text-properties (match-beginning 2) (match-end 2)
6190 (list 'invisible t
6191 'org-dwidth t 'org-dwidth-n 1))
6192 (if (and (eq (char-after (match-beginning 3)) ?{)
6193 (eq (char-before (match-end 3)) ?}))
6194 (progn
6195 (add-text-properties
6196 (match-beginning 3) (1+ (match-beginning 3))
6197 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6198 (add-text-properties
6199 (1- (match-end 3)) (match-end 3)
6200 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6201 t)))))
6203 ;;;; Visibility cycling, including org-goto and indirect buffer
6205 ;;; Cycling
6207 (defvar org-cycle-global-status nil)
6208 (make-variable-buffer-local 'org-cycle-global-status)
6209 (defvar org-cycle-subtree-status nil)
6210 (make-variable-buffer-local 'org-cycle-subtree-status)
6212 ;;;###autoload
6214 (defvar org-inlinetask-min-level)
6216 (defun org-cycle (&optional arg)
6217 "TAB-action and visibility cycling for Org-mode.
6219 This is the command invoked in Org-mode by the TAB key. Its main purpose
6220 is outline visibility cycling, but it also invokes other actions
6221 in special contexts.
6223 - When this function is called with a prefix argument, rotate the entire
6224 buffer through 3 states (global cycling)
6225 1. OVERVIEW: Show only top-level headlines.
6226 2. CONTENTS: Show all headlines of all levels, but no body text.
6227 3. SHOW ALL: Show everything.
6228 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6229 determined by the variable `org-startup-folded', and by any VISIBILITY
6230 properties in the buffer.
6231 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6232 including any drawers.
6234 - When inside a table, re-align the table and move to the next field.
6236 - When point is at the beginning of a headline, rotate the subtree started
6237 by this line through 3 different states (local cycling)
6238 1. FOLDED: Only the main headline is shown.
6239 2. CHILDREN: The main headline and the direct children are shown.
6240 From this state, you can move to one of the children
6241 and zoom in further.
6242 3. SUBTREE: Show the entire subtree, including body text.
6243 If there is no subtree, switch directly from CHILDREN to FOLDED.
6245 - When point is at the beginning of an empty headline and the variable
6246 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6247 of the headline by demoting and promoting it to likely levels. This
6248 speeds up creation document structure by pressing TAB once or several
6249 times right after creating a new headline.
6251 - When there is a numeric prefix, go up to a heading with level ARG, do
6252 a `show-subtree' and return to the previous cursor position. If ARG
6253 is negative, go up that many levels.
6255 - When point is not at the beginning of a headline, execute the global
6256 binding for TAB, which is re-indenting the line. See the option
6257 `org-cycle-emulate-tab' for details.
6259 - Special case: if point is at the beginning of the buffer and there is
6260 no headline in line 1, this function will act as if called with prefix arg
6261 (C-u TAB, same as S-TAB) also when called without prefix arg.
6262 But only if also the variable `org-cycle-global-at-bob' is t."
6263 (interactive "P")
6264 (org-load-modules-maybe)
6265 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6266 (and org-cycle-level-after-item/entry-creation
6267 (or (org-cycle-level)
6268 (org-cycle-item-indentation))))
6269 (let* ((limit-level
6270 (or org-cycle-max-level
6271 (and (boundp 'org-inlinetask-min-level)
6272 org-inlinetask-min-level
6273 (1- org-inlinetask-min-level))))
6274 (nstars (and limit-level
6275 (if org-odd-levels-only
6276 (and limit-level (1- (* limit-level 2)))
6277 limit-level)))
6278 (org-outline-regexp
6279 (if (not (derived-mode-p 'org-mode))
6280 outline-regexp
6281 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6282 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6283 (not (looking-at org-outline-regexp))))
6284 (org-cycle-hook
6285 (if bob-special
6286 (delq 'org-optimize-window-after-visibility-change
6287 (copy-sequence org-cycle-hook))
6288 org-cycle-hook))
6289 (pos (point)))
6291 (if (or bob-special (equal arg '(4)))
6292 ;; special case: use global cycling
6293 (setq arg t))
6295 (cond
6297 ((equal arg '(16))
6298 (setq last-command 'dummy)
6299 (org-set-startup-visibility)
6300 (message "Startup visibility, plus VISIBILITY properties"))
6302 ((equal arg '(64))
6303 (show-all)
6304 (message "Entire buffer visible, including drawers"))
6306 ;; Table: enter it or move to the next field.
6307 ((org-at-table-p 'any)
6308 (if (org-at-table.el-p)
6309 (message "Use C-c ' to edit table.el tables")
6310 (if arg (org-table-edit-field t)
6311 (org-table-justify-field-maybe)
6312 (call-interactively 'org-table-next-field))))
6314 ((run-hook-with-args-until-success
6315 'org-tab-after-check-for-table-hook))
6317 ;; Global cycling: delegate to `org-cycle-internal-global'.
6318 ((eq arg t) (org-cycle-internal-global))
6320 ;; Drawers: delegate to `org-flag-drawer'.
6321 ((and org-drawers org-drawer-regexp
6322 (save-excursion
6323 (beginning-of-line 1)
6324 (looking-at org-drawer-regexp)))
6325 (org-flag-drawer ; toggle block visibility
6326 (not (get-char-property (match-end 0) 'invisible))))
6328 ;; Show-subtree, ARG levels up from here.
6329 ((integerp arg)
6330 (save-excursion
6331 (org-back-to-heading)
6332 (outline-up-heading (if (< arg 0) (- arg)
6333 (- (funcall outline-level) arg)))
6334 (org-show-subtree)))
6336 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6337 ((and (featurep 'org-inlinetask)
6338 (org-inlinetask-at-task-p)
6339 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6340 (org-inlinetask-toggle-visibility))
6342 ((org-try-cdlatex-tab))
6344 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6345 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6346 (save-excursion (beginning-of-line 1)
6347 (looking-at org-outline-regexp)))
6348 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6349 (org-cycle-internal-local))
6351 ;; From there: TAB emulation and template completion.
6352 (buffer-read-only (org-back-to-heading))
6354 ((run-hook-with-args-until-success
6355 'org-tab-after-check-for-cycling-hook))
6357 ((org-try-structure-completion))
6359 ((run-hook-with-args-until-success
6360 'org-tab-before-tab-emulation-hook))
6362 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6363 (or (not (bolp))
6364 (not (looking-at org-outline-regexp))))
6365 (call-interactively (global-key-binding "\t")))
6367 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6368 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6369 (or (and (eq org-cycle-emulate-tab 'white)
6370 (= (match-end 0) (point-at-eol)))
6371 (and (eq org-cycle-emulate-tab 'whitestart)
6372 (>= (match-end 0) pos))))
6374 (eq org-cycle-emulate-tab t))
6375 (call-interactively (global-key-binding "\t")))
6377 (t (save-excursion
6378 (org-back-to-heading)
6379 (org-cycle)))))))
6381 (defun org-cycle-internal-global ()
6382 "Do the global cycling action."
6383 ;; Hack to avoid display of messages for .org attachments in Gnus
6384 (let ((ga (string-match "\\*fontification" (buffer-name))))
6385 (cond
6386 ((and (eq last-command this-command)
6387 (eq org-cycle-global-status 'overview))
6388 ;; We just created the overview - now do table of contents
6389 ;; This can be slow in very large buffers, so indicate action
6390 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6391 (unless ga (message "CONTENTS..."))
6392 (org-content)
6393 (unless ga (message "CONTENTS...done"))
6394 (setq org-cycle-global-status 'contents)
6395 (run-hook-with-args 'org-cycle-hook 'contents))
6397 ((and (eq last-command this-command)
6398 (eq org-cycle-global-status 'contents))
6399 ;; We just showed the table of contents - now show everything
6400 (run-hook-with-args 'org-pre-cycle-hook 'all)
6401 (show-all)
6402 (unless ga (message "SHOW ALL"))
6403 (setq org-cycle-global-status 'all)
6404 (run-hook-with-args 'org-cycle-hook 'all))
6407 ;; Default action: go to overview
6408 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6409 (org-overview)
6410 (unless ga (message "OVERVIEW"))
6411 (setq org-cycle-global-status 'overview)
6412 (run-hook-with-args 'org-cycle-hook 'overview)))))
6414 (defun org-cycle-internal-local ()
6415 "Do the local cycling action."
6416 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6417 ;; First, determine end of headline (EOH), end of subtree or item
6418 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6419 (save-excursion
6420 (if (org-at-item-p)
6421 (progn
6422 (beginning-of-line)
6423 (setq struct (org-list-struct))
6424 (setq eoh (point-at-eol))
6425 (setq eos (org-list-get-item-end-before-blank (point) struct))
6426 (setq has-children (org-list-has-child-p (point) struct)))
6427 (org-back-to-heading)
6428 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6429 (setq eos (save-excursion
6430 (org-end-of-subtree t)
6431 (unless (eobp)
6432 (skip-chars-forward " \t\n"))
6433 (if (eobp) (point) (1- (point)))))
6434 (setq has-children
6435 (or (save-excursion
6436 (let ((level (funcall outline-level)))
6437 (outline-next-heading)
6438 (and (org-at-heading-p t)
6439 (> (funcall outline-level) level))))
6440 (save-excursion
6441 (org-list-search-forward (org-item-beginning-re) eos t)))))
6442 ;; Determine end invisible part of buffer (EOL)
6443 (beginning-of-line 2)
6444 ;; XEmacs doesn't have `next-single-char-property-change'
6445 (if (featurep 'xemacs)
6446 (while (and (not (eobp)) ;; this is like `next-line'
6447 (get-char-property (1- (point)) 'invisible))
6448 (beginning-of-line 2))
6449 (while (and (not (eobp)) ;; this is like `next-line'
6450 (get-char-property (1- (point)) 'invisible))
6451 (goto-char (next-single-char-property-change (point) 'invisible))
6452 (and (eolp) (beginning-of-line 2))))
6453 (setq eol (point)))
6454 ;; Find out what to do next and set `this-command'
6455 (cond
6456 ((= eos eoh)
6457 ;; Nothing is hidden behind this heading
6458 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6459 (message "EMPTY ENTRY")
6460 (setq org-cycle-subtree-status nil)
6461 (save-excursion
6462 (goto-char eos)
6463 (outline-next-heading)
6464 (if (outline-invisible-p) (org-flag-heading nil))))
6465 ((and (or (>= eol eos)
6466 (not (string-match "\\S-" (buffer-substring eol eos))))
6467 (or has-children
6468 (not (setq children-skipped
6469 org-cycle-skip-children-state-if-no-children))))
6470 ;; Entire subtree is hidden in one line: children view
6471 (run-hook-with-args 'org-pre-cycle-hook 'children)
6472 (if (org-at-item-p)
6473 (org-list-set-item-visibility (point-at-bol) struct 'children)
6474 (org-show-entry)
6475 (org-with-limited-levels (show-children))
6476 ;; FIXME: This slows down the func way too much.
6477 ;; How keep drawers hidden in subtree anyway?
6478 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6479 ;; (org-cycle-hide-drawers 'subtree))
6481 ;; Fold every list in subtree to top-level items.
6482 (when (eq org-cycle-include-plain-lists 'integrate)
6483 (save-excursion
6484 (org-back-to-heading)
6485 (while (org-list-search-forward (org-item-beginning-re) eos t)
6486 (beginning-of-line 1)
6487 (let* ((struct (org-list-struct))
6488 (prevs (org-list-prevs-alist struct))
6489 (end (org-list-get-bottom-point struct)))
6490 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6491 (org-list-get-all-items (point) struct prevs))
6492 (goto-char end))))))
6493 (message "CHILDREN")
6494 (save-excursion
6495 (goto-char eos)
6496 (outline-next-heading)
6497 (if (outline-invisible-p) (org-flag-heading nil)))
6498 (setq org-cycle-subtree-status 'children)
6499 (run-hook-with-args 'org-cycle-hook 'children))
6500 ((or children-skipped
6501 (and (eq last-command this-command)
6502 (eq org-cycle-subtree-status 'children)))
6503 ;; We just showed the children, or no children are there,
6504 ;; now show everything.
6505 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6506 (outline-flag-region eoh eos nil)
6507 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6508 (setq org-cycle-subtree-status 'subtree)
6509 (run-hook-with-args 'org-cycle-hook 'subtree))
6511 ;; Default action: hide the subtree.
6512 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6513 (outline-flag-region eoh eos t)
6514 (message "FOLDED")
6515 (setq org-cycle-subtree-status 'folded)
6516 (run-hook-with-args 'org-cycle-hook 'folded)))))
6518 ;;;###autoload
6519 (defun org-global-cycle (&optional arg)
6520 "Cycle the global visibility. For details see `org-cycle'.
6521 With \\[universal-argument] prefix arg, switch to startup visibility.
6522 With a numeric prefix, show all headlines up to that level."
6523 (interactive "P")
6524 (let ((org-cycle-include-plain-lists
6525 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6526 (cond
6527 ((integerp arg)
6528 (show-all)
6529 (hide-sublevels arg)
6530 (setq org-cycle-global-status 'contents))
6531 ((equal arg '(4))
6532 (org-set-startup-visibility)
6533 (message "Startup visibility, plus VISIBILITY properties."))
6535 (org-cycle '(4))))))
6537 (defun org-set-startup-visibility ()
6538 "Set the visibility required by startup options and properties."
6539 (cond
6540 ((eq org-startup-folded t)
6541 (org-cycle '(4)))
6542 ((eq org-startup-folded 'content)
6543 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6544 (org-cycle '(4)) (org-cycle '(4)))))
6545 (unless (eq org-startup-folded 'showeverything)
6546 (if org-hide-block-startup (org-hide-block-all))
6547 (org-set-visibility-according-to-property 'no-cleanup)
6548 (org-cycle-hide-archived-subtrees 'all)
6549 (org-cycle-hide-drawers 'all)
6550 (org-cycle-show-empty-lines t)))
6552 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6553 "Switch subtree visibilities according to :VISIBILITY: property."
6554 (interactive)
6555 (let (org-show-entry-below state)
6556 (save-excursion
6557 (goto-char (point-min))
6558 (while (re-search-forward
6559 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6560 nil t)
6561 (setq state (match-string 1))
6562 (save-excursion
6563 (org-back-to-heading t)
6564 (hide-subtree)
6565 (org-reveal)
6566 (cond
6567 ((equal state '("fold" "folded"))
6568 (hide-subtree))
6569 ((equal state "children")
6570 (org-show-hidden-entry)
6571 (show-children))
6572 ((equal state "content")
6573 (save-excursion
6574 (save-restriction
6575 (org-narrow-to-subtree)
6576 (org-content))))
6577 ((member state '("all" "showall"))
6578 (show-subtree)))))
6579 (unless no-cleanup
6580 (org-cycle-hide-archived-subtrees 'all)
6581 (org-cycle-hide-drawers 'all)
6582 (org-cycle-show-empty-lines 'all)))))
6584 ;; This function uses outline-regexp instead of the more fundamental
6585 ;; org-outline-regexp so that org-cycle-global works outside of Org
6586 ;; buffers, where outline-regexp is needed.
6587 (defun org-overview ()
6588 "Switch to overview mode, showing only top-level headlines.
6589 Really, this shows all headlines with level equal or greater than the level
6590 of the first headline in the buffer. This is important, because if the
6591 first headline is not level one, then (hide-sublevels 1) gives confusing
6592 results."
6593 (interactive)
6594 (let ((level (save-excursion
6595 (goto-char (point-min))
6596 (if (re-search-forward (concat "^" outline-regexp) nil t)
6597 (progn
6598 (goto-char (match-beginning 0))
6599 (funcall outline-level))))))
6600 (and level (hide-sublevels level))))
6602 (defun org-content (&optional arg)
6603 "Show all headlines in the buffer, like a table of contents.
6604 With numerical argument N, show content up to level N."
6605 (interactive "P")
6606 (save-excursion
6607 ;; Visit all headings and show their offspring
6608 (and (integerp arg) (org-overview))
6609 (goto-char (point-max))
6610 (catch 'exit
6611 (while (and (progn (condition-case nil
6612 (outline-previous-visible-heading 1)
6613 (error (goto-char (point-min))))
6615 (looking-at org-outline-regexp))
6616 (if (integerp arg)
6617 (show-children (1- arg))
6618 (show-branches))
6619 (if (bobp) (throw 'exit nil))))))
6622 (defun org-optimize-window-after-visibility-change (state)
6623 "Adjust the window after a change in outline visibility.
6624 This function is the default value of the hook `org-cycle-hook'."
6625 (when (get-buffer-window (current-buffer))
6626 (cond
6627 ((eq state 'content) nil)
6628 ((eq state 'all) nil)
6629 ((eq state 'folded) nil)
6630 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6631 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6633 (defun org-remove-empty-overlays-at (pos)
6634 "Remove outline overlays that do not contain non-white stuff."
6635 (mapc
6636 (lambda (o)
6637 (and (eq 'outline (overlay-get o 'invisible))
6638 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6639 (overlay-end o))))
6640 (delete-overlay o)))
6641 (overlays-at pos)))
6643 (defun org-clean-visibility-after-subtree-move ()
6644 "Fix visibility issues after moving a subtree."
6645 ;; First, find a reasonable region to look at:
6646 ;; Start two siblings above, end three below
6647 (let* ((beg (save-excursion
6648 (and (org-get-last-sibling)
6649 (org-get-last-sibling))
6650 (point)))
6651 (end (save-excursion
6652 (and (org-get-next-sibling)
6653 (org-get-next-sibling)
6654 (org-get-next-sibling))
6655 (if (org-at-heading-p)
6656 (point-at-eol)
6657 (point))))
6658 (level (looking-at "\\*+"))
6659 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6660 (save-excursion
6661 (save-restriction
6662 (narrow-to-region beg end)
6663 (when re
6664 ;; Properly fold already folded siblings
6665 (goto-char (point-min))
6666 (while (re-search-forward re nil t)
6667 (if (and (not (outline-invisible-p))
6668 (save-excursion
6669 (goto-char (point-at-eol)) (outline-invisible-p)))
6670 (hide-entry))))
6671 (org-cycle-show-empty-lines 'overview)
6672 (org-cycle-hide-drawers 'overview)))))
6674 (defun org-cycle-show-empty-lines (state)
6675 "Show empty lines above all visible headlines.
6676 The region to be covered depends on STATE when called through
6677 `org-cycle-hook'. Lisp program can use t for STATE to get the
6678 entire buffer covered. Note that an empty line is only shown if there
6679 are at least `org-cycle-separator-lines' empty lines before the headline."
6680 (when (not (= org-cycle-separator-lines 0))
6681 (save-excursion
6682 (let* ((n (abs org-cycle-separator-lines))
6683 (re (cond
6684 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6685 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6686 (t (let ((ns (number-to-string (- n 2))))
6687 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6688 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6689 beg end b e)
6690 (cond
6691 ((memq state '(overview contents t))
6692 (setq beg (point-min) end (point-max)))
6693 ((memq state '(children folded))
6694 (setq beg (point) end (progn (org-end-of-subtree t t)
6695 (beginning-of-line 2)
6696 (point)))))
6697 (when beg
6698 (goto-char beg)
6699 (while (re-search-forward re end t)
6700 (unless (get-char-property (match-end 1) 'invisible)
6701 (setq e (match-end 1))
6702 (if (< org-cycle-separator-lines 0)
6703 (setq b (save-excursion
6704 (goto-char (match-beginning 0))
6705 (org-back-over-empty-lines)
6706 (if (save-excursion
6707 (goto-char (max (point-min) (1- (point))))
6708 (org-at-heading-p))
6709 (1- (point))
6710 (point))))
6711 (setq b (match-beginning 1)))
6712 (outline-flag-region b e nil)))))))
6713 ;; Never hide empty lines at the end of the file.
6714 (save-excursion
6715 (goto-char (point-max))
6716 (outline-previous-heading)
6717 (outline-end-of-heading)
6718 (if (and (looking-at "[ \t\n]+")
6719 (= (match-end 0) (point-max)))
6720 (outline-flag-region (point) (match-end 0) nil))))
6722 (defun org-show-empty-lines-in-parent ()
6723 "Move to the parent and re-show empty lines before visible headlines."
6724 (save-excursion
6725 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6726 (org-cycle-show-empty-lines context))))
6728 (defun org-files-list ()
6729 "Return `org-agenda-files' list, plus all open org-mode files.
6730 This is useful for operations that need to scan all of a user's
6731 open and agenda-wise Org files."
6732 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6733 (dolist (buf (buffer-list))
6734 (with-current-buffer buf
6735 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6736 (let ((file (expand-file-name (buffer-file-name))))
6737 (unless (member file files)
6738 (push file files))))))
6739 files))
6741 (defsubst org-entry-beginning-position ()
6742 "Return the beginning position of the current entry."
6743 (save-excursion (outline-back-to-heading t) (point)))
6745 (defsubst org-entry-end-position ()
6746 "Return the end position of the current entry."
6747 (save-excursion (outline-next-heading) (point)))
6749 (defun org-cycle-hide-drawers (state)
6750 "Re-hide all drawers after a visibility state change."
6751 (when (and (derived-mode-p 'org-mode)
6752 (not (memq state '(overview folded contents))))
6753 (save-excursion
6754 (let* ((globalp (memq state '(contents all)))
6755 (beg (if globalp (point-min) (point)))
6756 (end (if globalp (point-max)
6757 (if (eq state 'children)
6758 (save-excursion (outline-next-heading) (point))
6759 (org-end-of-subtree t)))))
6760 (goto-char beg)
6761 (while (re-search-forward org-drawer-regexp end t)
6762 (org-flag-drawer t))))))
6764 (defun org-cycle-hide-inline-tasks (state)
6765 "Re-hide inline task when switching to 'contents visibility state."
6766 (when (and (eq state 'contents)
6767 (boundp 'org-inlinetask-min-level)
6768 org-inlinetask-min-level)
6769 (hide-sublevels (1- org-inlinetask-min-level))))
6771 (defun org-flag-drawer (flag)
6772 "When FLAG is non-nil, hide the drawer we are within.
6773 Otherwise make it visible."
6774 (save-excursion
6775 (beginning-of-line 1)
6776 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6777 (let ((b (match-end 0)))
6778 (if (re-search-forward
6779 "^[ \t]*:END:"
6780 (save-excursion (outline-next-heading) (point)) t)
6781 (outline-flag-region b (point-at-eol) flag)
6782 (error ":END: line missing at position %s" b))))))
6784 (defun org-subtree-end-visible-p ()
6785 "Is the end of the current subtree visible?"
6786 (pos-visible-in-window-p
6787 (save-excursion (org-end-of-subtree t) (point))))
6789 (defun org-first-headline-recenter (&optional N)
6790 "Move cursor to the first headline and recenter the headline.
6791 Optional argument N means put the headline into the Nth line of the window."
6792 (goto-char (point-min))
6793 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6794 (beginning-of-line)
6795 (recenter (prefix-numeric-value N))))
6797 ;;; Saving and restoring visibility
6799 (defun org-outline-overlay-data (&optional use-markers)
6800 "Return a list of the locations of all outline overlays.
6801 These are overlays with the `invisible' property value `outline'.
6802 The return value is a list of cons cells, with start and stop
6803 positions for each overlay.
6804 If USE-MARKERS is set, return the positions as markers."
6805 (let (beg end)
6806 (save-excursion
6807 (save-restriction
6808 (widen)
6809 (delq nil
6810 (mapcar (lambda (o)
6811 (when (eq (overlay-get o 'invisible) 'outline)
6812 (setq beg (overlay-start o)
6813 end (overlay-end o))
6814 (and beg end (> end beg)
6815 (if use-markers
6816 (cons (move-marker (make-marker) beg)
6817 (move-marker (make-marker) end))
6818 (cons beg end)))))
6819 (overlays-in (point-min) (point-max))))))))
6821 (defun org-set-outline-overlay-data (data)
6822 "Create visibility overlays for all positions in DATA.
6823 DATA should have been made by `org-outline-overlay-data'."
6824 (let (o)
6825 (save-excursion
6826 (save-restriction
6827 (widen)
6828 (show-all)
6829 (mapc (lambda (c)
6830 (outline-flag-region (car c) (cdr c) t))
6831 data)))))
6833 ;;; Folding of blocks
6835 (defvar org-hide-block-overlays nil
6836 "Overlays hiding blocks.")
6837 (make-variable-buffer-local 'org-hide-block-overlays)
6839 (defun org-block-map (function &optional start end)
6840 "Call FUNCTION at the head of all source blocks in the current buffer.
6841 Optional arguments START and END can be used to limit the range."
6842 (let ((start (or start (point-min)))
6843 (end (or end (point-max))))
6844 (save-excursion
6845 (goto-char start)
6846 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6847 (save-excursion
6848 (save-match-data
6849 (goto-char (match-beginning 0))
6850 (funcall function)))))))
6852 (defun org-hide-block-toggle-all ()
6853 "Toggle the visibility of all blocks in the current buffer."
6854 (org-block-map #'org-hide-block-toggle))
6856 (defun org-hide-block-all ()
6857 "Fold all blocks in the current buffer."
6858 (interactive)
6859 (org-show-block-all)
6860 (org-block-map #'org-hide-block-toggle-maybe))
6862 (defun org-show-block-all ()
6863 "Unfold all blocks in the current buffer."
6864 (interactive)
6865 (mapc 'delete-overlay org-hide-block-overlays)
6866 (setq org-hide-block-overlays nil))
6868 (defun org-hide-block-toggle-maybe ()
6869 "Toggle visibility of block at point."
6870 (interactive)
6871 (let ((case-fold-search t))
6872 (if (save-excursion
6873 (beginning-of-line 1)
6874 (looking-at org-block-regexp))
6875 (progn (org-hide-block-toggle)
6876 t) ;; to signal that we took action
6877 nil))) ;; to signal that we did not
6879 (defun org-hide-block-toggle (&optional force)
6880 "Toggle the visibility of the current block."
6881 (interactive)
6882 (save-excursion
6883 (beginning-of-line)
6884 (if (re-search-forward org-block-regexp nil t)
6885 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6886 (end (match-end 0)) ;; end of entire body
6888 (if (memq t (mapcar (lambda (overlay)
6889 (eq (overlay-get overlay 'invisible)
6890 'org-hide-block))
6891 (overlays-at start)))
6892 (if (or (not force) (eq force 'off))
6893 (mapc (lambda (ov)
6894 (when (member ov org-hide-block-overlays)
6895 (setq org-hide-block-overlays
6896 (delq ov org-hide-block-overlays)))
6897 (when (eq (overlay-get ov 'invisible)
6898 'org-hide-block)
6899 (delete-overlay ov)))
6900 (overlays-at start)))
6901 (setq ov (make-overlay start end))
6902 (overlay-put ov 'invisible 'org-hide-block)
6903 ;; make the block accessible to isearch
6904 (overlay-put
6905 ov 'isearch-open-invisible
6906 (lambda (ov)
6907 (when (member ov org-hide-block-overlays)
6908 (setq org-hide-block-overlays
6909 (delq ov org-hide-block-overlays)))
6910 (when (eq (overlay-get ov 'invisible)
6911 'org-hide-block)
6912 (delete-overlay ov))))
6913 (push ov org-hide-block-overlays)))
6914 (error "Not looking at a source block"))))
6916 ;; org-tab-after-check-for-cycling-hook
6917 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6918 ;; Remove overlays when changing major mode
6919 (add-hook 'org-mode-hook
6920 (lambda () (org-add-hook 'change-major-mode-hook
6921 'org-show-block-all 'append 'local)))
6923 ;;; Org-goto
6925 (defvar org-goto-window-configuration nil)
6926 (defvar org-goto-marker nil)
6927 (defvar org-goto-map
6928 (let ((map (make-sparse-keymap)))
6929 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6930 (while (setq cmd (pop cmds))
6931 (substitute-key-definition cmd cmd map global-map)))
6932 (suppress-keymap map)
6933 (org-defkey map "\C-m" 'org-goto-ret)
6934 (org-defkey map [(return)] 'org-goto-ret)
6935 (org-defkey map [(left)] 'org-goto-left)
6936 (org-defkey map [(right)] 'org-goto-right)
6937 (org-defkey map [(control ?g)] 'org-goto-quit)
6938 (org-defkey map "\C-i" 'org-cycle)
6939 (org-defkey map [(tab)] 'org-cycle)
6940 (org-defkey map [(down)] 'outline-next-visible-heading)
6941 (org-defkey map [(up)] 'outline-previous-visible-heading)
6942 (if org-goto-auto-isearch
6943 (if (fboundp 'define-key-after)
6944 (define-key-after map [t] 'org-goto-local-auto-isearch)
6945 nil)
6946 (org-defkey map "q" 'org-goto-quit)
6947 (org-defkey map "n" 'outline-next-visible-heading)
6948 (org-defkey map "p" 'outline-previous-visible-heading)
6949 (org-defkey map "f" 'outline-forward-same-level)
6950 (org-defkey map "b" 'outline-backward-same-level)
6951 (org-defkey map "u" 'outline-up-heading))
6952 (org-defkey map "/" 'org-occur)
6953 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6954 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6955 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6956 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6957 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6958 map))
6960 (defconst org-goto-help
6961 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6962 RET=jump to location [Q]uit and return to previous location
6963 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6965 (defvar org-goto-start-pos) ; dynamically scoped parameter
6967 ;; FIXME: Docstring does not mention both interfaces
6968 (defun org-goto (&optional alternative-interface)
6969 "Look up a different location in the current file, keeping current visibility.
6971 When you want look-up or go to a different location in a
6972 document, the fastest way is often to fold the entire buffer and
6973 then dive into the tree. This method has the disadvantage, that
6974 the previous location will be folded, which may not be what you
6975 want.
6977 This command works around this by showing a copy of the current
6978 buffer in an indirect buffer, in overview mode. You can dive
6979 into the tree in that copy, use org-occur and incremental search
6980 to find a location. When pressing RET or `Q', the command
6981 returns to the original buffer in which the visibility is still
6982 unchanged. After RET it will also jump to the location selected
6983 in the indirect buffer and expose the headline hierarchy above.
6985 With a prefix argument, use the alternative interface: e.g. if
6986 `org-goto-interface' is 'outline use 'outline-path-completion."
6987 (interactive "P")
6988 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6989 (org-refile-use-outline-path t)
6990 (org-refile-target-verify-function nil)
6991 (interface
6992 (if (not alternative-interface)
6993 org-goto-interface
6994 (if (eq org-goto-interface 'outline)
6995 'outline-path-completion
6996 'outline)))
6997 (org-goto-start-pos (point))
6998 (selected-point
6999 (if (eq interface 'outline)
7000 (car (org-get-location (current-buffer) org-goto-help))
7001 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7002 (org-refile-check-position pa)
7003 (nth 3 pa)))))
7004 (if selected-point
7005 (progn
7006 (org-mark-ring-push org-goto-start-pos)
7007 (goto-char selected-point)
7008 (if (or (outline-invisible-p) (org-invisible-p2))
7009 (org-show-context 'org-goto)))
7010 (message "Quit"))))
7012 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7013 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7014 (defvar org-goto-local-auto-isearch-map) ; defined below
7016 (defun org-get-location (buf help)
7017 "Let the user select a location in the Org-mode buffer BUF.
7018 This function uses a recursive edit. It returns the selected position
7019 or nil."
7020 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7021 (isearch-hide-immediately nil)
7022 (isearch-search-fun-function
7023 (lambda () 'org-goto-local-search-headings))
7024 (org-goto-selected-point org-goto-exit-command)
7025 (pop-up-frames nil)
7026 (special-display-buffer-names nil)
7027 (special-display-regexps nil)
7028 (special-display-function nil))
7029 (save-excursion
7030 (save-window-excursion
7031 (delete-other-windows)
7032 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7033 (org-pop-to-buffer-same-window
7034 (condition-case nil
7035 (make-indirect-buffer (current-buffer) "*org-goto*")
7036 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7037 (with-output-to-temp-buffer "*Help*"
7038 (princ help))
7039 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7040 (setq buffer-read-only nil)
7041 (let ((org-startup-truncated t)
7042 (org-startup-folded nil)
7043 (org-startup-align-all-tables nil))
7044 (org-mode)
7045 (org-overview))
7046 (setq buffer-read-only t)
7047 (if (and (boundp 'org-goto-start-pos)
7048 (integer-or-marker-p org-goto-start-pos))
7049 (let ((org-show-hierarchy-above t)
7050 (org-show-siblings t)
7051 (org-show-following-heading t))
7052 (goto-char org-goto-start-pos)
7053 (and (outline-invisible-p) (org-show-context)))
7054 (goto-char (point-min)))
7055 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7056 (message "Select location and press RET")
7057 (use-local-map org-goto-map)
7058 (recursive-edit)
7060 (kill-buffer "*org-goto*")
7061 (cons org-goto-selected-point org-goto-exit-command)))
7063 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7064 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7065 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7066 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7068 (defun org-goto-local-search-headings (string bound noerror)
7069 "Search and make sure that any matches are in headlines."
7070 (catch 'return
7071 (while (if isearch-forward
7072 (search-forward string bound noerror)
7073 (search-backward string bound noerror))
7074 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7075 (and (member :headline context)
7076 (not (member :tags context))))
7077 (throw 'return (point))))))
7079 (defun org-goto-local-auto-isearch ()
7080 "Start isearch."
7081 (interactive)
7082 (goto-char (point-min))
7083 (let ((keys (this-command-keys)))
7084 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7085 (isearch-mode t)
7086 (isearch-process-search-char (string-to-char keys)))))
7088 (defun org-goto-ret (&optional arg)
7089 "Finish `org-goto' by going to the new location."
7090 (interactive "P")
7091 (setq org-goto-selected-point (point)
7092 org-goto-exit-command 'return)
7093 (throw 'exit nil))
7095 (defun org-goto-left ()
7096 "Finish `org-goto' by going to the new location."
7097 (interactive)
7098 (if (org-at-heading-p)
7099 (progn
7100 (beginning-of-line 1)
7101 (setq org-goto-selected-point (point)
7102 org-goto-exit-command 'left)
7103 (throw 'exit nil))
7104 (error "Not on a heading")))
7106 (defun org-goto-right ()
7107 "Finish `org-goto' by going to the new location."
7108 (interactive)
7109 (if (org-at-heading-p)
7110 (progn
7111 (setq org-goto-selected-point (point)
7112 org-goto-exit-command 'right)
7113 (throw 'exit nil))
7114 (error "Not on a heading")))
7116 (defun org-goto-quit ()
7117 "Finish `org-goto' without cursor motion."
7118 (interactive)
7119 (setq org-goto-selected-point nil)
7120 (setq org-goto-exit-command 'quit)
7121 (throw 'exit nil))
7123 ;;; Indirect buffer display of subtrees
7125 (defvar org-indirect-dedicated-frame nil
7126 "This is the frame being used for indirect tree display.")
7127 (defvar org-last-indirect-buffer nil)
7129 (defun org-tree-to-indirect-buffer (&optional arg)
7130 "Create indirect buffer and narrow it to current subtree.
7131 With a numerical prefix ARG, go up to this level and then take that tree.
7132 If ARG is negative, go up that many levels.
7134 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7135 indirect buffer previously made with this command, to avoid proliferation of
7136 indirect buffers. However, when you call the command with a \
7137 \\[universal-argument] prefix, or
7138 when `org-indirect-buffer-display' is `new-frame', the last buffer
7139 is kept so that you can work with several indirect buffers at the same time.
7140 If `org-indirect-buffer-display' is `dedicated-frame', the \
7141 \\[universal-argument] prefix also
7142 requests that a new frame be made for the new buffer, so that the dedicated
7143 frame is not changed."
7144 (interactive "P")
7145 (let ((cbuf (current-buffer))
7146 (cwin (selected-window))
7147 (pos (point))
7148 beg end level heading ibuf)
7149 (save-excursion
7150 (org-back-to-heading t)
7151 (when (numberp arg)
7152 (setq level (org-outline-level))
7153 (if (< arg 0) (setq arg (+ level arg)))
7154 (while (> (setq level (org-outline-level)) arg)
7155 (org-up-heading-safe)))
7156 (setq beg (point)
7157 heading (org-get-heading))
7158 (org-end-of-subtree t t)
7159 (if (org-at-heading-p) (backward-char 1))
7160 (setq end (point)))
7161 (if (and (buffer-live-p org-last-indirect-buffer)
7162 (not (eq org-indirect-buffer-display 'new-frame))
7163 (not arg))
7164 (kill-buffer org-last-indirect-buffer))
7165 (setq ibuf (org-get-indirect-buffer cbuf)
7166 org-last-indirect-buffer ibuf)
7167 (cond
7168 ((or (eq org-indirect-buffer-display 'new-frame)
7169 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7170 (select-frame (make-frame))
7171 (delete-other-windows)
7172 (org-pop-to-buffer-same-window ibuf)
7173 (org-set-frame-title heading))
7174 ((eq org-indirect-buffer-display 'dedicated-frame)
7175 (raise-frame
7176 (select-frame (or (and org-indirect-dedicated-frame
7177 (frame-live-p org-indirect-dedicated-frame)
7178 org-indirect-dedicated-frame)
7179 (setq org-indirect-dedicated-frame (make-frame)))))
7180 (delete-other-windows)
7181 (org-pop-to-buffer-same-window ibuf)
7182 (org-set-frame-title (concat "Indirect: " heading)))
7183 ((eq org-indirect-buffer-display 'current-window)
7184 (org-pop-to-buffer-same-window ibuf))
7185 ((eq org-indirect-buffer-display 'other-window)
7186 (pop-to-buffer ibuf))
7187 (t (error "Invalid value")))
7188 (if (featurep 'xemacs)
7189 (save-excursion (org-mode) (turn-on-font-lock)))
7190 (narrow-to-region beg end)
7191 (show-all)
7192 (goto-char pos)
7193 (run-hook-with-args 'org-cycle-hook 'all)
7194 (and (window-live-p cwin) (select-window cwin))))
7196 (defun org-get-indirect-buffer (&optional buffer)
7197 (setq buffer (or buffer (current-buffer)))
7198 (let ((n 1) (base (buffer-name buffer)) bname)
7199 (while (buffer-live-p
7200 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7201 (setq n (1+ n)))
7202 (condition-case nil
7203 (make-indirect-buffer buffer bname 'clone)
7204 (error (make-indirect-buffer buffer bname)))))
7206 (defun org-set-frame-title (title)
7207 "Set the title of the current frame to the string TITLE."
7208 ;; FIXME: how to name a single frame in XEmacs???
7209 (unless (featurep 'xemacs)
7210 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7212 ;;;; Structure editing
7214 ;;; Inserting headlines
7216 (defun org-previous-line-empty-p ()
7217 (save-excursion
7218 (and (not (bobp))
7219 (or (beginning-of-line 0) t)
7220 (save-match-data
7221 (looking-at "[ \t]*$")))))
7223 (defun org-insert-heading (&optional force-heading invisible-ok)
7224 "Insert a new heading or item with same depth at point.
7225 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7226 If point is at the beginning of a headline, insert a sibling before the
7227 current headline. If point is not at the beginning, split the line,
7228 create the new headline with the text in the current line after point
7229 \(but see also the variable `org-M-RET-may-split-line').
7231 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7232 This is important for non-interactive uses of the command."
7233 (interactive "P")
7234 (if (or (= (buffer-size) 0)
7235 (and (not (save-excursion
7236 (and (ignore-errors (org-back-to-heading invisible-ok))
7237 (org-at-heading-p))))
7238 (or force-heading (not (org-in-item-p)))))
7239 (progn
7240 (insert "\n* ")
7241 (run-hooks 'org-insert-heading-hook))
7242 (when (or force-heading (not (org-insert-item)))
7243 (let* ((empty-line-p nil)
7244 (level nil)
7245 (on-heading (org-at-heading-p))
7246 (head (save-excursion
7247 (condition-case nil
7248 (progn
7249 (org-back-to-heading invisible-ok)
7250 (when (and (not on-heading)
7251 (featurep 'org-inlinetask)
7252 (integerp org-inlinetask-min-level)
7253 (>= (length (match-string 0))
7254 org-inlinetask-min-level))
7255 ;; Find a heading level before the inline task
7256 (while (and (setq level (org-up-heading-safe))
7257 (>= level org-inlinetask-min-level)))
7258 (if (org-at-heading-p)
7259 (org-back-to-heading invisible-ok)
7260 (error "This should not happen")))
7261 (setq empty-line-p (org-previous-line-empty-p))
7262 (match-string 0))
7263 (error "*"))))
7264 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7265 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7266 pos hide-previous previous-pos)
7267 (cond
7268 ((and (org-at-heading-p) (bolp)
7269 (or (bobp)
7270 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7271 ;; insert before the current line
7272 (open-line (if blank 2 1)))
7273 ((and (bolp)
7274 (not org-insert-heading-respect-content)
7275 (or (bobp)
7276 (save-excursion
7277 (backward-char 1) (not (outline-invisible-p)))))
7278 ;; insert right here
7279 nil)
7281 ;; somewhere in the line
7282 (save-excursion
7283 (setq previous-pos (point-at-bol))
7284 (end-of-line)
7285 (setq hide-previous (outline-invisible-p)))
7286 (and org-insert-heading-respect-content (org-show-subtree))
7287 (let ((split
7288 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7289 (save-excursion
7290 (let ((p (point)))
7291 (goto-char (point-at-bol))
7292 (and (looking-at org-complex-heading-regexp)
7293 (match-beginning 4)
7294 (> p (match-beginning 4)))))))
7295 tags pos)
7296 (cond
7297 (org-insert-heading-respect-content
7298 (org-end-of-subtree nil t)
7299 (when (featurep 'org-inlinetask)
7300 (while (and (not (eobp))
7301 (looking-at "\\(\\*+\\)[ \t]+")
7302 (>= (length (match-string 1))
7303 org-inlinetask-min-level))
7304 (org-end-of-subtree nil t)))
7305 (or (bolp) (newline))
7306 (or (org-previous-line-empty-p)
7307 (and blank (newline)))
7308 (open-line 1))
7309 ((org-at-heading-p)
7310 (when hide-previous
7311 (show-children)
7312 (org-show-entry))
7313 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7314 (setq tags (and (match-end 2) (match-string 2)))
7315 (and (match-end 1)
7316 (delete-region (match-beginning 1) (match-end 1)))
7317 (setq pos (point-at-bol))
7318 (or split (end-of-line 1))
7319 (delete-horizontal-space)
7320 (if (string-match "\\`\\*+\\'"
7321 (buffer-substring (point-at-bol) (point)))
7322 (insert " "))
7323 (newline (if blank 2 1))
7324 (when tags
7325 (save-excursion
7326 (goto-char pos)
7327 (end-of-line 1)
7328 (insert " " tags)
7329 (org-set-tags nil 'align))))
7331 (or split (end-of-line 1))
7332 (newline (if blank 2 1)))))))
7333 (insert head) (just-one-space)
7334 (setq pos (point))
7335 (end-of-line 1)
7336 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7337 (when (and org-insert-heading-respect-content hide-previous)
7338 (save-excursion
7339 (goto-char previous-pos)
7340 (hide-subtree)))
7341 (run-hooks 'org-insert-heading-hook)))))
7343 (defun org-get-heading (&optional no-tags no-todo)
7344 "Return the heading of the current entry, without the stars.
7345 When NO-TAGS is non-nil, don't include tags.
7346 When NO-TODO is non-nil, don't include TODO keywords."
7347 (save-excursion
7348 (org-back-to-heading t)
7349 (cond
7350 ((and no-tags no-todo)
7351 (looking-at org-complex-heading-regexp)
7352 (match-string 4))
7353 (no-tags
7354 (looking-at (concat org-outline-regexp
7355 "\\(.*?\\)"
7356 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7357 (match-string 1))
7358 (no-todo
7359 (looking-at org-todo-line-regexp)
7360 (match-string 3))
7361 (t (looking-at org-heading-regexp)
7362 (match-string 2)))))
7364 (defun org-heading-components ()
7365 "Return the components of the current heading.
7366 This is a list with the following elements:
7367 - the level as an integer
7368 - the reduced level, different if `org-odd-levels-only' is set.
7369 - the TODO keyword, or nil
7370 - the priority character, like ?A, or nil if no priority is given
7371 - the headline text itself, or the tags string if no headline text
7372 - the tags string, or nil."
7373 (save-excursion
7374 (org-back-to-heading t)
7375 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7376 (list (length (match-string 1))
7377 (org-reduced-level (length (match-string 1)))
7378 (org-match-string-no-properties 2)
7379 (and (match-end 3) (aref (match-string 3) 2))
7380 (org-match-string-no-properties 4)
7381 (org-match-string-no-properties 5)))))
7383 (defun org-get-entry ()
7384 "Get the entry text, after heading, entire subtree."
7385 (save-excursion
7386 (org-back-to-heading t)
7387 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7389 (defun org-insert-heading-after-current ()
7390 "Insert a new heading with same level as current, after current subtree."
7391 (interactive)
7392 (org-back-to-heading)
7393 (org-insert-heading)
7394 (org-move-subtree-down)
7395 (end-of-line 1))
7397 (defun org-insert-heading-respect-content ()
7398 (interactive)
7399 (let ((org-insert-heading-respect-content t))
7400 (org-insert-heading t)))
7402 (defun org-insert-todo-heading-respect-content (&optional force-state)
7403 (interactive "P")
7404 (let ((org-insert-heading-respect-content t))
7405 (org-insert-todo-heading force-state t)))
7407 (defun org-insert-todo-heading (arg &optional force-heading)
7408 "Insert a new heading with the same level and TODO state as current heading.
7409 If the heading has no TODO state, or if the state is DONE, use the first
7410 state (TODO by default). Also with prefix arg, force first state."
7411 (interactive "P")
7412 (when (or force-heading (not (org-insert-item 'checkbox)))
7413 (org-insert-heading force-heading)
7414 (save-excursion
7415 (org-back-to-heading)
7416 (outline-previous-heading)
7417 (looking-at org-todo-line-regexp))
7418 (let*
7419 ((new-mark-x
7420 (if (or arg
7421 (not (match-beginning 2))
7422 (member (match-string 2) org-done-keywords))
7423 (car org-todo-keywords-1)
7424 (match-string 2)))
7425 (new-mark
7427 (run-hook-with-args-until-success
7428 'org-todo-get-default-hook new-mark-x nil)
7429 new-mark-x)))
7430 (beginning-of-line 1)
7431 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7432 (if org-treat-insert-todo-heading-as-state-change
7433 (org-todo new-mark)
7434 (insert new-mark " "))))
7435 (when org-provide-todo-statistics
7436 (org-update-parent-todo-statistics))))
7438 (defun org-insert-subheading (arg)
7439 "Insert a new subheading and demote it.
7440 Works for outline headings and for plain lists alike."
7441 (interactive "P")
7442 (org-insert-heading arg)
7443 (cond
7444 ((org-at-heading-p) (org-do-demote))
7445 ((org-at-item-p) (org-indent-item))))
7447 (defun org-insert-todo-subheading (arg)
7448 "Insert a new subheading with TODO keyword or checkbox and demote it.
7449 Works for outline headings and for plain lists alike."
7450 (interactive "P")
7451 (org-insert-todo-heading arg)
7452 (cond
7453 ((org-at-heading-p) (org-do-demote))
7454 ((org-at-item-p) (org-indent-item))))
7456 ;;; Promotion and Demotion
7458 (defvar org-after-demote-entry-hook nil
7459 "Hook run after an entry has been demoted.
7460 The cursor will be at the beginning of the entry.
7461 When a subtree is being demoted, the hook will be called for each node.")
7463 (defvar org-after-promote-entry-hook nil
7464 "Hook run after an entry has been promoted.
7465 The cursor will be at the beginning of the entry.
7466 When a subtree is being promoted, the hook will be called for each node.")
7468 (defun org-promote-subtree ()
7469 "Promote the entire subtree.
7470 See also `org-promote'."
7471 (interactive)
7472 (save-excursion
7473 (org-with-limited-levels (org-map-tree 'org-promote)))
7474 (org-fix-position-after-promote))
7476 (defun org-demote-subtree ()
7477 "Demote the entire subtree. See `org-demote'.
7478 See also `org-promote'."
7479 (interactive)
7480 (save-excursion
7481 (org-with-limited-levels (org-map-tree 'org-demote)))
7482 (org-fix-position-after-promote))
7485 (defun org-do-promote ()
7486 "Promote the current heading higher up the tree.
7487 If the region is active in `transient-mark-mode', promote all headings
7488 in the region."
7489 (interactive)
7490 (save-excursion
7491 (if (org-region-active-p)
7492 (org-map-region 'org-promote (region-beginning) (region-end))
7493 (org-promote)))
7494 (org-fix-position-after-promote))
7496 (defun org-do-demote ()
7497 "Demote the current heading lower down the tree.
7498 If the region is active in `transient-mark-mode', demote all headings
7499 in the region."
7500 (interactive)
7501 (save-excursion
7502 (if (org-region-active-p)
7503 (org-map-region 'org-demote (region-beginning) (region-end))
7504 (org-demote)))
7505 (org-fix-position-after-promote))
7507 (defun org-fix-position-after-promote ()
7508 "Make sure that after pro/demotion cursor position is right."
7509 (let ((pos (point)))
7510 (when (save-excursion
7511 (beginning-of-line 1)
7512 (looking-at org-todo-line-regexp)
7513 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7514 (cond ((eobp) (insert " "))
7515 ((eolp) (insert " "))
7516 ((equal (char-after) ?\ ) (forward-char 1))))))
7518 (defun org-current-level ()
7519 "Return the level of the current entry, or nil if before the first headline.
7520 The level is the number of stars at the beginning of the headline."
7521 (save-excursion
7522 (org-with-limited-levels
7523 (if (ignore-errors (org-back-to-heading t))
7524 (funcall outline-level)))))
7526 (defun org-get-previous-line-level ()
7527 "Return the outline depth of the last headline before the current line.
7528 Returns 0 for the first headline in the buffer, and nil if before the
7529 first headline."
7530 (let ((current-level (org-current-level))
7531 (prev-level (when (> (line-number-at-pos) 1)
7532 (save-excursion
7533 (beginning-of-line 0)
7534 (org-current-level)))))
7535 (cond ((null current-level) nil) ; Before first headline
7536 ((null prev-level) 0) ; At first headline
7537 (prev-level))))
7539 (defun org-reduced-level (l)
7540 "Compute the effective level of a heading.
7541 This takes into account the setting of `org-odd-levels-only'."
7542 (cond
7543 ((zerop l) 0)
7544 (org-odd-levels-only (1+ (floor (/ l 2))))
7545 (t l)))
7547 (defun org-level-increment ()
7548 "Return the number of stars that will be added or removed at a
7549 time to headlines when structure editing, based on the value of
7550 `org-odd-levels-only'."
7551 (if org-odd-levels-only 2 1))
7553 (defun org-get-valid-level (level &optional change)
7554 "Rectify a level change under the influence of `org-odd-levels-only'
7555 LEVEL is a current level, CHANGE is by how much the level should be
7556 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7557 even level numbers will become the next higher odd number."
7558 (if org-odd-levels-only
7559 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7560 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7561 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7562 (max 1 (+ level (or change 0)))))
7564 (if (boundp 'define-obsolete-function-alias)
7565 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7566 (define-obsolete-function-alias 'org-get-legal-level
7567 'org-get-valid-level)
7568 (define-obsolete-function-alias 'org-get-legal-level
7569 'org-get-valid-level "23.1")))
7571 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7572 ;; ̀org-with-limited-levels'
7573 (defun org-promote ()
7574 "Promote the current heading higher up the tree.
7575 If the region is active in `transient-mark-mode', promote all headings
7576 in the region."
7577 (org-back-to-heading t)
7578 (let* ((level (save-match-data (funcall outline-level)))
7579 (after-change-functions (remove 'flyspell-after-change-function
7580 after-change-functions))
7581 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7582 (diff (abs (- level (length up-head) -1))))
7583 (cond ((and (= level 1) org-called-with-limited-levels
7584 org-allow-promoting-top-level-subtree)
7585 (replace-match "# " nil t))
7586 ((= level 1)
7587 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7588 (t (replace-match up-head nil t)))
7589 ;; Fixup tag positioning
7590 (unless (= level 1)
7591 (and org-auto-align-tags (org-set-tags nil t))
7592 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7593 (run-hooks 'org-after-promote-entry-hook)))
7595 (defun org-demote ()
7596 "Demote the current heading lower down the tree.
7597 If the region is active in `transient-mark-mode', demote all headings
7598 in the region."
7599 (org-back-to-heading t)
7600 (let* ((level (save-match-data (funcall outline-level)))
7601 (after-change-functions (remove 'flyspell-after-change-function
7602 after-change-functions))
7603 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7604 (diff (abs (- level (length down-head) -1))))
7605 (replace-match down-head nil t)
7606 ;; Fixup tag positioning
7607 (and org-auto-align-tags (org-set-tags nil t))
7608 (if org-adapt-indentation (org-fixup-indentation diff))
7609 (run-hooks 'org-after-demote-entry-hook)))
7611 (defun org-cycle-level ()
7612 "Cycle the level of an empty headline through possible states.
7613 This goes first to child, then to parent, level, then up the hierarchy.
7614 After top level, it switches back to sibling level."
7615 (interactive)
7616 (let ((org-adapt-indentation nil))
7617 (when (org-point-at-end-of-empty-headline)
7618 (setq this-command 'org-cycle-level) ; Only needed for caching
7619 (let ((cur-level (org-current-level))
7620 (prev-level (org-get-previous-line-level)))
7621 (cond
7622 ;; If first headline in file, promote to top-level.
7623 ((= prev-level 0)
7624 (loop repeat (/ (- cur-level 1) (org-level-increment))
7625 do (org-do-promote)))
7626 ;; If same level as prev, demote one.
7627 ((= prev-level cur-level)
7628 (org-do-demote))
7629 ;; If parent is top-level, promote to top level if not already.
7630 ((= prev-level 1)
7631 (loop repeat (/ (- cur-level 1) (org-level-increment))
7632 do (org-do-promote)))
7633 ;; If top-level, return to prev-level.
7634 ((= cur-level 1)
7635 (loop repeat (/ (- prev-level 1) (org-level-increment))
7636 do (org-do-demote)))
7637 ;; If less than prev-level, promote one.
7638 ((< cur-level prev-level)
7639 (org-do-promote))
7640 ;; If deeper than prev-level, promote until higher than
7641 ;; prev-level.
7642 ((> cur-level prev-level)
7643 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7644 do (org-do-promote))))
7645 t))))
7647 (defun org-map-tree (fun)
7648 "Call FUN for every heading underneath the current one."
7649 (org-back-to-heading)
7650 (let ((level (funcall outline-level)))
7651 (save-excursion
7652 (funcall fun)
7653 (while (and (progn
7654 (outline-next-heading)
7655 (> (funcall outline-level) level))
7656 (not (eobp)))
7657 (funcall fun)))))
7659 (defun org-map-region (fun beg end)
7660 "Call FUN for every heading between BEG and END."
7661 (let ((org-ignore-region t))
7662 (save-excursion
7663 (setq end (copy-marker end))
7664 (goto-char beg)
7665 (if (and (re-search-forward org-outline-regexp-bol nil t)
7666 (< (point) end))
7667 (funcall fun))
7668 (while (and (progn
7669 (outline-next-heading)
7670 (< (point) end))
7671 (not (eobp)))
7672 (funcall fun)))))
7674 (defvar org-property-end-re) ; silence byte-compiler
7675 (defun org-fixup-indentation (diff)
7676 "Change the indentation in the current entry by DIFF.
7677 However, if any line in the current entry has no indentation, or if it
7678 would end up with no indentation after the change, nothing at all is done."
7679 (save-excursion
7680 (let ((end (save-excursion (outline-next-heading)
7681 (point-marker)))
7682 (prohibit (if (> diff 0)
7683 "^\\S-"
7684 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7685 col)
7686 (unless (save-excursion (end-of-line 1)
7687 (re-search-forward prohibit end t))
7688 (while (and (< (point) end)
7689 (re-search-forward "^[ \t]+" end t))
7690 (goto-char (match-end 0))
7691 (setq col (current-column))
7692 (if (< diff 0) (replace-match ""))
7693 (org-indent-to-column (+ diff col))))
7694 (move-marker end nil))))
7696 (defun org-convert-to-odd-levels ()
7697 "Convert an org-mode file with all levels allowed to one with odd levels.
7698 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7699 level 5 etc."
7700 (interactive)
7701 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7702 (let ((outline-level 'org-outline-level)
7703 (org-odd-levels-only nil) n)
7704 (save-excursion
7705 (goto-char (point-min))
7706 (while (re-search-forward "^\\*\\*+ " nil t)
7707 (setq n (- (length (match-string 0)) 2))
7708 (while (>= (setq n (1- n)) 0)
7709 (org-demote))
7710 (end-of-line 1))))))
7712 (defun org-convert-to-oddeven-levels ()
7713 "Convert an org-mode file with only odd levels to one with odd/even levels.
7714 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7715 file contains a section with an even level, conversion would
7716 destroy the structure of the file. An error is signaled in this
7717 case."
7718 (interactive)
7719 (goto-char (point-min))
7720 ;; First check if there are no even levels
7721 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7722 (org-show-context t)
7723 (error "Not all levels are odd in this file. Conversion not possible"))
7724 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7725 (let ((outline-regexp org-outline-regexp)
7726 (outline-level 'org-outline-level)
7727 (org-odd-levels-only nil) n)
7728 (save-excursion
7729 (goto-char (point-min))
7730 (while (re-search-forward "^\\*\\*+ " nil t)
7731 (setq n (/ (1- (length (match-string 0))) 2))
7732 (while (>= (setq n (1- n)) 0)
7733 (org-promote))
7734 (end-of-line 1))))))
7736 (defun org-tr-level (n)
7737 "Make N odd if required."
7738 (if org-odd-levels-only (1+ (/ n 2)) n))
7740 ;;; Vertical tree motion, cutting and pasting of subtrees
7742 (defun org-move-subtree-up (&optional arg)
7743 "Move the current subtree up past ARG headlines of the same level."
7744 (interactive "p")
7745 (org-move-subtree-down (- (prefix-numeric-value arg))))
7747 (defun org-move-subtree-down (&optional arg)
7748 "Move the current subtree down past ARG headlines of the same level."
7749 (interactive "p")
7750 (setq arg (prefix-numeric-value arg))
7751 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7752 'org-get-last-sibling))
7753 (ins-point (make-marker))
7754 (cnt (abs arg))
7755 (col (current-column))
7756 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7757 ;; Select the tree
7758 (org-back-to-heading)
7759 (setq beg0 (point))
7760 (save-excursion
7761 (setq ne-beg (org-back-over-empty-lines))
7762 (setq beg (point)))
7763 (save-match-data
7764 (save-excursion (outline-end-of-heading)
7765 (setq folded (outline-invisible-p)))
7766 (outline-end-of-subtree))
7767 (outline-next-heading)
7768 (setq ne-end (org-back-over-empty-lines))
7769 (setq end (point))
7770 (goto-char beg0)
7771 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7772 ;; include less whitespace
7773 (save-excursion
7774 (goto-char beg)
7775 (forward-line (- ne-beg ne-end))
7776 (setq beg (point))))
7777 ;; Find insertion point, with error handling
7778 (while (> cnt 0)
7779 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7780 (progn (goto-char beg0)
7781 (error "Cannot move past superior level or buffer limit")))
7782 (setq cnt (1- cnt)))
7783 (if (> arg 0)
7784 ;; Moving forward - still need to move over subtree
7785 (progn (org-end-of-subtree t t)
7786 (save-excursion
7787 (org-back-over-empty-lines)
7788 (or (bolp) (newline)))))
7789 (setq ne-ins (org-back-over-empty-lines))
7790 (move-marker ins-point (point))
7791 (setq txt (buffer-substring beg end))
7792 (org-save-markers-in-region beg end)
7793 (delete-region beg end)
7794 (org-remove-empty-overlays-at beg)
7795 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7796 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7797 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7798 (let ((bbb (point)))
7799 (insert-before-markers txt)
7800 (org-reinstall-markers-in-region bbb)
7801 (move-marker ins-point bbb))
7802 (or (bolp) (insert "\n"))
7803 (setq ins-end (point))
7804 (goto-char ins-point)
7805 (org-skip-whitespace)
7806 (when (and (< arg 0)
7807 (org-first-sibling-p)
7808 (> ne-ins ne-beg))
7809 ;; Move whitespace back to beginning
7810 (save-excursion
7811 (goto-char ins-end)
7812 (let ((kill-whole-line t))
7813 (kill-line (- ne-ins ne-beg)) (point)))
7814 (insert (make-string (- ne-ins ne-beg) ?\n)))
7815 (move-marker ins-point nil)
7816 (if folded
7817 (hide-subtree)
7818 (org-show-entry)
7819 (show-children)
7820 (org-cycle-hide-drawers 'children))
7821 (org-clean-visibility-after-subtree-move)
7822 ;; move back to the initial column we were at
7823 (move-to-column col)))
7825 (defvar org-subtree-clip ""
7826 "Clipboard for cut and paste of subtrees.
7827 This is actually only a copy of the kill, because we use the normal kill
7828 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7830 (defvar org-subtree-clip-folded nil
7831 "Was the last copied subtree folded?
7832 This is used to fold the tree back after pasting.")
7834 (defun org-cut-subtree (&optional n)
7835 "Cut the current subtree into the clipboard.
7836 With prefix arg N, cut this many sequential subtrees.
7837 This is a short-hand for marking the subtree and then cutting it."
7838 (interactive "p")
7839 (org-copy-subtree n 'cut))
7841 (defun org-copy-subtree (&optional n cut force-store-markers)
7842 "Cut the current subtree into the clipboard.
7843 With prefix arg N, cut this many sequential subtrees.
7844 This is a short-hand for marking the subtree and then copying it.
7845 If CUT is non-nil, actually cut the subtree.
7846 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7847 of some markers in the region, even if CUT is non-nil. This is
7848 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7849 (interactive "p")
7850 (let (beg end folded (beg0 (point)))
7851 (if (org-called-interactively-p 'any)
7852 (org-back-to-heading nil) ; take what looks like a subtree
7853 (org-back-to-heading t)) ; take what is really there
7854 (org-back-over-empty-lines)
7855 (setq beg (point))
7856 (skip-chars-forward " \t\r\n")
7857 (save-match-data
7858 (save-excursion (outline-end-of-heading)
7859 (setq folded (outline-invisible-p)))
7860 (condition-case nil
7861 (org-forward-heading-same-level (1- n) t)
7862 (error nil))
7863 (org-end-of-subtree t t))
7864 (org-back-over-empty-lines)
7865 (setq end (point))
7866 (goto-char beg0)
7867 (when (> end beg)
7868 (setq org-subtree-clip-folded folded)
7869 (when (or cut force-store-markers)
7870 (org-save-markers-in-region beg end))
7871 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7872 (setq org-subtree-clip (current-kill 0))
7873 (message "%s: Subtree(s) with %d characters"
7874 (if cut "Cut" "Copied")
7875 (length org-subtree-clip)))))
7877 (defun org-paste-subtree (&optional level tree for-yank)
7878 "Paste the clipboard as a subtree, with modification of headline level.
7879 The entire subtree is promoted or demoted in order to match a new headline
7880 level.
7882 If the cursor is at the beginning of a headline, the same level as
7883 that headline is used to paste the tree
7885 If not, the new level is derived from the *visible* headings
7886 before and after the insertion point, and taken to be the inferior headline
7887 level of the two. So if the previous visible heading is level 3 and the
7888 next is level 4 (or vice versa), level 4 will be used for insertion.
7889 This makes sure that the subtree remains an independent subtree and does
7890 not swallow low level entries.
7892 You can also force a different level, either by using a numeric prefix
7893 argument, or by inserting the heading marker by hand. For example, if the
7894 cursor is after \"*****\", then the tree will be shifted to level 5.
7896 If optional TREE is given, use this text instead of the kill ring.
7898 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7899 move back over whitespace before inserting, and move point to the end of
7900 the inserted text when done."
7901 (interactive "P")
7902 (setq tree (or tree (and kill-ring (current-kill 0))))
7903 (unless (org-kill-is-subtree-p tree)
7904 (error "%s"
7905 (substitute-command-keys
7906 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7907 (org-with-limited-levels
7908 (let* ((visp (not (outline-invisible-p)))
7909 (txt tree)
7910 (^re_ "\\(\\*+\\)[ \t]*")
7911 (old-level (if (string-match org-outline-regexp-bol txt)
7912 (- (match-end 0) (match-beginning 0) 1)
7913 -1))
7914 (force-level (cond (level (prefix-numeric-value level))
7915 ((and (looking-at "[ \t]*$")
7916 (string-match
7917 "^\\*+$" (buffer-substring
7918 (point-at-bol) (point))))
7919 (- (match-end 1) (match-beginning 1)))
7920 ((and (bolp)
7921 (looking-at org-outline-regexp))
7922 (- (match-end 0) (point) 1))))
7923 (previous-level (save-excursion
7924 (condition-case nil
7925 (progn
7926 (outline-previous-visible-heading 1)
7927 (if (looking-at ^re_)
7928 (- (match-end 0) (match-beginning 0) 1)
7930 (error 1))))
7931 (next-level (save-excursion
7932 (condition-case nil
7933 (progn
7934 (or (looking-at org-outline-regexp)
7935 (outline-next-visible-heading 1))
7936 (if (looking-at ^re_)
7937 (- (match-end 0) (match-beginning 0) 1)
7939 (error 1))))
7940 (new-level (or force-level (max previous-level next-level)))
7941 (shift (if (or (= old-level -1)
7942 (= new-level -1)
7943 (= old-level new-level))
7945 (- new-level old-level)))
7946 (delta (if (> shift 0) -1 1))
7947 (func (if (> shift 0) 'org-demote 'org-promote))
7948 (org-odd-levels-only nil)
7949 beg end newend)
7950 ;; Remove the forced level indicator
7951 (if force-level
7952 (delete-region (point-at-bol) (point)))
7953 ;; Paste
7954 (beginning-of-line (if (bolp) 1 2))
7955 (unless for-yank (org-back-over-empty-lines))
7956 (setq beg (point))
7957 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7958 (insert-before-markers txt)
7959 (unless (string-match "\n\\'" txt) (insert "\n"))
7960 (setq newend (point))
7961 (org-reinstall-markers-in-region beg)
7962 (setq end (point))
7963 (goto-char beg)
7964 (skip-chars-forward " \t\n\r")
7965 (setq beg (point))
7966 (if (and (outline-invisible-p) visp)
7967 (save-excursion (outline-show-heading)))
7968 ;; Shift if necessary
7969 (unless (= shift 0)
7970 (save-restriction
7971 (narrow-to-region beg end)
7972 (while (not (= shift 0))
7973 (org-map-region func (point-min) (point-max))
7974 (setq shift (+ delta shift)))
7975 (goto-char (point-min))
7976 (setq newend (point-max))))
7977 (when (or (org-called-interactively-p 'interactive) for-yank)
7978 (message "Clipboard pasted as level %d subtree" new-level))
7979 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7980 kill-ring
7981 (eq org-subtree-clip (current-kill 0))
7982 org-subtree-clip-folded)
7983 ;; The tree was folded before it was killed/copied
7984 (hide-subtree))
7985 (and for-yank (goto-char newend)))))
7987 (defun org-kill-is-subtree-p (&optional txt)
7988 "Check if the current kill is an outline subtree, or a set of trees.
7989 Returns nil if kill does not start with a headline, or if the first
7990 headline level is not the largest headline level in the tree.
7991 So this will actually accept several entries of equal levels as well,
7992 which is OK for `org-paste-subtree'.
7993 If optional TXT is given, check this string instead of the current kill."
7994 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7995 (re (org-get-limited-outline-regexp))
7996 (^re (concat "^" re))
7997 (start-level (and kill
7998 (string-match
7999 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8000 kill)
8001 (- (match-end 2) (match-beginning 2) 1)))
8002 (start (1+ (or (match-beginning 2) -1))))
8003 (if (not start-level)
8004 (progn
8005 nil) ;; does not even start with a heading
8006 (catch 'exit
8007 (while (setq start (string-match ^re kill (1+ start)))
8008 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8009 (throw 'exit nil)))
8010 t))))
8012 (defvar org-markers-to-move nil
8013 "Markers that should be moved with a cut-and-paste operation.
8014 Those markers are stored together with their positions relative to
8015 the start of the region.")
8017 (defun org-save-markers-in-region (beg end)
8018 "Check markers in region.
8019 If these markers are between BEG and END, record their position relative
8020 to BEG, so that after moving the block of text, we can put the markers back
8021 into place.
8022 This function gets called just before an entry or tree gets cut from the
8023 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8024 called immediately, to move the markers with the entries."
8025 (setq org-markers-to-move nil)
8026 (when (featurep 'org-clock)
8027 (org-clock-save-markers-for-cut-and-paste beg end))
8028 (when (featurep 'org-agenda)
8029 (org-agenda-save-markers-for-cut-and-paste beg end)))
8031 (defun org-check-and-save-marker (marker beg end)
8032 "Check if MARKER is between BEG and END.
8033 If yes, remember the marker and the distance to BEG."
8034 (when (and (marker-buffer marker)
8035 (equal (marker-buffer marker) (current-buffer)))
8036 (if (and (>= marker beg) (< marker end))
8037 (push (cons marker (- marker beg)) org-markers-to-move))))
8039 (defun org-reinstall-markers-in-region (beg)
8040 "Move all remembered markers to their position relative to BEG."
8041 (mapc (lambda (x)
8042 (move-marker (car x) (+ beg (cdr x))))
8043 org-markers-to-move)
8044 (setq org-markers-to-move nil))
8046 (defun org-narrow-to-subtree ()
8047 "Narrow buffer to the current subtree."
8048 (interactive)
8049 (save-excursion
8050 (save-match-data
8051 (org-with-limited-levels
8052 (narrow-to-region
8053 (progn (org-back-to-heading t) (point))
8054 (progn (org-end-of-subtree t t)
8055 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8056 (point)))))))
8058 (defun org-narrow-to-block ()
8059 "Narrow buffer to the current block."
8060 (interactive)
8061 (let* ((case-fold-search t)
8062 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8063 "^[ \t]*#\\+end_.*")))
8064 (if blockp
8065 (narrow-to-region (car blockp) (cdr blockp))
8066 (error "Not in a block"))))
8068 (eval-when-compile
8069 (defvar org-property-drawer-re))
8071 (defvar org-property-start-re) ;; defined below
8072 (defun org-clone-subtree-with-time-shift (n &optional shift)
8073 "Clone the task (subtree) at point N times.
8074 The clones will be inserted as siblings.
8076 In interactive use, the user will be prompted for the number of
8077 clones to be produced, and for a time SHIFT, which may be a
8078 repeater as used in time stamps, for example `+3d'.
8080 When a valid repeater is given and the entry contains any time
8081 stamps, the clones will become a sequence in time, with time
8082 stamps in the subtree shifted for each clone produced. If SHIFT
8083 is nil or the empty string, time stamps will be left alone. The
8084 ID property of the original subtree is removed.
8086 If the original subtree did contain time stamps with a repeater,
8087 the following will happen:
8088 - the repeater will be removed in each clone
8089 - an additional clone will be produced, with the current, unshifted
8090 date(s) in the entry.
8091 - the original entry will be placed *after* all the clones, with
8092 repeater intact.
8093 - the start days in the repeater in the original entry will be shifted
8094 to past the last clone.
8095 In this way you can spell out a number of instances of a repeating task,
8096 and still retain the repeater to cover future instances of the task."
8097 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8098 (let (beg end template task idprop
8099 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8100 (drawer-re org-drawer-regexp))
8101 (if (not (and (integerp n) (> n 0)))
8102 (error "Invalid number of replications %s" n))
8103 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8104 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8105 shift)))
8106 (error "Invalid shift specification %s" shift))
8107 (when doshift
8108 (setq shift-n (string-to-number (match-string 1 shift))
8109 shift-what (cdr (assoc (match-string 2 shift)
8110 '(("d" . day) ("w" . week)
8111 ("m" . month) ("y" . year))))))
8112 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8113 (setq nmin 1 nmax n)
8114 (org-back-to-heading t)
8115 (setq beg (point))
8116 (setq idprop (org-entry-get nil "ID"))
8117 (org-end-of-subtree t t)
8118 (or (bolp) (insert "\n"))
8119 (setq end (point))
8120 (setq template (buffer-substring beg end))
8121 (when (and doshift
8122 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8123 (delete-region beg end)
8124 (setq end beg)
8125 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8126 (goto-char end)
8127 (loop for n from nmin to nmax do
8128 ;; prepare clone
8129 (with-temp-buffer
8130 (insert template)
8131 (org-mode)
8132 (goto-char (point-min))
8133 (org-show-subtree)
8134 (and idprop (if org-clone-delete-id
8135 (org-entry-delete nil "ID")
8136 (org-id-get-create t)))
8137 (unless (= n 0)
8138 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8139 (kill-whole-line))
8140 (goto-char (point-min))
8141 (while (re-search-forward drawer-re nil t)
8142 (mapc (lambda (d)
8143 (org-remove-empty-drawer-at d (point))) org-drawers)))
8144 (goto-char (point-min))
8145 (when doshift
8146 (while (re-search-forward org-ts-regexp-both nil t)
8147 (org-timestamp-change (* n shift-n) shift-what))
8148 (unless (= n n-no-remove)
8149 (goto-char (point-min))
8150 (while (re-search-forward org-ts-regexp nil t)
8151 (save-excursion
8152 (goto-char (match-beginning 0))
8153 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8154 (delete-region (match-beginning 1) (match-end 1)))))))
8155 (setq task (buffer-string)))
8156 (insert task))
8157 (goto-char beg)))
8159 ;;; Outline Sorting
8161 (defun org-sort (with-case)
8162 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8163 Optional argument WITH-CASE means sort case-sensitively."
8164 (interactive "P")
8165 (cond
8166 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8167 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8169 (org-call-with-arg 'org-sort-entries with-case))))
8171 (defun org-sort-remove-invisible (s)
8172 (remove-text-properties 0 (length s) org-rm-props s)
8173 (while (string-match org-bracket-link-regexp s)
8174 (setq s (replace-match (if (match-end 2)
8175 (match-string 3 s)
8176 (match-string 1 s)) t t s)))
8179 (defvar org-priority-regexp) ; defined later in the file
8181 (defvar org-after-sorting-entries-or-items-hook nil
8182 "Hook that is run after a bunch of entries or items have been sorted.
8183 When children are sorted, the cursor is in the parent line when this
8184 hook gets called. When a region or a plain list is sorted, the cursor
8185 will be in the first entry of the sorted region/list.")
8187 (defun org-sort-entries
8188 (&optional with-case sorting-type getkey-func compare-func property)
8189 "Sort entries on a certain level of an outline tree.
8190 If there is an active region, the entries in the region are sorted.
8191 Else, if the cursor is before the first entry, sort the top-level items.
8192 Else, the children of the entry at point are sorted.
8194 Sorting can be alphabetically, numerically, by date/time as given by
8195 a time stamp, by a property or by priority.
8197 The command prompts for the sorting type unless it has been given to the
8198 function through the SORTING-TYPE argument, which needs to be a character,
8199 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8200 precise meaning of each character:
8202 n Numerically, by converting the beginning of the entry/item to a number.
8203 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8204 t By date/time, either the first active time stamp in the entry, or, if
8205 none exist, by the first inactive one.
8206 s By the scheduled date/time.
8207 d By deadline date/time.
8208 c By creation time, which is assumed to be the first inactive time stamp
8209 at the beginning of a line.
8210 p By priority according to the cookie.
8211 r By the value of a property.
8213 Capital letters will reverse the sort order.
8215 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8216 called with point at the beginning of the record. It must return either
8217 a string or a number that should serve as the sorting key for that record.
8219 Comparing entries ignores case by default. However, with an optional argument
8220 WITH-CASE, the sorting considers case as well."
8221 (interactive "P")
8222 (let ((case-func (if with-case 'identity 'downcase))
8223 start beg end stars re re2
8224 txt what tmp)
8225 ;; Find beginning and end of region to sort
8226 (cond
8227 ((org-region-active-p)
8228 ;; we will sort the region
8229 (setq end (region-end)
8230 what "region")
8231 (goto-char (region-beginning))
8232 (if (not (org-at-heading-p)) (outline-next-heading))
8233 (setq start (point)))
8234 ((or (org-at-heading-p)
8235 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8236 ;; we will sort the children of the current headline
8237 (org-back-to-heading)
8238 (setq start (point)
8239 end (progn (org-end-of-subtree t t)
8240 (or (bolp) (insert "\n"))
8241 (org-back-over-empty-lines)
8242 (point))
8243 what "children")
8244 (goto-char start)
8245 (show-subtree)
8246 (outline-next-heading))
8248 ;; we will sort the top-level entries in this file
8249 (goto-char (point-min))
8250 (or (org-at-heading-p) (outline-next-heading))
8251 (setq start (point))
8252 (goto-char (point-max))
8253 (beginning-of-line 1)
8254 (when (looking-at ".*?\\S-")
8255 ;; File ends in a non-white line
8256 (end-of-line 1)
8257 (insert "\n"))
8258 (setq end (point-max))
8259 (setq what "top-level")
8260 (goto-char start)
8261 (show-all)))
8263 (setq beg (point))
8264 (if (>= beg end) (error "Nothing to sort"))
8266 (looking-at "\\(\\*+\\)")
8267 (setq stars (match-string 1)
8268 re (concat "^" (regexp-quote stars) " +")
8269 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8270 txt (buffer-substring beg end))
8271 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8272 (if (and (not (equal stars "*")) (string-match re2 txt))
8273 (error "Region to sort contains a level above the first entry"))
8275 (unless sorting-type
8276 (message
8277 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8278 [t]ime [s]cheduled [d]eadline [c]reated
8279 A/N/T/S/D/C/P/O/F means reversed:"
8280 what)
8281 (setq sorting-type (read-char-exclusive))
8283 (and (= (downcase sorting-type) ?f)
8284 (setq getkey-func
8285 (org-icompleting-read "Sort using function: "
8286 obarray 'fboundp t nil nil))
8287 (setq getkey-func (intern getkey-func)))
8289 (and (= (downcase sorting-type) ?r)
8290 (setq property
8291 (org-icompleting-read "Property: "
8292 (mapcar 'list (org-buffer-property-keys t))
8293 nil t))))
8295 (message "Sorting entries...")
8297 (save-restriction
8298 (narrow-to-region start end)
8299 (let ((dcst (downcase sorting-type))
8300 (case-fold-search nil)
8301 (now (current-time)))
8302 (sort-subr
8303 (/= dcst sorting-type)
8304 ;; This function moves to the beginning character of the "record" to
8305 ;; be sorted.
8306 (lambda nil
8307 (if (re-search-forward re nil t)
8308 (goto-char (match-beginning 0))
8309 (goto-char (point-max))))
8310 ;; This function moves to the last character of the "record" being
8311 ;; sorted.
8312 (lambda nil
8313 (save-match-data
8314 (condition-case nil
8315 (outline-forward-same-level 1)
8316 (error
8317 (goto-char (point-max))))))
8318 ;; This function returns the value that gets sorted against.
8319 (lambda nil
8320 (cond
8321 ((= dcst ?n)
8322 (if (looking-at org-complex-heading-regexp)
8323 (string-to-number (match-string 4))
8324 nil))
8325 ((= dcst ?a)
8326 (if (looking-at org-complex-heading-regexp)
8327 (funcall case-func (match-string 4))
8328 nil))
8329 ((= dcst ?t)
8330 (let ((end (save-excursion (outline-next-heading) (point))))
8331 (if (or (re-search-forward org-ts-regexp end t)
8332 (re-search-forward org-ts-regexp-both end t))
8333 (org-time-string-to-seconds (match-string 0))
8334 (org-float-time now))))
8335 ((= dcst ?c)
8336 (let ((end (save-excursion (outline-next-heading) (point))))
8337 (if (re-search-forward
8338 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8339 end t)
8340 (org-time-string-to-seconds (match-string 0))
8341 (org-float-time now))))
8342 ((= dcst ?s)
8343 (let ((end (save-excursion (outline-next-heading) (point))))
8344 (if (re-search-forward org-scheduled-time-regexp end t)
8345 (org-time-string-to-seconds (match-string 1))
8346 (org-float-time now))))
8347 ((= dcst ?d)
8348 (let ((end (save-excursion (outline-next-heading) (point))))
8349 (if (re-search-forward org-deadline-time-regexp end t)
8350 (org-time-string-to-seconds (match-string 1))
8351 (org-float-time now))))
8352 ((= dcst ?p)
8353 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8354 (string-to-char (match-string 2))
8355 org-default-priority))
8356 ((= dcst ?r)
8357 (or (org-entry-get nil property) ""))
8358 ((= dcst ?o)
8359 (if (looking-at org-complex-heading-regexp)
8360 (- 9999 (length (member (match-string 2)
8361 org-todo-keywords-1)))))
8362 ((= dcst ?f)
8363 (if getkey-func
8364 (progn
8365 (setq tmp (funcall getkey-func))
8366 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8367 tmp)
8368 (error "Invalid key function `%s'" getkey-func)))
8369 (t (error "Invalid sorting type `%c'" sorting-type))))
8371 (cond
8372 ((= dcst ?a) 'string<)
8373 ((= dcst ?f) compare-func)
8374 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8375 (run-hooks 'org-after-sorting-entries-or-items-hook)
8376 (message "Sorting entries...done")))
8378 (defun org-do-sort (table what &optional with-case sorting-type)
8379 "Sort TABLE of WHAT according to SORTING-TYPE.
8380 The user will be prompted for the SORTING-TYPE if the call to this
8381 function does not specify it. WHAT is only for the prompt, to indicate
8382 what is being sorted. The sorting key will be extracted from
8383 the car of the elements of the table.
8384 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8385 (unless sorting-type
8386 (message
8387 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8388 what)
8389 (setq sorting-type (read-char-exclusive)))
8390 (let ((dcst (downcase sorting-type))
8391 extractfun comparefun)
8392 ;; Define the appropriate functions
8393 (cond
8394 ((= dcst ?n)
8395 (setq extractfun 'string-to-number
8396 comparefun (if (= dcst sorting-type) '< '>)))
8397 ((= dcst ?a)
8398 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8399 (lambda(x) (downcase (org-sort-remove-invisible x))))
8400 comparefun (if (= dcst sorting-type)
8401 'string<
8402 (lambda (a b) (and (not (string< a b))
8403 (not (string= a b)))))))
8404 ((= dcst ?t)
8405 (setq extractfun
8406 (lambda (x)
8407 (if (or (string-match org-ts-regexp x)
8408 (string-match org-ts-regexp-both x))
8409 (org-float-time
8410 (org-time-string-to-time (match-string 0 x)))
8412 comparefun (if (= dcst sorting-type) '< '>)))
8413 (t (error "Invalid sorting type `%c'" sorting-type)))
8415 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8416 table)
8417 (lambda (a b) (funcall comparefun (car a) (car b))))))
8420 ;;; The orgstruct minor mode
8422 ;; Define a minor mode which can be used in other modes in order to
8423 ;; integrate the org-mode structure editing commands.
8425 ;; This is really a hack, because the org-mode structure commands use
8426 ;; keys which normally belong to the major mode. Here is how it
8427 ;; works: The minor mode defines all the keys necessary to operate the
8428 ;; structure commands, but wraps the commands into a function which
8429 ;; tests if the cursor is currently at a headline or a plain list
8430 ;; item. If that is the case, the structure command is used,
8431 ;; temporarily setting many Org-mode variables like regular
8432 ;; expressions for filling etc. However, when any of those keys is
8433 ;; used at a different location, function uses `key-binding' to look
8434 ;; up if the key has an associated command in another currently active
8435 ;; keymap (minor modes, major mode, global), and executes that
8436 ;; command. There might be problems if any of the keys is otherwise
8437 ;; used as a prefix key.
8439 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8440 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8441 ;; addresses this by checking explicitly for both bindings.
8443 (defvar orgstruct-mode-map (make-sparse-keymap)
8444 "Keymap for the minor `orgstruct-mode'.")
8446 (defvar org-local-vars nil
8447 "List of local variables, for use by `orgstruct-mode'.")
8449 ;;;###autoload
8450 (define-minor-mode orgstruct-mode
8451 "Toggle the minor mode `orgstruct-mode'.
8452 This mode is for using Org-mode structure commands in other
8453 modes. The following keys behave as if Org-mode were active, if
8454 the cursor is on a headline, or on a plain list item (both as
8455 defined by Org-mode).
8457 M-up Move entry/item up
8458 M-down Move entry/item down
8459 M-left Promote
8460 M-right Demote
8461 M-S-up Move entry/item up
8462 M-S-down Move entry/item down
8463 M-S-left Promote subtree
8464 M-S-right Demote subtree
8465 M-q Fill paragraph and items like in Org-mode
8466 C-c ^ Sort entries
8467 C-c - Cycle list bullet
8468 TAB Cycle item visibility
8469 M-RET Insert new heading/item
8470 S-M-RET Insert new TODO heading / Checkbox item
8471 C-c C-c Set tags / toggle checkbox"
8472 nil " OrgStruct" nil
8473 (org-load-modules-maybe)
8474 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8476 ;;;###autoload
8477 (defun turn-on-orgstruct ()
8478 "Unconditionally turn on `orgstruct-mode'."
8479 (orgstruct-mode 1))
8481 (defvar org-fb-vars nil)
8482 (make-variable-buffer-local 'org-fb-vars)
8483 (defun orgstruct++-mode (&optional arg)
8484 "Toggle `orgstruct-mode', the enhanced version of it.
8485 In addition to setting orgstruct-mode, this also exports all
8486 indentation and autofilling variables from org-mode into the
8487 buffer. It will also recognize item context in multiline items."
8488 (interactive "P")
8489 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8490 (if (< arg 1)
8491 (progn (orgstruct-mode -1)
8492 (mapc (lambda(v)
8493 (org-set-local (car v)
8494 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8495 org-fb-vars))
8496 (orgstruct-mode 1)
8497 (setq org-fb-vars nil)
8498 (let (var val)
8499 (mapc
8500 (lambda (x)
8501 (when (string-match
8502 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8503 (symbol-name (car x)))
8504 (setq var (car x) val (nth 1 x))
8505 (push (list var `(quote ,(eval var))) org-fb-vars)
8506 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8507 org-local-vars)
8508 (org-set-local 'orgstruct-is-++ t))))
8510 (defvar orgstruct-is-++ nil
8511 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8512 (make-variable-buffer-local 'orgstruct-is-++)
8514 ;;;###autoload
8515 (defun turn-on-orgstruct++ ()
8516 "Unconditionally turn on `orgstruct++-mode'."
8517 (orgstruct++-mode 1))
8519 (defun orgstruct-error ()
8520 "Error when there is no default binding for a structure key."
8521 (interactive)
8522 (error "This key has no function outside structure elements"))
8524 (defun orgstruct-setup ()
8525 "Setup orgstruct keymaps."
8526 (let ((nfunc 0)
8527 (bindings
8528 (list
8529 '([(meta up)] org-metaup)
8530 '([(meta down)] org-metadown)
8531 '([(meta left)] org-metaleft)
8532 '([(meta right)] org-metaright)
8533 '([(meta shift up)] org-shiftmetaup)
8534 '([(meta shift down)] org-shiftmetadown)
8535 '([(meta shift left)] org-shiftmetaleft)
8536 '([(meta shift right)] org-shiftmetaright)
8537 '([?\e (up)] org-metaup)
8538 '([?\e (down)] org-metadown)
8539 '([?\e (left)] org-metaleft)
8540 '([?\e (right)] org-metaright)
8541 '([?\e (shift up)] org-shiftmetaup)
8542 '([?\e (shift down)] org-shiftmetadown)
8543 '([?\e (shift left)] org-shiftmetaleft)
8544 '([?\e (shift right)] org-shiftmetaright)
8545 '([(shift up)] org-shiftup)
8546 '([(shift down)] org-shiftdown)
8547 '([(shift left)] org-shiftleft)
8548 '([(shift right)] org-shiftright)
8549 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8550 '("\M-q" fill-paragraph)
8551 '("\C-c^" org-sort)
8552 '("\C-c-" org-cycle-list-bullet)))
8553 elt key fun cmd)
8554 (while (setq elt (pop bindings))
8555 (setq nfunc (1+ nfunc))
8556 (setq key (org-key (car elt))
8557 fun (nth 1 elt)
8558 cmd (orgstruct-make-binding fun nfunc key))
8559 (org-defkey orgstruct-mode-map key cmd))
8561 ;; Prevent an error for users who forgot to make autoloads
8562 (require 'org-element)
8564 ;; Special treatment needed for TAB and RET
8565 (org-defkey orgstruct-mode-map [(tab)]
8566 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8567 (org-defkey orgstruct-mode-map "\C-i"
8568 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8570 (org-defkey orgstruct-mode-map "\M-\C-m"
8571 (orgstruct-make-binding 'org-insert-heading 105
8572 "\M-\C-m" [(meta return)]))
8573 (org-defkey orgstruct-mode-map [(meta return)]
8574 (orgstruct-make-binding 'org-insert-heading 106
8575 [(meta return)] "\M-\C-m"))
8577 (org-defkey orgstruct-mode-map [(shift meta return)]
8578 (orgstruct-make-binding 'org-insert-todo-heading 107
8579 [(meta return)] "\M-\C-m"))
8581 (org-defkey orgstruct-mode-map "\e\C-m"
8582 (orgstruct-make-binding 'org-insert-heading 108
8583 "\e\C-m" [?\e (return)]))
8584 (org-defkey orgstruct-mode-map [?\e (return)]
8585 (orgstruct-make-binding 'org-insert-heading 109
8586 [?\e (return)] "\e\C-m"))
8587 (org-defkey orgstruct-mode-map [?\e (shift return)]
8588 (orgstruct-make-binding 'org-insert-todo-heading 110
8589 [?\e (return)] "\e\C-m"))
8591 (unless org-local-vars
8592 (setq org-local-vars (org-get-local-variables)))
8596 (defun orgstruct-make-binding (fun n &rest keys)
8597 "Create a function for binding in the structure minor mode.
8598 FUN is the command to call inside a table. N is used to create a unique
8599 command name. KEYS are keys that should be checked in for a command
8600 to execute outside of tables."
8601 (eval
8602 (list 'defun
8603 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8604 '(arg)
8605 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8606 "Outside of structure, run the binding of `"
8607 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8608 "'.")
8609 '(interactive "p")
8610 (list 'if
8611 `(org-context-p 'headline 'item
8612 (and orgstruct-is-++
8613 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8614 'item-body))
8615 (list 'org-run-like-in-org-mode (list 'quote fun))
8616 (list 'let '(orgstruct-mode)
8617 (list 'call-interactively
8618 (append '(or)
8619 (mapcar (lambda (k)
8620 (list 'key-binding k))
8621 keys)
8622 '('orgstruct-error))))))))
8624 (defun org-contextualize-keys (alist contexts)
8625 "Return valid elements in ALIST depending on CONTEXTS.
8627 `org-agenda-custom-commands' or `org-capture-templates' are the
8628 values used for ALIST, and `org-agenda-custom-commands-contexts'
8629 or `org-capture-templates-contexts' are the associated contexts
8630 definitions."
8631 (let ((contexts
8632 ;; normalize contexts
8633 (mapcar
8634 (lambda(c) (cond ((listp (cadr c))
8635 (list (car c) (car c) (cadr c)))
8636 ((string= "" (cadr c))
8637 (list (car c) (car c) (caddr c)))
8638 (t c))) contexts))
8639 (a alist) c r s)
8640 ;; loop over all commands or templates
8641 (while (setq c (pop a))
8642 (let (vrules repl)
8643 (cond
8644 ((not (assoc (car c) contexts))
8645 (push c r))
8646 ((and (assoc (car c) contexts)
8647 (setq vrules (org-contextualize-validate-key
8648 (car c) contexts)))
8649 (mapc (lambda (vr)
8650 (when (not (equal (car vr) (cadr vr)))
8651 (setq repl vr))) vrules)
8652 (if (not repl) (push c r)
8653 (push (cadr repl) s)
8654 (push
8655 (cons (car c)
8656 (cdr (or (assoc (cadr repl) alist)
8657 (error "Undefined key `%s' as contextual replacement for `%s'"
8658 (cadr repl) (car c)))))
8659 r))))))
8660 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8661 (delq
8663 (delete-dups
8664 (mapcar (lambda (x)
8665 (let ((tpl (car x)))
8666 (when (not (delq
8668 (mapcar (lambda(y)
8669 (equal y tpl)) s))) x)))
8670 (reverse r))))))
8672 (defun org-contextualize-validate-key (key contexts)
8673 "Check CONTEXTS for agenda or capture KEY."
8674 (let (r rr res)
8675 (while (setq r (pop contexts))
8676 (mapc
8677 (lambda (rr)
8678 (when
8679 (and (equal key (car r))
8680 (if (functionp rr) (funcall rr)
8681 (or (and (eq (car rr) 'in-file)
8682 (buffer-file-name)
8683 (string-match (cdr rr) (buffer-file-name)))
8684 (and (eq (car rr) 'in-mode)
8685 (string-match (cdr rr) (symbol-name major-mode)))
8686 (when (and (eq (car rr) 'not-in-file)
8687 (buffer-file-name))
8688 (not (string-match (cdr rr) (buffer-file-name))))
8689 (when (eq (car rr) 'not-in-mode)
8690 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8691 (push r res)))
8692 (car (last r))))
8693 (delete-dups (delq nil res))))
8695 (defun org-context-p (&rest contexts)
8696 "Check if local context is any of CONTEXTS.
8697 Possible values in the list of contexts are `table', `headline', and `item'."
8698 (let ((pos (point)))
8699 (goto-char (point-at-bol))
8700 (prog1 (or (and (memq 'table contexts)
8701 (looking-at "[ \t]*|"))
8702 (and (memq 'headline contexts)
8703 (looking-at org-outline-regexp))
8704 (and (memq 'item contexts)
8705 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8706 (and (memq 'item-body contexts)
8707 (org-in-item-p)))
8708 (goto-char pos))))
8710 (defun org-get-local-variables ()
8711 "Return a list of all local variables in an Org mode buffer."
8712 (let (varlist)
8713 (with-current-buffer (get-buffer-create "*Org tmp*")
8714 (erase-buffer)
8715 (org-mode)
8716 (setq varlist (buffer-local-variables)))
8717 (kill-buffer "*Org tmp*")
8718 (delq nil
8719 (mapcar
8720 (lambda (x)
8721 (setq x
8722 (if (symbolp x)
8723 (list x)
8724 (list (car x) (list 'quote (cdr x)))))
8725 (if (string-match
8726 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8727 (symbol-name (car x)))
8728 x nil))
8729 varlist))))
8731 (defun org-clone-local-variables (from-buffer &optional regexp)
8732 "Clone local variables from FROM-BUFFER.
8733 Optional argument REGEXP selects variables to clone."
8734 (mapc
8735 (lambda (pair)
8736 (and (symbolp (car pair))
8737 (or (null regexp)
8738 (string-match regexp (symbol-name (car pair))))
8739 (set (make-local-variable (car pair))
8740 (cdr pair))))
8741 (buffer-local-variables from-buffer)))
8743 ;;;###autoload
8744 (defun org-run-like-in-org-mode (cmd)
8745 "Run a command, pretending that the current buffer is in Org-mode.
8746 This will temporarily bind local variables that are typically bound in
8747 Org-mode to the values they have in Org-mode, and then interactively
8748 call CMD."
8749 (org-load-modules-maybe)
8750 (unless org-local-vars
8751 (setq org-local-vars (org-get-local-variables)))
8752 (eval (list 'let org-local-vars
8753 (list 'call-interactively (list 'quote cmd)))))
8755 ;;;; Archiving
8757 (defun org-get-category (&optional pos force-refresh)
8758 "Get the category applying to position POS."
8759 (save-match-data
8760 (if force-refresh (org-refresh-category-properties))
8761 (let ((pos (or pos (point))))
8762 (or (get-text-property pos 'org-category)
8763 (progn (org-refresh-category-properties)
8764 (get-text-property pos 'org-category))))))
8766 (defun org-refresh-category-properties ()
8767 "Refresh category text properties in the buffer."
8768 (let ((case-fold-search t)
8769 (inhibit-read-only t)
8770 (def-cat (cond
8771 ((null org-category)
8772 (if buffer-file-name
8773 (file-name-sans-extension
8774 (file-name-nondirectory buffer-file-name))
8775 "???"))
8776 ((symbolp org-category) (symbol-name org-category))
8777 (t org-category)))
8778 beg end cat pos optionp)
8779 (org-unmodified
8780 (save-excursion
8781 (save-restriction
8782 (widen)
8783 (goto-char (point-min))
8784 (put-text-property (point) (point-max) 'org-category def-cat)
8785 (while (re-search-forward
8786 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8787 (setq pos (match-end 0)
8788 optionp (equal (char-after (match-beginning 0)) ?#)
8789 cat (org-trim (match-string 2)))
8790 (if optionp
8791 (setq beg (point-at-bol) end (point-max))
8792 (org-back-to-heading t)
8793 (setq beg (point) end (org-end-of-subtree t t)))
8794 (put-text-property beg end 'org-category cat)
8795 (put-text-property beg end 'org-category-position beg)
8796 (goto-char pos)))))))
8799 ;;;; Link Stuff
8801 ;;; Link abbreviations
8803 (defun org-link-expand-abbrev (link)
8804 "Apply replacements as defined in `org-link-abbrev-alist'."
8805 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8806 (let* ((key (match-string 1 link))
8807 (as (or (assoc key org-link-abbrev-alist-local)
8808 (assoc key org-link-abbrev-alist)))
8809 (tag (and (match-end 2) (match-string 3 link)))
8810 rpl)
8811 (if (not as)
8812 link
8813 (setq rpl (cdr as))
8814 (cond
8815 ((symbolp rpl) (funcall rpl tag))
8816 ((string-match "%(\\([^)]+\\))" rpl)
8817 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8818 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8819 ((string-match "%h" rpl)
8820 (replace-match (url-hexify-string (or tag "")) t t rpl))
8821 (t (concat rpl tag)))))
8822 link))
8824 ;;; Storing and inserting links
8826 (defvar org-insert-link-history nil
8827 "Minibuffer history for links inserted with `org-insert-link'.")
8829 (defvar org-stored-links nil
8830 "Contains the links stored with `org-store-link'.")
8832 (defvar org-store-link-plist nil
8833 "Plist with info about the most recently link created with `org-store-link'.")
8835 (defvar org-link-protocols nil
8836 "Link protocols added to Org-mode using `org-add-link-type'.")
8838 (defvar org-store-link-functions nil
8839 "List of functions that are called to create and store a link.
8840 Each function will be called in turn until one returns a non-nil
8841 value. Each function should check if it is responsible for creating
8842 this link (for example by looking at the major mode).
8843 If not, it must exit and return nil.
8844 If yes, it should return a non-nil value after a calling
8845 `org-store-link-props' with a list of properties and values.
8846 Special properties are:
8848 :type The link prefix, like \"http\". This must be given.
8849 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8850 This is obligatory as well.
8851 :description Optional default description for the second pair
8852 of brackets in an Org-mode link. The user can still change
8853 this when inserting this link into an Org-mode buffer.
8855 In addition to these, any additional properties can be specified
8856 and then used in capture templates.")
8858 (defun org-add-link-type (type &optional follow export)
8859 "Add TYPE to the list of `org-link-types'.
8860 Re-compute all regular expressions depending on `org-link-types'
8862 FOLLOW and EXPORT are two functions.
8864 FOLLOW should take the link path as the single argument and do whatever
8865 is necessary to follow the link, for example find a file or display
8866 a mail message.
8868 EXPORT should format the link path for export to one of the export formats.
8869 It should be a function accepting three arguments:
8871 path the path of the link, the text after the prefix (like \"http:\")
8872 desc the description of the link, if any, or a description added by
8873 org-export-normalize-links if there is none
8874 format the export format, a symbol like `html' or `latex' or `ascii'..
8876 The function may use the FORMAT information to return different values
8877 depending on the format. The return value will be put literally into
8878 the exported file. If the return value is nil, this means Org should
8879 do what it normally does with links which do not have EXPORT defined.
8881 Org-mode has a built-in default for exporting links. If you are happy with
8882 this default, there is no need to define an export function for the link
8883 type. For a simple example of an export function, see `org-bbdb.el'."
8884 (add-to-list 'org-link-types type t)
8885 (org-make-link-regexps)
8886 (if (assoc type org-link-protocols)
8887 (setcdr (assoc type org-link-protocols) (list follow export))
8888 (push (list type follow export) org-link-protocols)))
8890 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8891 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8893 ;;;###autoload
8894 (defun org-store-link (arg)
8895 "\\<org-mode-map>Store an org-link to the current location.
8896 This link is added to `org-stored-links' and can later be inserted
8897 into an org-buffer with \\[org-insert-link].
8899 For some link types, a prefix arg is interpreted:
8900 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8901 For file links, arg negates `org-context-in-file-links'."
8902 (interactive "P")
8903 (org-load-modules-maybe)
8904 (setq org-store-link-plist nil) ; reset
8905 (org-with-limited-levels
8906 (let (link cpltxt desc description search txt custom-id agenda-link)
8907 (cond
8909 ((run-hook-with-args-until-success 'org-store-link-functions)
8910 (setq link (plist-get org-store-link-plist :link)
8911 desc (or (plist-get org-store-link-plist :description) link)))
8913 ((org-src-edit-buffer-p)
8914 (let (label gc)
8915 (while (or (not label)
8916 (save-excursion
8917 (save-restriction
8918 (widen)
8919 (goto-char (point-min))
8920 (re-search-forward
8921 (regexp-quote (format org-coderef-label-format label))
8922 nil t))))
8923 (when label (message "Label exists already") (sit-for 2))
8924 (setq label (read-string "Code line label: " label)))
8925 (end-of-line 1)
8926 (setq link (format org-coderef-label-format label))
8927 (setq gc (- 79 (length link)))
8928 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8929 (insert link)
8930 (setq link (concat "(" label ")") desc nil)))
8932 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8933 ;; We are in the agenda, link to referenced location
8934 (let ((m (or (get-text-property (point) 'org-hd-marker)
8935 (get-text-property (point) 'org-marker))))
8936 (when m
8937 (org-with-point-at m
8938 (setq agenda-link
8939 (if (org-called-interactively-p 'any)
8940 (call-interactively 'org-store-link)
8941 (org-store-link nil)))))))
8943 ((eq major-mode 'calendar-mode)
8944 (let ((cd (calendar-cursor-to-date)))
8945 (setq link
8946 (format-time-string
8947 (car org-time-stamp-formats)
8948 (apply 'encode-time
8949 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8950 nil nil nil))))
8951 (org-store-link-props :type "calendar" :date cd)))
8953 ((eq major-mode 'help-mode)
8954 (setq link (concat "help:" (save-excursion
8955 (goto-char (point-min))
8956 (looking-at "^[^ ]+")
8957 (match-string 0))))
8958 (org-store-link-props :type "help"))
8960 ((eq major-mode 'w3-mode)
8961 (setq cpltxt (if (and (buffer-name)
8962 (not (string-match "Untitled" (buffer-name))))
8963 (buffer-name)
8964 (url-view-url t))
8965 link (url-view-url t))
8966 (org-store-link-props :type "w3" :url (url-view-url t)))
8968 ((eq major-mode 'w3m-mode)
8969 (setq cpltxt (or w3m-current-title w3m-current-url)
8970 link w3m-current-url)
8971 (org-store-link-props :type "w3m" :url (url-view-url t)))
8973 ((setq search (run-hook-with-args-until-success
8974 'org-create-file-search-functions))
8975 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8976 "::" search))
8977 (setq cpltxt (or description link)))
8979 ((eq major-mode 'image-mode)
8980 (setq cpltxt (concat "file:"
8981 (abbreviate-file-name buffer-file-name))
8982 link cpltxt)
8983 (org-store-link-props :type "image" :file buffer-file-name))
8985 ((eq major-mode 'dired-mode)
8986 ;; link to the file in the current line
8987 (let ((file (dired-get-filename nil t)))
8988 (setq file (if file
8989 (abbreviate-file-name
8990 (expand-file-name (dired-get-filename nil t)))
8991 ;; otherwise, no file so use current directory.
8992 default-directory))
8993 (setq cpltxt (concat "file:" file)
8994 link cpltxt)))
8996 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8997 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8998 (cond
8999 ((org-in-regexp "<<\\(.*?\\)>>")
9000 (setq cpltxt
9001 (concat "file:"
9002 (abbreviate-file-name
9003 (buffer-file-name (buffer-base-buffer)))
9004 "::" (match-string 1))
9005 link cpltxt))
9006 ((and (featurep 'org-id)
9007 (or (eq org-link-to-org-use-id t)
9008 (and (org-called-interactively-p 'any)
9009 (or (eq org-link-to-org-use-id 'create-if-interactive)
9010 (and (eq org-link-to-org-use-id
9011 'create-if-interactive-and-no-custom-id)
9012 (not custom-id))))
9013 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9014 ;; We can make a link using the ID.
9015 (setq link (condition-case nil
9016 (prog1 (org-id-store-link)
9017 (setq desc (plist-get org-store-link-plist :description)))
9018 (error
9019 ;; probably before first headline, link to file only
9020 (concat "file:"
9021 (abbreviate-file-name
9022 (buffer-file-name (buffer-base-buffer))))))))
9024 ;; Just link to current headline
9025 (setq cpltxt (concat "file:"
9026 (abbreviate-file-name
9027 (buffer-file-name (buffer-base-buffer)))))
9028 ;; Add a context search string
9029 (when (org-xor org-context-in-file-links arg)
9030 (setq txt (cond
9031 ((org-at-heading-p) nil)
9032 ((org-region-active-p)
9033 (buffer-substring (region-beginning) (region-end)))))
9034 (when (or (null txt) (string-match "\\S-" txt))
9035 (setq cpltxt
9036 (concat cpltxt "::"
9037 (condition-case nil
9038 (org-make-org-heading-search-string txt)
9039 (error "")))
9040 desc (or (nth 4 (ignore-errors
9041 (org-heading-components))) "NONE"))))
9042 (if (string-match "::\\'" cpltxt)
9043 (setq cpltxt (substring cpltxt 0 -2)))
9044 (setq link cpltxt))))
9046 ((buffer-file-name (buffer-base-buffer))
9047 ;; Just link to this file here.
9048 (setq cpltxt (concat "file:"
9049 (abbreviate-file-name
9050 (buffer-file-name (buffer-base-buffer)))))
9051 ;; Add a context string
9052 (when (org-xor org-context-in-file-links arg)
9053 (setq txt (if (org-region-active-p)
9054 (buffer-substring (region-beginning) (region-end))
9055 (buffer-substring (point-at-bol) (point-at-eol))))
9056 ;; Only use search option if there is some text.
9057 (when (string-match "\\S-" txt)
9058 (setq cpltxt
9059 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9060 desc "NONE")))
9061 (setq link cpltxt))
9063 ((org-called-interactively-p 'interactive)
9064 (error "Cannot link to a buffer which is not visiting a file"))
9066 (t (setq link nil)))
9068 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9069 (setq link (or link cpltxt)
9070 desc (or desc cpltxt))
9071 (if (equal desc "NONE") (setq desc nil))
9073 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9074 (progn
9075 (setq org-stored-links
9076 (cons (list link desc) org-stored-links))
9077 (message "Stored: %s" (or desc link))
9078 (when custom-id
9079 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9080 "::#" custom-id))
9081 (setq org-stored-links
9082 (cons (list link desc) org-stored-links))))
9083 (or agenda-link (and link (org-make-link-string link desc)))))))
9085 (defun org-store-link-props (&rest plist)
9086 "Store link properties, extract names and addresses."
9087 (let (x adr)
9088 (when (setq x (plist-get plist :from))
9089 (setq adr (mail-extract-address-components x))
9090 (setq plist (plist-put plist :fromname (car adr)))
9091 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9092 (when (setq x (plist-get plist :to))
9093 (setq adr (mail-extract-address-components x))
9094 (setq plist (plist-put plist :toname (car adr)))
9095 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9096 (let ((from (plist-get plist :from))
9097 (to (plist-get plist :to)))
9098 (when (and from to org-from-is-user-regexp)
9099 (setq plist
9100 (plist-put plist :fromto
9101 (if (string-match org-from-is-user-regexp from)
9102 (concat "to %t")
9103 (concat "from %f"))))))
9104 (setq org-store-link-plist plist))
9106 (defun org-add-link-props (&rest plist)
9107 "Add these properties to the link property list."
9108 (let (key value)
9109 (while plist
9110 (setq key (pop plist) value (pop plist))
9111 (setq org-store-link-plist
9112 (plist-put org-store-link-plist key value)))))
9114 (defun org-email-link-description (&optional fmt)
9115 "Return the description part of an email link.
9116 This takes information from `org-store-link-plist' and formats it
9117 according to FMT (default from `org-email-link-description-format')."
9118 (setq fmt (or fmt org-email-link-description-format))
9119 (let* ((p org-store-link-plist)
9120 (to (plist-get p :toaddress))
9121 (from (plist-get p :fromaddress))
9122 (table
9123 (list
9124 (cons "%c" (plist-get p :fromto))
9125 (cons "%F" (plist-get p :from))
9126 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9127 (cons "%T" (plist-get p :to))
9128 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9129 (cons "%s" (plist-get p :subject))
9130 (cons "%d" (plist-get p :date))
9131 (cons "%m" (plist-get p :message-id)))))
9132 (when (string-match "%c" fmt)
9133 ;; Check if the user wrote this message
9134 (if (and org-from-is-user-regexp from to
9135 (save-match-data (string-match org-from-is-user-regexp from)))
9136 (setq fmt (replace-match "to %t" t t fmt))
9137 (setq fmt (replace-match "from %f" t t fmt))))
9138 (org-replace-escapes fmt table)))
9140 (defun org-make-org-heading-search-string (&optional string heading)
9141 "Make search string for STRING or current headline."
9142 (interactive)
9143 (let ((s (or string (org-get-heading)))
9144 (lines org-context-in-file-links))
9145 (unless (and string (not heading))
9146 ;; We are using a headline, clean up garbage in there.
9147 (if (string-match org-todo-regexp s)
9148 (setq s (replace-match "" t t s)))
9149 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9150 (setq s (replace-match "" t t s)))
9151 (setq s (org-trim s))
9152 (if (string-match (concat "^\\(" org-quote-string "\\|"
9153 org-comment-string "\\)") s)
9154 (setq s (replace-match "" t t s)))
9155 (while (string-match org-ts-regexp s)
9156 (setq s (replace-match "" t t s))))
9157 (or string (setq s (concat "*" s))) ; Add * for headlines
9158 (when (and string (integerp lines) (> lines 0))
9159 (let ((slines (org-split-string s "\n")))
9160 (when (< lines (length slines))
9161 (setq s (mapconcat
9162 'identity
9163 (reverse (nthcdr (- (length slines) lines)
9164 (reverse slines))) "\n")))))
9165 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9167 (defun org-make-link-string (link &optional description)
9168 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9169 (unless (string-match "\\S-" link)
9170 (error "Empty link"))
9171 (when (and description
9172 (stringp description)
9173 (not (string-match "\\S-" description)))
9174 (setq description nil))
9175 (when (stringp description)
9176 ;; Remove brackets from the description, they are fatal.
9177 (while (string-match "\\[" description)
9178 (setq description (replace-match "{" t t description)))
9179 (while (string-match "\\]" description)
9180 (setq description (replace-match "}" t t description))))
9181 (when (equal link description)
9182 ;; No description needed, it is identical
9183 (setq description nil))
9184 (when (and (not description)
9185 (not (string-match (org-image-file-name-regexp) link))
9186 (not (equal link (org-link-escape link))))
9187 (setq description (org-extract-attributes link)))
9188 (setq link
9189 (cond ((string-match (org-image-file-name-regexp) link) link)
9190 ((string-match org-link-types-re link)
9191 (concat (match-string 1 link)
9192 (org-link-escape (substring link (match-end 1)))))
9193 (t (org-link-escape link))))
9194 (concat "[[" link "]"
9195 (if description (concat "[" description "]") "")
9196 "]"))
9198 (defconst org-link-escape-chars
9199 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9200 "List of characters that should be escaped in link.
9201 This is the list that is used for internal purposes.")
9203 (defconst org-link-escape-chars-browser
9204 '(?\ )
9205 "List of escapes for characters that are problematic in links.
9206 This is the list that is used before handing over to the browser.")
9208 (defun org-link-escape (text &optional table merge)
9209 "Return percent escaped representation of TEXT.
9210 TEXT is a string with the text to escape.
9211 Optional argument TABLE is a list with characters that should be
9212 escaped. When nil, `org-link-escape-chars' is used.
9213 If optional argument MERGE is set, merge TABLE into
9214 `org-link-escape-chars'."
9215 (cond
9216 ((and table merge)
9217 (mapc (lambda (defchr)
9218 (unless (member defchr table)
9219 (setq table (cons defchr table)))) org-link-escape-chars))
9220 ((null table)
9221 (setq table org-link-escape-chars)))
9222 (mapconcat
9223 (lambda (char)
9224 (if (or (member char table)
9225 (and (or (< char 32) (= char 37) (> char 126))
9226 org-url-hexify-p))
9227 (mapconcat (lambda (sequence-element)
9228 (format "%%%.2X" sequence-element))
9229 (or (encode-coding-char char 'utf-8)
9230 (error "Unable to percent escape character: %s"
9231 (char-to-string char))) "")
9232 (char-to-string char))) text ""))
9234 (defun org-link-unescape (str)
9235 "Unhex hexified Unicode strings as returned from the JavaScript function
9236 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9237 (unless (and (null str) (string= "" str))
9238 (let ((pos 0) (case-fold-search t) unhexed)
9239 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9240 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9241 (setq str (replace-match unhexed t t str))
9242 (setq pos (+ pos (length unhexed))))))
9243 str)
9245 (defun org-link-unescape-compound (hex)
9246 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9247 Note: this function also decodes single byte encodings like
9248 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9249 (save-match-data
9250 (let* ((bytes (cdr (split-string hex "%")))
9251 (ret "")
9252 (eat 0)
9253 (sum 0))
9254 (while bytes
9255 (let* ((val (string-to-number (pop bytes) 16))
9256 (shift-xor
9257 (if (= 0 eat)
9258 (cond
9259 ((>= val 252) (cons 6 252))
9260 ((>= val 248) (cons 5 248))
9261 ((>= val 240) (cons 4 240))
9262 ((>= val 224) (cons 3 224))
9263 ((>= val 192) (cons 2 192))
9264 (t (cons 0 0)))
9265 (cons 6 128))))
9266 (if (>= val 192) (setq eat (car shift-xor)))
9267 (setq val (logxor val (cdr shift-xor)))
9268 (setq sum (+ (lsh sum (car shift-xor)) val))
9269 (if (> eat 0) (setq eat (- eat 1)))
9270 (cond
9271 ((= 0 eat) ;multi byte
9272 (setq ret (concat ret (org-char-to-string sum)))
9273 (setq sum 0))
9274 ((not bytes) ; single byte(s)
9275 (setq ret (org-link-unescape-single-byte-sequence hex))))
9276 )) ;; end (while bytes
9277 ret )))
9279 (defun org-link-unescape-single-byte-sequence (hex)
9280 "Unhexify hex-encoded single byte character sequences."
9281 (mapconcat (lambda (byte)
9282 (char-to-string (string-to-number byte 16)))
9283 (cdr (split-string hex "%")) ""))
9285 (defun org-xor (a b)
9286 "Exclusive or."
9287 (if a (not b) b))
9289 (defun org-fixup-message-id-for-http (s)
9290 "Replace special characters in a message id, so it can be used in an http query."
9291 (when (string-match "%" s)
9292 (setq s (mapconcat (lambda (c)
9293 (if (eq c ?%)
9294 "%25"
9295 (char-to-string c)))
9296 s "")))
9297 (while (string-match "<" s)
9298 (setq s (replace-match "%3C" t t s)))
9299 (while (string-match ">" s)
9300 (setq s (replace-match "%3E" t t s)))
9301 (while (string-match "@" s)
9302 (setq s (replace-match "%40" t t s)))
9305 (defun org-link-prettify (link)
9306 "Return a human-readable representation of LINK.
9307 The car of LINK must be a raw link the cdr of LINK must be either
9308 a link description or nil."
9309 (let ((desc (or (cadr link) "<no description>")))
9310 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9311 "<" (car link) ">")))
9313 ;;;###autoload
9314 (defun org-insert-link-global ()
9315 "Insert a link like Org-mode does.
9316 This command can be called in any mode to insert a link in Org-mode syntax."
9317 (interactive)
9318 (org-load-modules-maybe)
9319 (org-run-like-in-org-mode 'org-insert-link))
9321 (defun org-insert-all-links (&optional keep)
9322 "Insert all links in `org-stored-links'."
9323 (interactive "P")
9324 (let ((links (copy-sequence org-stored-links)) l)
9325 (while (setq l (if keep (pop links) (pop org-stored-links)))
9326 (insert "- ")
9327 (org-insert-link nil (car l) (cadr l))
9328 (insert "\n"))))
9330 (defun org-link-fontify-links-to-this-file ()
9331 "Fontify links to the current file in `org-stored-links'."
9332 (let ((f (buffer-file-name)) a b)
9333 (setq a (mapcar (lambda(l)
9334 (let ((ll (car l)))
9335 (when (and (string-match "^file:\\(.+\\)::" ll)
9336 (equal f (expand-file-name (match-string 1 ll))))
9337 ll)))
9338 org-stored-links))
9339 (when (featurep 'org-id)
9340 (setq b (mapcar (lambda(l)
9341 (let ((ll (car l)))
9342 (when (and (string-match "^id:\\(.+\\)$" ll)
9343 (equal f (expand-file-name
9344 (or (org-id-find-id-file
9345 (match-string 1 ll)) ""))))
9346 ll)))
9347 org-stored-links)))
9348 (mapcar (lambda(l)
9349 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9350 (delq nil (append a b)))))
9352 (defvar org-link-links-in-this-file nil)
9353 (defun org-insert-link (&optional complete-file link-location default-description)
9354 "Insert a link. At the prompt, enter the link.
9356 Completion can be used to insert any of the link protocol prefixes like
9357 http or ftp in use.
9359 The history can be used to select a link previously stored with
9360 `org-store-link'. When the empty string is entered (i.e. if you just
9361 press RET at the prompt), the link defaults to the most recently
9362 stored link. As SPC triggers completion in the minibuffer, you need to
9363 use M-SPC or C-q SPC to force the insertion of a space character.
9365 You will also be prompted for a description, and if one is given, it will
9366 be displayed in the buffer instead of the link.
9368 If there is already a link at point, this command will allow you to edit link
9369 and description parts.
9371 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9372 be selected using completion. The path to the file will be relative to the
9373 current directory if the file is in the current directory or a subdirectory.
9374 Otherwise, the link will be the absolute path as completed in the minibuffer
9375 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9376 option `org-link-file-path-type'.
9378 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9379 the current directory or below.
9381 With three \\[universal-argument] prefixes, negate the meaning of
9382 `org-keep-stored-link-after-insertion'.
9384 If `org-make-link-description-function' is non-nil, this function will be
9385 called with the link target, and the result will be the default
9386 link description.
9388 If the LINK-LOCATION parameter is non-nil, this value will be
9389 used as the link location instead of reading one interactively.
9391 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9392 be used as the default description."
9393 (interactive "P")
9394 (let* ((wcf (current-window-configuration))
9395 (origbuf (current-buffer))
9396 (region (if (org-region-active-p)
9397 (buffer-substring (region-beginning) (region-end))))
9398 (remove (and region (list (region-beginning) (region-end))))
9399 (desc region)
9400 tmphist ; byte-compile incorrectly complains about this
9401 (link link-location)
9402 (abbrevs org-link-abbrev-alist-local)
9403 entry file all-prefixes auto-desc)
9404 (cond
9405 (link-location) ; specified by arg, just use it.
9406 ((org-in-regexp org-bracket-link-regexp 1)
9407 ;; We do have a link at point, and we are going to edit it.
9408 (setq remove (list (match-beginning 0) (match-end 0)))
9409 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9410 (setq link (read-string "Link: "
9411 (org-link-unescape
9412 (org-match-string-no-properties 1)))))
9413 ((or (org-in-regexp org-angle-link-re)
9414 (org-in-regexp org-plain-link-re))
9415 ;; Convert to bracket link
9416 (setq remove (list (match-beginning 0) (match-end 0))
9417 link (read-string "Link: "
9418 (org-remove-angle-brackets (match-string 0)))))
9419 ((member complete-file '((4) (16)))
9420 ;; Completing read for file names.
9421 (setq link (org-file-complete-link complete-file)))
9423 ;; Read link, with completion for stored links.
9424 (org-link-fontify-links-to-this-file)
9425 (org-switch-to-buffer-other-window "*Org Links*")
9426 (with-current-buffer "*Org Links*"
9427 (erase-buffer)
9428 (insert "Insert a link.
9429 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9430 (when org-stored-links
9431 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9432 (insert (mapconcat 'org-link-prettify
9433 (reverse org-stored-links) "\n")))
9434 (goto-char (point-min)))
9435 (let ((cw (selected-window)))
9436 (select-window (get-buffer-window "*Org Links*" 'visible))
9437 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9438 (unless (pos-visible-in-window-p (point-max))
9439 (org-fit-window-to-buffer))
9440 (and (window-live-p cw) (select-window cw)))
9441 ;; Fake a link history, containing the stored links.
9442 (setq tmphist (append (mapcar 'car org-stored-links)
9443 org-insert-link-history))
9444 (setq all-prefixes (append (mapcar 'car abbrevs)
9445 (mapcar 'car org-link-abbrev-alist)
9446 org-link-types))
9447 (unwind-protect
9448 (progn
9449 (setq link
9450 (let ((org-completion-use-ido nil)
9451 (org-completion-use-iswitchb nil))
9452 (org-completing-read
9453 "Link: "
9454 (append
9455 (mapcar (lambda (x) (list (concat x ":")))
9456 all-prefixes)
9457 (mapcar 'car org-stored-links)
9458 (mapcar 'cadr org-stored-links))
9459 nil nil nil
9460 'tmphist
9461 (caar org-stored-links))))
9462 (if (not (string-match "\\S-" link))
9463 (error "No link selected"))
9464 (mapc (lambda(l)
9465 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9466 org-stored-links)
9467 (if (or (member link all-prefixes)
9468 (and (equal ":" (substring link -1))
9469 (member (substring link 0 -1) all-prefixes)
9470 (setq link (substring link 0 -1))))
9471 (setq link (with-current-buffer origbuf
9472 (org-link-try-special-completion link)))))
9473 (set-window-configuration wcf)
9474 (kill-buffer "*Org Links*"))
9475 (setq entry (assoc link org-stored-links))
9476 (or entry (push link org-insert-link-history))
9477 (setq desc (or desc (nth 1 entry)))))
9479 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9480 (not org-keep-stored-link-after-insertion))
9481 (setq org-stored-links (delq (assoc link org-stored-links)
9482 org-stored-links)))
9484 (if (string-match org-plain-link-re link)
9485 ;; URL-like link, normalize the use of angular brackets.
9486 (setq link (org-remove-angle-brackets link)))
9488 ;; Check if we are linking to the current file with a search option
9489 ;; If yes, simplify the link by using only the search option.
9490 (when (and buffer-file-name
9491 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9492 (let* ((path (match-string 1 link))
9493 (case-fold-search nil)
9494 (search (match-string 2 link)))
9495 (save-match-data
9496 (if (equal (file-truename buffer-file-name) (file-truename path))
9497 ;; We are linking to this same file, with a search option
9498 (setq link search)))))
9500 ;; Check if we can/should use a relative path. If yes, simplify the link
9501 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9502 (let* ((type (match-string 1 link))
9503 (path (match-string 2 link))
9504 (origpath path)
9505 (case-fold-search nil))
9506 (cond
9507 ((or (eq org-link-file-path-type 'absolute)
9508 (equal complete-file '(16)))
9509 (setq path (abbreviate-file-name (expand-file-name path))))
9510 ((eq org-link-file-path-type 'noabbrev)
9511 (setq path (expand-file-name path)))
9512 ((eq org-link-file-path-type 'relative)
9513 (setq path (file-relative-name path)))
9515 (save-match-data
9516 (if (string-match (concat "^" (regexp-quote
9517 (expand-file-name
9518 (file-name-as-directory
9519 default-directory))))
9520 (expand-file-name path))
9521 ;; We are linking a file with relative path name.
9522 (setq path (substring (expand-file-name path)
9523 (match-end 0)))
9524 (setq path (abbreviate-file-name (expand-file-name path)))))))
9525 (setq link (concat type path))
9526 (if (equal desc origpath)
9527 (setq desc path))))
9529 (if org-make-link-description-function
9530 (setq desc
9531 (or (condition-case nil
9532 (funcall org-make-link-description-function link desc)
9533 (error (progn (message "Can't get link description from `%s'"
9534 (symbol-name org-make-link-description-function))
9535 (sit-for 2) nil)))
9536 (read-string "Description: " default-description)))
9537 (if default-description (setq desc default-description)
9538 (setq desc (or (and auto-desc desc)
9539 (read-string "Description: " desc)))))
9541 (unless (string-match "\\S-" desc) (setq desc nil))
9542 (if remove (apply 'delete-region remove))
9543 (insert (org-make-link-string link desc))))
9545 (defun org-link-try-special-completion (type)
9546 "If there is completion support for link type TYPE, offer it."
9547 (let ((fun (intern (concat "org-" type "-complete-link"))))
9548 (if (functionp fun)
9549 (funcall fun)
9550 (read-string "Link (no completion support): " (concat type ":")))))
9552 (defun org-file-complete-link (&optional arg)
9553 "Create a file link using completion."
9554 (let (file link)
9555 (setq file (read-file-name "File: "))
9556 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9557 (pwd1 (file-name-as-directory (abbreviate-file-name
9558 (expand-file-name ".")))))
9559 (cond
9560 ((equal arg '(16))
9561 (setq link (concat
9562 "file:"
9563 (abbreviate-file-name (expand-file-name file)))))
9564 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9565 (setq link (concat "file:" (match-string 1 file))))
9566 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9567 (expand-file-name file))
9568 (setq link (concat
9569 "file:" (match-string 1 (expand-file-name file)))))
9570 (t (setq link (concat "file:" file)))))
9571 link))
9573 (defun org-completing-read (&rest args)
9574 "Completing-read with SPACE being a normal character."
9575 (let ((enable-recursive-minibuffers t)
9576 (minibuffer-local-completion-map
9577 (copy-keymap minibuffer-local-completion-map)))
9578 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9579 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9580 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9581 (apply 'org-icompleting-read args)))
9583 (defun org-completing-read-no-i (&rest args)
9584 (let (org-completion-use-ido org-completion-use-iswitchb)
9585 (apply 'org-completing-read args)))
9587 (defun org-iswitchb-completing-read (prompt choices &rest args)
9588 "Use iswitch as a completing-read replacement to choose from choices.
9589 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9590 from."
9591 (let* ((iswitchb-use-virtual-buffers nil)
9592 (iswitchb-make-buflist-hook
9593 (lambda ()
9594 (setq iswitchb-temp-buflist choices))))
9595 (iswitchb-read-buffer prompt)))
9597 (defun org-icompleting-read (&rest args)
9598 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9599 (org-without-partial-completion
9600 (if (and org-completion-use-ido
9601 (fboundp 'ido-completing-read)
9602 (boundp 'ido-mode) ido-mode
9603 (listp (second args)))
9604 (let ((ido-enter-matching-directory nil))
9605 (apply 'ido-completing-read (concat (car args))
9606 (if (consp (car (nth 1 args)))
9607 (mapcar 'car (nth 1 args))
9608 (nth 1 args))
9609 (cddr args)))
9610 (if (and org-completion-use-iswitchb
9611 (boundp 'iswitchb-mode) iswitchb-mode
9612 (listp (second args)))
9613 (apply 'org-iswitchb-completing-read (concat (car args))
9614 (if (consp (car (nth 1 args)))
9615 (mapcar 'car (nth 1 args))
9616 (nth 1 args))
9617 (cddr args))
9618 (apply 'completing-read args)))))
9620 (defun org-extract-attributes (s)
9621 "Extract the attributes cookie from a string and set as text property."
9622 (let (a attr (start 0) key value)
9623 (save-match-data
9624 (when (string-match "{{\\([^}]+\\)}}$" s)
9625 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9626 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9627 (setq key (match-string 1 a) value (match-string 2 a)
9628 start (match-end 0)
9629 attr (plist-put attr (intern key) value))))
9630 (org-add-props s nil 'org-attr attr))
9633 (defun org-extract-attributes-from-string (tag)
9634 (let (key value attr)
9635 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9636 (setq key (match-string 1 tag) value (match-string 2 tag)
9637 tag (replace-match "" t t tag)
9638 attr (plist-put attr (intern key) value)))
9639 (cons tag attr)))
9641 (defun org-attributes-to-string (plist)
9642 "Format a property list into an HTML attribute list."
9643 (let ((s "") key value)
9644 (while plist
9645 (setq key (pop plist) value (pop plist))
9646 (and value
9647 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9650 ;;; Opening/following a link
9652 (defvar org-link-search-failed nil)
9654 (defvar org-open-link-functions nil
9655 "Hook for functions finding a plain text link.
9656 These functions must take a single argument, the link content.
9657 They will be called for links that look like [[link text][description]]
9658 when LINK TEXT does not have a protocol like \"http:\" and does not look
9659 like a filename (e.g. \"./blue.png\").
9661 These functions will be called *before* Org attempts to resolve the
9662 link by doing text searches in the current buffer - so if you want a
9663 link \"[[target]]\" to still find \"<<target>>\", your function should
9664 handle this as a special case.
9666 When the function does handle the link, it must return a non-nil value.
9667 If it decides that it is not responsible for this link, it must return
9668 nil to indicate that that Org-mode can continue with other options
9669 like exact and fuzzy text search.")
9671 (defun org-next-link ()
9672 "Move forward to the next link.
9673 If the link is in hidden text, expose it."
9674 (interactive)
9675 (when (and org-link-search-failed (eq this-command last-command))
9676 (goto-char (point-min))
9677 (message "Link search wrapped back to beginning of buffer"))
9678 (setq org-link-search-failed nil)
9679 (let* ((pos (point))
9680 (ct (org-context))
9681 (a (assoc :link ct)))
9682 (if a (goto-char (nth 2 a)))
9683 (if (re-search-forward org-any-link-re nil t)
9684 (progn
9685 (goto-char (match-beginning 0))
9686 (if (outline-invisible-p) (org-show-context)))
9687 (goto-char pos)
9688 (setq org-link-search-failed t)
9689 (error "No further link found"))))
9691 (defun org-previous-link ()
9692 "Move backward to the previous link.
9693 If the link is in hidden text, expose it."
9694 (interactive)
9695 (when (and org-link-search-failed (eq this-command last-command))
9696 (goto-char (point-max))
9697 (message "Link search wrapped back to end of buffer"))
9698 (setq org-link-search-failed nil)
9699 (let* ((pos (point))
9700 (ct (org-context))
9701 (a (assoc :link ct)))
9702 (if a (goto-char (nth 1 a)))
9703 (if (re-search-backward org-any-link-re nil t)
9704 (progn
9705 (goto-char (match-beginning 0))
9706 (if (outline-invisible-p) (org-show-context)))
9707 (goto-char pos)
9708 (setq org-link-search-failed t)
9709 (error "No further link found"))))
9711 (defun org-translate-link (s)
9712 "Translate a link string if a translation function has been defined."
9713 (if (and org-link-translation-function
9714 (fboundp org-link-translation-function)
9715 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9716 (progn
9717 (setq s (funcall org-link-translation-function
9718 (match-string 1 s) (match-string 2 s)))
9719 (concat (car s) ":" (cdr s)))
9722 (defun org-translate-link-from-planner (type path)
9723 "Translate a link from Emacs Planner syntax so that Org can follow it.
9724 This is still an experimental function, your mileage may vary."
9725 (cond
9726 ((member type '("http" "https" "news" "ftp"))
9727 ;; standard Internet links are the same.
9728 nil)
9729 ((and (equal type "irc") (string-match "^//" path))
9730 ;; Planner has two / at the beginning of an irc link, we have 1.
9731 ;; We should have zero, actually....
9732 (setq path (substring path 1)))
9733 ((and (equal type "lisp") (string-match "^/" path))
9734 ;; Planner has a slash, we do not.
9735 (setq type "elisp" path (substring path 1)))
9736 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9737 ;; A typical message link. Planner has the id after the final slash,
9738 ;; we separate it with a hash mark
9739 (setq path (concat (match-string 1 path) "#"
9740 (org-remove-angle-brackets (match-string 2 path)))))
9742 (cons type path))
9744 (defun org-find-file-at-mouse (ev)
9745 "Open file link or URL at mouse."
9746 (interactive "e")
9747 (mouse-set-point ev)
9748 (org-open-at-point 'in-emacs))
9750 (defun org-open-at-mouse (ev)
9751 "Open file link or URL at mouse.
9752 See the docstring of `org-open-file' for details."
9753 (interactive "e")
9754 (mouse-set-point ev)
9755 (if (eq major-mode 'org-agenda-mode)
9756 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9757 (org-open-at-point))
9759 (defvar org-window-config-before-follow-link nil
9760 "The window configuration before following a link.
9761 This is saved in case the need arises to restore it.")
9763 (defvar org-open-link-marker (make-marker)
9764 "Marker pointing to the location where `org-open-at-point; was called.")
9766 ;;;###autoload
9767 (defun org-open-at-point-global ()
9768 "Follow a link like Org-mode does.
9769 This command can be called in any mode to follow a link that has
9770 Org-mode syntax."
9771 (interactive)
9772 (org-run-like-in-org-mode 'org-open-at-point))
9774 ;;;###autoload
9775 (defun org-open-link-from-string (s &optional arg reference-buffer)
9776 "Open a link in the string S, as if it was in Org-mode."
9777 (interactive "sLink: \nP")
9778 (let ((reference-buffer (or reference-buffer (current-buffer))))
9779 (with-temp-buffer
9780 (let ((org-inhibit-startup (not reference-buffer)))
9781 (org-mode)
9782 (insert s)
9783 (goto-char (point-min))
9784 (when reference-buffer
9785 (setq org-link-abbrev-alist-local
9786 (with-current-buffer reference-buffer
9787 org-link-abbrev-alist-local)))
9788 (org-open-at-point arg reference-buffer)))))
9790 (defvar org-open-at-point-functions nil
9791 "Hook that is run when following a link at point.
9793 Functions in this hook must return t if they identify and follow
9794 a link at point. If they don't find anything interesting at point,
9795 they must return nil.")
9797 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9798 (defun org-open-at-point (&optional arg reference-buffer)
9799 "Open link at or after point.
9800 If there is no link at point, this function will search forward up to
9801 the end of the current line.
9802 Normally, files will be opened by an appropriate application. If the
9803 optional prefix argument ARG is non-nil, Emacs will visit the file.
9804 With a double prefix argument, try to open outside of Emacs, in the
9805 application the system uses for this file type."
9806 (interactive "P")
9807 ;; if in a code block, then open the block's results
9808 (unless (call-interactively #'org-babel-open-src-block-result)
9809 (org-load-modules-maybe)
9810 (move-marker org-open-link-marker (point))
9811 (setq org-window-config-before-follow-link (current-window-configuration))
9812 (org-remove-occur-highlights nil nil t)
9813 (cond
9814 ((and (org-at-heading-p)
9815 (not (org-at-timestamp-p t))
9816 (not (org-in-regexp
9817 (concat org-plain-link-re "\\|"
9818 org-bracket-link-regexp "\\|"
9819 org-angle-link-re "\\|"
9820 "[ \t]:[^ \t\n]+:[ \t]*$")))
9821 (not (get-text-property (point) 'org-linked-text)))
9822 (or (org-offer-links-in-entry arg)
9823 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9824 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9825 ((and (org-at-timestamp-p t)
9826 (not (org-in-regexp org-bracket-link-regexp)))
9827 (org-follow-timestamp-link))
9828 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9829 (not (org-in-regexp org-bracket-link-regexp)))
9830 (org-footnote-action))
9832 (let (type path link line search (pos (point)))
9833 (catch 'match
9834 (save-excursion
9835 (skip-chars-forward "^]\n\r")
9836 (when (org-in-regexp org-bracket-link-regexp 1)
9837 (setq link (org-extract-attributes
9838 (org-link-unescape (org-match-string-no-properties 1))))
9839 (while (string-match " *\n *" link)
9840 (setq link (replace-match " " t t link)))
9841 (setq link (org-link-expand-abbrev link))
9842 (cond
9843 ((or (file-name-absolute-p link)
9844 (string-match "^\\.\\.?/" link))
9845 (setq type "file" path link))
9846 ((string-match org-link-re-with-space3 link)
9847 (setq type (match-string 1 link) path (match-string 2 link)))
9848 ((string-match "^help:+\\(.+\\)" link)
9849 (setq type "help" path (match-string 1 link)))
9850 (t (setq type "thisfile" path link)))
9851 (throw 'match t)))
9853 (when (get-text-property (point) 'org-linked-text)
9854 (setq type "thisfile"
9855 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9856 (1+ (point)) (point))
9857 path (buffer-substring
9858 (or (previous-single-property-change pos 'org-linked-text)
9859 (point-min))
9860 (or (next-single-property-change pos 'org-linked-text)
9861 (point-max))))
9862 (throw 'match t))
9864 (save-excursion
9865 (when (or (org-in-regexp org-angle-link-re)
9866 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9867 (save-match-data (not (looking-back "\\[\\[")))))
9868 (setq type (match-string 1)
9869 path (org-link-unescape (match-string 2)))
9870 (throw 'match t)))
9871 (save-excursion
9872 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9873 (setq type "tags"
9874 path (match-string 1))
9875 (while (string-match ":" path)
9876 (setq path (replace-match "+" t t path)))
9877 (throw 'match t)))
9878 (when (org-in-regexp "<\\([^><\n]+\\)>")
9879 (setq type "tree-match"
9880 path (match-string 1))
9881 (throw 'match t)))
9882 (unless path
9883 (error "No link found"))
9885 ;; switch back to reference buffer
9886 ;; needed when if called in a temporary buffer through
9887 ;; org-open-link-from-string
9888 (with-current-buffer (or reference-buffer (current-buffer))
9890 ;; Remove any trailing spaces in path
9891 (if (string-match " +\\'" path)
9892 (setq path (replace-match "" t t path)))
9893 (if (and org-link-translation-function
9894 (fboundp org-link-translation-function))
9895 ;; Check if we need to translate the link
9896 (let ((tmp (funcall org-link-translation-function type path)))
9897 (setq type (car tmp) path (cdr tmp))))
9899 (cond
9901 ((assoc type org-link-protocols)
9902 (funcall (nth 1 (assoc type org-link-protocols)) path))
9904 ((equal type "help")
9905 (let ((f-or-v (intern path)))
9906 (cond ((fboundp f-or-v)
9907 (describe-function f-or-v))
9908 ((boundp f-or-v)
9909 (describe-variable f-or-v))
9910 (t (error "Not a known function or variable")))))
9912 ((equal type "mailto")
9913 (let ((cmd (car org-link-mailto-program))
9914 (args (cdr org-link-mailto-program)) args1
9915 (address path) (subject "") a)
9916 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9917 (setq address (match-string 1 path)
9918 subject (org-link-escape (match-string 2 path))))
9919 (while args
9920 (cond
9921 ((not (stringp (car args))) (push (pop args) args1))
9922 (t (setq a (pop args))
9923 (if (string-match "%a" a)
9924 (setq a (replace-match address t t a)))
9925 (if (string-match "%s" a)
9926 (setq a (replace-match subject t t a)))
9927 (push a args1))))
9928 (apply cmd (nreverse args1))))
9930 ((member type '("http" "https" "ftp" "news"))
9931 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9932 (org-link-escape
9933 path org-link-escape-chars-browser)
9934 path))))
9936 ((string= type "doi")
9937 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9938 (org-link-escape
9939 path org-link-escape-chars-browser)
9940 path))))
9942 ((member type '("message"))
9943 (browse-url (concat type ":" path)))
9945 ((string= type "tags")
9946 (org-tags-view arg path))
9948 ((string= type "tree-match")
9949 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9951 ((string= type "file")
9952 (if (string-match "::\\([0-9]+\\)\\'" path)
9953 (setq line (string-to-number (match-string 1 path))
9954 path (substring path 0 (match-beginning 0)))
9955 (if (string-match "::\\(.+\\)\\'" path)
9956 (setq search (match-string 1 path)
9957 path (substring path 0 (match-beginning 0)))))
9958 (if (string-match "[*?{]" (file-name-nondirectory path))
9959 (dired path)
9960 (org-open-file path arg line search)))
9962 ((string= type "shell")
9963 (let ((buf (generate-new-buffer "*Org Shell Output"))
9964 (cmd path))
9965 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9966 (string-match org-confirm-shell-link-not-regexp cmd))
9967 (not org-confirm-shell-link-function)
9968 (funcall org-confirm-shell-link-function
9969 (format "Execute \"%s\" in shell? "
9970 (org-add-props cmd nil
9971 'face 'org-warning))))
9972 (progn
9973 (message "Executing %s" cmd)
9974 (shell-command cmd buf)
9975 (if (featurep 'midnight)
9976 (setq clean-buffer-list-kill-buffer-names
9977 (cons buf clean-buffer-list-kill-buffer-names))))
9978 (error "Abort"))))
9980 ((string= type "elisp")
9981 (let ((cmd path))
9982 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9983 (string-match org-confirm-elisp-link-not-regexp cmd))
9984 (not org-confirm-elisp-link-function)
9985 (funcall org-confirm-elisp-link-function
9986 (format "Execute \"%s\" as elisp? "
9987 (org-add-props cmd nil
9988 'face 'org-warning))))
9989 (message "%s => %s" cmd
9990 (if (equal (string-to-char cmd) ?\()
9991 (eval (read cmd))
9992 (call-interactively (read cmd))))
9993 (error "Abort"))))
9995 ((and (string= type "thisfile")
9996 (run-hook-with-args-until-success
9997 'org-open-link-functions path)))
9999 ((string= type "thisfile")
10000 (if arg
10001 (switch-to-buffer-other-window
10002 (org-get-buffer-for-internal-link (current-buffer)))
10003 (org-mark-ring-push))
10004 (let ((cmd `(org-link-search
10005 ,path
10006 ,(cond ((equal arg '(4)) ''occur)
10007 ((equal arg '(16)) ''org-occur))
10008 ,pos)))
10009 (condition-case nil (let ((org-link-search-inhibit-query t))
10010 (eval cmd))
10011 (error (progn (widen) (eval cmd))))))
10013 (t (browse-url-at-point)))))))
10014 (move-marker org-open-link-marker nil)
10015 (run-hook-with-args 'org-follow-link-hook)))
10017 (defun org-offer-links-in-entry (&optional nth zero)
10018 "Offer links in the current entry and follow the selected link.
10019 If there is only one link, follow it immediately as well.
10020 If NTH is an integer, immediately pick the NTH link found.
10021 If ZERO is a string, check also this string for a link, and if
10022 there is one, offer it as link number zero."
10023 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10024 "\\(" org-angle-link-re "\\)\\|"
10025 "\\(" org-plain-link-re "\\)"))
10026 (cnt ?0)
10027 (in-emacs (if (integerp nth) nil nth))
10028 have-zero end links link c)
10029 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10030 (push (match-string 0 zero) links)
10031 (setq cnt (1- cnt) have-zero t))
10032 (save-excursion
10033 (org-back-to-heading t)
10034 (setq end (save-excursion (outline-next-heading) (point)))
10035 (while (re-search-forward re end t)
10036 (push (match-string 0) links))
10037 (setq links (org-uniquify (reverse links))))
10039 (cond
10040 ((null links)
10041 (message "No links"))
10042 ((equal (length links) 1)
10043 (setq link (list (car links))))
10044 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10045 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10046 (t ; we have to select a link
10047 (save-excursion
10048 (save-window-excursion
10049 (delete-other-windows)
10050 (with-output-to-temp-buffer "*Select Link*"
10051 (mapc (lambda (l)
10052 (if (not (string-match org-bracket-link-regexp l))
10053 (princ (format "[%c] %s\n" (incf cnt)
10054 (org-remove-angle-brackets l)))
10055 (if (match-end 3)
10056 (princ (format "[%c] %s (%s)\n" (incf cnt)
10057 (match-string 3 l) (match-string 1 l)))
10058 (princ (format "[%c] %s\n" (incf cnt)
10059 (match-string 1 l))))))
10060 links))
10061 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10062 (message "Select link to open, RET to open all:")
10063 (setq c (read-char-exclusive))
10064 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10065 (when (equal c ?q) (error "Abort"))
10066 (if (equal c ?\C-m)
10067 (setq link links)
10068 (setq nth (- c ?0))
10069 (if have-zero (setq nth (1+ nth)))
10070 (unless (and (integerp nth) (>= (length links) nth))
10071 (error "Invalid link selection"))
10072 (setq link (list (nth (1- nth) links))))))
10073 (if link
10074 (let ((buf (current-buffer)))
10075 (dolist (l link)
10076 (org-open-link-from-string l in-emacs buf))
10078 nil)))
10080 ;; Add special file links that specify the way of opening
10082 (org-add-link-type "file+sys" 'org-open-file-with-system)
10083 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10084 (defun org-open-file-with-system (path)
10085 "Open file at PATH using the system way of opening it."
10086 (org-open-file path 'system))
10087 (defun org-open-file-with-emacs (path)
10088 "Open file at PATH in Emacs."
10089 (org-open-file path 'emacs))
10090 (defun org-remove-file-link-modifiers ()
10091 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10092 (goto-char (point-min))
10093 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10094 (org-if-unprotected
10095 (replace-match "file:" t t))))
10096 (eval-after-load "org-exp"
10097 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10098 'org-remove-file-link-modifiers))
10100 ;;;; Time estimates
10102 (defun org-get-effort (&optional pom)
10103 "Get the effort estimate for the current entry."
10104 (org-entry-get pom org-effort-property))
10106 ;;; File search
10108 (defvar org-create-file-search-functions nil
10109 "List of functions to construct the right search string for a file link.
10110 These functions are called in turn with point at the location to
10111 which the link should point.
10113 A function in the hook should first test if it would like to
10114 handle this file type, for example by checking the `major-mode'
10115 or the file extension. If it decides not to handle this file, it
10116 should just return nil to give other functions a chance. If it
10117 does handle the file, it must return the search string to be used
10118 when following the link. The search string will be part of the
10119 file link, given after a double colon, and `org-open-at-point'
10120 will automatically search for it. If special measures must be
10121 taken to make the search successful, another function should be
10122 added to the companion hook `org-execute-file-search-functions',
10123 which see.
10125 A function in this hook may also use `setq' to set the variable
10126 `description' to provide a suggestion for the descriptive text to
10127 be used for this link when it gets inserted into an Org-mode
10128 buffer with \\[org-insert-link].")
10130 (defvar org-execute-file-search-functions nil
10131 "List of functions to execute a file search triggered by a link.
10133 Functions added to this hook must accept a single argument, the
10134 search string that was part of the file link, the part after the
10135 double colon. The function must first check if it would like to
10136 handle this search, for example by checking the `major-mode' or
10137 the file extension. If it decides not to handle this search, it
10138 should just return nil to give other functions a chance. If it
10139 does handle the search, it must return a non-nil value to keep
10140 other functions from trying.
10142 Each function can access the current prefix argument through the
10143 variable `current-prefix-argument'. Note that a single prefix is
10144 used to force opening a link in Emacs, so it may be good to only
10145 use a numeric or double prefix to guide the search function.
10147 In case this is needed, a function in this hook can also restore
10148 the window configuration before `org-open-at-point' was called using:
10150 (set-window-configuration org-window-config-before-follow-link)")
10152 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10153 (defun org-link-search (s &optional type avoid-pos stealth)
10154 "Search for a link search option.
10155 If S is surrounded by forward slashes, it is interpreted as a
10156 regular expression. In org-mode files, this will create an `org-occur'
10157 sparse tree. In ordinary files, `occur' will be used to list matches.
10158 If the current buffer is in `dired-mode', grep will be used to search
10159 in all files. If AVOID-POS is given, ignore matches near that position.
10161 When optional argument STEALTH is non-nil, do not modify
10162 visibility around point, thus ignoring
10163 `org-show-hierarchy-above', `org-show-following-heading' and
10164 `org-show-siblings' variables."
10165 (let ((case-fold-search t)
10166 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10167 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10168 (append '(("") (" ") ("\t") ("\n"))
10169 org-emphasis-alist)
10170 "\\|") "\\)"))
10171 (pos (point))
10172 (pre nil) (post nil)
10173 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10174 (cond
10175 ;; First check if there are any special search functions
10176 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10177 ;; Now try the builtin stuff
10178 ((and (equal (string-to-char s0) ?#)
10179 (> (length s0) 1)
10180 (save-excursion
10181 (goto-char (point-min))
10182 (and
10183 (re-search-forward
10184 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10185 (setq type 'dedicated
10186 pos (match-beginning 0))))
10187 ;; There is an exact target for this
10188 (goto-char pos)
10189 (org-back-to-heading t)))
10190 ((save-excursion
10191 (goto-char (point-min))
10192 (and
10193 (re-search-forward
10194 (concat "<<" (regexp-quote s0) ">>") nil t)
10195 (setq type 'dedicated
10196 pos (match-beginning 0))))
10197 ;; There is an exact target for this
10198 (goto-char pos))
10199 ((save-excursion
10200 (goto-char (point-min))
10201 (and
10202 (re-search-forward
10203 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10204 (setq type 'dedicated pos (match-beginning 0))))
10205 ;; Found an invisible target.
10206 (goto-char pos))
10207 ((save-excursion
10208 (goto-char (point-min))
10209 (and
10210 (re-search-forward
10211 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10212 (setq type 'dedicated pos (match-beginning 0))))
10213 ;; Found an element with a matching #+name affiliated keyword.
10214 (goto-char pos))
10215 ((and (string-match "^(\\(.*\\))$" s0)
10216 (save-excursion
10217 (goto-char (point-min))
10218 (and
10219 (re-search-forward
10220 (concat "[^[]" (regexp-quote
10221 (format org-coderef-label-format
10222 (match-string 1 s0))))
10223 nil t)
10224 (setq type 'dedicated
10225 pos (1+ (match-beginning 0))))))
10226 ;; There is a coderef target for this
10227 (goto-char pos))
10228 ((string-match "^/\\(.*\\)/$" s)
10229 ;; A regular expression
10230 (cond
10231 ((derived-mode-p 'org-mode)
10232 (org-occur (match-string 1 s)))
10233 ;;((eq major-mode 'dired-mode)
10234 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10235 (t (org-do-occur (match-string 1 s)))))
10236 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10237 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10238 (goto-char (point-min))
10239 (cond
10240 ((let (case-fold-search)
10241 (re-search-forward (format org-complex-heading-regexp-format
10242 (regexp-quote s))
10243 nil t))
10244 ;; OK, found a match
10245 (setq type 'dedicated)
10246 (goto-char (match-beginning 0)))
10247 ((and (not org-link-search-inhibit-query)
10248 (eq org-link-search-must-match-exact-headline 'query-to-create)
10249 (y-or-n-p "No match - create this as a new heading? "))
10250 (goto-char (point-max))
10251 (or (bolp) (newline))
10252 (insert "* " s "\n")
10253 (beginning-of-line 0))
10255 (goto-char pos)
10256 (error "No match"))))
10258 ;; A normal search string
10259 (when (equal (string-to-char s) ?*)
10260 ;; Anchor on headlines, post may include tags.
10261 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10262 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10263 s (substring s 1)))
10264 (remove-text-properties
10265 0 (length s)
10266 '(face nil mouse-face nil keymap nil fontified nil) s)
10267 ;; Make a series of regular expressions to find a match
10268 (setq words (org-split-string s "[ \n\r\t]+")
10270 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10271 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10272 "\\)" markers)
10273 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10274 re2a (concat "[ \t\r\n]" re2a_)
10275 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10276 re4 (concat "[^a-zA-Z_]" re4_)
10278 re1 (concat pre re2 post)
10279 re3 (concat pre (if pre re4_ re4) post)
10280 re5 (concat pre ".*" re4)
10281 re2 (concat pre re2)
10282 re2a (concat pre (if pre re2a_ re2a))
10283 re4 (concat pre (if pre re4_ re4))
10284 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10285 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10286 re5 "\\)"
10288 (cond
10289 ((eq type 'org-occur) (org-occur reall))
10290 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10291 (t (goto-char (point-min))
10292 (setq type 'fuzzy)
10293 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10294 (org-search-not-self 1 re1 nil t)
10295 (org-search-not-self 1 re2 nil t)
10296 (org-search-not-self 1 re2a nil t)
10297 (org-search-not-self 1 re3 nil t)
10298 (org-search-not-self 1 re4 nil t)
10299 (org-search-not-self 1 re5 nil t)
10301 (goto-char (match-beginning 1))
10302 (goto-char pos)
10303 (error "No match"))))))
10304 (and (derived-mode-p 'org-mode)
10305 (not stealth)
10306 (org-show-context 'link-search))
10307 type))
10309 (defun org-search-not-self (group &rest args)
10310 "Execute `re-search-forward', but only accept matches that do not
10311 enclose the position of `org-open-link-marker'."
10312 (let ((m org-open-link-marker))
10313 (catch 'exit
10314 (while (apply 're-search-forward args)
10315 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10316 (goto-char (match-end group))
10317 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10318 (> (match-beginning 0) (marker-position m))
10319 (< (match-end 0) (marker-position m)))
10320 (save-match-data
10321 (or (not (org-in-regexp
10322 org-bracket-link-analytic-regexp 1))
10323 (not (match-end 4)) ; no description
10324 (and (<= (match-beginning 4) (point))
10325 (>= (match-end 4) (point))))))
10326 (throw 'exit (point))))))))
10328 (defun org-get-buffer-for-internal-link (buffer)
10329 "Return a buffer to be used for displaying the link target of internal links."
10330 (cond
10331 ((not org-display-internal-link-with-indirect-buffer)
10332 buffer)
10333 ((string-match "(Clone)$" (buffer-name buffer))
10334 (message "Buffer is already a clone, not making another one")
10335 ;; we also do not modify visibility in this case
10336 buffer)
10337 (t ; make a new indirect buffer for displaying the link
10338 (let* ((bn (buffer-name buffer))
10339 (ibn (concat bn "(Clone)"))
10340 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10341 (with-current-buffer ib (org-overview))
10342 ib))))
10344 (defun org-do-occur (regexp &optional cleanup)
10345 "Call the Emacs command `occur'.
10346 If CLEANUP is non-nil, remove the printout of the regular expression
10347 in the *Occur* buffer. This is useful if the regex is long and not useful
10348 to read."
10349 (occur regexp)
10350 (when cleanup
10351 (let ((cwin (selected-window)) win beg end)
10352 (when (setq win (get-buffer-window "*Occur*"))
10353 (select-window win))
10354 (goto-char (point-min))
10355 (when (re-search-forward "match[a-z]+" nil t)
10356 (setq beg (match-end 0))
10357 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10358 (setq end (1- (match-beginning 0)))))
10359 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10360 (goto-char (point-min))
10361 (select-window cwin))))
10363 ;;; The mark ring for links jumps
10365 (defvar org-mark-ring nil
10366 "Mark ring for positions before jumps in Org-mode.")
10367 (defvar org-mark-ring-last-goto nil
10368 "Last position in the mark ring used to go back.")
10369 ;; Fill and close the ring
10370 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10371 (loop for i from 1 to org-mark-ring-length do
10372 (push (make-marker) org-mark-ring))
10373 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10374 org-mark-ring)
10376 (defun org-mark-ring-push (&optional pos buffer)
10377 "Put the current position or POS into the mark ring and rotate it."
10378 (interactive)
10379 (setq pos (or pos (point)))
10380 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10381 (move-marker (car org-mark-ring)
10382 (or pos (point))
10383 (or buffer (current-buffer)))
10384 (message "%s"
10385 (substitute-command-keys
10386 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10388 (defun org-mark-ring-goto (&optional n)
10389 "Jump to the previous position in the mark ring.
10390 With prefix arg N, jump back that many stored positions. When
10391 called several times in succession, walk through the entire ring.
10392 Org-mode commands jumping to a different position in the current file,
10393 or to another Org-mode file, automatically push the old position
10394 onto the ring."
10395 (interactive "p")
10396 (let (p m)
10397 (if (eq last-command this-command)
10398 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10399 (setq p org-mark-ring))
10400 (setq org-mark-ring-last-goto p)
10401 (setq m (car p))
10402 (org-pop-to-buffer-same-window (marker-buffer m))
10403 (goto-char m)
10404 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10406 (defun org-remove-angle-brackets (s)
10407 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10408 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10410 (defun org-add-angle-brackets (s)
10411 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10412 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10414 (defun org-remove-double-quotes (s)
10415 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10416 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10419 ;;; Following specific links
10421 (defun org-follow-timestamp-link ()
10422 "Open an agenda view for the time-stamp date/range at point."
10423 (cond
10424 ((org-at-date-range-p t)
10425 (let ((org-agenda-start-on-weekday)
10426 (t1 (match-string 1))
10427 (t2 (match-string 2)) tt1 tt2)
10428 (setq tt1 (time-to-days (org-time-string-to-time t1))
10429 tt2 (time-to-days (org-time-string-to-time t2)))
10430 (let ((org-agenda-buffer-tmp-name
10431 (format "*Org Agenda(a:%s)"
10432 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10433 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10434 ((org-at-timestamp-p t)
10435 (let ((org-agenda-buffer-tmp-name
10436 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10437 (org-agenda-list nil (time-to-days (org-time-string-to-time
10438 (substring (match-string 1) 0 10)))
10439 1)))
10440 (t (error "This should not happen"))))
10443 ;;; Following file links
10444 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10445 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10446 (declare-function mailcap-mime-info
10447 "mailcap" (string &optional request no-decode))
10448 (defvar org-wait nil)
10449 (defun org-open-file (path &optional in-emacs line search)
10450 "Open the file at PATH.
10451 First, this expands any special file name abbreviations. Then the
10452 configuration variable `org-file-apps' is checked if it contains an
10453 entry for this file type, and if yes, the corresponding command is launched.
10455 If no application is found, Emacs simply visits the file.
10457 With optional prefix argument IN-EMACS, Emacs will visit the file.
10458 With a double \\[universal-argument] \\[universal-argument] \
10459 prefix arg, Org tries to avoid opening in Emacs
10460 and to use an external application to visit the file.
10462 Optional LINE specifies a line to go to, optional SEARCH a string
10463 to search for. If LINE or SEARCH is given, the file will be
10464 opened in Emacs, unless an entry from org-file-apps that makes
10465 use of groups in a regexp matches.
10467 If you want to change the way frames are used when following a
10468 link, please customize `org-link-frame-setup'.
10470 If the file does not exist, an error is thrown."
10471 (let* ((file (if (equal path "")
10472 buffer-file-name
10473 (substitute-in-file-name (expand-file-name path))))
10474 (file-apps (append org-file-apps (org-default-apps)))
10475 (apps (org-remove-if
10476 'org-file-apps-entry-match-against-dlink-p file-apps))
10477 (apps-dlink (org-remove-if-not
10478 'org-file-apps-entry-match-against-dlink-p file-apps))
10479 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10480 (dirp (if remp nil (file-directory-p file)))
10481 (file (if (and dirp org-open-directory-means-index-dot-org)
10482 (concat (file-name-as-directory file) "index.org")
10483 file))
10484 (a-m-a-p (assq 'auto-mode apps))
10485 (dfile (downcase file))
10486 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10487 (link (cond ((and (eq line nil)
10488 (eq search nil))
10489 file)
10490 (line
10491 (concat file "::" (number-to-string line)))
10492 (search
10493 (concat file "::" search))))
10494 (dlink (downcase link))
10495 (old-buffer (current-buffer))
10496 (old-pos (point))
10497 (old-mode major-mode)
10498 ext cmd link-match-data)
10499 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10500 (setq ext (match-string 1 dfile))
10501 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10502 (setq ext (match-string 1 dfile))))
10503 (cond
10504 ((member in-emacs '((16) system))
10505 (setq cmd (cdr (assoc 'system apps))))
10506 (in-emacs (setq cmd 'emacs))
10508 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10509 (and dirp (cdr (assoc 'directory apps)))
10510 ; first, try matching against apps-dlink
10511 ; if we get a match here, store the match data for later
10512 (let ((match (assoc-default dlink apps-dlink
10513 'string-match)))
10514 (if match
10515 (progn (setq link-match-data (match-data))
10516 match)
10517 (progn (setq in-emacs (or in-emacs line search))
10518 nil))) ; if we have no match in apps-dlink,
10519 ; always open the file in emacs if line or search
10520 ; is given (for backwards compatibility)
10521 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10522 'string-match)
10523 (cdr (assoc ext apps))
10524 (cdr (assoc t apps))))))
10525 (when (eq cmd 'system)
10526 (setq cmd (cdr (assoc 'system apps))))
10527 (when (eq cmd 'default)
10528 (setq cmd (cdr (assoc t apps))))
10529 (when (eq cmd 'mailcap)
10530 (require 'mailcap)
10531 (mailcap-parse-mailcaps)
10532 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10533 (command (mailcap-mime-info mime-type)))
10534 (if (stringp command)
10535 (setq cmd command)
10536 (setq cmd 'emacs))))
10537 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10538 (not (file-exists-p file))
10539 (not org-open-non-existing-files))
10540 (error "No such file: %s" file))
10541 (cond
10542 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10543 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10544 (while (string-match "['\"]%s['\"]" cmd)
10545 (setq cmd (replace-match "%s" t t cmd)))
10546 (while (string-match "%s" cmd)
10547 (setq cmd (replace-match
10548 (save-match-data
10549 (shell-quote-argument
10550 (convert-standard-filename file)))
10551 t t cmd)))
10553 ;; Replace "%1", "%2" etc. in command with group matches from regex
10554 (save-match-data
10555 (let ((match-index 1)
10556 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10557 (set-match-data link-match-data)
10558 (while (<= match-index number-of-groups)
10559 (let ((regex (concat "%" (number-to-string match-index)))
10560 (replace-with (match-string match-index dlink)))
10561 (while (string-match regex cmd)
10562 (setq cmd (replace-match replace-with t t cmd))))
10563 (setq match-index (+ match-index 1)))))
10565 (save-window-excursion
10566 (message "Running %s...done" cmd)
10567 (start-process-shell-command cmd nil cmd)
10568 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10569 ((or (stringp cmd)
10570 (eq cmd 'emacs))
10571 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10572 (widen)
10573 (if line (org-goto-line line)
10574 (if search (org-link-search search))))
10575 ((consp cmd)
10576 (let ((file (convert-standard-filename file)))
10577 (save-match-data
10578 (set-match-data link-match-data)
10579 (eval cmd))))
10580 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10581 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10582 (or (not (equal old-buffer (current-buffer)))
10583 (not (equal old-pos (point))))
10584 (org-mark-ring-push old-pos old-buffer))))
10586 (defun org-file-apps-entry-match-against-dlink-p (entry)
10587 "This function returns non-nil if `entry' uses a regular
10588 expression which should be matched against the whole link by
10589 org-open-file.
10591 It assumes that is the case when the entry uses a regular
10592 expression which has at least one grouping construct and the
10593 action is either a lisp form or a command string containing
10594 '%1', i.e. using at least one subexpression match as a
10595 parameter."
10596 (let ((selector (car entry))
10597 (action (cdr entry)))
10598 (if (stringp selector)
10599 (and (> (regexp-opt-depth selector) 0)
10600 (or (and (stringp action)
10601 (string-match "%[0-9]" action))
10602 (consp action)))
10603 nil)))
10605 (defun org-default-apps ()
10606 "Return the default applications for this operating system."
10607 (cond
10608 ((eq system-type 'darwin)
10609 org-file-apps-defaults-macosx)
10610 ((eq system-type 'windows-nt)
10611 org-file-apps-defaults-windowsnt)
10612 (t org-file-apps-defaults-gnu)))
10614 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10615 "Convert extensions to regular expressions in the cars of LIST.
10616 Also, weed out any non-string entries, because the return value is used
10617 only for regexp matching.
10618 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10619 point to the symbol `emacs', indicating that the file should
10620 be opened in Emacs."
10621 (append
10622 (delq nil
10623 (mapcar (lambda (x)
10624 (if (not (stringp (car x)))
10626 (if (string-match "\\W" (car x))
10628 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10629 list))
10630 (if add-auto-mode
10631 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10633 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10634 (defun org-file-remote-p (file)
10635 "Test whether FILE specifies a location on a remote system.
10636 Return non-nil if the location is indeed remote.
10638 For example, the filename \"/user@host:/foo\" specifies a location
10639 on the system \"/user@host:\"."
10640 (cond ((fboundp 'file-remote-p)
10641 (file-remote-p file))
10642 ((fboundp 'tramp-handle-file-remote-p)
10643 (tramp-handle-file-remote-p file))
10644 ((and (boundp 'ange-ftp-name-format)
10645 (string-match (car ange-ftp-name-format) file))
10646 t)))
10649 ;;;; Refiling
10651 (defun org-get-org-file ()
10652 "Read a filename, with default directory `org-directory'."
10653 (let ((default (or org-default-notes-file remember-data-file)))
10654 (read-file-name (format "File name [%s]: " default)
10655 (file-name-as-directory org-directory)
10656 default)))
10658 (defun org-notes-order-reversed-p ()
10659 "Check if the current file should receive notes in reversed order."
10660 (cond
10661 ((not org-reverse-note-order) nil)
10662 ((eq t org-reverse-note-order) t)
10663 ((not (listp org-reverse-note-order)) nil)
10664 (t (catch 'exit
10665 (let ((all org-reverse-note-order)
10666 entry)
10667 (while (setq entry (pop all))
10668 (if (string-match (car entry) buffer-file-name)
10669 (throw 'exit (cdr entry))))
10670 nil)))))
10672 (defvar org-refile-target-table nil
10673 "The list of refile targets, created by `org-refile'.")
10675 (defvar org-agenda-new-buffers nil
10676 "Buffers created to visit agenda files.")
10678 (defvar org-refile-cache nil
10679 "Cache for refile targets.")
10681 (defvar org-refile-markers nil
10682 "All the markers used for caching refile locations.")
10684 (defun org-refile-marker (pos)
10685 "Get a new refile marker, but only if caching is in use."
10686 (if (not org-refile-use-cache)
10688 (let ((m (make-marker)))
10689 (move-marker m pos)
10690 (push m org-refile-markers)
10691 m)))
10693 (defun org-refile-cache-clear ()
10694 "Clear the refile cache and disable all the markers."
10695 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10696 (setq org-refile-markers nil)
10697 (setq org-refile-cache nil)
10698 (message "Refile cache has been cleared"))
10700 (defun org-refile-cache-check-set (set)
10701 "Check if all the markers in the cache still have live buffers."
10702 (let (marker)
10703 (catch 'exit
10704 (while (and set (setq marker (nth 3 (pop set))))
10705 ;; if org-refile-use-outline-path is 'file, marker may be nil
10706 (when (and marker (null (marker-buffer marker)))
10707 (message "not found") (sit-for 3)
10708 (throw 'exit nil)))
10709 t)))
10711 (defun org-refile-cache-put (set &rest identifiers)
10712 "Push the refile targets SET into the cache, under IDENTIFIERS."
10713 (let* ((key (sha1 (prin1-to-string identifiers)))
10714 (entry (assoc key org-refile-cache)))
10715 (if entry
10716 (setcdr entry set)
10717 (push (cons key set) org-refile-cache))))
10719 (defun org-refile-cache-get (&rest identifiers)
10720 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10721 (cond
10722 ((not org-refile-cache) nil)
10723 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10725 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10726 org-refile-cache))))
10727 (and set (org-refile-cache-check-set set) set)))))
10729 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10730 "Produce a table with refile targets."
10731 (let ((case-fold-search nil)
10732 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10733 (entries (or org-refile-targets '((nil . (:level . 1)))))
10734 targets tgs txt re files f desc descre fast-path-p level pos0)
10735 (message "Getting targets...")
10736 (with-current-buffer (or default-buffer (current-buffer))
10737 (while (setq entry (pop entries))
10738 (setq files (car entry) desc (cdr entry))
10739 (setq fast-path-p nil)
10740 (cond
10741 ((null files) (setq files (list (current-buffer))))
10742 ((eq files 'org-agenda-files)
10743 (setq files (org-agenda-files 'unrestricted)))
10744 ((and (symbolp files) (fboundp files))
10745 (setq files (funcall files)))
10746 ((and (symbolp files) (boundp files))
10747 (setq files (symbol-value files))))
10748 (if (stringp files) (setq files (list files)))
10749 (cond
10750 ((eq (car desc) :tag)
10751 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10752 ((eq (car desc) :todo)
10753 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10754 ((eq (car desc) :regexp)
10755 (setq descre (cdr desc)))
10756 ((eq (car desc) :level)
10757 (setq descre (concat "^\\*\\{" (number-to-string
10758 (if org-odd-levels-only
10759 (1- (* 2 (cdr desc)))
10760 (cdr desc)))
10761 "\\}[ \t]")))
10762 ((eq (car desc) :maxlevel)
10763 (setq fast-path-p t)
10764 (setq descre (concat "^\\*\\{1," (number-to-string
10765 (if org-odd-levels-only
10766 (1- (* 2 (cdr desc)))
10767 (cdr desc)))
10768 "\\}[ \t]")))
10769 (t (error "Bad refiling target description %s" desc)))
10770 (while (setq f (pop files))
10771 (with-current-buffer
10772 (if (bufferp f) f (org-get-agenda-file-buffer f))
10774 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10775 (progn
10776 (if (bufferp f) (setq f (buffer-file-name
10777 (buffer-base-buffer f))))
10778 (setq f (and f (expand-file-name f)))
10779 (if (eq org-refile-use-outline-path 'file)
10780 (push (list (file-name-nondirectory f) f nil nil) tgs))
10781 (save-excursion
10782 (save-restriction
10783 (widen)
10784 (goto-char (point-min))
10785 (while (re-search-forward descre nil t)
10786 (goto-char (setq pos0 (point-at-bol)))
10787 (catch 'next
10788 (when org-refile-target-verify-function
10789 (save-match-data
10790 (or (funcall org-refile-target-verify-function)
10791 (throw 'next t))))
10792 (when (and (looking-at org-complex-heading-regexp)
10793 (not (member (match-string 4) excluded-entries))
10794 (match-string 4))
10795 (setq level (org-reduced-level
10796 (- (match-end 1) (match-beginning 1)))
10797 txt (org-link-display-format (match-string 4))
10798 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10799 re (format org-complex-heading-regexp-format
10800 (regexp-quote (match-string 4))))
10801 (when org-refile-use-outline-path
10802 (setq txt (mapconcat
10803 'org-protect-slash
10804 (append
10805 (if (eq org-refile-use-outline-path
10806 'file)
10807 (list (file-name-nondirectory
10808 (buffer-file-name
10809 (buffer-base-buffer))))
10810 (if (eq org-refile-use-outline-path
10811 'full-file-path)
10812 (list (buffer-file-name
10813 (buffer-base-buffer)))))
10814 (org-get-outline-path fast-path-p
10815 level txt)
10816 (list txt))
10817 "/")))
10818 (push (list txt f re (org-refile-marker (point)))
10819 tgs)))
10820 (when (= (point) pos0)
10821 ;; verification function has not moved point
10822 (goto-char (point-at-eol))))))))
10823 (when org-refile-use-cache
10824 (org-refile-cache-put tgs (buffer-file-name) descre))
10825 (setq targets (append tgs targets))
10826 ))))
10827 (message "Getting targets...done")
10828 (nreverse targets)))
10830 (defun org-protect-slash (s)
10831 (while (string-match "/" s)
10832 (setq s (replace-match "\\" t t s)))
10835 (defvar org-olpa (make-vector 20 nil))
10837 (defun org-get-outline-path (&optional fastp level heading)
10838 "Return the outline path to the current entry, as a list.
10840 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10841 routine which makes outline path derivations for an entire file,
10842 avoiding backtracing. Refile target collection makes use of that."
10843 (if fastp
10844 (progn
10845 (if (> level 19)
10846 (error "Outline path failure, more than 19 levels"))
10847 (loop for i from level upto 19 do
10848 (aset org-olpa i nil))
10849 (prog1
10850 (delq nil (append org-olpa nil))
10851 (aset org-olpa level heading)))
10852 (let (rtn case-fold-search)
10853 (save-excursion
10854 (save-restriction
10855 (widen)
10856 (while (org-up-heading-safe)
10857 (when (looking-at org-complex-heading-regexp)
10858 (push (org-match-string-no-properties 4) rtn)))
10859 rtn)))))
10861 (defun org-format-outline-path (path &optional width prefix separator)
10862 "Format the outline path PATH for display.
10863 WIDTH is the maximum number of characters that is available.
10864 PREFIX is a prefix to be included in the returned string,
10865 such as the file name.
10866 SEPARATOR is inserted between the different parts of the path,
10867 the default is \"/\"."
10868 (setq width (or width 79))
10869 (if prefix (setq width (- width (length prefix))))
10870 (if (not path)
10871 (or prefix "")
10872 (let* ((nsteps (length path))
10873 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10874 (maxwidth (if (<= total-width width)
10875 10000 ;; everything fits
10876 ;; we need to shorten the level headings
10877 (/ (- width nsteps) nsteps)))
10878 (org-odd-levels-only nil)
10879 (n 0)
10880 (total (1+ (length prefix))))
10881 (setq maxwidth (max maxwidth 10))
10882 (concat prefix
10883 (if prefix (or separator "/"))
10884 (mapconcat
10885 (lambda (h)
10886 (setq n (1+ n))
10887 (if (and (= n nsteps) (< maxwidth 10000))
10888 (setq maxwidth (- total-width total)))
10889 (if (< (length h) maxwidth)
10890 (progn (setq total (+ total (length h) 1)) h)
10891 (setq h (substring h 0 (- maxwidth 2))
10892 total (+ total maxwidth 1))
10893 (if (string-match "[ \t]+\\'" h)
10894 (setq h (substring h 0 (match-beginning 0))))
10895 (setq h (concat h "..")))
10896 (org-add-props h nil 'face
10897 (nth (% (1- n) org-n-level-faces)
10898 org-level-faces))
10900 path (or separator "/"))))))
10902 (defun org-display-outline-path (&optional file current separator just-return-string)
10903 "Display the current outline path in the echo area.
10905 If FILE is non-nil, prepend the output with the file name.
10906 If CURRENT is non-nil, append the current heading to the output.
10907 SEPARATOR is passed through to `org-format-outline-path'. It separates
10908 the different parts of the path and defaults to \"/\".
10909 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10910 (interactive "P")
10911 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10912 (case-fold-search nil)
10913 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10914 res)
10915 (if current (setq path (append path
10916 (save-excursion
10917 (org-back-to-heading t)
10918 (if (looking-at org-complex-heading-regexp)
10919 (list (match-string 4)))))))
10920 (setq res
10921 (org-format-outline-path
10922 path
10923 (1- (frame-width))
10924 (and file bfn (concat (file-name-nondirectory bfn) separator))
10925 separator))
10926 (if just-return-string
10927 (org-no-properties res)
10928 (message "%s" res))))
10930 (defvar org-refile-history nil
10931 "History for refiling operations.")
10933 (defvar org-after-refile-insert-hook nil
10934 "Hook run after `org-refile' has inserted its stuff at the new location.
10935 Note that this is still *before* the stuff will be removed from
10936 the *old* location.")
10938 (defvar org-capture-last-stored-marker)
10939 (defvar org-refile-keep nil
10940 "Non-nil means `org-refile' will copy instead of refile.")
10942 (defun org-copy ()
10943 "Like `org-refile', but copy."
10944 (interactive)
10945 (let ((org-refile-keep t))
10946 (funcall 'org-refile nil nil nil "Copy")))
10948 (defun org-refile (&optional goto default-buffer rfloc msg)
10949 "Move the entry or entries at point to another heading.
10950 The list of target headings is compiled using the information in
10951 `org-refile-targets', which see.
10953 At the target location, the entry is filed as a subitem of the target
10954 heading. Depending on `org-reverse-note-order', the new subitem will
10955 either be the first or the last subitem.
10957 If there is an active region, all entries in that region will be moved.
10958 However, the region must fulfill the requirement that the first heading
10959 is the first one sets the top-level of the moved text - at most siblings
10960 below it are allowed.
10962 With prefix arg GOTO, the command will only visit the target location
10963 and not actually move anything.
10965 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10966 go to the location where the last refiling operation has put the subtree.
10967 With a prefix argument of `2', refile to the running clock.
10969 RFLOC can be a refile location obtained in a different way.
10971 MSG is a string to replace \"Refile\" in the default prompt with
10972 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10974 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10976 If you are using target caching (see `org-refile-use-cache'),
10977 you have to clear the target cache in order to find new targets.
10978 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10979 prefix argument (`C-u C-u C-u C-c C-w')."
10981 (interactive "P")
10982 (if (member goto '(0 (64)))
10983 (org-refile-cache-clear)
10984 (let* ((actionmsg (or msg "Refile"))
10985 (cbuf (current-buffer))
10986 (regionp (org-region-active-p))
10987 (region-start (and regionp (region-beginning)))
10988 (region-end (and regionp (region-end)))
10989 (region-length (and regionp (- region-end region-start)))
10990 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10991 pos it nbuf file re level reversed)
10992 (setq last-command nil)
10993 (when regionp
10994 (goto-char region-start)
10995 (or (bolp) (goto-char (point-at-bol)))
10996 (setq region-start (point))
10997 (unless (or (org-kill-is-subtree-p
10998 (buffer-substring region-start region-end))
10999 (prog1 org-refile-active-region-within-subtree
11000 (org-toggle-heading)))
11001 (error "The region is not a (sequence of) subtree(s)")))
11002 (if (equal goto '(16))
11003 (org-refile-goto-last-stored)
11004 (when (or
11005 (and (equal goto 2)
11006 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11007 (prog1
11008 (setq it (list (or org-clock-heading "running clock")
11009 (buffer-file-name
11010 (marker-buffer org-clock-hd-marker))
11012 (marker-position org-clock-hd-marker)))
11013 (setq goto nil)))
11014 (setq it (or rfloc
11015 (let (heading-text)
11016 (save-excursion
11017 (unless goto
11018 (org-back-to-heading t)
11019 (setq heading-text
11020 (nth 4 (org-heading-components))))
11022 (org-refile-get-location
11023 (cond (goto "Goto")
11024 (regionp (concat actionmsg " region to"))
11025 (t (concat actionmsg " subtree \""
11026 heading-text "\" to")))
11027 default-buffer
11028 (and (not (equal '(4) goto))
11029 org-refile-allow-creating-parent-nodes)
11030 goto))))))
11031 (setq file (nth 1 it)
11032 re (nth 2 it)
11033 pos (nth 3 it))
11034 (if (and (not goto)
11036 (equal (buffer-file-name) file)
11037 (if regionp
11038 (and (>= pos region-start)
11039 (<= pos region-end))
11040 (and (>= pos (point))
11041 (< pos (save-excursion
11042 (org-end-of-subtree t t))))))
11043 (error "Cannot refile to position inside the tree or region"))
11045 (setq nbuf (or (find-buffer-visiting file)
11046 (find-file-noselect file)))
11047 (if goto
11048 (progn
11049 (org-pop-to-buffer-same-window nbuf)
11050 (goto-char pos)
11051 (org-show-context 'org-goto))
11052 (if regionp
11053 (progn
11054 (org-kill-new (buffer-substring region-start region-end))
11055 (org-save-markers-in-region region-start region-end))
11056 (org-copy-subtree 1 nil t))
11057 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11058 (find-file-noselect file)))
11059 (setq reversed (org-notes-order-reversed-p))
11060 (save-excursion
11061 (save-restriction
11062 (widen)
11063 (if pos
11064 (progn
11065 (goto-char pos)
11066 (looking-at org-outline-regexp)
11067 (setq level (org-get-valid-level (funcall outline-level) 1))
11068 (goto-char
11069 (if reversed
11070 (or (outline-next-heading) (point-max))
11071 (or (save-excursion (org-get-next-sibling))
11072 (org-end-of-subtree t t)
11073 (point-max)))))
11074 (setq level 1)
11075 (if (not reversed)
11076 (goto-char (point-max))
11077 (goto-char (point-min))
11078 (or (outline-next-heading) (goto-char (point-max)))))
11079 (if (not (bolp)) (newline))
11080 (org-paste-subtree level)
11081 (when org-log-refile
11082 (org-add-log-setup 'refile nil nil 'findpos
11083 org-log-refile)
11084 (unless (eq org-log-refile 'note)
11085 (save-excursion (org-add-log-note))))
11086 (and org-auto-align-tags
11087 (let ((org-loop-over-headlines-in-active-region nil))
11088 (org-set-tags nil t)))
11089 (bookmark-set "org-refile-last-stored")
11090 ;; If we are refiling for capture, make sure that the
11091 ;; last-capture pointers point here
11092 (when (org-bound-and-true-p org-refile-for-capture)
11093 (bookmark-set "org-capture-last-stored-marker")
11094 (move-marker org-capture-last-stored-marker (point)))
11095 (if (fboundp 'deactivate-mark) (deactivate-mark))
11096 (run-hooks 'org-after-refile-insert-hook))))
11097 (unless org-refile-keep
11098 (if regionp
11099 (delete-region (point) (+ (point) region-length))
11100 (org-cut-subtree)))
11101 (when (featurep 'org-inlinetask)
11102 (org-inlinetask-remove-END-maybe))
11103 (setq org-markers-to-move nil)
11104 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11106 (defun org-refile-goto-last-stored ()
11107 "Go to the location where the last refile was stored."
11108 (interactive)
11109 (bookmark-jump "org-refile-last-stored")
11110 (message "This is the location of the last refile"))
11112 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11113 no-exclude)
11114 "Prompt the user for a refile location, using PROMPT.
11115 PROMPT should not be suffixed with a colon and a space, because
11116 this function appends the default value from
11117 `org-refile-history' automatically, if that is not empty.
11118 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11119 this is used for the GOTO interface."
11120 (let ((org-refile-targets org-refile-targets)
11121 (org-refile-use-outline-path org-refile-use-outline-path)
11122 excluded-entries)
11123 (when (and (derived-mode-p 'org-mode)
11124 (not org-refile-use-cache)
11125 (not no-exclude))
11126 (org-map-tree
11127 (lambda()
11128 (setq excluded-entries
11129 (append excluded-entries (list (org-get-heading t t)))))))
11130 (setq org-refile-target-table
11131 (org-refile-get-targets default-buffer excluded-entries)))
11132 (unless org-refile-target-table
11133 (error "No refile targets"))
11134 (let* ((cbuf (current-buffer))
11135 (partial-completion-mode nil)
11136 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11137 (cfunc (if (and org-refile-use-outline-path
11138 org-outline-path-complete-in-steps)
11139 'org-olpath-completing-read
11140 'org-icompleting-read))
11141 (extra (if org-refile-use-outline-path "/" ""))
11142 (cbnex (concat (buffer-name) extra))
11143 (filename (and cfn (expand-file-name cfn)))
11144 (tbl (mapcar
11145 (lambda (x)
11146 (if (and (not (member org-refile-use-outline-path
11147 '(file full-file-path)))
11148 (not (equal filename (nth 1 x))))
11149 (cons (concat (car x) extra " ("
11150 (file-name-nondirectory (nth 1 x)) ")")
11151 (cdr x))
11152 (cons (concat (car x) extra) (cdr x))))
11153 org-refile-target-table))
11154 (completion-ignore-case t)
11155 cdef
11156 (prompt (concat prompt
11157 (or (and (car org-refile-history)
11158 (concat " (default " (car org-refile-history) ")"))
11159 (and (assoc cbnex tbl) (setq cdef cbnex)
11160 (concat " (default " cbnex ")"))) ": "))
11161 pa answ parent-target child parent old-hist)
11162 (setq old-hist org-refile-history)
11163 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11164 nil 'org-refile-history (or cdef (car org-refile-history))))
11165 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11166 (org-refile-check-position pa)
11167 (if pa
11168 (progn
11169 (when (or (not org-refile-history)
11170 (not (eq old-hist org-refile-history))
11171 (not (equal (car pa) (car org-refile-history))))
11172 (setq org-refile-history
11173 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11174 org-refile-history
11175 (cdr org-refile-history))))
11176 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11177 (pop org-refile-history)))
11179 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11180 (progn
11181 (setq parent (match-string 1 answ)
11182 child (match-string 2 answ))
11183 (setq parent-target (or (assoc parent tbl)
11184 (assoc (concat parent "/") tbl)))
11185 (when (and parent-target
11186 (or (eq new-nodes t)
11187 (and (eq new-nodes 'confirm)
11188 (y-or-n-p (format "Create new node \"%s\"? "
11189 child)))))
11190 (org-refile-new-child parent-target child)))
11191 (error "Invalid target location")))))
11193 (declare-function org-string-nw-p "org-macs.el" (s))
11194 (defun org-refile-check-position (refile-pointer)
11195 "Check if the refile pointer matches the readline to which it points."
11196 (let* ((file (nth 1 refile-pointer))
11197 (re (nth 2 refile-pointer))
11198 (pos (nth 3 refile-pointer))
11199 buffer)
11200 (when (org-string-nw-p re)
11201 (setq buffer (if (markerp pos)
11202 (marker-buffer pos)
11203 (or (find-buffer-visiting file)
11204 (find-file-noselect file))))
11205 (with-current-buffer buffer
11206 (save-excursion
11207 (save-restriction
11208 (widen)
11209 (goto-char pos)
11210 (beginning-of-line 1)
11211 (unless (org-looking-at-p re)
11212 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11214 (defun org-refile-new-child (parent-target child)
11215 "Use refile target PARENT-TARGET to add new CHILD below it."
11216 (unless parent-target
11217 (error "Cannot find parent for new node"))
11218 (let ((file (nth 1 parent-target))
11219 (pos (nth 3 parent-target))
11220 level)
11221 (with-current-buffer (or (find-buffer-visiting file)
11222 (find-file-noselect file))
11223 (save-excursion
11224 (save-restriction
11225 (widen)
11226 (if pos
11227 (goto-char pos)
11228 (goto-char (point-max))
11229 (if (not (bolp)) (newline)))
11230 (when (looking-at org-outline-regexp)
11231 (setq level (funcall outline-level))
11232 (org-end-of-subtree t t))
11233 (org-back-over-empty-lines)
11234 (insert "\n" (make-string
11235 (if pos (org-get-valid-level level 1) 1) ?*)
11236 " " child "\n")
11237 (beginning-of-line 0)
11238 (list (concat (car parent-target) "/" child) file "" (point)))))))
11240 (defun org-olpath-completing-read (prompt collection &rest args)
11241 "Read an outline path like a file name."
11242 (let ((thetable collection)
11243 (org-completion-use-ido nil) ; does not work with ido.
11244 (org-completion-use-iswitchb nil)) ; or iswitchb
11245 (apply
11246 'org-icompleting-read prompt
11247 (lambda (string predicate &optional flag)
11248 (let (rtn r f (l (length string)))
11249 (cond
11250 ((eq flag nil)
11251 ;; try completion
11252 (try-completion string thetable))
11253 ((eq flag t)
11254 ;; all-completions
11255 (setq rtn (all-completions string thetable predicate))
11256 (mapcar
11257 (lambda (x)
11258 (setq r (substring x l))
11259 (if (string-match " ([^)]*)$" x)
11260 (setq f (match-string 0 x))
11261 (setq f ""))
11262 (if (string-match "/" r)
11263 (concat string (substring r 0 (match-end 0)) f)
11265 rtn))
11266 ((eq flag 'lambda)
11267 ;; exact match?
11268 (assoc string thetable)))))
11269 args)))
11271 ;;;; Dynamic blocks
11273 (defun org-find-dblock (name)
11274 "Find the first dynamic block with name NAME in the buffer.
11275 If not found, stay at current position and return nil."
11276 (let ((case-fold-search t) pos)
11277 (save-excursion
11278 (goto-char (point-min))
11279 (setq pos (and (re-search-forward
11280 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11281 (match-beginning 0))))
11282 (if pos (goto-char pos))
11283 pos))
11285 (defconst org-dblock-start-re
11286 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11287 "Matches the start line of a dynamic block, with parameters.")
11289 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11290 "Matches the end of a dynamic block.")
11292 (defun org-create-dblock (plist)
11293 "Create a dynamic block section, with parameters taken from PLIST.
11294 PLIST must contain a :name entry which is used as name of the block."
11295 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11296 (end-of-line 1)
11297 (newline))
11298 (let ((col (current-column))
11299 (name (plist-get plist :name)))
11300 (insert "#+BEGIN: " name)
11301 (while plist
11302 (if (eq (car plist) :name)
11303 (setq plist (cddr plist))
11304 (insert " " (prin1-to-string (pop plist)))))
11305 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11306 (beginning-of-line -2)))
11308 (defun org-prepare-dblock ()
11309 "Prepare dynamic block for refresh.
11310 This empties the block, puts the cursor at the insert position and returns
11311 the property list including an extra property :name with the block name."
11312 (unless (looking-at org-dblock-start-re)
11313 (error "Not at a dynamic block"))
11314 (let* ((begdel (1+ (match-end 0)))
11315 (name (org-no-properties (match-string 1)))
11316 (params (append (list :name name)
11317 (read (concat "(" (match-string 3) ")")))))
11318 (save-excursion
11319 (beginning-of-line 1)
11320 (skip-chars-forward " \t")
11321 (setq params (plist-put params :indentation-column (current-column))))
11322 (unless (re-search-forward org-dblock-end-re nil t)
11323 (error "Dynamic block not terminated"))
11324 (setq params
11325 (append params
11326 (list :content (buffer-substring
11327 begdel (match-beginning 0)))))
11328 (delete-region begdel (match-beginning 0))
11329 (goto-char begdel)
11330 (open-line 1)
11331 params))
11333 (defun org-map-dblocks (&optional command)
11334 "Apply COMMAND to all dynamic blocks in the current buffer.
11335 If COMMAND is not given, use `org-update-dblock'."
11336 (let ((cmd (or command 'org-update-dblock)))
11337 (save-excursion
11338 (goto-char (point-min))
11339 (while (re-search-forward org-dblock-start-re nil t)
11340 (goto-char (match-beginning 0))
11341 (save-excursion
11342 (condition-case nil
11343 (funcall cmd)
11344 (error (message "Error during update of dynamic block"))))
11345 (unless (re-search-forward org-dblock-end-re nil t)
11346 (error "Dynamic block not terminated"))))))
11348 (defun org-dblock-update (&optional arg)
11349 "User command for updating dynamic blocks.
11350 Update the dynamic block at point. With prefix ARG, update all dynamic
11351 blocks in the buffer."
11352 (interactive "P")
11353 (if arg
11354 (org-update-all-dblocks)
11355 (or (looking-at org-dblock-start-re)
11356 (org-beginning-of-dblock))
11357 (org-update-dblock)))
11359 (defun org-update-dblock ()
11360 "Update the dynamic block at point.
11361 This means to empty the block, parse for parameters and then call
11362 the correct writing function."
11363 (interactive)
11364 (save-window-excursion
11365 (let* ((pos (point))
11366 (line (org-current-line))
11367 (params (org-prepare-dblock))
11368 (name (plist-get params :name))
11369 (indent (plist-get params :indentation-column))
11370 (cmd (intern (concat "org-dblock-write:" name))))
11371 (message "Updating dynamic block `%s' at line %d..." name line)
11372 (funcall cmd params)
11373 (message "Updating dynamic block `%s' at line %d...done" name line)
11374 (goto-char pos)
11375 (when (and indent (> indent 0))
11376 (setq indent (make-string indent ?\ ))
11377 (save-excursion
11378 (org-beginning-of-dblock)
11379 (forward-line 1)
11380 (while (not (looking-at org-dblock-end-re))
11381 (insert indent)
11382 (beginning-of-line 2))
11383 (when (looking-at org-dblock-end-re)
11384 (and (looking-at "[ \t]+")
11385 (replace-match ""))
11386 (insert indent)))))))
11388 (defun org-beginning-of-dblock ()
11389 "Find the beginning of the dynamic block at point.
11390 Error if there is no such block at point."
11391 (let ((pos (point))
11392 beg)
11393 (end-of-line 1)
11394 (if (and (re-search-backward org-dblock-start-re nil t)
11395 (setq beg (match-beginning 0))
11396 (re-search-forward org-dblock-end-re nil t)
11397 (> (match-end 0) pos))
11398 (goto-char beg)
11399 (goto-char pos)
11400 (error "Not in a dynamic block"))))
11402 ;;;###autoload
11403 (defun org-update-all-dblocks ()
11404 "Update all dynamic blocks in the buffer.
11405 This function can be used in a hook."
11406 (interactive)
11407 (when (derived-mode-p 'org-mode)
11408 (org-map-dblocks 'org-update-dblock)))
11411 ;;;; Completion
11413 (defconst org-additional-option-like-keywords
11414 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11415 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11416 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11417 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11418 "BEGIN:" "END:"
11419 "ORGTBL" "TBLFM:" "TBLNAME:"
11420 "BEGIN_EXAMPLE" "END_EXAMPLE"
11421 "BEGIN_VERBATIM" "END_VERBATIM"
11422 "BEGIN_QUOTE" "END_QUOTE"
11423 "BEGIN_VERSE" "END_VERSE"
11424 "BEGIN_CENTER" "END_CENTER"
11425 "BEGIN_SRC" "END_SRC"
11426 "BEGIN_RESULT" "END_RESULT"
11427 "BEGIN_lstlisting" "END_lstlisting"
11428 "NAME:" "RESULTS:"
11429 "HEADER:" "HEADERS:"
11430 "COLUMNS:" "PROPERTY:"
11431 "CAPTION:" "LABEL:"
11432 "SETUPFILE:"
11433 "INCLUDE:"
11434 "BIND:"
11435 "MACRO:"))
11437 (defconst org-options-keywords
11438 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11439 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11440 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11441 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11442 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11443 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11444 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11446 (defconst org-additional-option-like-keywords-for-flyspell
11447 (delete-dups
11448 (split-string
11449 (mapconcat (lambda(k)
11450 (replace-regexp-in-string
11451 "_\\|:" " "
11452 (concat k " " (downcase k) " " (upcase k))))
11453 (append org-options-keywords org-additional-option-like-keywords)
11454 " ")
11455 " +" t)))
11457 (defcustom org-structure-template-alist
11459 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11460 "<src lang=\"?\">\n\n</src>")
11461 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11462 "<example>\n?\n</example>")
11463 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11464 "<quote>\n?\n</quote>")
11465 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11466 "<verse>\n?\n</verse>")
11467 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11468 "<center>\n?\n</center>")
11469 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11470 "<literal style=\"latex\">\n?\n</literal>")
11471 ("L" "#+LaTeX: "
11472 "<literal style=\"latex\">?</literal>")
11473 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11474 "<literal style=\"html\">\n?\n</literal>")
11475 ("H" "#+HTML: "
11476 "<literal style=\"html\">?</literal>")
11477 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11478 ("A" "#+ASCII: ")
11479 ("i" "#+INDEX: ?"
11480 "#+INDEX: ?")
11481 ("I" "#+INCLUDE: %file ?"
11482 "<include file=%file markup=\"?\">")
11484 "Structure completion elements.
11485 This is a list of abbreviation keys and values. The value gets inserted
11486 if you type `<' followed by the key and then press the completion key,
11487 usually `M-TAB'. %file will be replaced by a file name after prompting
11488 for the file using completion. The cursor will be placed at the position
11489 of the `?` in the template.
11490 There are two templates for each key, the first uses the original Org syntax,
11491 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11492 the default when the /org-mtags.el/ module has been loaded. See also the
11493 variable `org-mtags-prefer-muse-templates'."
11494 :group 'org-completion
11495 :type '(repeat
11496 (string :tag "Key")
11497 (string :tag "Template")
11498 (string :tag "Muse Template")))
11500 (defun org-try-structure-completion ()
11501 "Try to complete a structure template before point.
11502 This looks for strings like \"<e\" on an otherwise empty line and
11503 expands them."
11504 (let ((l (buffer-substring (point-at-bol) (point)))
11506 (when (and (looking-at "[ \t]*$")
11507 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11508 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11509 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11510 (match-beginning 1)) a)
11511 t)))
11513 (defun org-complete-expand-structure-template (start cell)
11514 "Expand a structure template."
11515 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11516 (rpl (nth (if musep 2 1) cell))
11517 (ind ""))
11518 (delete-region start (point))
11519 (when (string-match "\\`#\\+" rpl)
11520 (cond
11521 ((bolp))
11522 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11523 (setq ind (buffer-substring (point-at-bol) (point))))
11524 (t (newline))))
11525 (setq start (point))
11526 (if (string-match "%file" rpl)
11527 (setq rpl (replace-match
11528 (concat
11529 "\""
11530 (save-match-data
11531 (abbreviate-file-name (read-file-name "Include file: ")))
11532 "\"")
11533 t t rpl)))
11534 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11535 (concat "\n" ind)))
11536 (insert rpl)
11537 (if (re-search-backward "\\?" start t) (delete-char 1))))
11539 ;;;; TODO, DEADLINE, Comments
11541 (defun org-toggle-comment ()
11542 "Change the COMMENT state of an entry."
11543 (interactive)
11544 (save-excursion
11545 (org-back-to-heading)
11546 (let (case-fold-search)
11547 (cond
11548 ((looking-at (format org-heading-keyword-regexp-format
11549 org-comment-string))
11550 (goto-char (match-end 1))
11551 (looking-at (concat " +" org-comment-string))
11552 (replace-match "" t t)
11553 (when (eolp) (insert " ")))
11554 ((looking-at org-outline-regexp)
11555 (goto-char (match-end 0))
11556 (insert org-comment-string " "))))))
11558 (defvar org-last-todo-state-is-todo nil
11559 "This is non-nil when the last TODO state change led to a TODO state.
11560 If the last change removed the TODO tag or switched to DONE, then
11561 this is nil.")
11563 (defvar org-setting-tags nil) ; dynamically skipped
11565 (defvar org-todo-setup-filter-hook nil
11566 "Hook for functions that pre-filter todo specs.
11567 Each function takes a todo spec and returns either nil or the spec
11568 transformed into canonical form." )
11570 (defvar org-todo-get-default-hook nil
11571 "Hook for functions that get a default item for todo.
11572 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11573 nil or a string to be used for the todo mark." )
11575 (defvar org-agenda-headline-snapshot-before-repeat)
11577 (defun org-current-effective-time ()
11578 "Return current time adjusted for `org-extend-today-until' variable."
11579 (let* ((ct (org-current-time))
11580 (dct (decode-time ct))
11581 (ct1
11582 (cond
11583 (org-use-last-clock-out-time-as-effective-time
11584 (or (org-clock-get-last-clock-out-time) ct))
11585 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11586 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11587 (t ct))))
11588 ct1))
11590 (defun org-todo-yesterday (&optional arg)
11591 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11592 (interactive "P")
11593 (if (eq major-mode 'org-agenda-mode)
11594 (apply 'org-agenda-todo-yesterday arg)
11595 (let* ((hour (third (decode-time
11596 (org-current-time))))
11597 (org-extend-today-until (1+ hour)))
11598 (org-todo arg))))
11600 (defun org-todo (&optional arg)
11601 "Change the TODO state of an item.
11602 The state of an item is given by a keyword at the start of the heading,
11603 like
11604 *** TODO Write paper
11605 *** DONE Call mom
11607 The different keywords are specified in the variable `org-todo-keywords'.
11608 By default the available states are \"TODO\" and \"DONE\".
11609 So for this example: when the item starts with TODO, it is changed to DONE.
11610 When it starts with DONE, the DONE is removed. And when neither TODO nor
11611 DONE are present, add TODO at the beginning of the heading.
11613 With \\[universal-argument] prefix arg, use completion to determine the new \
11614 state.
11615 With numeric prefix arg, switch to that state.
11616 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11617 keywords (nextset).
11618 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11619 With a numeric prefix arg of 0, inhibit note taking for the change.
11621 For calling through lisp, arg is also interpreted in the following way:
11622 'none -> empty state
11623 \"\"(empty string) -> switch to empty state
11624 'done -> switch to DONE
11625 'nextset -> switch to the next set of keywords
11626 'previousset -> switch to the previous set of keywords
11627 \"WAITING\" -> switch to the specified keyword, but only if it
11628 really is a member of `org-todo-keywords'."
11629 (interactive "P")
11630 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11631 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11632 'region-start-level 'region))
11633 org-loop-over-headlines-in-active-region)
11634 (org-map-entries
11635 `(org-todo ,arg)
11636 org-loop-over-headlines-in-active-region
11637 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11638 (if (equal arg '(16)) (setq arg 'nextset))
11639 (let ((org-blocker-hook org-blocker-hook)
11640 (case-fold-search nil))
11641 (when (equal arg '(64))
11642 (setq arg nil org-blocker-hook nil))
11643 (when (and org-blocker-hook
11644 (or org-inhibit-blocking
11645 (org-entry-get nil "NOBLOCKING")))
11646 (setq org-blocker-hook nil))
11647 (save-excursion
11648 (catch 'exit
11649 (org-back-to-heading t)
11650 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11651 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11652 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11653 (let* ((match-data (match-data))
11654 (startpos (point-at-bol))
11655 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11656 (org-log-done org-log-done)
11657 (org-log-repeat org-log-repeat)
11658 (org-todo-log-states org-todo-log-states)
11659 (org-inhibit-logging
11660 (if (equal arg 0)
11661 (progn (setq arg nil) 'note) org-inhibit-logging))
11662 (this (match-string 1))
11663 (hl-pos (match-beginning 0))
11664 (head (org-get-todo-sequence-head this))
11665 (ass (assoc head org-todo-kwd-alist))
11666 (interpret (nth 1 ass))
11667 (done-word (nth 3 ass))
11668 (final-done-word (nth 4 ass))
11669 (org-last-state (or this ""))
11670 (completion-ignore-case t)
11671 (member (member this org-todo-keywords-1))
11672 (tail (cdr member))
11673 (org-state (cond
11674 ((and org-todo-key-trigger
11675 (or (and (equal arg '(4))
11676 (eq org-use-fast-todo-selection 'prefix))
11677 (and (not arg) org-use-fast-todo-selection
11678 (not (eq org-use-fast-todo-selection
11679 'prefix)))))
11680 ;; Use fast selection
11681 (org-fast-todo-selection))
11682 ((and (equal arg '(4))
11683 (or (not org-use-fast-todo-selection)
11684 (not org-todo-key-trigger)))
11685 ;; Read a state with completion
11686 (org-icompleting-read
11687 "State: " (mapcar (lambda(x) (list x))
11688 org-todo-keywords-1)
11689 nil t))
11690 ((eq arg 'right)
11691 (if this
11692 (if tail (car tail) nil)
11693 (car org-todo-keywords-1)))
11694 ((eq arg 'left)
11695 (if (equal member org-todo-keywords-1)
11697 (if this
11698 (nth (- (length org-todo-keywords-1)
11699 (length tail) 2)
11700 org-todo-keywords-1)
11701 (org-last org-todo-keywords-1))))
11702 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11703 (setq arg nil))) ; hack to fall back to cycling
11704 (arg
11705 ;; user or caller requests a specific state
11706 (cond
11707 ((equal arg "") nil)
11708 ((eq arg 'none) nil)
11709 ((eq arg 'done) (or done-word (car org-done-keywords)))
11710 ((eq arg 'nextset)
11711 (or (car (cdr (member head org-todo-heads)))
11712 (car org-todo-heads)))
11713 ((eq arg 'previousset)
11714 (let ((org-todo-heads (reverse org-todo-heads)))
11715 (or (car (cdr (member head org-todo-heads)))
11716 (car org-todo-heads))))
11717 ((car (member arg org-todo-keywords-1)))
11718 ((stringp arg)
11719 (error "State `%s' not valid in this file" arg))
11720 ((nth (1- (prefix-numeric-value arg))
11721 org-todo-keywords-1))))
11722 ((null member) (or head (car org-todo-keywords-1)))
11723 ((equal this final-done-word) nil) ;; -> make empty
11724 ((null tail) nil) ;; -> first entry
11725 ((memq interpret '(type priority))
11726 (if (eq this-command last-command)
11727 (car tail)
11728 (if (> (length tail) 0)
11729 (or done-word (car org-done-keywords))
11730 nil)))
11732 (car tail))))
11733 (org-state (or
11734 (run-hook-with-args-until-success
11735 'org-todo-get-default-hook org-state org-last-state)
11736 org-state))
11737 (next (if org-state (concat " " org-state " ") " "))
11738 (change-plist (list :type 'todo-state-change :from this :to org-state
11739 :position startpos))
11740 dolog now-done-p)
11741 (when org-blocker-hook
11742 (setq org-last-todo-state-is-todo
11743 (not (member this org-done-keywords)))
11744 (unless (save-excursion
11745 (save-match-data
11746 (org-with-wide-buffer
11747 (run-hook-with-args-until-failure
11748 'org-blocker-hook change-plist))))
11749 (if (org-called-interactively-p 'interactive)
11750 (error "TODO state change from %s to %s blocked" this org-state)
11751 ;; fail silently
11752 (message "TODO state change from %s to %s blocked" this org-state)
11753 (throw 'exit nil))))
11754 (store-match-data match-data)
11755 (replace-match next t t)
11756 (unless (pos-visible-in-window-p hl-pos)
11757 (message "TODO state changed to %s" (org-trim next)))
11758 (unless head
11759 (setq head (org-get-todo-sequence-head org-state)
11760 ass (assoc head org-todo-kwd-alist)
11761 interpret (nth 1 ass)
11762 done-word (nth 3 ass)
11763 final-done-word (nth 4 ass)))
11764 (when (memq arg '(nextset previousset))
11765 (message "Keyword-Set %d/%d: %s"
11766 (- (length org-todo-sets) -1
11767 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11768 (length org-todo-sets)
11769 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11770 (setq org-last-todo-state-is-todo
11771 (not (member org-state org-done-keywords)))
11772 (setq now-done-p (and (member org-state org-done-keywords)
11773 (not (member this org-done-keywords))))
11774 (and logging (org-local-logging logging))
11775 (when (and (or org-todo-log-states org-log-done)
11776 (not (eq org-inhibit-logging t))
11777 (not (memq arg '(nextset previousset))))
11778 ;; we need to look at recording a time and note
11779 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11780 (nth 2 (assoc this org-todo-log-states))))
11781 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11782 (setq dolog 'time))
11783 (when (and org-state
11784 (member org-state org-not-done-keywords)
11785 (not (member this org-not-done-keywords)))
11786 ;; This is now a todo state and was not one before
11787 ;; If there was a CLOSED time stamp, get rid of it.
11788 (org-add-planning-info nil nil 'closed))
11789 (when (and now-done-p org-log-done)
11790 ;; It is now done, and it was not done before
11791 (org-add-planning-info 'closed (org-current-effective-time))
11792 (if (and (not dolog) (eq 'note org-log-done))
11793 (org-add-log-setup 'done org-state this 'findpos 'note)))
11794 (when (and org-state dolog)
11795 ;; This is a non-nil state, and we need to log it
11796 (org-add-log-setup 'state org-state this 'findpos dolog)))
11797 ;; Fixup tag positioning
11798 (org-todo-trigger-tag-changes org-state)
11799 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11800 (when org-provide-todo-statistics
11801 (org-update-parent-todo-statistics))
11802 (run-hooks 'org-after-todo-state-change-hook)
11803 (if (and arg (not (member org-state org-done-keywords)))
11804 (setq head (org-get-todo-sequence-head org-state)))
11805 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11806 ;; Do we need to trigger a repeat?
11807 (when now-done-p
11808 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11809 ;; This is for the agenda, take a snapshot of the headline.
11810 (save-match-data
11811 (setq org-agenda-headline-snapshot-before-repeat
11812 (org-get-heading))))
11813 (org-auto-repeat-maybe org-state))
11814 ;; Fixup cursor location if close to the keyword
11815 (if (and (outline-on-heading-p)
11816 (not (bolp))
11817 (save-excursion (beginning-of-line 1)
11818 (looking-at org-todo-line-regexp))
11819 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11820 (progn
11821 (goto-char (or (match-end 2) (match-end 1)))
11822 (and (looking-at " ") (just-one-space))))
11823 (when org-trigger-hook
11824 (save-excursion
11825 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11827 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11828 "Block turning an entry into a TODO, using the hierarchy.
11829 This checks whether the current task should be blocked from state
11830 changes. Such blocking occurs when:
11832 1. The task has children which are not all in a completed state.
11834 2. A task has a parent with the property :ORDERED:, and there
11835 are siblings prior to the current task with incomplete
11836 status.
11838 3. The parent of the task is blocked because it has siblings that should
11839 be done first, or is child of a block grandparent TODO entry."
11841 (if (not org-enforce-todo-dependencies)
11842 t ; if locally turned off don't block
11843 (catch 'dont-block
11844 ;; If this is not a todo state change, or if this entry is already DONE,
11845 ;; do not block
11846 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11847 (member (plist-get change-plist :from)
11848 (cons 'done org-done-keywords))
11849 (member (plist-get change-plist :to)
11850 (cons 'todo org-not-done-keywords))
11851 (not (plist-get change-plist :to)))
11852 (throw 'dont-block t))
11853 ;; If this task has children, and any are undone, it's blocked
11854 (save-excursion
11855 (org-back-to-heading t)
11856 (let ((this-level (funcall outline-level)))
11857 (outline-next-heading)
11858 (let ((child-level (funcall outline-level)))
11859 (while (and (not (eobp))
11860 (> child-level this-level))
11861 ;; this todo has children, check whether they are all
11862 ;; completed
11863 (if (and (not (org-entry-is-done-p))
11864 (org-entry-is-todo-p))
11865 (throw 'dont-block nil))
11866 (outline-next-heading)
11867 (setq child-level (funcall outline-level))))))
11868 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11869 ;; any previous siblings are undone, it's blocked
11870 (save-excursion
11871 (org-back-to-heading t)
11872 (let* ((pos (point))
11873 (parent-pos (and (org-up-heading-safe) (point))))
11874 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11875 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11876 (forward-line 1)
11877 (re-search-forward org-not-done-heading-regexp pos t))
11878 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11879 ;; Search further up the hierarchy, to see if an ancestor is blocked
11880 (while t
11881 (goto-char parent-pos)
11882 (if (not (looking-at org-not-done-heading-regexp))
11883 (throw 'dont-block t)) ; do not block, parent is not a TODO
11884 (setq pos (point))
11885 (setq parent-pos (and (org-up-heading-safe) (point)))
11886 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11887 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11888 (forward-line 1)
11889 (re-search-forward org-not-done-heading-regexp pos t))
11890 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11892 (defcustom org-track-ordered-property-with-tag nil
11893 "Should the ORDERED property also be shown as a tag?
11894 The ORDERED property decides if an entry should require subtasks to be
11895 completed in sequence. Since a property is not very visible, setting
11896 this option means that toggling the ORDERED property with the command
11897 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11898 not relevant for the behavior, but it makes things more visible.
11900 Note that toggling the tag with tags commands will not change the property
11901 and therefore not influence behavior!
11903 This can be t, meaning the tag ORDERED should be used, It can also be a
11904 string to select a different tag for this task."
11905 :group 'org-todo
11906 :type '(choice
11907 (const :tag "No tracking" nil)
11908 (const :tag "Track with ORDERED tag" t)
11909 (string :tag "Use other tag")))
11911 (defun org-toggle-ordered-property ()
11912 "Toggle the ORDERED property of the current entry.
11913 For better visibility, you can track the value of this property with a tag.
11914 See variable `org-track-ordered-property-with-tag'."
11915 (interactive)
11916 (let* ((t1 org-track-ordered-property-with-tag)
11917 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11918 (save-excursion
11919 (org-back-to-heading)
11920 (if (org-entry-get nil "ORDERED")
11921 (progn
11922 (org-delete-property "ORDERED")
11923 (and tag (org-toggle-tag tag 'off))
11924 (message "Subtasks can be completed in arbitrary order"))
11925 (org-entry-put nil "ORDERED" "t")
11926 (and tag (org-toggle-tag tag 'on))
11927 (message "Subtasks must be completed in sequence")))))
11929 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11930 (defun org-block-todo-from-checkboxes (change-plist)
11931 "Block turning an entry into a TODO, using checkboxes.
11932 This checks whether the current task should be blocked from state
11933 changes because there are unchecked boxes in this entry."
11934 (if (not org-enforce-todo-checkbox-dependencies)
11935 t ; if locally turned off don't block
11936 (catch 'dont-block
11937 ;; If this is not a todo state change, or if this entry is already DONE,
11938 ;; do not block
11939 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11940 (member (plist-get change-plist :from)
11941 (cons 'done org-done-keywords))
11942 (member (plist-get change-plist :to)
11943 (cons 'todo org-not-done-keywords))
11944 (not (plist-get change-plist :to)))
11945 (throw 'dont-block t))
11946 ;; If this task has checkboxes that are not checked, it's blocked
11947 (save-excursion
11948 (org-back-to-heading t)
11949 (let ((beg (point)) end)
11950 (outline-next-heading)
11951 (setq end (point))
11952 (goto-char beg)
11953 (if (org-list-search-forward
11954 (concat (org-item-beginning-re)
11955 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11956 "\\[[- ]\\]")
11957 end t)
11958 (progn
11959 (if (boundp 'org-blocked-by-checkboxes)
11960 (setq org-blocked-by-checkboxes t))
11961 (throw 'dont-block nil)))))
11962 t))) ; do not block
11964 (defun org-entry-blocked-p ()
11965 "Is the current entry blocked?"
11966 (if (org-entry-get nil "NOBLOCKING")
11967 nil ;; Never block this entry
11968 (not
11969 (run-hook-with-args-until-failure
11970 'org-blocker-hook
11971 (list :type 'todo-state-change
11972 :position (point)
11973 :from 'todo
11974 :to 'done)))))
11976 (defun org-update-statistics-cookies (all)
11977 "Update the statistics cookie, either from TODO or from checkboxes.
11978 This should be called with the cursor in a line with a statistics cookie."
11979 (interactive "P")
11980 (if all
11981 (progn
11982 (org-update-checkbox-count 'all)
11983 (org-map-entries 'org-update-parent-todo-statistics))
11984 (if (not (org-at-heading-p))
11985 (org-update-checkbox-count)
11986 (let ((pos (move-marker (make-marker) (point)))
11987 end l1 l2)
11988 (ignore-errors (org-back-to-heading t))
11989 (if (not (org-at-heading-p))
11990 (org-update-checkbox-count)
11991 (setq l1 (org-outline-level))
11992 (setq end (save-excursion
11993 (outline-next-heading)
11994 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11995 (point)))
11996 (if (and (save-excursion
11997 (re-search-forward
11998 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11999 (not (save-excursion (re-search-forward
12000 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12001 (org-update-checkbox-count)
12002 (if (and l2 (> l2 l1))
12003 (progn
12004 (goto-char end)
12005 (org-update-parent-todo-statistics))
12006 (goto-char pos)
12007 (beginning-of-line 1)
12008 (while (re-search-forward
12009 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12010 (point-at-eol) t)
12011 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12012 (goto-char pos)
12013 (move-marker pos nil)))))
12015 (defvar org-entry-property-inherited-from) ;; defined below
12016 (defun org-update-parent-todo-statistics ()
12017 "Update any statistics cookie in the parent of the current headline.
12018 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12019 the entire subtree and this will travel up the hierarchy and update
12020 statistics everywhere."
12021 (let* ((prop (save-excursion (org-up-heading-safe)
12022 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12023 (recursive (or (not org-hierarchical-todo-statistics)
12024 (and prop (string-match "\\<recursive\\>" prop))))
12025 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12027 (first t)
12028 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12029 level ltoggle l1 new ndel
12030 (cnt-all 0) (cnt-done 0) is-percent kwd
12031 checkbox-beg ov ovs ove cookie-present)
12032 (catch 'exit
12033 (save-excursion
12034 (beginning-of-line 1)
12035 (setq ltoggle (funcall outline-level))
12036 ;; Three situations are to consider:
12038 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12039 ;; to the top-level ancestor on the headline;
12041 ;; 2. If parent has "recursive" property, repeat up to the
12042 ;; headline setting that property, taking inheritance into
12043 ;; account;
12045 ;; 3. Else, move up to direct parent and proceed only once.
12046 (while (and (setq level (org-up-heading-safe))
12047 (or recursive first)
12048 (>= (point) lim))
12049 (setq first nil cookie-present nil)
12050 (unless (and level
12051 (not (string-match
12052 "\\<checkbox\\>"
12053 (downcase (or (org-entry-get nil "COOKIE_DATA")
12054 "")))))
12055 (throw 'exit nil))
12056 (while (re-search-forward box-re (point-at-eol) t)
12057 (setq cnt-all 0 cnt-done 0 cookie-present t)
12058 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12059 (save-match-data
12060 (unless (outline-next-heading) (throw 'exit nil))
12061 (while (and (looking-at org-complex-heading-regexp)
12062 (> (setq l1 (length (match-string 1))) level))
12063 (setq kwd (and (or recursive (= l1 ltoggle))
12064 (match-string 2)))
12065 (if (or (eq org-provide-todo-statistics 'all-headlines)
12066 (and (listp org-provide-todo-statistics)
12067 (or (member kwd org-provide-todo-statistics)
12068 (member kwd org-done-keywords))))
12069 (setq cnt-all (1+ cnt-all))
12070 (if (eq org-provide-todo-statistics t)
12071 (and kwd (setq cnt-all (1+ cnt-all)))))
12072 (and (member kwd org-done-keywords)
12073 (setq cnt-done (1+ cnt-done)))
12074 (outline-next-heading)))
12075 (setq new
12076 (if is-percent
12077 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12078 (format "[%d/%d]" cnt-done cnt-all))
12079 ndel (- (match-end 0) checkbox-beg))
12080 ;; handle overlays when updating cookie from column view
12081 (when (setq ov (car (overlays-at checkbox-beg)))
12082 (setq ovs (overlay-start ov) ove (overlay-end ov))
12083 (delete-overlay ov))
12084 (goto-char checkbox-beg)
12085 (insert new)
12086 (delete-region (point) (+ (point) ndel))
12087 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12088 (when ov (move-overlay ov ovs ove)))
12089 (when cookie-present
12090 (run-hook-with-args 'org-after-todo-statistics-hook
12091 cnt-done (- cnt-all cnt-done))))))
12092 (run-hooks 'org-todo-statistics-hook)))
12094 (defvar org-after-todo-statistics-hook nil
12095 "Hook that is called after a TODO statistics cookie has been updated.
12096 Each function is called with two arguments: the number of not-done entries
12097 and the number of done entries.
12099 For example, the following function, when added to this hook, will switch
12100 an entry to DONE when all children are done, and back to TODO when new
12101 entries are set to a TODO status. Note that this hook is only called
12102 when there is a statistics cookie in the headline!
12104 (defun org-summary-todo (n-done n-not-done)
12105 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12106 (let (org-log-done org-log-states) ; turn off logging
12107 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12110 (defvar org-todo-statistics-hook nil
12111 "Hook that is run whenever Org thinks TODO statistics should be updated.
12112 This hook runs even if there is no statistics cookie present, in which case
12113 `org-after-todo-statistics-hook' would not run.")
12115 (defun org-todo-trigger-tag-changes (state)
12116 "Apply the changes defined in `org-todo-state-tags-triggers'."
12117 (let ((l org-todo-state-tags-triggers)
12118 changes)
12119 (when (or (not state) (equal state ""))
12120 (setq changes (append changes (cdr (assoc "" l)))))
12121 (when (and (stringp state) (> (length state) 0))
12122 (setq changes (append changes (cdr (assoc state l)))))
12123 (when (member state org-not-done-keywords)
12124 (setq changes (append changes (cdr (assoc 'todo l)))))
12125 (when (member state org-done-keywords)
12126 (setq changes (append changes (cdr (assoc 'done l)))))
12127 (dolist (c changes)
12128 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12130 (defun org-local-logging (value)
12131 "Get logging settings from a property VALUE."
12132 (let* (words w a)
12133 ;; directly set the variables, they are already local.
12134 (setq org-log-done nil
12135 org-log-repeat nil
12136 org-todo-log-states nil)
12137 (setq words (org-split-string value))
12138 (while (setq w (pop words))
12139 (cond
12140 ((setq a (assoc w org-startup-options))
12141 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12142 (set (nth 1 a) (nth 2 a))))
12143 ((setq a (org-extract-log-state-settings w))
12144 (and (member (car a) org-todo-keywords-1)
12145 (push a org-todo-log-states)))))))
12147 (defun org-get-todo-sequence-head (kwd)
12148 "Return the head of the TODO sequence to which KWD belongs.
12149 If KWD is not set, check if there is a text property remembering the
12150 right sequence."
12151 (let (p)
12152 (cond
12153 ((not kwd)
12154 (or (get-text-property (point-at-bol) 'org-todo-head)
12155 (progn
12156 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12157 nil (point-at-eol)))
12158 (get-text-property p 'org-todo-head))))
12159 ((not (member kwd org-todo-keywords-1))
12160 (car org-todo-keywords-1))
12161 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12163 (defun org-fast-todo-selection ()
12164 "Fast TODO keyword selection with single keys.
12165 Returns the new TODO keyword, or nil if no state change should occur."
12166 (let* ((fulltable org-todo-key-alist)
12167 (done-keywords org-done-keywords) ;; needed for the faces.
12168 (maxlen (apply 'max (mapcar
12169 (lambda (x)
12170 (if (stringp (car x)) (string-width (car x)) 0))
12171 fulltable)))
12172 (expert nil)
12173 (fwidth (+ maxlen 3 1 3))
12174 (ncol (/ (- (window-width) 4) fwidth))
12175 tg cnt e c tbl
12176 groups ingroup)
12177 (save-excursion
12178 (save-window-excursion
12179 (if expert
12180 (set-buffer (get-buffer-create " *Org todo*"))
12181 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12182 (erase-buffer)
12183 (org-set-local 'org-done-keywords done-keywords)
12184 (setq tbl fulltable cnt 0)
12185 (while (setq e (pop tbl))
12186 (cond
12187 ((equal e '(:startgroup))
12188 (push '() groups) (setq ingroup t)
12189 (when (not (= cnt 0))
12190 (setq cnt 0)
12191 (insert "\n"))
12192 (insert "{ "))
12193 ((equal e '(:endgroup))
12194 (setq ingroup nil cnt 0)
12195 (insert "}\n"))
12196 ((equal e '(:newline))
12197 (when (not (= cnt 0))
12198 (setq cnt 0)
12199 (insert "\n")
12200 (setq e (car tbl))
12201 (while (equal (car tbl) '(:newline))
12202 (insert "\n")
12203 (setq tbl (cdr tbl)))))
12205 (setq tg (car e) c (cdr e))
12206 (if ingroup (push tg (car groups)))
12207 (setq tg (org-add-props tg nil 'face
12208 (org-get-todo-face tg)))
12209 (if (and (= cnt 0) (not ingroup)) (insert " "))
12210 (insert "[" c "] " tg (make-string
12211 (- fwidth 4 (length tg)) ?\ ))
12212 (when (= (setq cnt (1+ cnt)) ncol)
12213 (insert "\n")
12214 (if ingroup (insert " "))
12215 (setq cnt 0)))))
12216 (insert "\n")
12217 (goto-char (point-min))
12218 (if (not expert) (org-fit-window-to-buffer))
12219 (message "[a-z..]:Set [SPC]:clear")
12220 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12221 (cond
12222 ((or (= c ?\C-g)
12223 (and (= c ?q) (not (rassoc c fulltable))))
12224 (setq quit-flag t))
12225 ((= c ?\ ) nil)
12226 ((setq e (rassoc c fulltable) tg (car e))
12228 (t (setq quit-flag t)))))))
12230 (defun org-entry-is-todo-p ()
12231 (member (org-get-todo-state) org-not-done-keywords))
12233 (defun org-entry-is-done-p ()
12234 (member (org-get-todo-state) org-done-keywords))
12236 (defun org-get-todo-state ()
12237 (save-excursion
12238 (org-back-to-heading t)
12239 (and (looking-at org-todo-line-regexp)
12240 (match-end 2)
12241 (match-string 2))))
12243 (defun org-at-date-range-p (&optional inactive-ok)
12244 "Is the cursor inside a date range?"
12245 (interactive)
12246 (save-excursion
12247 (catch 'exit
12248 (let ((pos (point)))
12249 (skip-chars-backward "^[<\r\n")
12250 (skip-chars-backward "<[")
12251 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12252 (>= (match-end 0) pos)
12253 (throw 'exit t))
12254 (skip-chars-backward "^<[\r\n")
12255 (skip-chars-backward "<[")
12256 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12257 (>= (match-end 0) pos)
12258 (throw 'exit t)))
12259 nil)))
12261 (defun org-get-repeat (&optional tagline)
12262 "Check if there is a deadline/schedule with repeater in this entry."
12263 (save-match-data
12264 (save-excursion
12265 (org-back-to-heading t)
12266 (and (re-search-forward (if tagline
12267 (concat tagline "\\s-*" org-repeat-re)
12268 org-repeat-re)
12269 (org-entry-end-position) t)
12270 (match-string-no-properties 1)))))
12272 (defvar org-last-changed-timestamp)
12273 (defvar org-last-inserted-timestamp)
12274 (defvar org-log-post-message)
12275 (defvar org-log-note-purpose)
12276 (defvar org-log-note-how)
12277 (defvar org-log-note-extra)
12278 (defun org-auto-repeat-maybe (done-word)
12279 "Check if the current headline contains a repeated deadline/schedule.
12280 If yes, set TODO state back to what it was and change the base date
12281 of repeating deadline/scheduled time stamps to new date.
12282 This function is run automatically after each state change to a DONE state."
12283 ;; last-state is dynamically scoped into this function
12284 (let* ((repeat (org-get-repeat))
12285 (aa (assoc org-last-state org-todo-kwd-alist))
12286 (interpret (nth 1 aa))
12287 (head (nth 2 aa))
12288 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12289 (msg "Entry repeats: ")
12290 (org-log-done nil)
12291 (org-todo-log-states nil)
12292 re type n what ts time to-state)
12293 (when repeat
12294 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12295 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12296 org-todo-repeat-to-state))
12297 (unless (and to-state (member to-state org-todo-keywords-1))
12298 (setq to-state (if (eq interpret 'type) org-last-state head)))
12299 (org-todo to-state)
12300 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12301 (org-entry-put nil "LAST_REPEAT" (format-time-string
12302 (org-time-stamp-format t t))))
12303 (when org-log-repeat
12304 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12305 (memq 'org-add-log-note post-command-hook))
12306 ;; OK, we are already setup for some record
12307 (if (eq org-log-repeat 'note)
12308 ;; make sure we take a note, not only a time stamp
12309 (setq org-log-note-how 'note))
12310 ;; Set up for taking a record
12311 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12312 org-last-state
12313 'findpos org-log-repeat)))
12314 (org-back-to-heading t)
12315 (org-add-planning-info nil nil 'closed)
12316 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12317 org-deadline-time-regexp "\\)\\|\\("
12318 org-ts-regexp "\\)"))
12319 (while (re-search-forward
12320 re (save-excursion (outline-next-heading) (point)) t)
12321 (setq type (if (match-end 1) org-scheduled-string
12322 (if (match-end 3) org-deadline-string "Plain:"))
12323 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12324 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12325 (setq n (string-to-number (match-string 2 ts))
12326 what (match-string 3 ts))
12327 (if (equal what "w") (setq n (* n 7) what "d"))
12328 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12329 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12330 ;; Preparation, see if we need to modify the start date for the change
12331 (when (match-end 1)
12332 (setq time (save-match-data (org-time-string-to-time ts)))
12333 (cond
12334 ((equal (match-string 1 ts) ".")
12335 ;; Shift starting date to today
12336 (org-timestamp-change
12337 (- (org-today) (time-to-days time))
12338 'day))
12339 ((equal (match-string 1 ts) "+")
12340 (let ((nshiftmax 10) (nshift 0))
12341 (while (or (= nshift 0)
12342 (<= (time-to-days time)
12343 (time-to-days (current-time))))
12344 (when (= (incf nshift) nshiftmax)
12345 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12346 (error "Abort")))
12347 (org-timestamp-change n (cdr (assoc what whata)))
12348 (org-at-timestamp-p t)
12349 (setq ts (match-string 1))
12350 (setq time (save-match-data (org-time-string-to-time ts)))))
12351 (org-timestamp-change (- n) (cdr (assoc what whata)))
12352 ;; rematch, so that we have everything in place for the real shift
12353 (org-at-timestamp-p t)
12354 (setq ts (match-string 1))
12355 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12356 (org-timestamp-change n (cdr (assoc what whata)))
12357 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12358 (setq org-log-post-message msg)
12359 (message "%s" msg))))
12361 (defun org-show-todo-tree (arg)
12362 "Make a compact tree which shows all headlines marked with TODO.
12363 The tree will show the lines where the regexp matches, and all higher
12364 headlines above the match.
12365 With a \\[universal-argument] prefix, prompt for a regexp to match.
12366 With a numeric prefix N, construct a sparse tree for the Nth element
12367 of `org-todo-keywords-1'."
12368 (interactive "P")
12369 (let ((case-fold-search nil)
12370 (kwd-re
12371 (cond ((null arg) org-not-done-regexp)
12372 ((equal arg '(4))
12373 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12374 (mapcar 'list org-todo-keywords-1))))
12375 (concat "\\("
12376 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12377 "\\)\\>")))
12378 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12379 (regexp-quote (nth (1- (prefix-numeric-value arg))
12380 org-todo-keywords-1)))
12381 (t (error "Invalid prefix argument: %s" arg)))))
12382 (message "%d TODO entries found"
12383 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12385 (defun org-deadline (&optional remove time)
12386 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12387 With argument REMOVE, remove any deadline from the item.
12388 With argument TIME, set the deadline at the corresponding date. TIME
12389 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12390 (interactive "P")
12391 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12392 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12393 'region-start-level 'region))
12394 org-loop-over-headlines-in-active-region)
12395 (org-map-entries
12396 `(org-deadline ',remove ,time)
12397 org-loop-over-headlines-in-active-region
12398 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12399 (let* ((old-date (org-entry-get nil "DEADLINE"))
12400 (repeater (and old-date
12401 (string-match
12402 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12403 old-date)
12404 (match-string 1 old-date))))
12405 (if remove
12406 (progn
12407 (when (and old-date org-log-redeadline)
12408 (org-add-log-setup 'deldeadline nil old-date 'findpos
12409 org-log-redeadline))
12410 (org-remove-timestamp-with-keyword org-deadline-string)
12411 (message "Item no longer has a deadline."))
12412 (org-add-planning-info 'deadline time 'closed)
12413 (when (and old-date org-log-redeadline
12414 (not (equal old-date
12415 (substring org-last-inserted-timestamp 1 -1))))
12416 (org-add-log-setup 'redeadline nil old-date 'findpos
12417 org-log-redeadline))
12418 (when repeater
12419 (save-excursion
12420 (org-back-to-heading t)
12421 (when (re-search-forward (concat org-deadline-string " "
12422 org-last-inserted-timestamp)
12423 (save-excursion
12424 (outline-next-heading) (point)) t)
12425 (goto-char (1- (match-end 0)))
12426 (insert " " repeater)
12427 (setq org-last-inserted-timestamp
12428 (concat (substring org-last-inserted-timestamp 0 -1)
12429 " " repeater
12430 (substring org-last-inserted-timestamp -1))))))
12431 (message "Deadline on %s" org-last-inserted-timestamp)))))
12433 (defun org-schedule (&optional remove time)
12434 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12435 With argument REMOVE, remove any scheduling date from the item.
12436 With argument TIME, scheduled at the corresponding date. TIME can
12437 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12438 (interactive "P")
12439 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12440 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12441 'region-start-level 'region))
12442 org-loop-over-headlines-in-active-region)
12443 (org-map-entries
12444 `(org-schedule ',remove ,time)
12445 org-loop-over-headlines-in-active-region
12446 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12447 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12448 (repeater (and old-date
12449 (string-match
12450 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12451 old-date)
12452 (match-string 1 old-date))))
12453 (if remove
12454 (progn
12455 (when (and old-date org-log-reschedule)
12456 (org-add-log-setup 'delschedule nil old-date 'findpos
12457 org-log-reschedule))
12458 (org-remove-timestamp-with-keyword org-scheduled-string)
12459 (message "Item is no longer scheduled."))
12460 (org-add-planning-info 'scheduled time 'closed)
12461 (when (and old-date org-log-reschedule
12462 (not (equal old-date
12463 (substring org-last-inserted-timestamp 1 -1))))
12464 (org-add-log-setup 'reschedule nil old-date 'findpos
12465 org-log-reschedule))
12466 (when repeater
12467 (save-excursion
12468 (org-back-to-heading t)
12469 (when (re-search-forward (concat org-scheduled-string " "
12470 org-last-inserted-timestamp)
12471 (save-excursion
12472 (outline-next-heading) (point)) t)
12473 (goto-char (1- (match-end 0)))
12474 (insert " " repeater)
12475 (setq org-last-inserted-timestamp
12476 (concat (substring org-last-inserted-timestamp 0 -1)
12477 " " repeater
12478 (substring org-last-inserted-timestamp -1))))))
12479 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12481 (defun org-get-scheduled-time (pom &optional inherit)
12482 "Get the scheduled time as a time tuple, of a format suitable
12483 for calling org-schedule with, or if there is no scheduling,
12484 returns nil."
12485 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12486 (when time
12487 (apply 'encode-time (org-parse-time-string time)))))
12489 (defun org-get-deadline-time (pom &optional inherit)
12490 "Get the deadline as a time tuple, of a format suitable for
12491 calling org-deadline with, or if there is no scheduling, returns
12492 nil."
12493 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12494 (when time
12495 (apply 'encode-time (org-parse-time-string time)))))
12497 (defun org-remove-timestamp-with-keyword (keyword)
12498 "Remove all time stamps with KEYWORD in the current entry."
12499 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12500 beg)
12501 (save-excursion
12502 (org-back-to-heading t)
12503 (setq beg (point))
12504 (outline-next-heading)
12505 (while (re-search-backward re beg t)
12506 (replace-match "")
12507 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12508 (equal (char-before) ?\ ))
12509 (backward-delete-char 1)
12510 (if (string-match "^[ \t]*$" (buffer-substring
12511 (point-at-bol) (point-at-eol)))
12512 (delete-region (point-at-bol)
12513 (min (point-max) (1+ (point-at-eol))))))))))
12515 (defun org-add-planning-info (what &optional time &rest remove)
12516 "Insert new timestamp with keyword in the line directly after the headline.
12517 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12518 If non is given, the user is prompted for a date.
12519 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12520 be removed."
12521 (interactive)
12522 (let (org-time-was-given org-end-time-was-given ts
12523 end default-time default-input)
12525 (catch 'exit
12526 (when (and (memq what '(scheduled deadline))
12527 (or (not time)
12528 (and (stringp time)
12529 (string-match "^[-+]+[0-9]" time))))
12530 ;; Try to get a default date/time from existing timestamp
12531 (save-excursion
12532 (org-back-to-heading t)
12533 (setq end (save-excursion (outline-next-heading) (point)))
12534 (when (re-search-forward (if (eq what 'scheduled)
12535 org-scheduled-time-regexp
12536 org-deadline-time-regexp)
12537 end t)
12538 (setq ts (match-string 1)
12539 default-time
12540 (apply 'encode-time (org-parse-time-string ts))
12541 default-input (and ts (org-get-compact-tod ts))))))
12542 (when what
12543 (setq time
12544 (if (stringp time)
12545 ;; This is a string (relative or absolute), set proper date
12546 (apply 'encode-time
12547 (org-read-date-analyze
12548 time default-time (decode-time default-time)))
12549 ;; If necessary, get the time from the user
12550 (or time (org-read-date nil 'to-time nil nil
12551 default-time default-input)))))
12553 (when (and org-insert-labeled-timestamps-at-point
12554 (member what '(scheduled deadline)))
12555 (insert
12556 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12557 (org-insert-time-stamp time org-time-was-given
12558 nil nil nil (list org-end-time-was-given))
12559 (setq what nil))
12560 (save-excursion
12561 (save-restriction
12562 (let (col list elt ts buffer-invisibility-spec)
12563 (org-back-to-heading t)
12564 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12565 (goto-char (match-end 1))
12566 (setq col (current-column))
12567 (goto-char (match-end 0))
12568 (if (eobp) (insert "\n") (forward-char 1))
12569 (when (and (not what)
12570 (not (looking-at
12571 (concat "[ \t]*"
12572 org-keyword-time-not-clock-regexp))))
12573 ;; Nothing to add, nothing to remove...... :-)
12574 (throw 'exit nil))
12575 (if (and (not (looking-at org-outline-regexp))
12576 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12577 "[^\r\n]*"))
12578 (not (equal (match-string 1) org-clock-string)))
12579 (narrow-to-region (match-beginning 0) (match-end 0))
12580 (insert-before-markers "\n")
12581 (backward-char 1)
12582 (narrow-to-region (point) (point))
12583 (and org-adapt-indentation (org-indent-to-column col)))
12584 ;; Check if we have to remove something.
12585 (setq list (cons what remove))
12586 (while list
12587 (setq elt (pop list))
12588 (when (or (and (eq elt 'scheduled)
12589 (re-search-forward org-scheduled-time-regexp nil t))
12590 (and (eq elt 'deadline)
12591 (re-search-forward org-deadline-time-regexp nil t))
12592 (and (eq elt 'closed)
12593 (re-search-forward org-closed-time-regexp nil t)))
12594 (replace-match "")
12595 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12596 (and (looking-at "[ \t]+") (replace-match ""))
12597 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12598 (when what
12599 (insert
12600 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12601 (cond ((eq what 'scheduled) org-scheduled-string)
12602 ((eq what 'deadline) org-deadline-string)
12603 ((eq what 'closed) org-closed-string))
12604 " ")
12605 (setq ts (org-insert-time-stamp
12606 time
12607 (or org-time-was-given
12608 (and (eq what 'closed) org-log-done-with-time))
12609 (eq what 'closed)
12610 nil nil (list org-end-time-was-given)))
12611 (insert
12612 (if (not (or (bolp) (eq (char-before) ?\ )
12613 (memq (char-after) '(32 10))
12614 (eobp))) " " ""))
12615 (end-of-line 1))
12616 (goto-char (point-min))
12617 (widen)
12618 (if (and (looking-at "[ \t]*\n")
12619 (equal (char-before) ?\n))
12620 (delete-region (1- (point)) (point-at-eol)))
12621 ts))))))
12623 (defvar org-log-note-marker (make-marker))
12624 (defvar org-log-note-purpose nil)
12625 (defvar org-log-note-state nil)
12626 (defvar org-log-note-previous-state nil)
12627 (defvar org-log-note-how nil)
12628 (defvar org-log-note-extra nil)
12629 (defvar org-log-note-window-configuration nil)
12630 (defvar org-log-note-return-to (make-marker))
12631 (defvar org-log-note-effective-time nil
12632 "Remembered current time so that dynamically scoped
12633 `org-extend-today-until' affects tha timestamps in state change
12634 log")
12636 (defvar org-log-post-message nil
12637 "Message to be displayed after a log note has been stored.
12638 The auto-repeater uses this.")
12640 (defun org-add-note ()
12641 "Add a note to the current entry.
12642 This is done in the same way as adding a state change note."
12643 (interactive)
12644 (org-add-log-setup 'note nil nil 'findpos nil))
12646 (defvar org-property-end-re)
12647 (defun org-add-log-setup (&optional purpose state prev-state
12648 findpos how extra)
12649 "Set up the post command hook to take a note.
12650 If this is about to TODO state change, the new state is expected in STATE.
12651 When FINDPOS is non-nil, find the correct position for the note in
12652 the current entry. If not, assume that it can be inserted at point.
12653 HOW is an indicator what kind of note should be created.
12654 EXTRA is additional text that will be inserted into the notes buffer."
12655 (let* ((org-log-into-drawer (org-log-into-drawer))
12656 (drawer (cond ((stringp org-log-into-drawer)
12657 org-log-into-drawer)
12658 (org-log-into-drawer "LOGBOOK"))))
12659 (save-restriction
12660 (save-excursion
12661 (when findpos
12662 (org-back-to-heading t)
12663 (narrow-to-region (point) (save-excursion
12664 (outline-next-heading) (point)))
12665 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12666 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12667 "[^\r\n]*\\)?"))
12668 (goto-char (match-end 0))
12669 (cond
12670 (drawer
12671 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12672 nil t)
12673 (progn
12674 (goto-char (match-end 0))
12675 (or org-log-states-order-reversed
12676 (and (re-search-forward org-property-end-re nil t)
12677 (goto-char (1- (match-beginning 0))))))
12678 (insert "\n:" drawer ":\n:END:")
12679 (beginning-of-line 0)
12680 (org-indent-line)
12681 (beginning-of-line 2)
12682 (org-indent-line)
12683 (end-of-line 0)))
12684 ((and org-log-state-notes-insert-after-drawers
12685 (save-excursion
12686 (forward-line) (looking-at org-drawer-regexp)))
12687 (forward-line)
12688 (while (looking-at org-drawer-regexp)
12689 (goto-char (match-end 0))
12690 (re-search-forward org-property-end-re (point-max) t)
12691 (forward-line))
12692 (forward-line -1)))
12693 (unless org-log-states-order-reversed
12694 (and (= (char-after) ?\n) (forward-char 1))
12695 (org-skip-over-state-notes)
12696 (skip-chars-backward " \t\n\r")))
12697 (move-marker org-log-note-marker (point))
12698 (setq org-log-note-purpose purpose
12699 org-log-note-state state
12700 org-log-note-previous-state prev-state
12701 org-log-note-how how
12702 org-log-note-extra extra
12703 org-log-note-effective-time (org-current-effective-time))
12704 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12706 (defun org-skip-over-state-notes ()
12707 "Skip past the list of State notes in an entry."
12708 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12709 (when (ignore-errors (goto-char (org-in-item-p)))
12710 (let* ((struct (org-list-struct))
12711 (prevs (org-list-prevs-alist struct)))
12712 (while (looking-at "[ \t]*- State")
12713 (goto-char (or (org-list-get-next-item (point) struct prevs)
12714 (org-list-get-item-end (point) struct)))))))
12716 (defun org-add-log-note (&optional purpose)
12717 "Pop up a window for taking a note, and add this note later at point."
12718 (remove-hook 'post-command-hook 'org-add-log-note)
12719 (setq org-log-note-window-configuration (current-window-configuration))
12720 (delete-other-windows)
12721 (move-marker org-log-note-return-to (point))
12722 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12723 (goto-char org-log-note-marker)
12724 (org-switch-to-buffer-other-window "*Org Note*")
12725 (erase-buffer)
12726 (if (memq org-log-note-how '(time state))
12727 (let (current-prefix-arg) (org-store-log-note))
12728 (let ((org-inhibit-startup t)) (org-mode))
12729 (insert (format "# Insert note for %s.
12730 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12731 (cond
12732 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12733 ((eq org-log-note-purpose 'done) "closed todo item")
12734 ((eq org-log-note-purpose 'state)
12735 (format "state change from \"%s\" to \"%s\""
12736 (or org-log-note-previous-state "")
12737 (or org-log-note-state "")))
12738 ((eq org-log-note-purpose 'reschedule)
12739 "rescheduling")
12740 ((eq org-log-note-purpose 'delschedule)
12741 "no longer scheduled")
12742 ((eq org-log-note-purpose 'redeadline)
12743 "changing deadline")
12744 ((eq org-log-note-purpose 'deldeadline)
12745 "removing deadline")
12746 ((eq org-log-note-purpose 'refile)
12747 "refiling")
12748 ((eq org-log-note-purpose 'note)
12749 "this entry")
12750 (t (error "This should not happen")))))
12751 (if org-log-note-extra (insert org-log-note-extra))
12752 (org-set-local 'org-finish-function 'org-store-log-note)
12753 (run-hooks 'org-log-buffer-setup-hook)))
12755 (defvar org-note-abort nil) ; dynamically scoped
12756 (defun org-store-log-note ()
12757 "Finish taking a log note, and insert it to where it belongs."
12758 (let ((txt (buffer-string))
12759 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12760 lines ind bul)
12761 (kill-buffer (current-buffer))
12762 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12763 (setq txt (replace-match "" t t txt)))
12764 (if (string-match "\\s-+\\'" txt)
12765 (setq txt (replace-match "" t t txt)))
12766 (setq lines (org-split-string txt "\n"))
12767 (when (and note (string-match "\\S-" note))
12768 (setq note
12769 (org-replace-escapes
12770 note
12771 (list (cons "%u" (user-login-name))
12772 (cons "%U" user-full-name)
12773 (cons "%t" (format-time-string
12774 (org-time-stamp-format 'long 'inactive)
12775 org-log-note-effective-time))
12776 (cons "%T" (format-time-string
12777 (org-time-stamp-format 'long nil)
12778 org-log-note-effective-time))
12779 (cons "%d" (format-time-string
12780 (org-time-stamp-format nil 'inactive)
12781 org-log-note-effective-time))
12782 (cons "%D" (format-time-string
12783 (org-time-stamp-format nil nil)
12784 org-log-note-effective-time))
12785 (cons "%s" (if org-log-note-state
12786 (concat "\"" org-log-note-state "\"")
12787 ""))
12788 (cons "%S" (if org-log-note-previous-state
12789 (concat "\"" org-log-note-previous-state "\"")
12790 "\"\"")))))
12791 (if lines (setq note (concat note " \\\\")))
12792 (push note lines))
12793 (when (or current-prefix-arg org-note-abort)
12794 (when org-log-into-drawer
12795 (org-remove-empty-drawer-at
12796 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12797 org-log-note-marker))
12798 (setq lines nil))
12799 (when lines
12800 (with-current-buffer (marker-buffer org-log-note-marker)
12801 (save-excursion
12802 (goto-char org-log-note-marker)
12803 (move-marker org-log-note-marker nil)
12804 (end-of-line 1)
12805 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12806 (setq ind (save-excursion
12807 (if (ignore-errors (goto-char (org-in-item-p)))
12808 (let ((struct (org-list-struct)))
12809 (org-list-get-ind
12810 (org-list-get-top-point struct) struct))
12811 (skip-chars-backward " \r\t\n")
12812 (cond
12813 ((and (org-at-heading-p)
12814 org-adapt-indentation)
12815 (1+ (org-current-level)))
12816 ((org-at-heading-p) 0)
12817 (t (org-get-indentation))))))
12818 (setq bul (org-list-bullet-string "-"))
12819 (org-indent-line-to ind)
12820 (insert bul (pop lines))
12821 (let ((ind-body (+ (length bul) ind)))
12822 (while lines
12823 (insert "\n")
12824 (org-indent-line-to ind-body)
12825 (insert (pop lines))))
12826 (message "Note stored")
12827 (org-back-to-heading t)
12828 (org-cycle-hide-drawers 'children)))))
12829 (set-window-configuration org-log-note-window-configuration)
12830 (with-current-buffer (marker-buffer org-log-note-return-to)
12831 (goto-char org-log-note-return-to))
12832 (move-marker org-log-note-return-to nil)
12833 (and org-log-post-message (message "%s" org-log-post-message)))
12835 (defun org-remove-empty-drawer-at (drawer pos)
12836 "Remove an empty drawer DRAWER at position POS.
12837 POS may also be a marker."
12838 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12839 (save-excursion
12840 (save-restriction
12841 (widen)
12842 (goto-char pos)
12843 (if (org-in-regexp
12844 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12845 (replace-match ""))))))
12847 (defvar org-ts-type nil)
12848 (defun org-sparse-tree (&optional arg type)
12849 "Create a sparse tree, prompt for the details.
12850 This command can create sparse trees. You first need to select the type
12851 of match used to create the tree:
12853 t Show all TODO entries.
12854 T Show entries with a specific TODO keyword.
12855 m Show entries selected by a tags/property match.
12856 p Enter a property name and its value (both with completion on existing
12857 names/values) and show entries with that property.
12858 r Show entries matching a regular expression (`/' can be used as well).
12859 b Show deadlines and scheduled items before a date.
12860 a Show deadlines and scheduled items after a date.
12861 d Show deadlines due within `org-deadline-warning-days'.
12862 D Show deadlines and scheduled items between a date range."
12863 (interactive "P")
12864 (let (ans kwd value ts-type)
12865 (setq type (or type org-sparse-tree-default-date-type))
12866 (setq org-ts-type type)
12867 (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"
12868 (cond ((eq type 'all) "all timestamps")
12869 ((eq type 'scheduled) "only scheduled")
12870 ((eq type 'deadline) "only deadline")
12871 ((eq type 'active) "only active timestamps")
12872 ((eq type 'inactive) "only inactive timestamps")
12873 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12874 (t "scheduled/deadline")))
12875 (setq ans (read-char-exclusive))
12876 (cond
12877 ((equal ans ?c)
12878 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12879 ((equal ans ?d)
12880 (call-interactively 'org-check-deadlines))
12881 ((equal ans ?b)
12882 (call-interactively 'org-check-before-date))
12883 ((equal ans ?a)
12884 (call-interactively 'org-check-after-date))
12885 ((equal ans ?D)
12886 (call-interactively 'org-check-dates-range))
12887 ((equal ans ?t)
12888 (org-show-todo-tree nil))
12889 ((equal ans ?T)
12890 (org-show-todo-tree '(4)))
12891 ((member ans '(?T ?m))
12892 (call-interactively 'org-match-sparse-tree))
12893 ((member ans '(?p ?P))
12894 (setq kwd (org-icompleting-read "Property: "
12895 (mapcar 'list (org-buffer-property-keys))))
12896 (setq value (org-icompleting-read "Value: "
12897 (mapcar 'list (org-property-values kwd))))
12898 (unless (string-match "\\`{.*}\\'" value)
12899 (setq value (concat "\"" value "\"")))
12900 (org-match-sparse-tree arg (concat kwd "=" value)))
12901 ((member ans '(?r ?R ?/))
12902 (call-interactively 'org-occur))
12903 (t (error "No such sparse tree command \"%c\"" ans)))))
12905 (defvar org-occur-highlights nil
12906 "List of overlays used for occur matches.")
12907 (make-variable-buffer-local 'org-occur-highlights)
12908 (defvar org-occur-parameters nil
12909 "Parameters of the active org-occur calls.
12910 This is a list, each call to org-occur pushes as cons cell,
12911 containing the regular expression and the callback, onto the list.
12912 The list can contain several entries if `org-occur' has been called
12913 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12914 will only contain one set of parameters. When the highlights are
12915 removed (for example with `C-c C-c', or with the next edit (depending
12916 on `org-remove-highlights-with-change'), this variable is emptied
12917 as well.")
12918 (make-variable-buffer-local 'org-occur-parameters)
12920 (defun org-occur (regexp &optional keep-previous callback)
12921 "Make a compact tree which shows all matches of REGEXP.
12922 The tree will show the lines where the regexp matches, and all higher
12923 headlines above the match. It will also show the heading after the match,
12924 to make sure editing the matching entry is easy.
12925 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12926 call to `org-occur' will be kept, to allow stacking of calls to this
12927 command.
12928 If CALLBACK is non-nil, it is a function which is called to confirm
12929 that the match should indeed be shown."
12930 (interactive "sRegexp: \nP")
12931 (when (equal regexp "")
12932 (error "Regexp cannot be empty"))
12933 (unless keep-previous
12934 (org-remove-occur-highlights nil nil t))
12935 (push (cons regexp callback) org-occur-parameters)
12936 (let ((cnt 0))
12937 (save-excursion
12938 (goto-char (point-min))
12939 (if (or (not keep-previous) ; do not want to keep
12940 (not org-occur-highlights)) ; no previous matches
12941 ;; hide everything
12942 (org-overview))
12943 (while (re-search-forward regexp nil t)
12944 (when (or (not callback)
12945 (save-match-data (funcall callback)))
12946 (setq cnt (1+ cnt))
12947 (when org-highlight-sparse-tree-matches
12948 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12949 (org-show-context 'occur-tree))))
12950 (when org-remove-highlights-with-change
12951 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12952 nil 'local))
12953 (unless org-sparse-tree-open-archived-trees
12954 (org-hide-archived-subtrees (point-min) (point-max)))
12955 (run-hooks 'org-occur-hook)
12956 (if (org-called-interactively-p 'interactive)
12957 (message "%d match(es) for regexp %s" cnt regexp))
12958 cnt))
12960 (defun org-occur-next-match (&optional n reset)
12961 "Function for `next-error-function' to find sparse tree matches.
12962 N is the number of matches to move, when negative move backwards.
12963 RESET is entirely ignored - this function always goes back to the
12964 starting point when no match is found."
12965 (let* ((limit (if (< n 0) (point-min) (point-max)))
12966 (search-func (if (< n 0)
12967 'previous-single-char-property-change
12968 'next-single-char-property-change))
12969 (n (abs n))
12970 (pos (point))
12972 (catch 'exit
12973 (while (setq p1 (funcall search-func (point) 'org-type))
12974 (when (equal p1 limit)
12975 (goto-char pos)
12976 (error "No more matches"))
12977 (when (equal (get-char-property p1 'org-type) 'org-occur)
12978 (setq n (1- n))
12979 (when (= n 0)
12980 (goto-char p1)
12981 (throw 'exit (point))))
12982 (goto-char p1))
12983 (goto-char p1)
12984 (error "No more matches"))))
12986 (defun org-show-context (&optional key)
12987 "Make sure point and context are visible.
12988 How much context is shown depends upon the variables
12989 `org-show-hierarchy-above', `org-show-following-heading',
12990 `org-show-entry-below' and `org-show-siblings'."
12991 (let ((heading-p (org-at-heading-p t))
12992 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12993 (following-p (org-get-alist-option org-show-following-heading key))
12994 (entry-p (org-get-alist-option org-show-entry-below key))
12995 (siblings-p (org-get-alist-option org-show-siblings key)))
12996 (catch 'exit
12997 ;; Show heading or entry text
12998 (if (and heading-p (not entry-p))
12999 (org-flag-heading nil) ; only show the heading
13000 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13001 (org-show-hidden-entry))) ; show entire entry
13002 (when following-p
13003 ;; Show next sibling, or heading below text
13004 (save-excursion
13005 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13006 (org-flag-heading nil))))
13007 (when siblings-p (org-show-siblings))
13008 (when hierarchy-p
13009 ;; show all higher headings, possibly with siblings
13010 (save-excursion
13011 (while (and (condition-case nil
13012 (progn (org-up-heading-all 1) t)
13013 (error nil))
13014 (not (bobp)))
13015 (org-flag-heading nil)
13016 (when siblings-p (org-show-siblings))))))))
13018 (defvar org-reveal-start-hook nil
13019 "Hook run before revealing a location.")
13021 (defun org-reveal (&optional siblings)
13022 "Show current entry, hierarchy above it, and the following headline.
13023 This can be used to show a consistent set of context around locations
13024 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13025 not t for the search context.
13027 With optional argument SIBLINGS, on each level of the hierarchy all
13028 siblings are shown. This repairs the tree structure to what it would
13029 look like when opened with hierarchical calls to `org-cycle'.
13030 With double optional argument \\[universal-argument] \\[universal-argument], \
13031 go to the parent and show the
13032 entire tree."
13033 (interactive "P")
13034 (run-hooks 'org-reveal-start-hook)
13035 (let ((org-show-hierarchy-above t)
13036 (org-show-following-heading t)
13037 (org-show-siblings (if siblings t org-show-siblings)))
13038 (org-show-context nil))
13039 (when (equal siblings '(16))
13040 (save-excursion
13041 (when (org-up-heading-safe)
13042 (org-show-subtree)
13043 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13045 (defun org-highlight-new-match (beg end)
13046 "Highlight from BEG to END and mark the highlight is an occur headline."
13047 (let ((ov (make-overlay beg end)))
13048 (overlay-put ov 'face 'secondary-selection)
13049 (overlay-put ov 'org-type 'org-occur)
13050 (push ov org-occur-highlights)))
13052 (defun org-remove-occur-highlights (&optional beg end noremove)
13053 "Remove the occur highlights from the buffer.
13054 BEG and END are ignored. If NOREMOVE is nil, remove this function
13055 from the `before-change-functions' in the current buffer."
13056 (interactive)
13057 (unless org-inhibit-highlight-removal
13058 (mapc 'delete-overlay org-occur-highlights)
13059 (setq org-occur-highlights nil)
13060 (setq org-occur-parameters nil)
13061 (unless noremove
13062 (remove-hook 'before-change-functions
13063 'org-remove-occur-highlights 'local))))
13065 ;;;; Priorities
13067 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13068 "Regular expression matching the priority indicator.")
13070 (defvar org-remove-priority-next-time nil)
13072 (defun org-priority-up ()
13073 "Increase the priority of the current item."
13074 (interactive)
13075 (org-priority 'up))
13077 (defun org-priority-down ()
13078 "Decrease the priority of the current item."
13079 (interactive)
13080 (org-priority 'down))
13082 (defun org-priority (&optional action show)
13083 "Change the priority of an item.
13084 ACTION can be `set', `up', `down', or a character."
13085 (interactive "P")
13086 (if (equal action '(4))
13087 (org-show-priority)
13088 (unless org-enable-priority-commands
13089 (error "Priority commands are disabled"))
13090 (setq action (or action 'set))
13091 (let (current new news have remove)
13092 (save-excursion
13093 (org-back-to-heading t)
13094 (if (looking-at org-priority-regexp)
13095 (setq current (string-to-char (match-string 2))
13096 have t))
13097 (cond
13098 ((eq action 'remove)
13099 (setq remove t new ?\ ))
13100 ((or (eq action 'set)
13101 (if (featurep 'xemacs) (characterp action) (integerp action)))
13102 (if (not (eq action 'set))
13103 (setq new action)
13104 (message "Priority %c-%c, SPC to remove: "
13105 org-highest-priority org-lowest-priority)
13106 (save-match-data
13107 (setq new (read-char-exclusive))))
13108 (if (and (= (upcase org-highest-priority) org-highest-priority)
13109 (= (upcase org-lowest-priority) org-lowest-priority))
13110 (setq new (upcase new)))
13111 (cond ((equal new ?\ ) (setq remove t))
13112 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13113 (error "Priority must be between `%c' and `%c'"
13114 org-highest-priority org-lowest-priority))))
13115 ((eq action 'up)
13116 (setq new (if have
13117 (1- current) ; normal cycling
13118 ;; last priority was empty
13119 (if (eq last-command this-command)
13120 org-lowest-priority ; wrap around empty to lowest
13121 ;; default
13122 (if org-priority-start-cycle-with-default
13123 org-default-priority
13124 (1- org-default-priority))))))
13125 ((eq action 'down)
13126 (setq new (if have
13127 (1+ current) ; normal cycling
13128 ;; last priority was empty
13129 (if (eq last-command this-command)
13130 org-highest-priority ; wrap around empty to highest
13131 ;; default
13132 (if org-priority-start-cycle-with-default
13133 org-default-priority
13134 (1+ org-default-priority))))))
13135 (t (error "Invalid action")))
13136 (if (or (< (upcase new) org-highest-priority)
13137 (> (upcase new) org-lowest-priority))
13138 (if (and (memq action '(up down))
13139 (not have) (not (eq last-command this-command)))
13140 ;; `new' is from default priority
13141 (error
13142 "The default can not be set, see `org-default-priority' why")
13143 ;; normal cycling: `new' is beyond highest/lowest priority
13144 ;; and is wrapped around to the empty priority
13145 (setq remove t)))
13146 (setq news (format "%c" new))
13147 (if have
13148 (if remove
13149 (replace-match "" t t nil 1)
13150 (replace-match news t t nil 2))
13151 (if remove
13152 (error "No priority cookie found in line")
13153 (let ((case-fold-search nil))
13154 (looking-at org-todo-line-regexp))
13155 (if (match-end 2)
13156 (progn
13157 (goto-char (match-end 2))
13158 (insert " [#" news "]"))
13159 (goto-char (match-beginning 3))
13160 (insert "[#" news "] "))))
13161 (org-preserve-lc (org-set-tags nil 'align)))
13162 (if remove
13163 (message "Priority removed")
13164 (message "Priority of current item set to %s" news)))))
13166 (defun org-show-priority ()
13167 "Show the priority of the current item.
13168 This priority is composed of the main priority given with the [#A] cookies,
13169 and by additional input from the age of a schedules or deadline entry."
13170 (interactive)
13171 (let ((pri (if (eq major-mode 'org-agenda-mode)
13172 (org-get-at-bol 'priority)
13173 (save-excursion
13174 (save-match-data
13175 (beginning-of-line)
13176 (and (looking-at org-heading-regexp)
13177 (org-get-priority (match-string 0))))))))
13178 (message "Priority is %d" (if pri pri -1000))))
13180 (defun org-get-priority (s)
13181 "Find priority cookie and return priority."
13182 (if (functionp org-get-priority-function)
13183 (funcall org-get-priority-function)
13184 (save-match-data
13185 (if (not (string-match org-priority-regexp s))
13186 (* 1000 (- org-lowest-priority org-default-priority))
13187 (* 1000 (- org-lowest-priority
13188 (string-to-char (match-string 2 s))))))))
13190 ;;;; Tags
13192 (defvar org-agenda-archives-mode)
13193 (defvar org-map-continue-from nil
13194 "Position from where mapping should continue.
13195 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13197 (defvar org-scanner-tags nil
13198 "The current tag list while the tags scanner is running.")
13199 (defvar org-trust-scanner-tags nil
13200 "Should `org-get-tags-at' use the tags for the scanner.
13201 This is for internal dynamical scoping only.
13202 When this is non-nil, the function `org-get-tags-at' will return the value
13203 of `org-scanner-tags' instead of building the list by itself. This
13204 can lead to large speed-ups when the tags scanner is used in a file with
13205 many entries, and when the list of tags is retrieved, for example to
13206 obtain a list of properties. Building the tags list for each entry in such
13207 a file becomes an N^2 operation - but with this variable set, it scales
13208 as N.")
13210 (defun org-scan-tags (action matcher todo-only &optional start-level)
13211 "Scan headline tags with inheritance and produce output ACTION.
13213 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13214 or `agenda' to produce an entry list for an agenda view. It can also be
13215 a Lisp form or a function that should be called at each matched headline, in
13216 this case the return value is a list of all return values from these calls.
13218 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13219 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13220 only lines with a not-done TODO keyword are included in the output.
13221 This should be the same variable that was scoped into
13222 and set by `org-make-tags-matcher' when it constructed MATCHER.
13224 START-LEVEL can be a string with asterisks, reducing the scope to
13225 headlines matching this string."
13226 (require 'org-agenda)
13227 (let* ((re (concat "^"
13228 (if start-level
13229 ;; Get the correct level to match
13230 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13231 org-outline-regexp)
13232 " *\\(\\<\\("
13233 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13234 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13235 (props (list 'face 'default
13236 'done-face 'org-agenda-done
13237 'undone-face 'default
13238 'mouse-face 'highlight
13239 'org-not-done-regexp org-not-done-regexp
13240 'org-todo-regexp org-todo-regexp
13241 'org-complex-heading-regexp org-complex-heading-regexp
13242 'help-echo
13243 (format "mouse-2 or RET jump to org file %s"
13244 (abbreviate-file-name
13245 (or (buffer-file-name (buffer-base-buffer))
13246 (buffer-name (buffer-base-buffer)))))))
13247 (case-fold-search nil)
13248 (org-map-continue-from nil)
13249 lspos tags tags-list
13250 (tags-alist (list (cons 0 org-file-tags)))
13251 (llast 0) rtn rtn1 level category i txt
13252 todo marker entry priority)
13253 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13254 (setq action (list 'lambda nil action)))
13255 (save-excursion
13256 (goto-char (point-min))
13257 (when (eq action 'sparse-tree)
13258 (org-overview)
13259 (org-remove-occur-highlights))
13260 (while (re-search-forward re nil t)
13261 (setq org-map-continue-from nil)
13262 (catch :skip
13263 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13264 tags (if (match-end 4) (org-match-string-no-properties 4)))
13265 (goto-char (setq lspos (match-beginning 0)))
13266 (setq level (org-reduced-level (org-outline-level))
13267 category (org-get-category))
13268 (setq i llast llast level)
13269 ;; remove tag lists from same and sublevels
13270 (while (>= i level)
13271 (when (setq entry (assoc i tags-alist))
13272 (setq tags-alist (delete entry tags-alist)))
13273 (setq i (1- i)))
13274 ;; add the next tags
13275 (when tags
13276 (setq tags (org-split-string tags ":")
13277 tags-alist
13278 (cons (cons level tags) tags-alist)))
13279 ;; compile tags for current headline
13280 (setq tags-list
13281 (if org-use-tag-inheritance
13282 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13283 tags)
13284 org-scanner-tags tags-list)
13285 (when org-use-tag-inheritance
13286 (setcdr (car tags-alist)
13287 (mapcar (lambda (x)
13288 (setq x (copy-sequence x))
13289 (org-add-prop-inherited x))
13290 (cdar tags-alist))))
13291 (when (and tags org-use-tag-inheritance
13292 (or (not (eq t org-use-tag-inheritance))
13293 org-tags-exclude-from-inheritance))
13294 ;; selective inheritance, remove uninherited ones
13295 (setcdr (car tags-alist)
13296 (org-remove-uninherited-tags (cdar tags-alist))))
13297 (when (and
13299 ;; eval matcher only when the todo condition is OK
13300 (and (or (not todo-only) (member todo org-not-done-keywords))
13301 (let ((case-fold-search t) (org-trust-scanner-tags t))
13302 (eval matcher)))
13304 ;; Call the skipper, but return t if it does not skip,
13305 ;; so that the `and' form continues evaluating
13306 (progn
13307 (unless (eq action 'sparse-tree) (org-agenda-skip))
13310 ;; Check if timestamps are deselecting this entry
13311 (or (not todo-only)
13312 (and (member todo org-not-done-keywords)
13313 (or (not org-agenda-tags-todo-honor-ignore-options)
13314 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13316 ;; Extra check for the archive tag
13317 ;; FIXME: Does the skipper already do this????
13319 (not (member org-archive-tag tags-list))
13320 ;; we have an archive tag, should we use this anyway?
13321 (or (not org-agenda-skip-archived-trees)
13322 (and (eq action 'agenda) org-agenda-archives-mode))))
13324 ;; select this headline
13325 (cond
13326 ((eq action 'sparse-tree)
13327 (and org-highlight-sparse-tree-matches
13328 (org-get-heading) (match-end 0)
13329 (org-highlight-new-match
13330 (match-beginning 1) (match-end 1)))
13331 (org-show-context 'tags-tree))
13332 ((eq action 'agenda)
13333 (setq txt (org-agenda-format-item
13335 (concat
13336 (if (eq org-tags-match-list-sublevels 'indented)
13337 (make-string (1- level) ?.) "")
13338 (org-get-heading))
13339 level category
13340 tags-list)
13341 priority (org-get-priority txt))
13342 (goto-char lspos)
13343 (setq marker (org-agenda-new-marker))
13344 (org-add-props txt props
13345 'org-marker marker 'org-hd-marker marker 'org-category category
13346 'todo-state todo
13347 'priority priority 'type "tagsmatch")
13348 (push txt rtn))
13349 ((functionp action)
13350 (setq org-map-continue-from nil)
13351 (save-excursion
13352 (setq rtn1 (funcall action))
13353 (push rtn1 rtn)))
13354 (t (error "Invalid action")))
13356 ;; if we are to skip sublevels, jump to end of subtree
13357 (unless org-tags-match-list-sublevels
13358 (org-end-of-subtree t)
13359 (backward-char 1))))
13360 ;; Get the correct position from where to continue
13361 (if org-map-continue-from
13362 (goto-char org-map-continue-from)
13363 (and (= (point) lspos) (end-of-line 1)))))
13364 (when (and (eq action 'sparse-tree)
13365 (not org-sparse-tree-open-archived-trees))
13366 (org-hide-archived-subtrees (point-min) (point-max)))
13367 (nreverse rtn)))
13369 (defun org-remove-uninherited-tags (tags)
13370 "Remove all tags that are not inherited from the list TAGS."
13371 (cond
13372 ((eq org-use-tag-inheritance t)
13373 (if org-tags-exclude-from-inheritance
13374 (org-delete-all org-tags-exclude-from-inheritance tags)
13375 tags))
13376 ((not org-use-tag-inheritance) nil)
13377 ((stringp org-use-tag-inheritance)
13378 (delq nil (mapcar
13379 (lambda (x)
13380 (if (and (string-match org-use-tag-inheritance x)
13381 (not (member x org-tags-exclude-from-inheritance)))
13382 x nil))
13383 tags)))
13384 ((listp org-use-tag-inheritance)
13385 (delq nil (mapcar
13386 (lambda (x)
13387 (if (member x org-use-tag-inheritance) x nil))
13388 tags)))))
13390 (defun org-match-sparse-tree (&optional todo-only match)
13391 "Create a sparse tree according to tags string MATCH.
13392 MATCH can contain positive and negative selection of tags, like
13393 \"+WORK+URGENT-WITHBOSS\".
13394 If optional argument TODO-ONLY is non-nil, only select lines that are
13395 also TODO lines."
13396 (interactive "P")
13397 (org-agenda-prepare-buffers (list (current-buffer)))
13398 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13400 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13402 (defvar org-cached-props nil)
13403 (defun org-cached-entry-get (pom property)
13404 (if (or (eq t org-use-property-inheritance)
13405 (and (stringp org-use-property-inheritance)
13406 (string-match org-use-property-inheritance property))
13407 (and (listp org-use-property-inheritance)
13408 (member property org-use-property-inheritance)))
13409 ;; Caching is not possible, check it directly
13410 (org-entry-get pom property 'inherit)
13411 ;; Get all properties, so that we can do complicated checks easily
13412 (cdr (assoc property (or org-cached-props
13413 (setq org-cached-props
13414 (org-entry-properties pom)))))))
13416 (defun org-global-tags-completion-table (&optional files)
13417 "Return the list of all tags in all agenda buffer/files.
13418 Optional FILES argument is a list of files which can be used
13419 instead of the agenda files."
13420 (save-excursion
13421 (org-uniquify
13422 (delq nil
13423 (apply 'append
13424 (mapcar
13425 (lambda (file)
13426 (set-buffer (find-file-noselect file))
13427 (append (org-get-buffer-tags)
13428 (mapcar (lambda (x) (if (stringp (car-safe x))
13429 (list (car-safe x)) nil))
13430 org-tag-alist)))
13431 (if (and files (car files))
13432 files
13433 (org-agenda-files))))))))
13435 (defun org-make-tags-matcher (match)
13436 "Create the TAGS/TODO matcher form for the selection string MATCH.
13438 The variable `todo-only' is scoped dynamically into this function.
13439 It will be set to t if the matcher restricts matching to TODO entries,
13440 otherwise will not be touched.
13442 Returns a cons of the selection string MATCH and the constructed
13443 lisp form implementing the matcher. The matcher is to be evaluated
13444 at an Org entry, with point on the headline, and returns t if the
13445 entry matches the selection string MATCH. The returned lisp form
13446 references two variables with information about the entry, which
13447 must be bound around the form's evaluation: todo, the TODO keyword
13448 at the entry (or nil of none); and tags-list, the list of all tags
13449 at the entry including inherited ones. Additionally, the category
13450 of the entry (if any) must be specified as the text property
13451 'org-category on the headline.
13453 See also `org-scan-tags'.
13455 (declare (special todo-only))
13456 (unless (boundp 'todo-only)
13457 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13458 (unless match
13459 ;; Get a new match request, with completion
13460 (let ((org-last-tags-completion-table
13461 (org-global-tags-completion-table)))
13462 (setq match (org-completing-read-no-i
13463 "Match: " 'org-tags-completion-function nil nil nil
13464 'org-tags-history))))
13466 ;; Parse the string and create a lisp form
13467 (let ((match0 match)
13468 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13469 minus tag mm
13470 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13471 orterms term orlist re-p str-p level-p level-op time-p
13472 prop-p pn pv po gv rest)
13473 (if (string-match "/+" match)
13474 ;; match contains also a todo-matching request
13475 (progn
13476 (setq tagsmatch (substring match 0 (match-beginning 0))
13477 todomatch (substring match (match-end 0)))
13478 (if (string-match "^!" todomatch)
13479 (setq todo-only t todomatch (substring todomatch 1)))
13480 (if (string-match "^\\s-*$" todomatch)
13481 (setq todomatch nil)))
13482 ;; only matching tags
13483 (setq tagsmatch match todomatch nil))
13485 ;; Make the tags matcher
13486 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13487 (setq tagsmatcher t)
13488 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13489 (while (setq term (pop orterms))
13490 (while (and (equal (substring term -1) "\\") orterms)
13491 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13492 (while (string-match re term)
13493 (setq rest (substring term (match-end 0))
13494 minus (and (match-end 1)
13495 (equal (match-string 1 term) "-"))
13496 tag (save-match-data (replace-regexp-in-string
13497 "\\\\-" "-"
13498 (match-string 2 term)))
13499 re-p (equal (string-to-char tag) ?{)
13500 level-p (match-end 4)
13501 prop-p (match-end 5)
13502 mm (cond
13503 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13504 (level-p
13505 (setq level-op (org-op-to-function (match-string 3 term)))
13506 `(,level-op level ,(string-to-number
13507 (match-string 4 term))))
13508 (prop-p
13509 (setq pn (match-string 5 term)
13510 po (match-string 6 term)
13511 pv (match-string 7 term)
13512 re-p (equal (string-to-char pv) ?{)
13513 str-p (equal (string-to-char pv) ?\")
13514 time-p (save-match-data
13515 (string-match "^\"[[<].*[]>]\"$" pv))
13516 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13517 (if time-p (setq pv (org-matcher-time pv)))
13518 (setq po (org-op-to-function po (if time-p 'time str-p)))
13519 (cond
13520 ((equal pn "CATEGORY")
13521 (setq gv '(get-text-property (point) 'org-category)))
13522 ((equal pn "TODO")
13523 (setq gv 'todo))
13525 (setq gv `(org-cached-entry-get nil ,pn))))
13526 (if re-p
13527 (if (eq po 'org<>)
13528 `(not (string-match ,pv (or ,gv "")))
13529 `(string-match ,pv (or ,gv "")))
13530 (if str-p
13531 `(,po (or ,gv "") ,pv)
13532 `(,po (string-to-number (or ,gv ""))
13533 ,(string-to-number pv) ))))
13534 (t `(member ,tag tags-list)))
13535 mm (if minus (list 'not mm) mm)
13536 term rest)
13537 (push mm tagsmatcher))
13538 (push (if (> (length tagsmatcher) 1)
13539 (cons 'and tagsmatcher)
13540 (car tagsmatcher))
13541 orlist)
13542 (setq tagsmatcher nil))
13543 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13544 (setq tagsmatcher
13545 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13546 ;; Make the todo matcher
13547 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13548 (setq todomatcher t)
13549 (setq orterms (org-split-string todomatch "|") orlist nil)
13550 (while (setq term (pop orterms))
13551 (while (string-match re term)
13552 (setq minus (and (match-end 1)
13553 (equal (match-string 1 term) "-"))
13554 kwd (match-string 2 term)
13555 re-p (equal (string-to-char kwd) ?{)
13556 term (substring term (match-end 0))
13557 mm (if re-p
13558 `(string-match ,(substring kwd 1 -1) todo)
13559 (list 'equal 'todo kwd))
13560 mm (if minus (list 'not mm) mm))
13561 (push mm todomatcher))
13562 (push (if (> (length todomatcher) 1)
13563 (cons 'and todomatcher)
13564 (car todomatcher))
13565 orlist)
13566 (setq todomatcher nil))
13567 (setq todomatcher (if (> (length orlist) 1)
13568 (cons 'or orlist) (car orlist))))
13570 ;; Return the string and lisp forms of the matcher
13571 (setq matcher (if todomatcher
13572 (list 'and tagsmatcher todomatcher)
13573 tagsmatcher))
13574 (when todo-only
13575 (setq matcher (list 'and '(member todo org-not-done-keywords)
13576 matcher)))
13577 (cons match0 matcher)))
13579 (defun org-op-to-function (op &optional stringp)
13580 "Turn an operator into the appropriate function."
13581 (setq op
13582 (cond
13583 ((equal op "<" ) '(< string< org-time<))
13584 ((equal op ">" ) '(> org-string> org-time>))
13585 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13586 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13587 ((member op '("=" "==")) '(= string= org-time=))
13588 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13589 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13591 (defun org<> (a b) (not (= a b)))
13592 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13593 (defun org-string>= (a b) (not (string< a b)))
13594 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13595 (defun org-string<> (a b) (not (string= 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) (> a b)))
13600 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13601 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13602 (defun org-2ft (s)
13603 "Convert S to a floating point time.
13604 If S is already a number, just return it. If it is a string, parse
13605 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13606 (cond
13607 ((numberp s) s)
13608 ((stringp s)
13609 (condition-case nil
13610 (float-time (apply 'encode-time (org-parse-time-string s)))
13611 (error 0.)))
13612 (t 0.)))
13614 (defun org-time-today ()
13615 "Time in seconds today at 0:00.
13616 Returns the float number of seconds since the beginning of the
13617 epoch to the beginning of today (00:00)."
13618 (float-time (apply 'encode-time
13619 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13621 (defun org-matcher-time (s)
13622 "Interpret a time comparison value."
13623 (save-match-data
13624 (cond
13625 ((string= s "<now>") (float-time))
13626 ((string= s "<today>") (org-time-today))
13627 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13628 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13629 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13630 (+ (org-time-today)
13631 (* (string-to-number (match-string 1 s))
13632 (cdr (assoc (match-string 2 s)
13633 '(("d" . 86400.0) ("w" . 604800.0)
13634 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13635 (t (org-2ft s)))))
13637 (defun org-match-any-p (re list)
13638 "Does re match any element of list?"
13639 (setq list (mapcar (lambda (x) (string-match re x)) list))
13640 (delq nil list))
13642 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13643 (defvar org-tags-overlay (make-overlay 1 1))
13644 (org-detach-overlay org-tags-overlay)
13646 (defun org-get-local-tags-at (&optional pos)
13647 "Get a list of tags defined in the current headline."
13648 (org-get-tags-at pos 'local))
13650 (defun org-get-local-tags ()
13651 "Get a list of tags defined in the current headline."
13652 (org-get-tags-at nil 'local))
13654 (defun org-get-tags-at (&optional pos local)
13655 "Get a list of all headline tags applicable at POS.
13656 POS defaults to point. If tags are inherited, the list contains
13657 the targets in the same sequence as the headlines appear, i.e.
13658 the tags of the current headline come last.
13659 When LOCAL is non-nil, only return tags from the current headline,
13660 ignore inherited ones."
13661 (interactive)
13662 (if (and org-trust-scanner-tags
13663 (or (not pos) (equal pos (point)))
13664 (not local))
13665 org-scanner-tags
13666 (let (tags ltags lastpos parent)
13667 (save-excursion
13668 (save-restriction
13669 (widen)
13670 (goto-char (or pos (point)))
13671 (save-match-data
13672 (catch 'done
13673 (condition-case nil
13674 (progn
13675 (org-back-to-heading t)
13676 (while (not (equal lastpos (point)))
13677 (setq lastpos (point))
13678 (when (looking-at
13679 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13680 (setq ltags (org-split-string
13681 (org-match-string-no-properties 1) ":"))
13682 (when parent
13683 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13684 (setq tags (append
13685 (if parent
13686 (org-remove-uninherited-tags ltags)
13687 ltags)
13688 tags)))
13689 (or org-use-tag-inheritance (throw 'done t))
13690 (if local (throw 'done t))
13691 (or (org-up-heading-safe) (error nil))
13692 (setq parent t)))
13693 (error nil)))))
13694 (if local
13695 tags
13696 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13698 (defun org-add-prop-inherited (s)
13699 (add-text-properties 0 (length s) '(inherited t) s)
13702 (defun org-toggle-tag (tag &optional onoff)
13703 "Toggle the tag TAG for the current line.
13704 If ONOFF is `on' or `off', don't toggle but set to this state."
13705 (let (res current)
13706 (save-excursion
13707 (org-back-to-heading t)
13708 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13709 (point-at-eol) t)
13710 (progn
13711 (setq current (match-string 1))
13712 (replace-match ""))
13713 (setq current ""))
13714 (setq current (nreverse (org-split-string current ":")))
13715 (cond
13716 ((eq onoff 'on)
13717 (setq res t)
13718 (or (member tag current) (push tag current)))
13719 ((eq onoff 'off)
13720 (or (not (member tag current)) (setq current (delete tag current))))
13721 (t (if (member tag current)
13722 (setq current (delete tag current))
13723 (setq res t)
13724 (push tag current))))
13725 (end-of-line 1)
13726 (if current
13727 (progn
13728 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13729 (org-set-tags nil t))
13730 (delete-horizontal-space))
13731 (run-hooks 'org-after-tags-change-hook))
13732 res))
13734 (defun org-align-tags-here (to-col)
13735 ;; Assumes that this is a headline
13736 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13737 (beginning-of-line 1)
13738 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13739 (< pos (match-beginning 2)))
13740 (progn
13741 (setq tags-l (- (match-end 2) (match-beginning 2)))
13742 (goto-char (match-beginning 1))
13743 (insert " ")
13744 (delete-region (point) (1+ (match-beginning 2)))
13745 (setq ncol (max (current-column)
13746 (1+ col)
13747 (if (> to-col 0)
13748 to-col
13749 (- (abs to-col) tags-l))))
13750 (setq p (point))
13751 (insert (make-string (- ncol (current-column)) ?\ ))
13752 (setq ncol (current-column))
13753 (when indent-tabs-mode (tabify p (point-at-eol)))
13754 (org-move-to-column (min ncol col) t))
13755 (goto-char pos))))
13757 (defun org-set-tags-command (&optional arg just-align)
13758 "Call the set-tags command for the current entry."
13759 (interactive "P")
13760 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13761 (org-set-tags arg just-align)
13762 (save-excursion
13763 (org-back-to-heading t)
13764 (org-set-tags arg just-align))))
13766 (defun org-set-tags-to (data)
13767 "Set the tags of the current entry to DATA, replacing the current tags.
13768 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13769 If DATA is nil or the empty string, any tags will be removed."
13770 (interactive "sTags: ")
13771 (setq data
13772 (cond
13773 ((eq data nil) "")
13774 ((equal data "") "")
13775 ((stringp data)
13776 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13777 ":"))
13778 ((listp data)
13779 (concat ":" (mapconcat 'identity data ":") ":"))))
13780 (when data
13781 (save-excursion
13782 (org-back-to-heading t)
13783 (when (looking-at org-complex-heading-regexp)
13784 (if (match-end 5)
13785 (progn
13786 (goto-char (match-beginning 5))
13787 (insert data)
13788 (delete-region (point) (point-at-eol))
13789 (org-set-tags nil 'align))
13790 (goto-char (point-at-eol))
13791 (insert " " data)
13792 (org-set-tags nil 'align)))
13793 (beginning-of-line 1)
13794 (if (looking-at ".*?\\([ \t]+\\)$")
13795 (delete-region (match-beginning 1) (match-end 1))))))
13797 (defun org-align-all-tags ()
13798 "Align the tags i all headings."
13799 (interactive)
13800 (save-excursion
13801 (or (ignore-errors (org-back-to-heading t))
13802 (outline-next-heading))
13803 (if (org-at-heading-p)
13804 (org-set-tags t)
13805 (message "No headings"))))
13807 (defvar org-indent-indentation-per-level)
13808 (defun org-set-tags (&optional arg just-align)
13809 "Set the tags for the current headline.
13810 With prefix ARG, realign all tags in headings in the current buffer."
13811 (interactive "P")
13812 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13813 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13814 'region-start-level 'region))
13815 org-loop-over-headlines-in-active-region)
13816 (org-map-entries
13817 ;; We don't use ARG and JUST-ALIGN here these args are not
13818 ;; useful when looping over headlines
13819 `(org-set-tags)
13820 org-loop-over-headlines-in-active-region
13821 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13822 (let* ((re org-outline-regexp-bol)
13823 (current (unless arg (org-get-tags-string)))
13824 (col (current-column))
13825 (org-setting-tags t)
13826 table current-tags inherited-tags ; computed below when needed
13827 tags p0 c0 c1 rpl di tc level)
13828 (if arg
13829 (save-excursion
13830 (goto-char (point-min))
13831 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13832 (while (re-search-forward re nil t)
13833 (org-set-tags nil t)
13834 (end-of-line 1)))
13835 (message "All tags realigned to column %d" org-tags-column))
13836 (if just-align
13837 (setq tags current)
13838 ;; Get a new set of tags from the user
13839 (save-excursion
13840 (setq table (append org-tag-persistent-alist
13841 (or org-tag-alist (org-get-buffer-tags))
13842 (and
13843 org-complete-tags-always-offer-all-agenda-tags
13844 (org-global-tags-completion-table
13845 (org-agenda-files))))
13846 org-last-tags-completion-table table
13847 current-tags (org-split-string current ":")
13848 inherited-tags (nreverse
13849 (nthcdr (length current-tags)
13850 (nreverse (org-get-tags-at))))
13851 tags
13852 (if (or (eq t org-use-fast-tag-selection)
13853 (and org-use-fast-tag-selection
13854 (delq nil (mapcar 'cdr table))))
13855 (org-fast-tag-selection
13856 current-tags inherited-tags table
13857 (if org-fast-tag-selection-include-todo
13858 org-todo-key-alist))
13859 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13860 (org-trim
13861 (org-icompleting-read "Tags: "
13862 'org-tags-completion-function
13863 nil nil current 'org-tags-history))))))
13864 (while (string-match "[-+&]+" tags)
13865 ;; No boolean logic, just a list
13866 (setq tags (replace-match ":" t t tags))))
13868 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13870 (if org-tags-sort-function
13871 (setq tags (mapconcat 'identity
13872 (sort (org-split-string
13873 tags (org-re "[^[:alnum:]_@#%]+"))
13874 org-tags-sort-function) ":")))
13876 (if (string-match "\\`[\t ]*\\'" tags)
13877 (setq tags "")
13878 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13879 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13881 ;; Insert new tags at the correct column
13882 (beginning-of-line 1)
13883 (setq level (or (and (looking-at org-outline-regexp)
13884 (- (match-end 0) (point) 1))
13886 (cond
13887 ((and (equal current "") (equal tags "")))
13888 ((re-search-forward
13889 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13890 (point-at-eol) t)
13891 (if (equal tags "")
13892 (setq rpl "")
13893 (goto-char (match-beginning 0))
13894 (setq c0 (current-column)
13895 ;; compute offset for the case of org-indent-mode active
13896 di (if org-indent-mode
13897 (* (1- org-indent-indentation-per-level) (1- level))
13899 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13900 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13901 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13902 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13903 (replace-match rpl t t)
13904 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13905 tags)
13906 (t (error "Tags alignment failed")))
13907 (org-move-to-column col)
13908 (unless just-align
13909 (run-hooks 'org-after-tags-change-hook))))))
13911 (defun org-change-tag-in-region (beg end tag off)
13912 "Add or remove TAG for each entry in the region.
13913 This works in the agenda, and also in an org-mode buffer."
13914 (interactive
13915 (list (region-beginning) (region-end)
13916 (let ((org-last-tags-completion-table
13917 (if (derived-mode-p 'org-mode)
13918 (org-get-buffer-tags)
13919 (org-global-tags-completion-table))))
13920 (org-icompleting-read
13921 "Tag: " 'org-tags-completion-function nil nil nil
13922 'org-tags-history))
13923 (progn
13924 (message "[s]et or [r]emove? ")
13925 (equal (read-char-exclusive) ?r))))
13926 (if (fboundp 'deactivate-mark) (deactivate-mark))
13927 (let ((agendap (equal major-mode 'org-agenda-mode))
13928 l1 l2 m buf pos newhead (cnt 0))
13929 (goto-char end)
13930 (setq l2 (1- (org-current-line)))
13931 (goto-char beg)
13932 (setq l1 (org-current-line))
13933 (loop for l from l1 to l2 do
13934 (org-goto-line l)
13935 (setq m (get-text-property (point) 'org-hd-marker))
13936 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13937 (and agendap m))
13938 (setq buf (if agendap (marker-buffer m) (current-buffer))
13939 pos (if agendap m (point)))
13940 (with-current-buffer buf
13941 (save-excursion
13942 (save-restriction
13943 (goto-char pos)
13944 (setq cnt (1+ cnt))
13945 (org-toggle-tag tag (if off 'off 'on))
13946 (setq newhead (org-get-heading)))))
13947 (and agendap (org-agenda-change-all-lines newhead m))))
13948 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13950 (defun org-tags-completion-function (string predicate &optional flag)
13951 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13952 (confirm (lambda (x) (stringp (car x)))))
13953 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13954 (setq s1 (match-string 1 string)
13955 s2 (match-string 2 string))
13956 (setq s1 "" s2 string))
13957 (cond
13958 ((eq flag nil)
13959 ;; try completion
13960 (setq rtn (try-completion s2 ctable confirm))
13961 (if (stringp rtn)
13962 (setq rtn
13963 (concat s1 s2 (substring rtn (length s2))
13964 (if (and org-add-colon-after-tag-completion
13965 (assoc rtn ctable))
13966 ":" ""))))
13967 rtn)
13968 ((eq flag t)
13969 ;; all-completions
13970 (all-completions s2 ctable confirm)
13972 ((eq flag 'lambda)
13973 ;; exact match?
13974 (assoc s2 ctable)))
13977 (defun org-fast-tag-insert (kwd tags face &optional end)
13978 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13979 (insert (format "%-12s" (concat kwd ":"))
13980 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13981 (or end "")))
13983 (defun org-fast-tag-show-exit (flag)
13984 (save-excursion
13985 (org-goto-line 3)
13986 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13987 (replace-match ""))
13988 (when flag
13989 (end-of-line 1)
13990 (org-move-to-column (- (window-width) 19) t)
13991 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13993 (defun org-set-current-tags-overlay (current prefix)
13994 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13995 (if (featurep 'xemacs)
13996 (org-overlay-display org-tags-overlay (concat prefix s)
13997 'secondary-selection)
13998 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13999 (org-overlay-display org-tags-overlay (concat prefix s)))))
14001 (defvar org-last-tag-selection-key nil)
14002 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14003 "Fast tag selection with single keys.
14004 CURRENT is the current list of tags in the headline, INHERITED is the
14005 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14006 possibly with grouping information. TODO-TABLE is a similar table with
14007 TODO keywords, should these have keys assigned to them.
14008 If the keys are nil, a-z are automatically assigned.
14009 Returns the new tags string, or nil to not change the current settings."
14010 (let* ((fulltable (append table todo-table))
14011 (maxlen (apply 'max (mapcar
14012 (lambda (x)
14013 (if (stringp (car x)) (string-width (car x)) 0))
14014 fulltable)))
14015 (buf (current-buffer))
14016 (expert (eq org-fast-tag-selection-single-key 'expert))
14017 (buffer-tags nil)
14018 (fwidth (+ maxlen 3 1 3))
14019 (ncol (/ (- (window-width) 4) fwidth))
14020 (i-face 'org-done)
14021 (c-face 'org-todo)
14022 tg cnt e c char c1 c2 ntable tbl rtn
14023 ov-start ov-end ov-prefix
14024 (exit-after-next org-fast-tag-selection-single-key)
14025 (done-keywords org-done-keywords)
14026 groups ingroup)
14027 (save-excursion
14028 (beginning-of-line 1)
14029 (if (looking-at
14030 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14031 (setq ov-start (match-beginning 1)
14032 ov-end (match-end 1)
14033 ov-prefix "")
14034 (setq ov-start (1- (point-at-eol))
14035 ov-end (1+ ov-start))
14036 (skip-chars-forward "^\n\r")
14037 (setq ov-prefix
14038 (concat
14039 (buffer-substring (1- (point)) (point))
14040 (if (> (current-column) org-tags-column)
14042 (make-string (- org-tags-column (current-column)) ?\ ))))))
14043 (move-overlay org-tags-overlay ov-start ov-end)
14044 (save-window-excursion
14045 (if expert
14046 (set-buffer (get-buffer-create " *Org tags*"))
14047 (delete-other-windows)
14048 (split-window-vertically)
14049 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14050 (erase-buffer)
14051 (org-set-local 'org-done-keywords done-keywords)
14052 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14053 (org-fast-tag-insert "Current" current c-face "\n\n")
14054 (org-fast-tag-show-exit exit-after-next)
14055 (org-set-current-tags-overlay current ov-prefix)
14056 (setq tbl fulltable char ?a cnt 0)
14057 (while (setq e (pop tbl))
14058 (cond
14059 ((equal (car e) :startgroup)
14060 (push '() groups) (setq ingroup t)
14061 (when (not (= cnt 0))
14062 (setq cnt 0)
14063 (insert "\n"))
14064 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14065 ((equal (car e) :endgroup)
14066 (setq ingroup nil cnt 0)
14067 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14068 ((equal e '(:newline))
14069 (when (not (= cnt 0))
14070 (setq cnt 0)
14071 (insert "\n")
14072 (setq e (car tbl))
14073 (while (equal (car tbl) '(:newline))
14074 (insert "\n")
14075 (setq tbl (cdr tbl)))))
14077 (setq tg (copy-sequence (car e)) c2 nil)
14078 (if (cdr e)
14079 (setq c (cdr e))
14080 ;; automatically assign a character.
14081 (setq c1 (string-to-char
14082 (downcase (substring
14083 tg (if (= (string-to-char tg) ?@) 1 0)))))
14084 (if (or (rassoc c1 ntable) (rassoc c1 table))
14085 (while (or (rassoc char ntable) (rassoc char table))
14086 (setq char (1+ char)))
14087 (setq c2 c1))
14088 (setq c (or c2 char)))
14089 (if ingroup (push tg (car groups)))
14090 (setq tg (org-add-props tg nil 'face
14091 (cond
14092 ((not (assoc tg table))
14093 (org-get-todo-face tg))
14094 ((member tg current) c-face)
14095 ((member tg inherited) i-face))))
14096 (if (and (= cnt 0) (not ingroup)) (insert " "))
14097 (insert "[" c "] " tg (make-string
14098 (- fwidth 4 (length tg)) ?\ ))
14099 (push (cons tg c) ntable)
14100 (when (= (setq cnt (1+ cnt)) ncol)
14101 (insert "\n")
14102 (if ingroup (insert " "))
14103 (setq cnt 0)))))
14104 (setq ntable (nreverse ntable))
14105 (insert "\n")
14106 (goto-char (point-min))
14107 (if (not expert) (org-fit-window-to-buffer))
14108 (setq rtn
14109 (catch 'exit
14110 (while t
14111 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14112 (if (not groups) "no " "")
14113 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14114 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14115 (setq org-last-tag-selection-key c)
14116 (cond
14117 ((= c ?\r) (throw 'exit t))
14118 ((= c ?!)
14119 (setq groups (not groups))
14120 (goto-char (point-min))
14121 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14122 ((= c ?\C-c)
14123 (if (not expert)
14124 (org-fast-tag-show-exit
14125 (setq exit-after-next (not exit-after-next)))
14126 (setq expert nil)
14127 (delete-other-windows)
14128 (set-window-buffer (split-window-vertically) " *Org tags*")
14129 (org-switch-to-buffer-other-window " *Org tags*")
14130 (org-fit-window-to-buffer)))
14131 ((or (= c ?\C-g)
14132 (and (= c ?q) (not (rassoc c ntable))))
14133 (org-detach-overlay org-tags-overlay)
14134 (setq quit-flag t))
14135 ((= c ?\ )
14136 (setq current nil)
14137 (if exit-after-next (setq exit-after-next 'now)))
14138 ((= c ?\t)
14139 (condition-case nil
14140 (setq tg (org-icompleting-read
14141 "Tag: "
14142 (or buffer-tags
14143 (with-current-buffer buf
14144 (org-get-buffer-tags)))))
14145 (quit (setq tg "")))
14146 (when (string-match "\\S-" tg)
14147 (add-to-list 'buffer-tags (list tg))
14148 (if (member tg current)
14149 (setq current (delete tg current))
14150 (push tg current)))
14151 (if exit-after-next (setq exit-after-next 'now)))
14152 ((setq e (rassoc c todo-table) tg (car e))
14153 (with-current-buffer buf
14154 (save-excursion (org-todo tg)))
14155 (if exit-after-next (setq exit-after-next 'now)))
14156 ((setq e (rassoc c ntable) tg (car e))
14157 (if (member tg current)
14158 (setq current (delete tg current))
14159 (loop for g in groups do
14160 (if (member tg g)
14161 (mapc (lambda (x)
14162 (setq current (delete x current)))
14163 g)))
14164 (push tg current))
14165 (if exit-after-next (setq exit-after-next 'now))))
14167 ;; Create a sorted list
14168 (setq current
14169 (sort current
14170 (lambda (a b)
14171 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14172 (if (eq exit-after-next 'now) (throw 'exit t))
14173 (goto-char (point-min))
14174 (beginning-of-line 2)
14175 (delete-region (point) (point-at-eol))
14176 (org-fast-tag-insert "Current" current c-face)
14177 (org-set-current-tags-overlay current ov-prefix)
14178 (while (re-search-forward
14179 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14180 (setq tg (match-string 1))
14181 (add-text-properties
14182 (match-beginning 1) (match-end 1)
14183 (list 'face
14184 (cond
14185 ((member tg current) c-face)
14186 ((member tg inherited) i-face)
14187 (t (get-text-property (match-beginning 1) 'face))))))
14188 (goto-char (point-min)))))
14189 (org-detach-overlay org-tags-overlay)
14190 (if rtn
14191 (mapconcat 'identity current ":")
14192 nil))))
14194 (defun org-get-tags-string ()
14195 "Get the TAGS string in the current headline."
14196 (unless (org-at-heading-p t)
14197 (error "Not on a heading"))
14198 (save-excursion
14199 (beginning-of-line 1)
14200 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14201 (org-match-string-no-properties 1)
14202 "")))
14204 (defun org-get-tags ()
14205 "Get the list of tags specified in the current headline."
14206 (org-split-string (org-get-tags-string) ":"))
14208 (defun org-get-buffer-tags ()
14209 "Get a table of all tags used in the buffer, for completion."
14210 (let (tags)
14211 (save-excursion
14212 (goto-char (point-min))
14213 (while (re-search-forward
14214 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14215 (when (equal (char-after (point-at-bol 0)) ?*)
14216 (mapc (lambda (x) (add-to-list 'tags x))
14217 (org-split-string (org-match-string-no-properties 1) ":")))))
14218 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14219 (mapcar 'list tags)))
14221 ;;;; The mapping API
14223 ;;;###autoload
14224 (defun org-map-entries (func &optional match scope &rest skip)
14225 "Call FUNC at each headline selected by MATCH in SCOPE.
14227 FUNC is a function or a lisp form. The function will be called without
14228 arguments, with the cursor positioned at the beginning of the headline.
14229 The return values of all calls to the function will be collected and
14230 returned as a list.
14232 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14233 does not need to preserve point. After evaluation, the cursor will be
14234 moved to the end of the line (presumably of the headline of the
14235 processed entry) and search continues from there. Under some
14236 circumstances, this may not produce the wanted results. For example,
14237 if you have removed (e.g. archived) the current (sub)tree it could
14238 mean that the next entry will be skipped entirely. In such cases, you
14239 can specify the position from where search should continue by making
14240 FUNC set the variable `org-map-continue-from' to the desired buffer
14241 position.
14243 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14244 Only headlines that are matched by this query will be considered during
14245 the iteration. When MATCH is nil or t, all headlines will be
14246 visited by the iteration.
14248 SCOPE determines the scope of this command. It can be any of:
14250 nil The current buffer, respecting the restriction if any
14251 tree The subtree started with the entry at point
14252 region The entries within the active region, if any
14253 region-start-level
14254 The entries within the active region, but only those at
14255 the same level than the first one.
14256 file The current buffer, without restriction
14257 file-with-archives
14258 The current buffer, and any archives associated with it
14259 agenda All agenda files
14260 agenda-with-archives
14261 All agenda files with any archive files associated with them
14262 \(file1 file2 ...)
14263 If this is a list, all files in the list will be scanned
14265 The remaining args are treated as settings for the skipping facilities of
14266 the scanner. The following items can be given here:
14268 archive skip trees with the archive tag.
14269 comment skip trees with the COMMENT keyword
14270 function or Emacs Lisp form:
14271 will be used as value for `org-agenda-skip-function', so whenever
14272 the function returns t, FUNC will not be called for that
14273 entry and search will continue from the point where the
14274 function leaves it.
14276 If your function needs to retrieve the tags including inherited tags
14277 at the *current* entry, you can use the value of the variable
14278 `org-scanner-tags' which will be much faster than getting the value
14279 with `org-get-tags-at'. If your function gets properties with
14280 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14281 to t around the call to `org-entry-properties' to get the same speedup.
14282 Note that if your function moves around to retrieve tags and properties at
14283 a *different* entry, you cannot use these techniques."
14284 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14285 (not (org-region-active-p)))
14286 (let* ((org-agenda-archives-mode nil) ; just to make sure
14287 (org-agenda-skip-archived-trees (memq 'archive skip))
14288 (org-agenda-skip-comment-trees (memq 'comment skip))
14289 (org-agenda-skip-function
14290 (car (org-delete-all '(comment archive) skip)))
14291 (org-tags-match-list-sublevels t)
14292 (start-level (eq scope 'region-start-level))
14293 matcher file res
14294 org-todo-keywords-for-agenda
14295 org-done-keywords-for-agenda
14296 org-todo-keyword-alist-for-agenda
14297 org-drawers-for-agenda
14298 org-tag-alist-for-agenda
14299 todo-only)
14301 (cond
14302 ((eq match t) (setq matcher t))
14303 ((eq match nil) (setq matcher t))
14304 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14306 (save-excursion
14307 (save-restriction
14308 (cond ((eq scope 'tree)
14309 (org-back-to-heading t)
14310 (org-narrow-to-subtree)
14311 (setq scope nil))
14312 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14313 (org-region-active-p))
14314 ;; If needed, set start-level to a string like "2"
14315 (when start-level
14316 (save-excursion
14317 (goto-char (region-beginning))
14318 (unless (org-at-heading-p) (outline-next-heading))
14319 (setq start-level (org-current-level))))
14320 (narrow-to-region (region-beginning)
14321 (save-excursion
14322 (goto-char (region-end))
14323 (unless (and (bolp) (org-at-heading-p))
14324 (outline-next-heading))
14325 (point)))
14326 (setq scope nil)))
14328 (if (not scope)
14329 (progn
14330 (org-agenda-prepare-buffers
14331 (list (buffer-file-name (current-buffer))))
14332 (setq res (org-scan-tags func matcher todo-only start-level)))
14333 ;; Get the right scope
14334 (cond
14335 ((and scope (listp scope) (symbolp (car scope)))
14336 (setq scope (eval scope)))
14337 ((eq scope 'agenda)
14338 (setq scope (org-agenda-files t)))
14339 ((eq scope 'agenda-with-archives)
14340 (setq scope (org-agenda-files t))
14341 (setq scope (org-add-archive-files scope)))
14342 ((eq scope 'file)
14343 (setq scope (list (buffer-file-name))))
14344 ((eq scope 'file-with-archives)
14345 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14346 (org-agenda-prepare-buffers scope)
14347 (while (setq file (pop scope))
14348 (with-current-buffer (org-find-base-buffer-visiting file)
14349 (save-excursion
14350 (save-restriction
14351 (widen)
14352 (goto-char (point-min))
14353 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14354 res)))
14356 ;;;; Properties
14358 ;;; Setting and retrieving properties
14360 (defconst org-special-properties
14361 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14362 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14363 "The special properties valid in Org-mode.
14365 These are properties that are not defined in the property drawer,
14366 but in some other way.")
14368 (defconst org-default-properties
14369 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14370 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14371 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14372 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14373 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14374 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14375 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14376 "Some properties that are used by Org-mode for various purposes.
14377 Being in this list makes sure that they are offered for completion.")
14379 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14380 "Regular expression matching the first line of a property drawer.")
14382 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14383 "Regular expression matching the last line of a property drawer.")
14385 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14386 "Regular expression matching the first line of a property drawer.")
14388 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14389 "Regular expression matching the first line of a property drawer.")
14391 (defconst org-property-drawer-re
14392 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14393 org-property-end-re "\\)\n?")
14394 "Matches an entire property drawer.")
14396 (defconst org-clock-drawer-re
14397 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14398 org-property-end-re "\\)\n?")
14399 "Matches an entire clock drawer.")
14401 (defsubst org-re-property (property)
14402 "Return a regexp matching a PROPERTY line.
14403 Match group 1 will be set to the value."
14404 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14406 (defsubst org-re-property-keyword (property)
14407 "Return a regexp matching a PROPERTY line, possibly with no
14408 value for the property."
14409 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14411 (defun org-property-action ()
14412 "Do an action on properties."
14413 (interactive)
14414 (let (c)
14415 (org-at-property-p)
14416 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14417 (setq c (read-char-exclusive))
14418 (cond
14419 ((equal c ?s)
14420 (call-interactively 'org-set-property))
14421 ((equal c ?d)
14422 (call-interactively 'org-delete-property))
14423 ((equal c ?D)
14424 (call-interactively 'org-delete-property-globally))
14425 ((equal c ?c)
14426 (call-interactively 'org-compute-property-at-point))
14427 (t (error "No such property action %c" c)))))
14429 (defun org-inc-effort ()
14430 "Increment the value of the effort property in the current entry."
14431 (interactive)
14432 (org-set-effort nil t))
14434 (defun org-set-effort (&optional value increment)
14435 "Set the effort property of the current entry.
14436 With numerical prefix arg, use the nth allowed value, 0 stands for the
14437 10th allowed value.
14439 When INCREMENT is non-nil, set the property to the next allowed value."
14440 (interactive "P")
14441 (if (equal value 0) (setq value 10))
14442 (let* ((completion-ignore-case t)
14443 (prop org-effort-property)
14444 (cur (org-entry-get nil prop))
14445 (allowed (org-property-get-allowed-values nil prop 'table))
14446 (existing (mapcar 'list (org-property-values prop)))
14448 (val (cond
14449 ((stringp value) value)
14450 ((and allowed (integerp value))
14451 (or (car (nth (1- value) allowed))
14452 (car (org-last allowed))))
14453 ((and allowed increment)
14454 (or (caadr (member (list cur) allowed))
14455 (error "Allowed effort values are not set")))
14456 (allowed
14457 (message "Select 1-9,0, [RET%s]: %s"
14458 (if cur (concat "=" cur) "")
14459 (mapconcat 'car allowed " "))
14460 (setq rpl (read-char-exclusive))
14461 (if (equal rpl ?\r)
14463 (setq rpl (- rpl ?0))
14464 (if (equal rpl 0) (setq rpl 10))
14465 (if (and (> rpl 0) (<= rpl (length allowed)))
14466 (car (nth (1- rpl) allowed))
14467 (org-completing-read "Effort: " allowed nil))))
14469 (let (org-completion-use-ido org-completion-use-iswitchb)
14470 (org-completing-read
14471 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14472 (concat "[" cur "]") "")
14473 ": ")
14474 existing nil nil "" nil cur))))))
14475 (unless (equal (org-entry-get nil prop) val)
14476 (org-entry-put nil prop val))
14477 (message "%s is now %s" prop val)))
14479 (defun org-at-property-p ()
14480 "Is cursor inside a property drawer?"
14481 (save-excursion
14482 (beginning-of-line 1)
14483 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14484 (save-match-data ;; Used by calling procedures
14485 (let ((p (point))
14486 (range (unless (org-before-first-heading-p)
14487 (org-get-property-block))))
14488 (and range (<= (car range) p) (< p (cdr range))))))))
14490 (defun org-get-property-block (&optional beg end force)
14491 "Return the (beg . end) range of the body of the property drawer.
14492 BEG and END are the beginning and end of the current subtree, or of
14493 the part before the first headline. If they are not given, they will
14494 be found. If the drawer does not exist and FORCE is non-nil, create
14495 the drawer."
14496 (catch 'exit
14497 (save-excursion
14498 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14499 (progn (org-back-to-heading t) (point))))
14500 (end (or end (and (not (outline-next-heading)) (point-max))
14501 (point))))
14502 (goto-char beg)
14503 (if (re-search-forward org-property-start-re end t)
14504 (setq beg (1+ (match-end 0)))
14505 (if force
14506 (save-excursion
14507 (org-insert-property-drawer)
14508 (setq end (progn (outline-next-heading) (point))))
14509 (throw 'exit nil))
14510 (goto-char beg)
14511 (if (re-search-forward org-property-start-re end t)
14512 (setq beg (1+ (match-end 0)))))
14513 (if (re-search-forward org-property-end-re end t)
14514 (setq end (match-beginning 0))
14515 (or force (throw 'exit nil))
14516 (goto-char beg)
14517 (setq end beg)
14518 (org-indent-line)
14519 (insert ":END:\n"))
14520 (cons beg end)))))
14522 (defun org-entry-properties (&optional pom which specific)
14523 "Get all properties of the entry at point-or-marker POM.
14524 This includes the TODO keyword, the tags, time strings for deadline,
14525 scheduled, and clocking, and any additional properties defined in the
14526 entry. The return value is an alist, keys may occur multiple times
14527 if the property key was used several times.
14528 POM may also be nil, in which case the current entry is used.
14529 If WHICH is nil or `all', get all properties. If WHICH is
14530 `special' or `standard', only get that subclass. If WHICH
14531 is a string only get exactly this property. SPECIFIC can be a string, the
14532 specific property we are interested in. Specifying it can speed
14533 things up because then unnecessary parsing is avoided."
14534 (setq which (or which 'all))
14535 (org-with-point-at pom
14536 (let ((clockstr (substring org-clock-string 0 -1))
14537 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14538 (case-fold-search nil)
14539 beg end range props sum-props key key1 value string clocksum clocksumt)
14540 (save-excursion
14541 (when (condition-case nil
14542 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14543 (error nil))
14544 (setq beg (point))
14545 (setq sum-props (get-text-property (point) 'org-summaries))
14546 (setq clocksum (get-text-property (point) :org-clock-minutes)
14547 clocksumt (get-text-property (point) :org-clock-minutes-today))
14548 (outline-next-heading)
14549 (setq end (point))
14550 (when (memq which '(all special))
14551 ;; Get the special properties, like TODO and tags
14552 (goto-char beg)
14553 (when (and (or (not specific) (string= specific "TODO"))
14554 (looking-at org-todo-line-regexp) (match-end 2))
14555 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14556 (when (and (or (not specific) (string= specific "PRIORITY"))
14557 (looking-at org-priority-regexp))
14558 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14559 (when (or (not specific) (string= specific "FILE"))
14560 (push (cons "FILE" buffer-file-name) props))
14561 (when (and (or (not specific) (string= specific "TAGS"))
14562 (setq value (org-get-tags-string))
14563 (string-match "\\S-" value))
14564 (push (cons "TAGS" value) props))
14565 (when (and (or (not specific) (string= specific "ALLTAGS"))
14566 (setq value (org-get-tags-at)))
14567 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14568 ":"))
14569 props))
14570 (when (or (not specific) (string= specific "BLOCKED"))
14571 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14572 (when (or (not specific)
14573 (member specific
14574 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14575 "TIMESTAMP" "TIMESTAMP_IA")))
14576 (catch 'match
14577 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14578 (setq key (if (match-end 1)
14579 (substring (org-match-string-no-properties 1)
14580 0 -1))
14581 string (if (equal key clockstr)
14582 (org-trim
14583 (buffer-substring-no-properties
14584 (match-beginning 3) (goto-char
14585 (point-at-eol))))
14586 (substring (org-match-string-no-properties 3)
14587 1 -1)))
14588 ;; Get the correct property name from the key. This is
14589 ;; necessary if the user has configured time keywords.
14590 (setq key1 (concat key ":"))
14591 (cond
14592 ((not key)
14593 (setq key
14594 (if (= (char-after (match-beginning 3)) ?\[)
14595 "TIMESTAMP_IA" "TIMESTAMP")))
14596 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14597 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14598 ((equal key1 org-closed-string) (setq key "CLOSED"))
14599 ((equal key1 org-clock-string) (setq key "CLOCK")))
14600 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14601 (progn
14602 (push (cons key string) props)
14603 ;; no need to search further if match is found
14604 (throw 'match t))
14605 (when (or (equal key "CLOCK") (not (assoc key props)))
14606 (push (cons key string) props)))))))
14608 (when (memq which '(all standard))
14609 ;; Get the standard properties, like :PROP: ...
14610 (setq range (org-get-property-block beg end))
14611 (when range
14612 (goto-char (car range))
14613 (while (re-search-forward
14614 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14615 (cdr range) t)
14616 (setq key (org-match-string-no-properties 1)
14617 value (org-trim (or (org-match-string-no-properties 2) "")))
14618 (unless (member key excluded)
14619 (push (cons key (or value "")) props)))))
14620 (if clocksum
14621 (push (cons "CLOCKSUM"
14622 (org-columns-number-to-string (/ (float clocksum) 60.)
14623 'add_times))
14624 props))
14625 (if clocksumt
14626 (push (cons "CLOCKSUM_T"
14627 (org-columns-number-to-string (/ (float clocksumt) 60.)
14628 'add_times))
14629 props))
14630 (unless (assoc "CATEGORY" props)
14631 (push (cons "CATEGORY" (org-get-category)) props))
14632 (append sum-props (nreverse props)))))))
14634 (defun org-entry-get (pom property &optional inherit literal-nil)
14635 "Get value of PROPERTY for entry or content at point-or-marker POM.
14636 If INHERIT is non-nil and the entry does not have the property,
14637 then also check higher levels of the hierarchy.
14638 If INHERIT is the symbol `selective', use inheritance only if the setting
14639 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14640 If the property is present but empty, the return value is the empty string.
14641 If the property is not present at all, nil is returned.
14643 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14644 do not interpret it as the list atom nil. This is used for inheritance
14645 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14646 (org-with-point-at pom
14647 (if (and inherit (if (eq inherit 'selective)
14648 (org-property-inherit-p property)
14650 (org-entry-get-with-inheritance property literal-nil)
14651 (if (member property org-special-properties)
14652 ;; We need a special property. Use `org-entry-properties' to
14653 ;; retrieve it, but specify the wanted property
14654 (cdr (assoc property (org-entry-properties nil 'special property)))
14655 (let* ((range (org-get-property-block))
14656 (props (list (or (assoc property org-file-properties)
14657 (assoc property org-global-properties)
14658 (assoc property org-global-properties-fixed))))
14659 (ap (lambda (key)
14660 (when (re-search-forward
14661 (org-re-property key) (cdr range) t)
14662 (setq props
14663 (org-update-property-plist
14665 (if (match-end 1)
14666 (org-match-string-no-properties 1) "")
14667 props)))))
14668 val)
14669 (when (and range (goto-char (car range)))
14670 (funcall ap property)
14671 (goto-char (car range))
14672 (while (funcall ap (concat property "+")))
14673 (setq val (cdr (assoc property props)))
14674 (when val (if literal-nil val (org-not-nil val)))))))))
14676 (defun org-property-or-variable-value (var &optional inherit)
14677 "Check if there is a property fixing the value of VAR.
14678 If yes, return this value. If not, return the current value of the variable."
14679 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14680 (if (and prop (stringp prop) (string-match "\\S-" prop))
14681 (read prop)
14682 (symbol-value var))))
14684 (defun org-entry-delete (pom property)
14685 "Delete the property PROPERTY from entry at point-or-marker POM."
14686 (org-with-point-at pom
14687 (if (member property org-special-properties)
14688 nil ; cannot delete these properties.
14689 (let ((range (org-get-property-block)))
14690 (if (and range
14691 (goto-char (car range))
14692 (re-search-forward
14693 (org-re-property property)
14694 (cdr range) t))
14695 (progn
14696 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14698 nil)))))
14700 ;; Multi-values properties are properties that contain multiple values
14701 ;; These values are assumed to be single words, separated by whitespace.
14702 (defun org-entry-add-to-multivalued-property (pom property value)
14703 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14704 (let* ((old (org-entry-get pom property))
14705 (values (and old (org-split-string old "[ \t]"))))
14706 (setq value (org-entry-protect-space value))
14707 (unless (member value values)
14708 (setq values (cons value values))
14709 (org-entry-put pom property
14710 (mapconcat 'identity values " ")))))
14712 (defun org-entry-remove-from-multivalued-property (pom property value)
14713 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14714 (let* ((old (org-entry-get pom property))
14715 (values (and old (org-split-string old "[ \t]"))))
14716 (setq value (org-entry-protect-space value))
14717 (when (member value values)
14718 (setq values (delete value values))
14719 (org-entry-put pom property
14720 (mapconcat 'identity values " ")))))
14722 (defun org-entry-member-in-multivalued-property (pom property value)
14723 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14724 (let* ((old (org-entry-get pom property))
14725 (values (and old (org-split-string old "[ \t]"))))
14726 (setq value (org-entry-protect-space value))
14727 (member value values)))
14729 (defun org-entry-get-multivalued-property (pom property)
14730 "Return a list of values in a multivalued property."
14731 (let* ((value (org-entry-get pom property))
14732 (values (and value (org-split-string value "[ \t]"))))
14733 (mapcar 'org-entry-restore-space values)))
14735 (defun org-entry-put-multivalued-property (pom property &rest values)
14736 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14737 VALUES should be a list of strings. Spaces will be protected."
14738 (org-entry-put pom property
14739 (mapconcat 'org-entry-protect-space values " "))
14740 (let* ((value (org-entry-get pom property))
14741 (values (and value (org-split-string value "[ \t]"))))
14742 (mapcar 'org-entry-restore-space values)))
14744 (defun org-entry-protect-space (s)
14745 "Protect spaces and newline in string S."
14746 (while (string-match " " s)
14747 (setq s (replace-match "%20" t t s)))
14748 (while (string-match "\n" s)
14749 (setq s (replace-match "%0A" t t s)))
14752 (defun org-entry-restore-space (s)
14753 "Restore spaces and newline in string S."
14754 (while (string-match "%20" s)
14755 (setq s (replace-match " " t t s)))
14756 (while (string-match "%0A" s)
14757 (setq s (replace-match "\n" t t s)))
14760 (defvar org-entry-property-inherited-from (make-marker)
14761 "Marker pointing to the entry from where a property was inherited.
14762 Each call to `org-entry-get-with-inheritance' will set this marker to the
14763 location of the entry where the inheritance search matched. If there was
14764 no match, the marker will point nowhere.
14765 Note that also `org-entry-get' calls this function, if the INHERIT flag
14766 is set.")
14768 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14769 "Get PROPERTY of entry or content at point, search higher levels if needed.
14770 The search will stop at the first ancestor which has the property defined.
14771 If the value found is \"nil\", return nil to show that the property
14772 should be considered as undefined (this is the meaning of nil here).
14773 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14774 (move-marker org-entry-property-inherited-from nil)
14775 (let (tmp)
14776 (save-excursion
14777 (save-restriction
14778 (widen)
14779 (catch 'ex
14780 (while t
14781 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14782 (or (ignore-errors (org-back-to-heading t))
14783 (goto-char (point-min)))
14784 (move-marker org-entry-property-inherited-from (point))
14785 (throw 'ex tmp))
14786 (or (ignore-errors (org-up-heading-safe))
14787 (throw 'ex nil))))))
14788 (setq tmp (or tmp
14789 (cdr (assoc property org-file-properties))
14790 (cdr (assoc property org-global-properties))
14791 (cdr (assoc property org-global-properties-fixed))))
14792 (if literal-nil tmp (org-not-nil tmp))))
14794 (defvar org-property-changed-functions nil
14795 "Hook called when the value of a property has changed.
14796 Each hook function should accept two arguments, the name of the property
14797 and the new value.")
14799 (defun org-entry-put (pom property value)
14800 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14801 (org-with-point-at pom
14802 (org-back-to-heading t)
14803 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14804 range)
14805 (cond
14806 ((equal property "TODO")
14807 (when (and (stringp value) (string-match "\\S-" value)
14808 (not (member value org-todo-keywords-1)))
14809 (error "\"%s\" is not a valid TODO state" value))
14810 (if (or (not value)
14811 (not (string-match "\\S-" value)))
14812 (setq value 'none))
14813 (org-todo value)
14814 (org-set-tags nil 'align))
14815 ((equal property "PRIORITY")
14816 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14817 (string-to-char value) ?\ ))
14818 (org-set-tags nil 'align))
14819 ((equal property "CLOCKSUM")
14820 (if (not (re-search-forward
14821 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14822 (error "Cannot find a clock log")
14823 (goto-char (- (match-end 1) 2))
14824 (cond
14825 ((eq value 'earlier) (org-timestamp-down))
14826 ((eq value 'later) (org-timestamp-up)))
14827 (org-clock-sum-current-item)))
14828 ((equal property "SCHEDULED")
14829 (if (re-search-forward org-scheduled-time-regexp end t)
14830 (cond
14831 ((eq value 'earlier) (org-timestamp-change -1 'day))
14832 ((eq value 'later) (org-timestamp-change 1 'day))
14833 (t (call-interactively 'org-schedule)))
14834 (call-interactively 'org-schedule)))
14835 ((equal property "DEADLINE")
14836 (if (re-search-forward org-deadline-time-regexp end t)
14837 (cond
14838 ((eq value 'earlier) (org-timestamp-change -1 'day))
14839 ((eq value 'later) (org-timestamp-change 1 'day))
14840 (t (call-interactively 'org-deadline)))
14841 (call-interactively 'org-deadline)))
14842 ((member property org-special-properties)
14843 (error "The %s property can not yet be set with `org-entry-put'"
14844 property))
14845 (t ; a non-special property
14846 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14847 (setq range (org-get-property-block beg end 'force))
14848 (goto-char (car range))
14849 (if (re-search-forward
14850 (org-re-property-keyword property) (cdr range) t)
14851 (progn
14852 (delete-region (match-beginning 0) (match-end 0))
14853 (goto-char (match-beginning 0)))
14854 (goto-char (cdr range))
14855 (insert "\n")
14856 (backward-char 1)
14857 (org-indent-line))
14858 (insert ":" property ":")
14859 (and value (insert " " value))
14860 (org-indent-line)))))
14861 (run-hook-with-args 'org-property-changed-functions property value)))
14863 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14864 "Get all property keys in the current buffer.
14865 With INCLUDE-SPECIALS, also list the special properties that reflect things
14866 like tags and TODO state.
14867 With INCLUDE-DEFAULTS, also include properties that has special meaning
14868 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14869 and others.
14870 With INCLUDE-COLUMNS, also include property names given in COLUMN
14871 formats in the current buffer."
14872 (let (rtn range cfmt s p)
14873 (save-excursion
14874 (save-restriction
14875 (widen)
14876 (goto-char (point-min))
14877 (while (re-search-forward org-property-start-re nil t)
14878 (setq range (org-get-property-block))
14879 (goto-char (car range))
14880 (while (re-search-forward
14881 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14882 (cdr range) t)
14883 (add-to-list 'rtn (org-match-string-no-properties 1)))
14884 (outline-next-heading))))
14886 (when include-specials
14887 (setq rtn (append org-special-properties rtn)))
14889 (when include-defaults
14890 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14891 (add-to-list 'rtn org-effort-property))
14893 (when include-columns
14894 (save-excursion
14895 (save-restriction
14896 (widen)
14897 (goto-char (point-min))
14898 (while (re-search-forward
14899 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14900 nil t)
14901 (setq cfmt (match-string 2) s 0)
14902 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14903 cfmt s)
14904 (setq s (match-end 0)
14905 p (match-string 1 cfmt))
14906 (unless (or (equal p "ITEM")
14907 (member p org-special-properties))
14908 (add-to-list 'rtn (match-string 1 cfmt))))))))
14910 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14912 (defun org-property-values (key)
14913 "Return a list of all values of property KEY in the current buffer."
14914 (save-excursion
14915 (save-restriction
14916 (widen)
14917 (goto-char (point-min))
14918 (let ((re (org-re-property key))
14919 values)
14920 (while (re-search-forward re nil t)
14921 (add-to-list 'values (org-trim (match-string 1))))
14922 (delete "" values)))))
14924 (defun org-insert-property-drawer ()
14925 "Insert a property drawer into the current entry."
14926 (org-back-to-heading t)
14927 (looking-at org-outline-regexp)
14928 (let ((indent (if org-adapt-indentation
14929 (- (match-end 0) (match-beginning 0))
14931 (beg (point))
14932 (re (concat "^[ \t]*" org-keyword-time-regexp))
14933 end hiddenp)
14934 (outline-next-heading)
14935 (setq end (point))
14936 (goto-char beg)
14937 (while (re-search-forward re end t))
14938 (setq hiddenp (outline-invisible-p))
14939 (end-of-line 1)
14940 (and (equal (char-after) ?\n) (forward-char 1))
14941 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14942 (if (member (match-string 1) '("CLOCK:" ":END:"))
14943 ;; just skip this line
14944 (beginning-of-line 2)
14945 ;; Drawer start, find the end
14946 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14947 (beginning-of-line 1)))
14948 (org-skip-over-state-notes)
14949 (skip-chars-backward " \t\n\r")
14950 (if (eq (char-before) ?*) (forward-char 1))
14951 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14952 (beginning-of-line 0)
14953 (org-indent-to-column indent)
14954 (beginning-of-line 2)
14955 (org-indent-to-column indent)
14956 (beginning-of-line 0)
14957 (if hiddenp
14958 (save-excursion
14959 (org-back-to-heading t)
14960 (hide-entry))
14961 (org-flag-drawer t))))
14963 (defun org-insert-drawer (&optional arg drawer)
14964 "Insert a drawer at point.
14966 Optional argument DRAWER, when non-nil, is a string representing
14967 drawer's name. Otherwise, the user is prompted for a name.
14969 If a region is active, insert the drawer around that region
14970 instead.
14972 Point is left between drawer's boundaries."
14973 (interactive "P")
14974 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14975 "LOGBOOK"))
14976 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14977 ;; internally by Org. They are meant to be inserted
14978 ;; automatically.
14979 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14980 ;; Remove system drawers from list. Note: For some reason,
14981 ;; `org-completing-read' ignores the predicate while
14982 ;; `completing-read' handles it fine.
14983 (drawer (if arg "PROPERTIES"
14984 (or drawer
14985 (completing-read
14986 "Drawer: " org-drawers
14987 (lambda (d) (not (member d system-drawers))))))))
14988 (cond
14989 ;; With C-u, fall back on `org-insert-property-drawer'
14990 (arg (org-insert-property-drawer))
14991 ;; With an active region, insert a drawer at point.
14992 ((not (org-region-active-p))
14993 (progn
14994 (unless (bolp) (insert "\n"))
14995 (insert (format ":%s:\n\n:END:\n" drawer))
14996 (forward-line -2)))
14997 ;; Otherwise, insert the drawer at point
14999 (let ((rbeg (region-beginning))
15000 (rend (copy-marker (region-end))))
15001 (unwind-protect
15002 (progn
15003 (goto-char rbeg)
15004 (beginning-of-line)
15005 (when (save-excursion
15006 (re-search-forward org-outline-regexp-bol rend t))
15007 (error "Drawers cannot contain headlines"))
15008 ;; Position point at the beginning of the first
15009 ;; non-blank line in region. Insert drawer's opening
15010 ;; there, then indent it.
15011 (org-skip-whitespace)
15012 (beginning-of-line)
15013 (insert ":" drawer ":\n")
15014 (forward-line -1)
15015 (indent-for-tab-command)
15016 ;; Move point to the beginning of the first blank line
15017 ;; after the last non-blank line in region. Insert
15018 ;; drawer's closing, then indent it.
15019 (goto-char rend)
15020 (skip-chars-backward " \r\t\n")
15021 (insert "\n:END:")
15022 (deactivate-mark t)
15023 (indent-for-tab-command)
15024 (unless (eolp) (insert "\n")))
15025 ;; Clear marker, whatever the outcome of insertion is.
15026 (set-marker rend nil)))))))
15028 (defvar org-property-set-functions-alist nil
15029 "Property set function alist.
15030 Each entry should have the following format:
15032 (PROPERTY . READ-FUNCTION)
15034 The read function will be called with the same argument as
15035 `org-completing-read'.")
15037 (defun org-set-property-function (property)
15038 "Get the function that should be used to set PROPERTY.
15039 This is computed according to `org-property-set-functions-alist'."
15040 (or (cdr (assoc property org-property-set-functions-alist))
15041 'org-completing-read))
15043 (defun org-read-property-value (property)
15044 "Read PROPERTY value from user."
15045 (let* ((completion-ignore-case t)
15046 (allowed (org-property-get-allowed-values nil property 'table))
15047 (cur (org-entry-get nil property))
15048 (prompt (concat property " value"
15049 (if (and cur (string-match "\\S-" cur))
15050 (concat " [" cur "]") "") ": "))
15051 (set-function (org-set-property-function property))
15052 (val (if allowed
15053 (funcall set-function prompt allowed nil
15054 (not (get-text-property 0 'org-unrestricted
15055 (caar allowed))))
15056 (let (org-completion-use-ido org-completion-use-iswitchb)
15057 (funcall set-function prompt
15058 (mapcar 'list (org-property-values property))
15059 nil nil "" nil cur)))))
15060 (if (equal val "")
15062 val)))
15064 (defvar org-last-set-property nil)
15065 (defun org-read-property-name ()
15066 "Read a property name."
15067 (let* ((completion-ignore-case t)
15068 (keys (org-buffer-property-keys nil t t))
15069 (default-prop (or (save-excursion
15070 (save-match-data
15071 (beginning-of-line)
15072 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15073 (null (string= (match-string 1) "END"))
15074 (match-string 1))))
15075 org-last-set-property))
15076 (property (org-icompleting-read
15077 (concat "Property"
15078 (if default-prop (concat " [" default-prop "]") "")
15079 ": ")
15080 (mapcar 'list keys)
15081 nil nil nil nil
15082 default-prop
15084 (if (member property keys)
15085 property
15086 (or (cdr (assoc (downcase property)
15087 (mapcar (lambda (x) (cons (downcase x) x))
15088 keys)))
15089 property))))
15091 (defun org-set-property (property value)
15092 "In the current entry, set PROPERTY to VALUE.
15093 When called interactively, this will prompt for a property name, offering
15094 completion on existing and default properties. And then it will prompt
15095 for a value, offering completion either on allowed values (via an inherited
15096 xxx_ALL property) or on existing values in other instances of this property
15097 in the current file."
15098 (interactive (list nil nil))
15099 (let* ((property (or property (org-read-property-name)))
15100 (value (or value (org-read-property-value property)))
15101 (fn (cdr (assoc property org-properties-postprocess-alist))))
15102 (setq org-last-set-property property)
15103 ;; Possibly postprocess the inserted value:
15104 (when fn (setq value (funcall fn value)))
15105 (unless (equal (org-entry-get nil property) value)
15106 (org-entry-put nil property value))))
15108 (defun org-delete-property (property)
15109 "In the current entry, delete PROPERTY."
15110 (interactive
15111 (let* ((completion-ignore-case t)
15112 (prop (org-icompleting-read "Property: "
15113 (org-entry-properties nil 'standard))))
15114 (list prop)))
15115 (message "Property %s %s" property
15116 (if (org-entry-delete nil property)
15117 "deleted"
15118 "was not present in the entry")))
15120 (defun org-delete-property-globally (property)
15121 "Remove PROPERTY globally, from all entries."
15122 (interactive
15123 (let* ((completion-ignore-case t)
15124 (prop (org-icompleting-read
15125 "Globally remove property: "
15126 (mapcar 'list (org-buffer-property-keys)))))
15127 (list prop)))
15128 (save-excursion
15129 (save-restriction
15130 (widen)
15131 (goto-char (point-min))
15132 (let ((cnt 0))
15133 (while (re-search-forward
15134 (org-re-property property)
15135 nil t)
15136 (setq cnt (1+ cnt))
15137 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15138 (message "Property \"%s\" removed from %d entries" property cnt)))))
15140 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15142 (defun org-compute-property-at-point ()
15143 "Compute the property at point.
15144 This looks for an enclosing column format, extracts the operator and
15145 then applies it to the property in the column format's scope."
15146 (interactive)
15147 (unless (org-at-property-p)
15148 (error "Not at a property"))
15149 (let ((prop (org-match-string-no-properties 2)))
15150 (org-columns-get-format-and-top-level)
15151 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15152 (error "No operator defined for property %s" prop))
15153 (org-columns-compute prop)))
15155 (defvar org-property-allowed-value-functions nil
15156 "Hook for functions supplying allowed values for a specific property.
15157 The functions must take a single argument, the name of the property, and
15158 return a flat list of allowed values. If \":ETC\" is one of
15159 the values, this means that these values are intended as defaults for
15160 completion, but that other values should be allowed too.
15161 The functions must return nil if they are not responsible for this
15162 property.")
15164 (defun org-property-get-allowed-values (pom property &optional table)
15165 "Get allowed values for the property PROPERTY.
15166 When TABLE is non-nil, return an alist that can directly be used for
15167 completion."
15168 (let (vals)
15169 (cond
15170 ((equal property "TODO")
15171 (setq vals (org-with-point-at pom
15172 (append org-todo-keywords-1 '("")))))
15173 ((equal property "PRIORITY")
15174 (let ((n org-lowest-priority))
15175 (while (>= n org-highest-priority)
15176 (push (char-to-string n) vals)
15177 (setq n (1- n)))))
15178 ((member property org-special-properties))
15179 ((setq vals (run-hook-with-args-until-success
15180 'org-property-allowed-value-functions property)))
15182 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15183 (when (and vals (string-match "\\S-" vals))
15184 (setq vals (car (read-from-string (concat "(" vals ")"))))
15185 (setq vals (mapcar (lambda (x)
15186 (cond ((stringp x) x)
15187 ((numberp x) (number-to-string x))
15188 ((symbolp x) (symbol-name x))
15189 (t "???")))
15190 vals)))))
15191 (when (member ":ETC" vals)
15192 (setq vals (remove ":ETC" vals))
15193 (org-add-props (car vals) '(org-unrestricted t)))
15194 (if table (mapcar 'list vals) vals)))
15196 (defun org-property-previous-allowed-value (&optional previous)
15197 "Switch to the next allowed value for this property."
15198 (interactive)
15199 (org-property-next-allowed-value t))
15201 (defun org-property-next-allowed-value (&optional previous)
15202 "Switch to the next allowed value for this property."
15203 (interactive)
15204 (unless (org-at-property-p)
15205 (error "Not at a property"))
15206 (let* ((key (match-string 2))
15207 (value (match-string 3))
15208 (allowed (or (org-property-get-allowed-values (point) key)
15209 (and (member value '("[ ]" "[-]" "[X]"))
15210 '("[ ]" "[X]"))))
15211 nval)
15212 (unless allowed
15213 (error "Allowed values for this property have not been defined"))
15214 (if previous (setq allowed (reverse allowed)))
15215 (if (member value allowed)
15216 (setq nval (car (cdr (member value allowed)))))
15217 (setq nval (or nval (car allowed)))
15218 (if (equal nval value)
15219 (error "Only one allowed value for this property"))
15220 (org-at-property-p)
15221 (replace-match (concat " :" key ": " nval) t t)
15222 (org-indent-line)
15223 (beginning-of-line 1)
15224 (skip-chars-forward " \t")
15225 (run-hook-with-args 'org-property-changed-functions key nval)))
15227 (defun org-find-olp (path &optional this-buffer)
15228 "Return a marker pointing to the entry at outline path OLP.
15229 If anything goes wrong, throw an error.
15230 You can wrap this call to catch the error like this:
15232 (condition-case msg
15233 (org-mobile-locate-entry (match-string 4))
15234 (error (nth 1 msg)))
15236 The return value will then be either a string with the error message,
15237 or a marker if everything is OK.
15239 If THIS-BUFFER is set, the outline path does not contain a file,
15240 only headings."
15241 (let* ((file (if this-buffer buffer-file-name (pop path)))
15242 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15243 (level 1)
15244 (lmin 1)
15245 (lmax 1)
15246 limit re end found pos heading cnt flevel)
15247 (unless buffer (error "File not found :%s" file))
15248 (with-current-buffer buffer
15249 (save-excursion
15250 (save-restriction
15251 (widen)
15252 (setq limit (point-max))
15253 (goto-char (point-min))
15254 (while (setq heading (pop path))
15255 (setq re (format org-complex-heading-regexp-format
15256 (regexp-quote heading)))
15257 (setq cnt 0 pos (point))
15258 (while (re-search-forward re end t)
15259 (setq level (- (match-end 1) (match-beginning 1)))
15260 (if (and (>= level lmin) (<= level lmax))
15261 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15262 (when (= cnt 0) (error "Heading not found on level %d: %s"
15263 lmax heading))
15264 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15265 lmax heading))
15266 (goto-char found)
15267 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15268 (setq end (save-excursion (org-end-of-subtree t t))))
15269 (when (org-at-heading-p)
15270 (move-marker (make-marker) (point))))))))
15272 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15273 "Find node HEADING in BUFFER.
15274 Return a marker to the heading if it was found, or nil if not.
15275 If POS-ONLY is set, return just the position instead of a marker.
15277 The heading text must match exact, but it may have a TODO keyword,
15278 a priority cookie and tags in the standard locations."
15279 (with-current-buffer (or buffer (current-buffer))
15280 (save-excursion
15281 (save-restriction
15282 (widen)
15283 (goto-char (point-min))
15284 (let (case-fold-search)
15285 (if (re-search-forward
15286 (format org-complex-heading-regexp-format
15287 (regexp-quote heading)) nil t)
15288 (if pos-only
15289 (match-beginning 0)
15290 (move-marker (make-marker) (match-beginning 0)))))))))
15292 (defun org-find-exact-heading-in-directory (heading &optional dir)
15293 "Find Org node headline HEADING in all .org files in directory DIR.
15294 When the target headline is found, return a marker to this location."
15295 (let ((files (directory-files (or dir default-directory)
15296 nil "\\`[^.#].*\\.org\\'"))
15297 file visiting m buffer)
15298 (catch 'found
15299 (while (setq file (pop files))
15300 (message "trying %s" file)
15301 (setq visiting (org-find-base-buffer-visiting file))
15302 (setq buffer (or visiting (find-file-noselect file)))
15303 (setq m (org-find-exact-headline-in-buffer
15304 heading buffer))
15305 (when (and (not m) (not visiting)) (kill-buffer buffer))
15306 (and m (throw 'found m))))))
15308 (defun org-find-entry-with-id (ident)
15309 "Locate the entry that contains the ID property with exact value IDENT.
15310 IDENT can be a string, a symbol or a number, this function will search for
15311 the string representation of it.
15312 Return the position where this entry starts, or nil if there is no such entry."
15313 (interactive "sID: ")
15314 (let ((id (cond
15315 ((stringp ident) ident)
15316 ((symbol-name ident) (symbol-name ident))
15317 ((numberp ident) (number-to-string ident))
15318 (t (error "IDENT %s must be a string, symbol or number" ident))))
15319 (case-fold-search nil))
15320 (save-excursion
15321 (save-restriction
15322 (widen)
15323 (goto-char (point-min))
15324 (when (re-search-forward
15325 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15326 nil t)
15327 (org-back-to-heading t)
15328 (point))))))
15330 ;;;; Timestamps
15332 (defvar org-last-changed-timestamp nil)
15333 (defvar org-last-inserted-timestamp nil
15334 "The last time stamp inserted with `org-insert-time-stamp'.")
15335 (defvar org-time-was-given) ; dynamically scoped parameter
15336 (defvar org-end-time-was-given) ; dynamically scoped parameter
15337 (defvar org-ts-what) ; dynamically scoped parameter
15339 (defun org-time-stamp (arg &optional inactive)
15340 "Prompt for a date/time and insert a time stamp.
15341 If the user specifies a time like HH:MM or if this command is
15342 called with at least one prefix argument, the time stamp contains
15343 the date and the time. Otherwise, only the date is be included.
15345 All parts of a date not specified by the user is filled in from
15346 the current date/time. So if you just press return without
15347 typing anything, the time stamp will represent the current
15348 date/time.
15350 If there is already a timestamp at the cursor, it will be
15351 modified.
15353 With two universal prefix arguments, insert an active timestamp
15354 with the current time without prompting the user."
15355 (interactive "P")
15356 (let* ((ts nil)
15357 (default-time
15358 ;; Default time is either today, or, when entering a range,
15359 ;; the range start.
15360 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15361 (save-excursion
15362 (re-search-backward
15363 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15364 (- (point) 20) t)))
15365 (apply 'encode-time (org-parse-time-string (match-string 1)))
15366 (current-time)))
15367 (default-input (and ts (org-get-compact-tod ts)))
15368 (repeater (save-excursion
15369 (save-match-data
15370 (beginning-of-line)
15371 (when (re-search-forward
15372 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15373 (save-excursion (progn (end-of-line) (point))) t)
15374 (match-string 0)))))
15375 org-time-was-given org-end-time-was-given time)
15376 (cond
15377 ((and (org-at-timestamp-p t)
15378 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15379 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15380 (insert "--")
15381 (setq time (let ((this-command this-command))
15382 (org-read-date arg 'totime nil nil
15383 default-time default-input inactive)))
15384 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15385 ((org-at-timestamp-p t)
15386 (setq time (let ((this-command this-command))
15387 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15388 (when (org-at-timestamp-p t) ; just to get the match data
15389 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15390 (replace-match "")
15391 (setq org-last-changed-timestamp
15392 (org-insert-time-stamp
15393 time (or org-time-was-given arg)
15394 inactive nil nil (list org-end-time-was-given)))
15395 (when repeater (goto-char (1- (point))) (insert " " repeater)
15396 (setq org-last-changed-timestamp
15397 (concat (substring org-last-inserted-timestamp 0 -1)
15398 " " repeater ">"))))
15399 (message "Timestamp updated"))
15400 ((equal arg '(16))
15401 (org-insert-time-stamp (current-time) t))
15403 (setq time (let ((this-command this-command))
15404 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15405 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15406 nil nil (list org-end-time-was-given))))))
15408 ;; FIXME: can we use this for something else, like computing time differences?
15409 (defun org-get-compact-tod (s)
15410 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15411 (let* ((t1 (match-string 1 s))
15412 (h1 (string-to-number (match-string 2 s)))
15413 (m1 (string-to-number (match-string 3 s)))
15414 (t2 (and (match-end 4) (match-string 5 s)))
15415 (h2 (and t2 (string-to-number (match-string 6 s))))
15416 (m2 (and t2 (string-to-number (match-string 7 s))))
15417 dh dm)
15418 (if (not t2)
15420 (setq dh (- h2 h1) dm (- m2 m1))
15421 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15422 (concat t1 "+" (number-to-string dh)
15423 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15425 (defun org-time-stamp-inactive (&optional arg)
15426 "Insert an inactive time stamp.
15427 An inactive time stamp is enclosed in square brackets instead of angle
15428 brackets. It is inactive in the sense that it does not trigger agenda entries,
15429 does not link to the calendar and cannot be changed with the S-cursor keys.
15430 So these are more for recording a certain time/date."
15431 (interactive "P")
15432 (org-time-stamp arg 'inactive))
15434 (defvar org-date-ovl (make-overlay 1 1))
15435 (overlay-put org-date-ovl 'face 'org-date-selected)
15436 (org-detach-overlay org-date-ovl)
15438 (defvar org-ans1) ; dynamically scoped parameter
15439 (defvar org-ans2) ; dynamically scoped parameter
15441 (defvar org-plain-time-of-day-regexp) ; defined below
15443 (defvar org-overriding-default-time nil) ; dynamically scoped
15444 (defvar org-read-date-overlay nil)
15445 (defvar org-dcst nil) ; dynamically scoped
15446 (defvar org-read-date-history nil)
15447 (defvar org-read-date-final-answer nil)
15448 (defvar org-read-date-analyze-futurep nil)
15449 (defvar org-read-date-analyze-forced-year nil)
15450 (defvar org-read-date-inactive)
15452 (defun org-read-date (&optional org-with-time to-time from-string prompt
15453 default-time default-input inactive)
15454 "Read a date, possibly a time, and make things smooth for the user.
15455 The prompt will suggest to enter an ISO date, but you can also enter anything
15456 which will at least partially be understood by `parse-time-string'.
15457 Unrecognized parts of the date will default to the current day, month, year,
15458 hour and minute. If this command is called to replace a timestamp at point,
15459 or to enter the second timestamp of a range, the default time is taken
15460 from the existing stamp. Furthermore, the command prefers the future,
15461 so if you are giving a date where the year is not given, and the day-month
15462 combination is already past in the current year, it will assume you
15463 mean next year. For details, see the manual. A few examples:
15465 3-2-5 --> 2003-02-05
15466 feb 15 --> currentyear-02-15
15467 2/15 --> currentyear-02-15
15468 sep 12 9 --> 2009-09-12
15469 12:45 --> today 12:45
15470 22 sept 0:34 --> currentyear-09-22 0:34
15471 12 --> currentyear-currentmonth-12
15472 Fri --> nearest Friday (today or later)
15473 etc.
15475 Furthermore you can specify a relative date by giving, as the *first* thing
15476 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15477 change in days weeks, months, years.
15478 With a single plus or minus, the date is relative to today. With a double
15479 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15480 +4d --> four days from today
15481 +4 --> same as above
15482 +2w --> two weeks from today
15483 ++5 --> five days from default date
15485 The function understands only English month and weekday abbreviations.
15487 While prompting, a calendar is popped up - you can also select the
15488 date with the mouse (button 1). The calendar shows a period of three
15489 months. To scroll it to other months, use the keys `>' and `<'.
15490 If you don't like the calendar, turn it off with
15491 \(setq org-read-date-popup-calendar nil)
15493 With optional argument TO-TIME, the date will immediately be converted
15494 to an internal time.
15495 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15496 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15497 still enter a time, and this function will inform the calling routine
15498 about this change. The calling routine may then choose to change the
15499 format used to insert the time stamp into the buffer to include the time.
15500 With optional argument FROM-STRING, read from this string instead from
15501 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15502 the time/date that is used for everything that is not specified by the
15503 user."
15504 (require 'parse-time)
15505 (let* ((org-time-stamp-rounding-minutes
15506 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15507 (org-dcst org-display-custom-times)
15508 (ct (org-current-time))
15509 (org-def (or org-overriding-default-time default-time ct))
15510 (org-defdecode (decode-time org-def))
15511 (dummy (progn
15512 (when (< (nth 2 org-defdecode) org-extend-today-until)
15513 (setcar (nthcdr 2 org-defdecode) -1)
15514 (setcar (nthcdr 1 org-defdecode) 59)
15515 (setq org-def (apply 'encode-time org-defdecode)
15516 org-defdecode (decode-time org-def)))))
15517 (calendar-frame-setup nil)
15518 (calendar-setup nil)
15519 (calendar-move-hook nil)
15520 (calendar-view-diary-initially-flag nil)
15521 (calendar-view-holidays-initially-flag nil)
15522 (timestr (format-time-string
15523 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15524 (prompt (concat (if prompt (concat prompt " ") "")
15525 (format "Date+time [%s]: " timestr)))
15526 ans (org-ans0 "") org-ans1 org-ans2 final)
15528 (cond
15529 (from-string (setq ans from-string))
15530 (org-read-date-popup-calendar
15531 (save-excursion
15532 (save-window-excursion
15533 (calendar)
15534 (org-eval-in-calendar '(setq cursor-type nil) t)
15535 (unwind-protect
15536 (progn
15537 (calendar-forward-day (- (time-to-days org-def)
15538 (calendar-absolute-from-gregorian
15539 (calendar-current-date))))
15540 (org-eval-in-calendar nil t)
15541 (let* ((old-map (current-local-map))
15542 (map (copy-keymap calendar-mode-map))
15543 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15544 (org-defkey map (kbd "RET") 'org-calendar-select)
15545 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15546 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15547 (org-defkey minibuffer-local-map [(meta shift left)]
15548 (lambda () (interactive)
15549 (org-eval-in-calendar '(calendar-backward-month 1))))
15550 (org-defkey minibuffer-local-map [(meta shift right)]
15551 (lambda () (interactive)
15552 (org-eval-in-calendar '(calendar-forward-month 1))))
15553 (org-defkey minibuffer-local-map [(meta shift up)]
15554 (lambda () (interactive)
15555 (org-eval-in-calendar '(calendar-backward-year 1))))
15556 (org-defkey minibuffer-local-map [(meta shift down)]
15557 (lambda () (interactive)
15558 (org-eval-in-calendar '(calendar-forward-year 1))))
15559 (org-defkey minibuffer-local-map [?\e (shift left)]
15560 (lambda () (interactive)
15561 (org-eval-in-calendar '(calendar-backward-month 1))))
15562 (org-defkey minibuffer-local-map [?\e (shift right)]
15563 (lambda () (interactive)
15564 (org-eval-in-calendar '(calendar-forward-month 1))))
15565 (org-defkey minibuffer-local-map [?\e (shift up)]
15566 (lambda () (interactive)
15567 (org-eval-in-calendar '(calendar-backward-year 1))))
15568 (org-defkey minibuffer-local-map [?\e (shift down)]
15569 (lambda () (interactive)
15570 (org-eval-in-calendar '(calendar-forward-year 1))))
15571 (org-defkey minibuffer-local-map [(shift up)]
15572 (lambda () (interactive)
15573 (org-eval-in-calendar '(calendar-backward-week 1))))
15574 (org-defkey minibuffer-local-map [(shift down)]
15575 (lambda () (interactive)
15576 (org-eval-in-calendar '(calendar-forward-week 1))))
15577 (org-defkey minibuffer-local-map [(shift left)]
15578 (lambda () (interactive)
15579 (org-eval-in-calendar '(calendar-backward-day 1))))
15580 (org-defkey minibuffer-local-map [(shift right)]
15581 (lambda () (interactive)
15582 (org-eval-in-calendar '(calendar-forward-day 1))))
15583 (org-defkey minibuffer-local-map ">"
15584 (lambda () (interactive)
15585 (org-eval-in-calendar '(scroll-calendar-left 1))))
15586 (org-defkey minibuffer-local-map "<"
15587 (lambda () (interactive)
15588 (org-eval-in-calendar '(scroll-calendar-right 1))))
15589 (org-defkey minibuffer-local-map "\C-v"
15590 (lambda () (interactive)
15591 (org-eval-in-calendar
15592 '(calendar-scroll-left-three-months 1))))
15593 (org-defkey minibuffer-local-map "\M-v"
15594 (lambda () (interactive)
15595 (org-eval-in-calendar
15596 '(calendar-scroll-right-three-months 1))))
15597 (run-hooks 'org-read-date-minibuffer-setup-hook)
15598 (unwind-protect
15599 (progn
15600 (use-local-map map)
15601 (setq org-read-date-inactive inactive)
15602 (add-hook 'post-command-hook 'org-read-date-display)
15603 (setq org-ans0 (read-string prompt default-input
15604 'org-read-date-history nil))
15605 ;; org-ans0: from prompt
15606 ;; org-ans1: from mouse click
15607 ;; org-ans2: from calendar motion
15608 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15609 (remove-hook 'post-command-hook 'org-read-date-display)
15610 (use-local-map old-map)
15611 (when org-read-date-overlay
15612 (delete-overlay org-read-date-overlay)
15613 (setq org-read-date-overlay nil)))))
15614 (bury-buffer "*Calendar*")))))
15616 (t ; Naked prompt only
15617 (unwind-protect
15618 (setq ans (read-string prompt default-input
15619 'org-read-date-history timestr))
15620 (when org-read-date-overlay
15621 (delete-overlay org-read-date-overlay)
15622 (setq org-read-date-overlay nil)))))
15624 (setq final (org-read-date-analyze ans org-def org-defdecode))
15626 (when org-read-date-analyze-forced-year
15627 (message "Year was forced into %s"
15628 (if org-read-date-force-compatible-dates
15629 "compatible range (1970-2037)"
15630 "range representable on this machine"))
15631 (ding))
15633 ;; One round trip to get rid of 34th of August and stuff like that....
15634 (setq final (decode-time (apply 'encode-time final)))
15636 (setq org-read-date-final-answer ans)
15638 (if to-time
15639 (apply 'encode-time final)
15640 (if (and (boundp 'org-time-was-given) org-time-was-given)
15641 (format "%04d-%02d-%02d %02d:%02d"
15642 (nth 5 final) (nth 4 final) (nth 3 final)
15643 (nth 2 final) (nth 1 final))
15644 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15646 (defvar org-def)
15647 (defvar org-defdecode)
15648 (defvar org-with-time)
15649 (defun org-read-date-display ()
15650 "Display the current date prompt interpretation in the minibuffer."
15651 (when org-read-date-display-live
15652 (when org-read-date-overlay
15653 (delete-overlay org-read-date-overlay))
15654 (when (minibufferp (current-buffer))
15655 (save-excursion
15656 (end-of-line 1)
15657 (while (not (equal (buffer-substring
15658 (max (point-min) (- (point) 4)) (point))
15659 " "))
15660 (insert " ")))
15661 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15662 " " (or org-ans1 org-ans2)))
15663 (org-end-time-was-given nil)
15664 (f (org-read-date-analyze ans org-def org-defdecode))
15665 (fmts (if org-dcst
15666 org-time-stamp-custom-formats
15667 org-time-stamp-formats))
15668 (fmt (if (or org-with-time
15669 (and (boundp 'org-time-was-given) org-time-was-given))
15670 (cdr fmts)
15671 (car fmts)))
15672 (txt (format-time-string fmt (apply 'encode-time f)))
15673 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15674 (txt (concat "=> " txt)))
15675 (when (and org-end-time-was-given
15676 (string-match org-plain-time-of-day-regexp txt))
15677 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15678 org-end-time-was-given
15679 (substring txt (match-end 0)))))
15680 (when org-read-date-analyze-futurep
15681 (setq txt (concat txt " (=>F)")))
15682 (setq org-read-date-overlay
15683 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15684 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15686 (defun org-read-date-analyze (ans org-def org-defdecode)
15687 "Analyze the combined answer of the date prompt."
15688 ;; FIXME: cleanup and comment
15689 (let ((nowdecode (decode-time (current-time)))
15690 delta deltan deltaw deltadef year month day
15691 hour minute second wday pm h2 m2 tl wday1
15692 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15693 (setq org-read-date-analyze-futurep nil
15694 org-read-date-analyze-forced-year nil)
15695 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15696 (setq ans "+0"))
15698 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15699 (setq ans (replace-match "" t t ans)
15700 deltan (car delta)
15701 deltaw (nth 1 delta)
15702 deltadef (nth 2 delta)))
15704 ;; Check if there is an iso week date in there. If yes, store the
15705 ;; info and postpone interpreting it until the rest of the parsing
15706 ;; is done.
15707 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15708 (setq iso-year (if (match-end 1)
15709 (org-small-year-to-year
15710 (string-to-number (match-string 1 ans))))
15711 iso-weekday (if (match-end 3)
15712 (string-to-number (match-string 3 ans)))
15713 iso-week (string-to-number (match-string 2 ans)))
15714 (setq ans (replace-match "" t t ans)))
15716 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15717 (when (string-match
15718 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15719 (setq year (if (match-end 2)
15720 (string-to-number (match-string 2 ans))
15721 (progn (setq kill-year t)
15722 (string-to-number (format-time-string "%Y"))))
15723 month (string-to-number (match-string 3 ans))
15724 day (string-to-number (match-string 4 ans)))
15725 (if (< year 100) (setq year (+ 2000 year)))
15726 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15727 t nil ans)))
15729 ;; Help matching dotted european dates
15730 (when (string-match
15731 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15732 (setq year (if (match-end 3)
15733 (string-to-number (match-string 3 ans))
15734 (progn (setq kill-year t)
15735 (string-to-number (format-time-string "%Y"))))
15736 day (string-to-number (match-string 1 ans))
15737 month (string-to-number (match-string 2 ans))
15738 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15739 t nil ans)))
15741 ;; Help matching american dates, like 5/30 or 5/30/7
15742 (when (string-match
15743 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15744 (setq year (if (match-end 4)
15745 (string-to-number (match-string 4 ans))
15746 (progn (setq kill-year t)
15747 (string-to-number (format-time-string "%Y"))))
15748 month (string-to-number (match-string 1 ans))
15749 day (string-to-number (match-string 2 ans)))
15750 (if (< year 100) (setq year (+ 2000 year)))
15751 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15752 t nil ans)))
15753 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15754 ;; If there is a time with am/pm, and *no* time without it, we convert
15755 ;; so that matching will be successful.
15756 (loop for i from 1 to 2 do ; twice, for end time as well
15757 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15758 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15759 (setq hour (string-to-number (match-string 1 ans))
15760 minute (if (match-end 3)
15761 (string-to-number (match-string 3 ans))
15763 pm (equal ?p
15764 (string-to-char (downcase (match-string 4 ans)))))
15765 (if (and (= hour 12) (not pm))
15766 (setq hour 0)
15767 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15768 (setq ans (replace-match (format "%02d:%02d" hour minute)
15769 t t ans))))
15771 ;; Check if a time range is given as a duration
15772 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15773 (setq hour (string-to-number (match-string 1 ans))
15774 h2 (+ hour (string-to-number (match-string 3 ans)))
15775 minute (string-to-number (match-string 2 ans))
15776 m2 (+ minute (if (match-end 5) (string-to-number
15777 (match-string 5 ans))0)))
15778 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15779 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15780 t t ans)))
15782 ;; Check if there is a time range
15783 (when (boundp 'org-end-time-was-given)
15784 (setq org-time-was-given nil)
15785 (when (and (string-match org-plain-time-of-day-regexp ans)
15786 (match-end 8))
15787 (setq org-end-time-was-given (match-string 8 ans))
15788 (setq ans (concat (substring ans 0 (match-beginning 7))
15789 (substring ans (match-end 7))))))
15791 (setq tl (parse-time-string ans)
15792 day (or (nth 3 tl) (nth 3 org-defdecode))
15793 month (or (nth 4 tl)
15794 (if (and org-read-date-prefer-future
15795 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15796 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15797 (nth 4 org-defdecode)))
15798 year (or (and (not kill-year) (nth 5 tl))
15799 (if (and org-read-date-prefer-future
15800 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15801 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15802 (nth 5 org-defdecode)))
15803 hour (or (nth 2 tl) (nth 2 org-defdecode))
15804 minute (or (nth 1 tl) (nth 1 org-defdecode))
15805 second (or (nth 0 tl) 0)
15806 wday (nth 6 tl))
15808 (when (and (eq org-read-date-prefer-future 'time)
15809 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15810 (equal day (nth 3 nowdecode))
15811 (equal month (nth 4 nowdecode))
15812 (equal year (nth 5 nowdecode))
15813 (nth 2 tl)
15814 (or (< (nth 2 tl) (nth 2 nowdecode))
15815 (and (= (nth 2 tl) (nth 2 nowdecode))
15816 (nth 1 tl)
15817 (< (nth 1 tl) (nth 1 nowdecode)))))
15818 (setq day (1+ day)
15819 futurep t))
15821 ;; Special date definitions below
15822 (cond
15823 (iso-week
15824 ;; There was an iso week
15825 (require 'cal-iso)
15826 (setq futurep nil)
15827 (setq year (or iso-year year)
15828 day (or iso-weekday wday 1)
15829 wday nil ; to make sure that the trigger below does not match
15830 iso-date (calendar-gregorian-from-absolute
15831 (calendar-absolute-from-iso
15832 (list iso-week day year))))
15833 ; FIXME: Should we also push ISO weeks into the future?
15834 ; (when (and org-read-date-prefer-future
15835 ; (not iso-year)
15836 ; (< (calendar-absolute-from-gregorian iso-date)
15837 ; (time-to-days (current-time))))
15838 ; (setq year (1+ year)
15839 ; iso-date (calendar-gregorian-from-absolute
15840 ; (calendar-absolute-from-iso
15841 ; (list iso-week day year)))))
15842 (setq month (car iso-date)
15843 year (nth 2 iso-date)
15844 day (nth 1 iso-date)))
15845 (deltan
15846 (setq futurep nil)
15847 (unless deltadef
15848 (let ((now (decode-time (current-time))))
15849 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15850 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15851 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15852 ((equal deltaw "m") (setq month (+ month deltan)))
15853 ((equal deltaw "y") (setq year (+ year deltan)))))
15854 ((and wday (not (nth 3 tl)))
15855 ;; Weekday was given, but no day, so pick that day in the week
15856 ;; on or after the derived date.
15857 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15858 (unless (equal wday wday1)
15859 (setq day (+ day (% (- wday wday1 -7) 7))))))
15860 (if (and (boundp 'org-time-was-given)
15861 (nth 2 tl))
15862 (setq org-time-was-given t))
15863 (if (< year 100) (setq year (+ 2000 year)))
15864 ;; Check of the date is representable
15865 (if org-read-date-force-compatible-dates
15866 (progn
15867 (if (< year 1970)
15868 (setq year 1970 org-read-date-analyze-forced-year t))
15869 (if (> year 2037)
15870 (setq year 2037 org-read-date-analyze-forced-year t)))
15871 (condition-case nil
15872 (ignore (encode-time second minute hour day month year))
15873 (error
15874 (setq year (nth 5 org-defdecode))
15875 (setq org-read-date-analyze-forced-year t))))
15876 (setq org-read-date-analyze-futurep futurep)
15877 (list second minute hour day month year)))
15879 (defvar parse-time-weekdays)
15880 (defun org-read-date-get-relative (s today default)
15881 "Check string S for special relative date string.
15882 TODAY and DEFAULT are internal times, for today and for a default.
15883 Return shift list (N what def-flag)
15884 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15885 N is the number of WHATs to shift.
15886 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15887 the DEFAULT date rather than TODAY."
15888 (require 'parse-time)
15889 (when (and
15890 (string-match
15891 (concat
15892 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15893 "\\([0-9]+\\)?"
15894 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15895 "\\([ \t]\\|$\\)") s)
15896 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15897 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15898 (string-to-char (substring (match-string 1 s) -1))
15899 ?+))
15900 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15901 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15902 (what (if (match-end 3) (match-string 3 s) "d"))
15903 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15904 (date (if rel default today))
15905 (wday (nth 6 (decode-time date)))
15906 delta)
15907 (if wday1
15908 (progn
15909 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15910 (if (= dir ?-) (setq delta (- delta 7)))
15911 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15912 (list delta "d" rel))
15913 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15915 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15916 "Turn a user-specified date into the internal representation.
15917 The internal representation needed by the calendar is (month day year).
15918 This is a wrapper to handle the brain-dead convention in calendar that
15919 user function argument order change dependent on argument order."
15920 (if (boundp 'calendar-date-style)
15921 (cond
15922 ((eq calendar-date-style 'american)
15923 (list arg1 arg2 arg3))
15924 ((eq calendar-date-style 'european)
15925 (list arg2 arg1 arg3))
15926 ((eq calendar-date-style 'iso)
15927 (list arg2 arg3 arg1)))
15928 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15929 (if (org-bound-and-true-p european-calendar-style)
15930 (list arg2 arg1 arg3)
15931 (list arg1 arg2 arg3)))))
15933 (defun org-eval-in-calendar (form &optional keepdate)
15934 "Eval FORM in the calendar window and return to current window.
15935 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15936 otherwise stick to the current value of `org-ans2'."
15937 (let ((sf (selected-frame))
15938 (sw (selected-window)))
15939 (select-window (get-buffer-window "*Calendar*" t))
15940 (eval form)
15941 (when (and (not keepdate) (calendar-cursor-to-date))
15942 (let* ((date (calendar-cursor-to-date))
15943 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15944 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15945 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15946 (select-window sw)
15947 (org-select-frame-set-input-focus sf)))
15949 (defun org-calendar-select ()
15950 "Return to `org-read-date' with the date currently selected.
15951 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15952 (interactive)
15953 (when (calendar-cursor-to-date)
15954 (let* ((date (calendar-cursor-to-date))
15955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15956 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15957 (if (active-minibuffer-window) (exit-minibuffer))))
15959 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15960 "Insert a date stamp for the date given by the internal TIME.
15961 WITH-HM means use the stamp format that includes the time of the day.
15962 INACTIVE means use square brackets instead of angular ones, so that the
15963 stamp will not contribute to the agenda.
15964 PRE and POST are optional strings to be inserted before and after the
15965 stamp.
15966 The command returns the inserted time stamp."
15967 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15968 stamp)
15969 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15970 (insert-before-markers (or pre ""))
15971 (when (listp extra)
15972 (setq extra (car extra))
15973 (if (and (stringp extra)
15974 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15975 (setq extra (format "-%02d:%02d"
15976 (string-to-number (match-string 1 extra))
15977 (string-to-number (match-string 2 extra))))
15978 (setq extra nil)))
15979 (when extra
15980 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15981 (insert-before-markers (setq stamp (format-time-string fmt time)))
15982 (insert-before-markers (or post ""))
15983 (setq org-last-inserted-timestamp stamp)))
15985 (defun org-toggle-time-stamp-overlays ()
15986 "Toggle the use of custom time stamp formats."
15987 (interactive)
15988 (setq org-display-custom-times (not org-display-custom-times))
15989 (unless org-display-custom-times
15990 (let ((p (point-min)) (bmp (buffer-modified-p)))
15991 (while (setq p (next-single-property-change p 'display))
15992 (if (and (get-text-property p 'display)
15993 (eq (get-text-property p 'face) 'org-date))
15994 (remove-text-properties
15995 p (setq p (next-single-property-change p 'display))
15996 '(display t))))
15997 (set-buffer-modified-p bmp)))
15998 (if (featurep 'xemacs)
15999 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16000 (org-restart-font-lock)
16001 (setq org-table-may-need-update t)
16002 (if org-display-custom-times
16003 (message "Time stamps are overlaid with custom format")
16004 (message "Time stamp overlays removed")))
16006 (defun org-display-custom-time (beg end)
16007 "Overlay modified time stamp format over timestamp between BEG and END."
16008 (let* ((ts (buffer-substring beg end))
16009 t1 w1 with-hm tf time str w2 (off 0))
16010 (save-match-data
16011 (setq t1 (org-parse-time-string ts t))
16012 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16013 (setq off (- (match-end 0) (match-beginning 0)))))
16014 (setq end (- end off))
16015 (setq w1 (- end beg)
16016 with-hm (and (nth 1 t1) (nth 2 t1))
16017 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16018 time (org-fix-decoded-time t1)
16019 str (org-add-props
16020 (format-time-string
16021 (substring tf 1 -1) (apply 'encode-time time))
16022 nil 'mouse-face 'highlight)
16023 w2 (length str))
16024 (if (not (= w2 w1))
16025 (add-text-properties (1+ beg) (+ 2 beg)
16026 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16027 (if (featurep 'xemacs)
16028 (progn
16029 (put-text-property beg end 'invisible t)
16030 (put-text-property beg end 'end-glyph (make-glyph str)))
16031 (put-text-property beg end 'display str))))
16033 (defun org-translate-time (string)
16034 "Translate all timestamps in STRING to custom format.
16035 But do this only if the variable `org-display-custom-times' is set."
16036 (when org-display-custom-times
16037 (save-match-data
16038 (let* ((start 0)
16039 (re org-ts-regexp-both)
16040 t1 with-hm inactive tf time str beg end)
16041 (while (setq start (string-match re string start))
16042 (setq beg (match-beginning 0)
16043 end (match-end 0)
16044 t1 (save-match-data
16045 (org-parse-time-string (substring string beg end) t))
16046 with-hm (and (nth 1 t1) (nth 2 t1))
16047 inactive (equal (substring string beg (1+ beg)) "[")
16048 tf (funcall (if with-hm 'cdr 'car)
16049 org-time-stamp-custom-formats)
16050 time (org-fix-decoded-time t1)
16051 str (format-time-string
16052 (concat
16053 (if inactive "[" "<") (substring tf 1 -1)
16054 (if inactive "]" ">"))
16055 (apply 'encode-time time))
16056 string (replace-match str t t string)
16057 start (+ start (length str)))))))
16058 string)
16060 (defun org-fix-decoded-time (time)
16061 "Set 0 instead of nil for the first 6 elements of time.
16062 Don't touch the rest."
16063 (let ((n 0))
16064 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16066 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16068 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16069 "Difference between TIMESTAMP-STRING and now in days.
16070 If SECONDS is non-nil, return the difference in seconds."
16071 (let ((fdiff (if seconds 'time-to-seconds 'time-to-days)))
16072 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16073 (funcall fdiff (current-time)))))
16075 (defun org-deadline-close (timestamp-string &optional ndays)
16076 "Is the time in TIMESTAMP-STRING close to the current date?"
16077 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16078 (and (< (org-days-to-time timestamp-string) ndays)
16079 (not (org-entry-is-done-p))))
16081 (defun org-get-wdays (ts)
16082 "Get the deadline lead time appropriate for timestring TS."
16083 (cond
16084 ((<= org-deadline-warning-days 0)
16085 ;; 0 or negative, enforce this value no matter what
16086 (- org-deadline-warning-days))
16087 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16088 ;; lead time is specified.
16089 (floor (* (string-to-number (match-string 1 ts))
16090 (cdr (assoc (match-string 2 ts)
16091 '(("d" . 1) ("w" . 7)
16092 ("m" . 30.4) ("y" . 365.25)))))))
16093 ;; go for the default.
16094 (t org-deadline-warning-days)))
16096 (defun org-calendar-select-mouse (ev)
16097 "Return to `org-read-date' with the date currently selected.
16098 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16099 (interactive "e")
16100 (mouse-set-point ev)
16101 (when (calendar-cursor-to-date)
16102 (let* ((date (calendar-cursor-to-date))
16103 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16104 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16105 (if (active-minibuffer-window) (exit-minibuffer))))
16107 (defun org-check-deadlines (ndays)
16108 "Check if there are any deadlines due or past due.
16109 A deadline is considered due if it happens within `org-deadline-warning-days'
16110 days from today's date. If the deadline appears in an entry marked DONE,
16111 it is not shown. The prefix arg NDAYS can be used to test that many
16112 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16113 (interactive "P")
16114 (let* ((org-warn-days
16115 (cond
16116 ((equal ndays '(4)) 100000)
16117 (ndays (prefix-numeric-value ndays))
16118 (t (abs org-deadline-warning-days))))
16119 (case-fold-search nil)
16120 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16121 (callback
16122 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16124 (message "%d deadlines past-due or due within %d days"
16125 (org-occur regexp nil callback)
16126 org-warn-days)))
16128 (defsubst org-re-timestamp (type)
16129 "Return a regexp for timestamp TYPE.
16130 Allowed values for TYPE are:
16132 all: all timestamps
16133 active: only active timestamps (<...>)
16134 inactive: only inactive timestamps ([...])
16135 scheduled: only scheduled timestamps
16136 deadline: only deadline timestamps
16138 When TYPE is nil, fall back on returning a regexp that matches
16139 both scheduled and deadline timestamps."
16140 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16141 ((eq type 'active) org-ts-regexp)
16142 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16143 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16144 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16145 ((eq type 'scheduled-or-deadline)
16146 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16148 (defun org-check-before-date (date)
16149 "Check if there are deadlines or scheduled entries before DATE."
16150 (interactive (list (org-read-date)))
16151 (let ((case-fold-search nil)
16152 (regexp (org-re-timestamp org-ts-type))
16153 (callback
16154 (lambda () (time-less-p
16155 (org-time-string-to-time (match-string 1))
16156 (org-time-string-to-time date)))))
16157 (message "%d entries before %s"
16158 (org-occur regexp nil callback) date)))
16160 (defun org-check-after-date (date)
16161 "Check if there are deadlines or scheduled entries after DATE."
16162 (interactive (list (org-read-date)))
16163 (let ((case-fold-search nil)
16164 (regexp (org-re-timestamp org-ts-type))
16165 (callback
16166 (lambda () (not
16167 (time-less-p
16168 (org-time-string-to-time (match-string 1))
16169 (org-time-string-to-time date))))))
16170 (message "%d entries after %s"
16171 (org-occur regexp nil callback) date)))
16173 (defun org-check-dates-range (start-date end-date)
16174 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16175 (interactive (list (org-read-date nil nil nil "Range starts")
16176 (org-read-date nil nil nil "Range end")))
16177 (let ((case-fold-search nil)
16178 (regexp (org-re-timestamp org-ts-type))
16179 (callback
16180 (lambda ()
16181 (let ((match (match-string 1)))
16182 (and
16183 (not (time-less-p
16184 (org-time-string-to-time match)
16185 (org-time-string-to-time start-date)))
16186 (time-less-p
16187 (org-time-string-to-time match)
16188 (org-time-string-to-time end-date)))))))
16189 (message "%d entries between %s and %s"
16190 (org-occur regexp nil callback) start-date end-date)))
16192 (defun org-evaluate-time-range (&optional to-buffer)
16193 "Evaluate a time range by computing the difference between start and end.
16194 Normally the result is just printed in the echo area, but with prefix arg
16195 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16196 If the time range is actually in a table, the result is inserted into the
16197 next column.
16198 For time difference computation, a year is assumed to be exactly 365
16199 days in order to avoid rounding problems."
16200 (interactive "P")
16202 (org-clock-update-time-maybe)
16203 (save-excursion
16204 (unless (org-at-date-range-p t)
16205 (goto-char (point-at-bol))
16206 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16207 (if (not (org-at-date-range-p t))
16208 (error "Not at a time-stamp range, and none found in current line")))
16209 (let* ((ts1 (match-string 1))
16210 (ts2 (match-string 2))
16211 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16212 (match-end (match-end 0))
16213 (time1 (org-time-string-to-time ts1))
16214 (time2 (org-time-string-to-time ts2))
16215 (t1 (org-float-time time1))
16216 (t2 (org-float-time time2))
16217 (diff (abs (- t2 t1)))
16218 (negative (< (- t2 t1) 0))
16219 ;; (ys (floor (* 365 24 60 60)))
16220 (ds (* 24 60 60))
16221 (hs (* 60 60))
16222 (fy "%dy %dd %02d:%02d")
16223 (fy1 "%dy %dd")
16224 (fd "%dd %02d:%02d")
16225 (fd1 "%dd")
16226 (fh "%02d:%02d")
16227 y d h m align)
16228 (if havetime
16229 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16231 d (floor (/ diff ds)) diff (mod diff ds)
16232 h (floor (/ diff hs)) diff (mod diff hs)
16233 m (floor (/ diff 60)))
16234 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16236 d (floor (+ (/ diff ds) 0.5))
16237 h 0 m 0))
16238 (if (not to-buffer)
16239 (message "%s" (org-make-tdiff-string y d h m))
16240 (if (org-at-table-p)
16241 (progn
16242 (goto-char match-end)
16243 (setq align t)
16244 (and (looking-at " *|") (goto-char (match-end 0))))
16245 (goto-char match-end))
16246 (if (looking-at
16247 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16248 (replace-match ""))
16249 (if negative (insert " -"))
16250 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16251 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16252 (insert " " (format fh h m))))
16253 (if align (org-table-align))
16254 (message "Time difference inserted")))))
16256 (defun org-make-tdiff-string (y d h m)
16257 (let ((fmt "")
16258 (l nil))
16259 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16260 l (push y l)))
16261 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16262 l (push d l)))
16263 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16264 l (push h l)))
16265 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16266 l (push m l)))
16267 (apply 'format fmt (nreverse l))))
16269 (defun org-time-string-to-time (s &optional buffer pos)
16270 "Convert a timestamp string into internal time."
16271 (condition-case errdata
16272 (apply 'encode-time (org-parse-time-string s))
16273 (error (error "Bad timestamp `%s'%s\nError was: %s"
16274 s (if (not (and buffer pos))
16276 (format " at %d in buffer `%s'" pos buffer))
16277 (cdr errdata)))))
16279 (defun org-time-string-to-seconds (s)
16280 "Convert a timestamp string to a number of seconds."
16281 (org-float-time (org-time-string-to-time s)))
16283 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16284 "Convert a time stamp to an absolute day number.
16285 If there is a specifier for a cyclic time stamp, get the closest date to
16286 DAYNR.
16287 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16288 The variable date is bound by the calendar when this is called."
16289 (cond
16290 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16291 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16292 daynr
16293 (+ daynr 1000)))
16294 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16295 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16296 (time-to-days (current-time))) (match-string 0 s)
16297 prefer show-all))
16298 (t (time-to-days
16299 (condition-case errdata
16300 (apply 'encode-time (org-parse-time-string s))
16301 (error (error "Bad timestamp `%s'%s\nError was: %s"
16302 s (if (not (and buffer pos))
16304 (format " at %d in buffer `%s'" pos buffer))
16305 (cdr errdata))))))))
16307 (defun org-days-to-iso-week (days)
16308 "Return the iso week number."
16309 (require 'cal-iso)
16310 (car (calendar-iso-from-absolute days)))
16312 (defun org-small-year-to-year (year)
16313 "Convert 2-digit years into 4-digit years.
16314 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16315 The year 2000 cannot be abbreviated. Any year larger than 99
16316 is returned unchanged."
16317 (if (< year 38)
16318 (setq year (+ 2000 year))
16319 (if (< year 100)
16320 (setq year (+ 1900 year))))
16321 year)
16323 (defun org-time-from-absolute (d)
16324 "Return the time corresponding to date D.
16325 D may be an absolute day number, or a calendar-type list (month day year)."
16326 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16327 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16329 (defun org-calendar-holiday ()
16330 "List of holidays, for Diary display in Org-mode."
16331 (require 'holidays)
16332 (let ((hl (funcall
16333 (if (fboundp 'calendar-check-holidays)
16334 'calendar-check-holidays 'check-calendar-holidays) date)))
16335 (if hl (mapconcat 'identity hl "; "))))
16337 (defun org-diary-sexp-entry (sexp entry date)
16338 "Process a SEXP diary ENTRY for DATE."
16339 (require 'diary-lib)
16340 (let ((result (if calendar-debug-sexp
16341 (let ((stack-trace-on-error t))
16342 (eval (car (read-from-string sexp))))
16343 (condition-case nil
16344 (eval (car (read-from-string sexp)))
16345 (error
16346 (beep)
16347 (message "Bad sexp at line %d in %s: %s"
16348 (org-current-line)
16349 (buffer-file-name) sexp)
16350 (sleep-for 2))))))
16351 (cond ((stringp result) (split-string result "; "))
16352 ((and (consp result)
16353 (not (consp (cdr result)))
16354 (stringp (cdr result))) (cdr result))
16355 ((and (consp result)
16356 (stringp (car result))) result)
16357 (result entry))))
16359 (defun org-diary-to-ical-string (frombuf)
16360 "Get iCalendar entries from diary entries in buffer FROMBUF.
16361 This uses the icalendar.el library."
16362 (let* ((tmpdir (if (featurep 'xemacs)
16363 (temp-directory)
16364 temporary-file-directory))
16365 (tmpfile (make-temp-name
16366 (expand-file-name "orgics" tmpdir)))
16367 buf rtn b e)
16368 (with-current-buffer frombuf
16369 (icalendar-export-region (point-min) (point-max) tmpfile)
16370 (setq buf (find-buffer-visiting tmpfile))
16371 (set-buffer buf)
16372 (goto-char (point-min))
16373 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16374 (setq b (match-beginning 0)))
16375 (goto-char (point-max))
16376 (if (re-search-backward "^END:VEVENT" nil t)
16377 (setq e (match-end 0)))
16378 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16379 (kill-buffer buf)
16380 (delete-file tmpfile)
16381 rtn))
16383 (defun org-closest-date (start current change prefer show-all)
16384 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16385 When PREFER is `past', return a date that is either CURRENT or past.
16386 When PREFER is `future', return a date that is either CURRENT or future.
16387 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16388 ;; Make the proper lists from the dates
16389 (catch 'exit
16390 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16391 dn dw sday cday n1 n2 n0
16392 d m y y1 y2 date1 date2 nmonths nm ny m2)
16394 (setq start (org-date-to-gregorian start)
16395 current (org-date-to-gregorian
16396 (if show-all
16397 current
16398 (time-to-days (current-time))))
16399 sday (calendar-absolute-from-gregorian start)
16400 cday (calendar-absolute-from-gregorian current))
16402 (if (<= cday sday) (throw 'exit sday))
16404 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16405 (setq dn (string-to-number (match-string 1 change))
16406 dw (cdr (assoc (match-string 2 change) a1)))
16407 (error "Invalid change specifier: %s" change))
16408 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16409 (cond
16410 ((eq dw 'day)
16411 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16412 n2 (+ n1 dn)))
16413 ((eq dw 'year)
16414 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16415 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16416 (setq date1 (list m d y1)
16417 n1 (calendar-absolute-from-gregorian date1)
16418 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16419 n2 (calendar-absolute-from-gregorian date2)))
16420 ((eq dw 'month)
16421 ;; approx number of month between the two dates
16422 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16423 ;; How often does dn fit in there?
16424 (setq d (nth 1 start) m (car start) y (nth 2 start)
16425 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16426 m (+ m nm)
16427 ny (floor (/ m 12))
16428 y (+ y ny)
16429 m (- m (* ny 12)))
16430 (while (> m 12) (setq m (- m 12) y (1+ y)))
16431 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16432 (setq m2 (+ m dn) y2 y)
16433 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16434 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16435 (while (<= n2 cday)
16436 (setq n1 n2 m m2 y y2)
16437 (setq m2 (+ m dn) y2 y)
16438 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16439 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16440 ;; Make sure n1 is the earlier date
16441 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16442 (if show-all
16443 (cond
16444 ((eq prefer 'past) (if (= cday n2) n2 n1))
16445 ((eq prefer 'future) (if (= cday n1) n1 n2))
16446 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16447 (cond
16448 ((eq prefer 'past) (if (= cday n2) n2 n1))
16449 ((eq prefer 'future) (if (= cday n1) n1 n2))
16450 (t (if (= cday n1) n1 n2)))))))
16452 (defun org-date-to-gregorian (date)
16453 "Turn any specification of DATE into a Gregorian date for the calendar."
16454 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16455 ((and (listp date) (= (length date) 3)) date)
16456 ((stringp date)
16457 (setq date (org-parse-time-string date))
16458 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16459 ((listp date)
16460 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16462 (defun org-parse-time-string (s &optional nodefault)
16463 "Parse the standard Org-mode time string.
16464 This should be a lot faster than the normal `parse-time-string'.
16465 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16466 hour and minute fields will be nil if not given."
16467 (if (string-match org-ts-regexp0 s)
16468 (list 0
16469 (if (or (match-beginning 8) (not nodefault))
16470 (string-to-number (or (match-string 8 s) "0")))
16471 (if (or (match-beginning 7) (not nodefault))
16472 (string-to-number (or (match-string 7 s) "0")))
16473 (string-to-number (match-string 4 s))
16474 (string-to-number (match-string 3 s))
16475 (string-to-number (match-string 2 s))
16476 nil nil nil)
16477 (error "Not a standard Org-mode time string: %s" s)))
16479 (defun org-timestamp-up (&optional arg)
16480 "Increase the date item at the cursor by one.
16481 If the cursor is on the year, change the year. If it is on the month,
16482 the day or the time, change that.
16483 With prefix ARG, change by that many units."
16484 (interactive "p")
16485 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16487 (defun org-timestamp-down (&optional arg)
16488 "Decrease 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-up-day (&optional arg)
16496 "Increase the date in the time stamp by one day.
16497 With prefix ARG, change that many days."
16498 (interactive "p")
16499 (if (and (not (org-at-timestamp-p t))
16500 (org-at-heading-p))
16501 (org-todo 'up)
16502 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16504 (defun org-timestamp-down-day (&optional arg)
16505 "Decrease the date in the time stamp by one day.
16506 With prefix ARG, change that many days."
16507 (interactive "p")
16508 (if (and (not (org-at-timestamp-p t))
16509 (org-at-heading-p))
16510 (org-todo 'down)
16511 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16513 (defun org-at-timestamp-p (&optional inactive-ok)
16514 "Determine if the cursor is in or at a timestamp."
16515 (interactive)
16516 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16517 (pos (point))
16518 (ans (or (looking-at tsr)
16519 (save-excursion
16520 (skip-chars-backward "^[<\n\r\t")
16521 (if (> (point) (point-min)) (backward-char 1))
16522 (and (looking-at tsr)
16523 (> (- (match-end 0) pos) -1))))))
16524 (and ans
16525 (boundp 'org-ts-what)
16526 (setq org-ts-what
16527 (cond
16528 ((= pos (match-beginning 0)) 'bracket)
16529 ;; Point is considered to be "on the bracket" whether
16530 ;; it's really on it or right after it.
16531 ((= pos (1- (match-end 0))) 'bracket)
16532 ((= pos (match-end 0)) 'after)
16533 ((org-pos-in-match-range pos 2) 'year)
16534 ((org-pos-in-match-range pos 3) 'month)
16535 ((org-pos-in-match-range pos 7) 'hour)
16536 ((org-pos-in-match-range pos 8) 'minute)
16537 ((or (org-pos-in-match-range pos 4)
16538 (org-pos-in-match-range pos 5)) 'day)
16539 ((and (> pos (or (match-end 8) (match-end 5)))
16540 (< pos (match-end 0)))
16541 (- pos (or (match-end 8) (match-end 5))))
16542 (t 'day))))
16543 ans))
16545 (defun org-toggle-timestamp-type ()
16546 "Toggle the type (<active> or [inactive]) of a time stamp."
16547 (interactive)
16548 (when (org-at-timestamp-p t)
16549 (let ((beg (match-beginning 0)) (end (match-end 0))
16550 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16551 (save-excursion
16552 (goto-char beg)
16553 (while (re-search-forward "[][<>]" end t)
16554 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16555 t t)))
16556 (message "Timestamp is now %sactive"
16557 (if (equal (char-after beg) ?<) "" "in")))))
16559 (defvar org-clock-history) ; defined in org-clock.el
16560 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16561 (defun org-timestamp-change (n &optional what updown)
16562 "Change the date in the time stamp at point.
16563 The date will be changed by N times WHAT. WHAT can be `day', `month',
16564 `year', `minute', `second'. If WHAT is not given, the cursor position
16565 in the timestamp determines what will be changed."
16566 (let ((origin (point)) origin-cat
16567 with-hm inactive
16568 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16569 org-ts-what
16570 extra rem
16571 ts time time0 fixnext clrgx)
16572 (if (not (org-at-timestamp-p t))
16573 (error "Not at a timestamp"))
16574 (if (and (not what) (eq org-ts-what 'bracket))
16575 (org-toggle-timestamp-type)
16576 ;; Point isn't on brackets. Remember the part of the time-stamp
16577 ;; the point was in. Indeed, size of time-stamps may change,
16578 ;; but point must be kept in the same category nonetheless.
16579 (setq origin-cat org-ts-what)
16580 (if (and (not what) (not (eq org-ts-what 'day))
16581 org-display-custom-times
16582 (get-text-property (point) 'display)
16583 (not (get-text-property (1- (point)) 'display)))
16584 (setq org-ts-what 'day))
16585 (setq org-ts-what (or what org-ts-what)
16586 inactive (= (char-after (match-beginning 0)) ?\[)
16587 ts (match-string 0))
16588 (replace-match "")
16589 (if (string-match
16590 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16592 (setq extra (match-string 1 ts)))
16593 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16594 (setq with-hm t))
16595 (setq time0 (org-parse-time-string ts))
16596 (when (and updown
16597 (eq org-ts-what 'minute)
16598 (not current-prefix-arg))
16599 ;; This looks like s-up and s-down. Change by one rounding step.
16600 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16601 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16602 (setcar (cdr time0) (+ (nth 1 time0)
16603 (if (> n 0) (- rem) (- dm rem))))))
16604 (setq time
16605 (encode-time (or (car time0) 0)
16606 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16607 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16608 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16609 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16610 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16611 (nthcdr 6 time0)))
16612 (when (and (member org-ts-what '(hour minute))
16613 extra
16614 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16615 (setq extra (org-modify-ts-extra
16616 extra
16617 (if (eq org-ts-what 'hour) 2 5)
16618 n dm)))
16619 (when (integerp org-ts-what)
16620 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16621 (if (eq what 'calendar)
16622 (let ((cal-date (org-get-date-from-calendar)))
16623 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16624 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16625 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16626 (setcar time0 (or (car time0) 0))
16627 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16628 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16629 (setq time (apply 'encode-time time0))))
16630 ;; Insert the new time-stamp, and ensure point stays in the same
16631 ;; category as before (i.e. not after the last position in that
16632 ;; category).
16633 (let ((pos (point)))
16634 ;; Stay before inserted string. `save-excursion' is of no use.
16635 (setq org-last-changed-timestamp
16636 (org-insert-time-stamp time with-hm inactive nil nil extra))
16637 (goto-char pos))
16638 (save-match-data
16639 (looking-at org-ts-regexp3)
16640 (goto-char (cond
16641 ;; `day' category ends before `hour' if any, or at
16642 ;; the end of the day name.
16643 ((eq origin-cat 'day)
16644 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16645 ((eq origin-cat 'hour) (min (match-end 7) origin))
16646 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16647 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16648 ;; `year' and `month' have both fixed size: point
16649 ;; couldn't have moved into another part.
16650 (t origin))))
16651 ;; Update clock if on a CLOCK line.
16652 (org-clock-update-time-maybe)
16653 ;; Maybe adjust the closest clock in `org-clock-history'
16654 (when org-clock-adjust-closest
16655 (if (not (and (org-at-clock-log-p)
16656 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16657 org-clock-history))))))
16658 (message "No clock to adjust")
16659 (cond ((save-excursion ; fix previous clock?
16660 (re-search-backward org-ts-regexp0 nil t)
16661 (org-looking-back (concat org-clock-string " \\[")))
16662 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16663 ((save-excursion ; fix next clock?
16664 (re-search-backward org-ts-regexp0 nil t)
16665 (looking-at (concat org-ts-regexp0 "\\] =>")))
16666 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16667 (save-window-excursion
16668 ;; Find closest clock to point, adjust the previous/next one in history
16669 (let* ((p (save-excursion (org-back-to-heading t)))
16670 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16671 (clfixnth
16672 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16673 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16674 (if (not clfixpos)
16675 (message "No clock to adjust")
16676 (save-excursion
16677 (org-goto-marker-or-bmk clfixpos)
16678 (org-show-subtree)
16679 (when (re-search-forward clrgx nil t)
16680 (goto-char (match-beginning 1))
16681 (let (org-clock-adjust-closest)
16682 (org-timestamp-change n org-ts-what updown))
16683 (message "Clock adjusted in %s for heading: %s"
16684 (file-name-nondirectory (buffer-file-name))
16685 (org-get-heading t t)))))))))
16686 ;; Try to recenter the calendar window, if any.
16687 (if (and org-calendar-follow-timestamp-change
16688 (get-buffer-window "*Calendar*" t)
16689 (memq org-ts-what '(day month year)))
16690 (org-recenter-calendar (time-to-days time))))))
16692 (defun org-modify-ts-extra (s pos n dm)
16693 "Change the different parts of the lead-time and repeat fields in timestamp."
16694 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16695 ng h m new rem)
16696 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16697 (cond
16698 ((or (org-pos-in-match-range pos 2)
16699 (org-pos-in-match-range pos 3))
16700 (setq m (string-to-number (match-string 3 s))
16701 h (string-to-number (match-string 2 s)))
16702 (if (org-pos-in-match-range pos 2)
16703 (setq h (+ h n))
16704 (setq n (* dm (org-no-warnings (signum n))))
16705 (when (not (= 0 (setq rem (% m dm))))
16706 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16707 (setq m (+ m n)))
16708 (if (< m 0) (setq m (+ m 60) h (1- h)))
16709 (if (> m 59) (setq m (- m 60) h (1+ h)))
16710 (setq h (min 24 (max 0 h)))
16711 (setq ng 1 new (format "-%02d:%02d" h m)))
16712 ((org-pos-in-match-range pos 6)
16713 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16714 ((org-pos-in-match-range pos 5)
16715 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16717 ((org-pos-in-match-range pos 9)
16718 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16719 ((org-pos-in-match-range pos 8)
16720 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16722 (when ng
16723 (setq s (concat
16724 (substring s 0 (match-beginning ng))
16726 (substring s (match-end ng))))))
16729 (defun org-recenter-calendar (date)
16730 "If the calendar is visible, recenter it to DATE."
16731 (let ((cwin (get-buffer-window "*Calendar*" t)))
16732 (when cwin
16733 (let ((calendar-move-hook nil))
16734 (with-selected-window cwin
16735 (calendar-goto-date (if (listp date) date
16736 (calendar-gregorian-from-absolute date))))))))
16738 (defun org-goto-calendar (&optional arg)
16739 "Go to the Emacs calendar at the current date.
16740 If there is a time stamp in the current line, go to that date.
16741 A prefix ARG can be used to force the current date."
16742 (interactive "P")
16743 (let ((tsr org-ts-regexp) diff
16744 (calendar-move-hook nil)
16745 (calendar-view-holidays-initially-flag nil)
16746 (calendar-view-diary-initially-flag nil))
16747 (if (or (org-at-timestamp-p)
16748 (save-excursion
16749 (beginning-of-line 1)
16750 (looking-at (concat ".*" tsr))))
16751 (let ((d1 (time-to-days (current-time)))
16752 (d2 (time-to-days
16753 (org-time-string-to-time (match-string 1)))))
16754 (setq diff (- d2 d1))))
16755 (calendar)
16756 (calendar-goto-today)
16757 (if (and diff (not arg)) (calendar-forward-day diff))))
16759 (defun org-get-date-from-calendar ()
16760 "Return a list (month day year) of date at point in calendar."
16761 (with-current-buffer "*Calendar*"
16762 (save-match-data
16763 (calendar-cursor-to-date))))
16765 (defun org-date-from-calendar ()
16766 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16767 If there is already a time stamp at the cursor position, update it."
16768 (interactive)
16769 (if (org-at-timestamp-p t)
16770 (org-timestamp-change 0 'calendar)
16771 (let ((cal-date (org-get-date-from-calendar)))
16772 (org-insert-time-stamp
16773 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16775 (defun org-minutes-to-hh:mm-string (m)
16776 "Compute H:MM from a number of minutes."
16777 (let ((h (/ m 60)))
16778 (setq m (- m (* 60 h)))
16779 (format org-time-clocksum-format h m)))
16781 (defun org-hh:mm-string-to-minutes (s)
16782 "Convert a string H:MM to a number of minutes.
16783 If the string is just a number, interpret it as minutes.
16784 In fact, the first hh:mm or number in the string will be taken,
16785 there can be extra stuff in the string.
16786 If no number is found, the return value is 0."
16787 (cond
16788 ((integerp s) s)
16789 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16790 (+ (* (string-to-number (match-string 1 s)) 60)
16791 (string-to-number (match-string 2 s))))
16792 ((string-match "\\([0-9]+\\)" s)
16793 (string-to-number (match-string 1 s)))
16794 (t 0)))
16796 (defcustom org-effort-durations
16797 `(("h" . 60)
16798 ("d" . ,(* 60 8))
16799 ("w" . ,(* 60 8 5))
16800 ("m" . ,(* 60 8 5 4))
16801 ("y" . ,(* 60 8 5 40)))
16802 "Conversion factor to minutes for an effort modifier.
16804 Each entry has the form (MODIFIER . MINUTES).
16806 In an effort string, a number followed by MODIFIER is multiplied
16807 by the specified number of MINUTES to obtain an effort in
16808 minutes.
16810 For example, if the value of this variable is ((\"hours\" . 60)), then an
16811 effort string \"2hours\" is equivalent to 120 minutes."
16812 :group 'org-agenda
16813 :version "24.1"
16814 :type '(alist :key-type (string :tag "Modifier")
16815 :value-type (number :tag "Minutes")))
16817 (defcustom org-image-actual-width t
16818 "Should we use the actual width of images when inlining them?
16820 When set to `t', always use the image width.
16822 When set to a number, use imagemagick (when available) to set
16823 the image's width to this value.
16825 When set to a number in a list, try to get the width from the
16826 #+ATTR.* keyword if it matches a width specification like
16827 width=\"[0-9]+\", and fall back on that number if none is found.
16829 When set to nil, try to get the width from an #+ATTR.* keyword
16830 and fall back on the original width if none is found.
16832 This requires Emacs >= 24.1, build with imagemagick support."
16833 :group 'org-appearance
16834 :version "24.3"
16835 :type '(choice
16836 (const :tag "Use the image width" t)
16837 (integer :tag "Use a number of pixels")
16838 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16839 (const :tag "Use #+ATTR* or don't resize" nil)))
16841 (defun org-duration-string-to-minutes (s &optional output-to-string)
16842 "Convert a duration string S to minutes.
16844 A bare number is interpreted as minutes, modifiers can be set by
16845 customizing `org-effort-durations' (which see).
16847 Entries containing a colon are interpreted as H:MM by
16848 `org-hh:mm-string-to-minutes'."
16849 (let ((result 0)
16850 (re (concat "\\([0-9.]+\\) *\\("
16851 (regexp-opt (mapcar 'car org-effort-durations))
16852 "\\)")))
16853 (while (string-match re s)
16854 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16855 (string-to-number (match-string 1 s))))
16856 (setq s (replace-match "" nil t s)))
16857 (setq result (floor result))
16858 (incf result (org-hh:mm-string-to-minutes s))
16859 (if output-to-string (number-to-string result) result)))
16861 ;;;; Files
16863 (defun org-save-all-org-buffers ()
16864 "Save all Org-mode buffers without user confirmation."
16865 (interactive)
16866 (message "Saving all Org-mode buffers...")
16867 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16868 (when (featurep 'org-id) (org-id-locations-save))
16869 (message "Saving all Org-mode buffers... done"))
16871 (defun org-revert-all-org-buffers ()
16872 "Revert all Org-mode buffers.
16873 Prompt for confirmation when there are unsaved changes.
16874 Be sure you know what you are doing before letting this function
16875 overwrite your changes.
16877 This function is useful in a setup where one tracks org files
16878 with a version control system, to revert on one machine after pulling
16879 changes from another. I believe the procedure must be like this:
16881 1. M-x org-save-all-org-buffers
16882 2. Pull changes from the other machine, resolve conflicts
16883 3. M-x org-revert-all-org-buffers"
16884 (interactive)
16885 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16886 (error "Abort"))
16887 (save-excursion
16888 (save-window-excursion
16889 (mapc
16890 (lambda (b)
16891 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16892 (with-current-buffer b buffer-file-name))
16893 (org-pop-to-buffer-same-window b)
16894 (revert-buffer t 'no-confirm)))
16895 (buffer-list))
16896 (when (and (featurep 'org-id) org-id-track-globally)
16897 (org-id-locations-load)))))
16899 ;;;; Agenda files
16901 ;;;###autoload
16902 (defun org-switchb (&optional arg)
16903 "Switch between Org buffers.
16904 With one prefix argument, restrict available buffers to files.
16905 With two prefix arguments, restrict available buffers to agenda files.
16907 Defaults to `iswitchb' for buffer name completion.
16908 Set `org-completion-use-ido' to make it use ido instead."
16909 (interactive "P")
16910 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16911 ((equal arg '(16)) (org-buffer-list 'agenda))
16912 (t (org-buffer-list))))
16913 (org-completion-use-iswitchb org-completion-use-iswitchb)
16914 (org-completion-use-ido org-completion-use-ido))
16915 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16916 (setq org-completion-use-iswitchb t))
16917 (org-pop-to-buffer-same-window
16918 (org-icompleting-read "Org buffer: "
16919 (mapcar 'list (mapcar 'buffer-name blist))
16920 nil t))))
16922 ;;; Define some older names previously used for this functionality
16923 ;;;###autoload
16924 (defalias 'org-ido-switchb 'org-switchb)
16925 ;;;###autoload
16926 (defalias 'org-iswitchb 'org-switchb)
16928 (defun org-buffer-list (&optional predicate exclude-tmp)
16929 "Return a list of Org buffers.
16930 PREDICATE can be `export', `files' or `agenda'.
16932 export restrict the list to Export buffers.
16933 files restrict the list to buffers visiting Org files.
16934 agenda restrict the list to buffers visiting agenda files.
16936 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16937 (let* ((bfn nil)
16938 (agenda-files (and (eq predicate 'agenda)
16939 (mapcar 'file-truename (org-agenda-files t))))
16940 (filter
16941 (cond
16942 ((eq predicate 'files)
16943 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16944 ((eq predicate 'export)
16945 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16946 ((eq predicate 'agenda)
16947 (lambda (b)
16948 (with-current-buffer b
16949 (and (derived-mode-p 'org-mode)
16950 (setq bfn (buffer-file-name b))
16951 (member (file-truename bfn) agenda-files)))))
16952 (t (lambda (b) (with-current-buffer b
16953 (or (derived-mode-p 'org-mode)
16954 (string-match "\*Org .*Export"
16955 (buffer-name b)))))))))
16956 (delq nil
16957 (mapcar
16958 (lambda(b)
16959 (if (and (funcall filter b)
16960 (or (not exclude-tmp)
16961 (not (string-match "tmp" (buffer-name b)))))
16963 nil))
16964 (buffer-list)))))
16966 (defun org-agenda-files (&optional unrestricted archives)
16967 "Get the list of agenda files.
16968 Optional UNRESTRICTED means return the full list even if a restriction
16969 is currently in place.
16970 When ARCHIVES is t, include all archive files that are really being
16971 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16972 `org-agenda-archives-mode' is t."
16973 (let ((files
16974 (cond
16975 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16976 ((stringp org-agenda-files) (org-read-agenda-file-list))
16977 ((listp org-agenda-files) org-agenda-files)
16978 (t (error "Invalid value of `org-agenda-files'")))))
16979 (setq files (apply 'append
16980 (mapcar (lambda (f)
16981 (if (file-directory-p f)
16982 (directory-files
16983 f t org-agenda-file-regexp)
16984 (list f)))
16985 files)))
16986 (when org-agenda-skip-unavailable-files
16987 (setq files (delq nil
16988 (mapcar (function
16989 (lambda (file)
16990 (and (file-readable-p file) file)))
16991 files))))
16992 (when (or (eq archives t)
16993 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16994 (setq files (org-add-archive-files files)))
16995 files))
16997 (defun org-agenda-file-p (&optional file)
16998 "Return non-nil, if FILE is an agenda file.
16999 If FILE is omitted, use the file associated with the current
17000 buffer."
17001 (member (or file (buffer-file-name))
17002 (org-agenda-files t)))
17004 (defun org-edit-agenda-file-list ()
17005 "Edit the list of agenda files.
17006 Depending on setup, this either uses customize to edit the variable
17007 `org-agenda-files', or it visits the file that is holding the list. In the
17008 latter case, the buffer is set up in a way that saving it automatically kills
17009 the buffer and restores the previous window configuration."
17010 (interactive)
17011 (if (stringp org-agenda-files)
17012 (let ((cw (current-window-configuration)))
17013 (find-file org-agenda-files)
17014 (org-set-local 'org-window-configuration cw)
17015 (org-add-hook 'after-save-hook
17016 (lambda ()
17017 (set-window-configuration
17018 (prog1 org-window-configuration
17019 (kill-buffer (current-buffer))))
17020 (org-install-agenda-files-menu)
17021 (message "New agenda file list installed"))
17022 nil 'local)
17023 (message "%s" (substitute-command-keys
17024 "Edit list and finish with \\[save-buffer]")))
17025 (customize-variable 'org-agenda-files)))
17027 (defun org-store-new-agenda-file-list (list)
17028 "Set new value for the agenda file list and save it correctly."
17029 (if (stringp org-agenda-files)
17030 (let ((fe (org-read-agenda-file-list t)) b u)
17031 (while (setq b (find-buffer-visiting org-agenda-files))
17032 (kill-buffer b))
17033 (with-temp-file org-agenda-files
17034 (insert
17035 (mapconcat
17036 (lambda (f) ;; Keep un-expanded entries.
17037 (if (setq u (assoc f fe))
17038 (cdr u)
17040 list "\n")
17041 "\n")))
17042 (let ((org-mode-hook nil) (org-inhibit-startup t)
17043 (org-insert-mode-line-in-empty-file nil))
17044 (setq org-agenda-files list)
17045 (customize-save-variable 'org-agenda-files org-agenda-files))))
17047 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17048 "Read the list of agenda files from a file.
17049 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17050 filenames, used by `org-store-new-agenda-file-list' to write back
17051 un-expanded file names."
17052 (when (file-directory-p org-agenda-files)
17053 (error "`org-agenda-files' cannot be a single directory"))
17054 (when (stringp org-agenda-files)
17055 (with-temp-buffer
17056 (insert-file-contents org-agenda-files)
17057 (mapcar
17058 (lambda (f)
17059 (let ((e (expand-file-name (substitute-in-file-name f)
17060 org-directory)))
17061 (if pair-with-expansion
17062 (cons e f)
17063 e)))
17064 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17066 ;;;###autoload
17067 (defun org-cycle-agenda-files ()
17068 "Cycle through the files in `org-agenda-files'.
17069 If the current buffer visits an agenda file, find the next one in the list.
17070 If the current buffer does not, find the first agenda file."
17071 (interactive)
17072 (let* ((fs (org-agenda-files t))
17073 (files (append fs (list (car fs))))
17074 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17075 file)
17076 (unless files (error "No agenda files"))
17077 (catch 'exit
17078 (while (setq file (pop files))
17079 (if (equal (file-truename file) tcf)
17080 (when (car files)
17081 (find-file (car files))
17082 (throw 'exit t))))
17083 (find-file (car fs)))
17084 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17086 (defun org-agenda-file-to-front (&optional to-end)
17087 "Move/add the current file to the top of the agenda file list.
17088 If the file is not present in the list, it is added to the front. If it is
17089 present, it is moved there. With optional argument TO-END, add/move to the
17090 end of the list."
17091 (interactive "P")
17092 (let ((org-agenda-skip-unavailable-files nil)
17093 (file-alist (mapcar (lambda (x)
17094 (cons (file-truename x) x))
17095 (org-agenda-files t)))
17096 (ctf (file-truename buffer-file-name))
17097 x had)
17098 (setq x (assoc ctf file-alist) had x)
17100 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17101 (if to-end
17102 (setq file-alist (append (delq x file-alist) (list x)))
17103 (setq file-alist (cons x (delq x file-alist))))
17104 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17105 (org-install-agenda-files-menu)
17106 (message "File %s to %s of agenda file list"
17107 (if had "moved" "added") (if to-end "end" "front"))))
17109 (defun org-remove-file (&optional file)
17110 "Remove current file from the list of files in variable `org-agenda-files'.
17111 These are the files which are being checked for agenda entries.
17112 Optional argument FILE means use this file instead of the current."
17113 (interactive)
17114 (let* ((org-agenda-skip-unavailable-files nil)
17115 (file (or file buffer-file-name))
17116 (true-file (file-truename file))
17117 (afile (abbreviate-file-name file))
17118 (files (delq nil (mapcar
17119 (lambda (x)
17120 (if (equal true-file
17121 (file-truename x))
17122 nil x))
17123 (org-agenda-files t)))))
17124 (if (not (= (length files) (length (org-agenda-files t))))
17125 (progn
17126 (org-store-new-agenda-file-list files)
17127 (org-install-agenda-files-menu)
17128 (message "Removed file: %s" afile))
17129 (message "File was not in list: %s (not removed)" afile))))
17131 (defun org-file-menu-entry (file)
17132 (vector file (list 'find-file file) t))
17134 (defun org-check-agenda-file (file)
17135 "Make sure FILE exists. If not, ask user what to do."
17136 (when (not (file-exists-p file))
17137 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17138 (abbreviate-file-name file))
17139 (let ((r (downcase (read-char-exclusive))))
17140 (cond
17141 ((equal r ?r)
17142 (org-remove-file file)
17143 (throw 'nextfile t))
17144 (t (error "Abort"))))))
17146 (defun org-get-agenda-file-buffer (file)
17147 "Get a buffer visiting FILE. If the buffer needs to be created, add
17148 it to the list of buffers which might be released later."
17149 (let ((buf (org-find-base-buffer-visiting file)))
17150 (if buf
17151 buf ; just return it
17152 ;; Make a new buffer and remember it
17153 (setq buf (find-file-noselect file))
17154 (if buf (push buf org-agenda-new-buffers))
17155 buf)))
17157 (defun org-release-buffers (blist)
17158 "Release all buffers in list, asking the user for confirmation when needed.
17159 When a buffer is unmodified, it is just killed. When modified, it is saved
17160 \(if the user agrees) and then killed."
17161 (let (buf file)
17162 (while (setq buf (pop blist))
17163 (setq file (buffer-file-name buf))
17164 (when (and (buffer-modified-p buf)
17165 file
17166 (y-or-n-p (format "Save file %s? " file)))
17167 (with-current-buffer buf (save-buffer)))
17168 (kill-buffer buf))))
17170 (defun org-agenda-prepare-buffers (files)
17171 "Create buffers for all agenda files, protect archived trees and comments."
17172 (interactive)
17173 (let ((pa '(:org-archived t))
17174 (pc '(:org-comment t))
17175 (pall '(:org-archived t :org-comment t))
17176 (inhibit-read-only t)
17177 (rea (concat ":" org-archive-tag ":"))
17178 bmp file re)
17179 (save-excursion
17180 (save-restriction
17181 (while (setq file (pop files))
17182 (catch 'nextfile
17183 (if (bufferp file)
17184 (set-buffer file)
17185 (org-check-agenda-file file)
17186 (set-buffer (org-get-agenda-file-buffer file)))
17187 (widen)
17188 (setq bmp (buffer-modified-p))
17189 (org-refresh-category-properties)
17190 (setq org-todo-keywords-for-agenda
17191 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17192 (setq org-done-keywords-for-agenda
17193 (append org-done-keywords-for-agenda org-done-keywords))
17194 (setq org-todo-keyword-alist-for-agenda
17195 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17196 (setq org-drawers-for-agenda
17197 (append org-drawers-for-agenda org-drawers))
17198 (setq org-tag-alist-for-agenda
17199 (append org-tag-alist-for-agenda org-tag-alist))
17201 (save-excursion
17202 (remove-text-properties (point-min) (point-max) pall)
17203 (when org-agenda-skip-archived-trees
17204 (goto-char (point-min))
17205 (while (re-search-forward rea nil t)
17206 (if (org-at-heading-p t)
17207 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17208 (goto-char (point-min))
17209 (setq re (format org-heading-keyword-regexp-format
17210 org-comment-string))
17211 (while (re-search-forward re nil t)
17212 (add-text-properties
17213 (match-beginning 0) (org-end-of-subtree t) pc)))
17214 (set-buffer-modified-p bmp)))))
17215 (setq org-todo-keywords-for-agenda
17216 (org-uniquify org-todo-keywords-for-agenda))
17217 (setq org-todo-keyword-alist-for-agenda
17218 (org-uniquify org-todo-keyword-alist-for-agenda)
17219 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17221 ;;;; Embedded LaTeX
17223 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17224 "Keymap for the minor `org-cdlatex-mode'.")
17226 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17227 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17228 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17229 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17230 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17232 (defvar org-cdlatex-texmathp-advice-is-done nil
17233 "Flag remembering if we have applied the advice to texmathp already.")
17235 (define-minor-mode org-cdlatex-mode
17236 "Toggle the minor `org-cdlatex-mode'.
17237 This mode supports entering LaTeX environment and math in LaTeX fragments
17238 in Org-mode.
17239 \\{org-cdlatex-mode-map}"
17240 nil " OCDL" nil
17241 (when org-cdlatex-mode
17242 (require 'cdlatex)
17243 (run-hooks 'cdlatex-mode-hook)
17244 (cdlatex-compute-tables))
17245 (unless org-cdlatex-texmathp-advice-is-done
17246 (setq org-cdlatex-texmathp-advice-is-done t)
17247 (defadvice texmathp (around org-math-always-on activate)
17248 "Always return t in org-mode buffers.
17249 This is because we want to insert math symbols without dollars even outside
17250 the LaTeX math segments. If Orgmode thinks that point is actually inside
17251 an embedded LaTeX fragment, let texmathp do its job.
17252 \\[org-cdlatex-mode-map]"
17253 (interactive)
17254 (let (p)
17255 (cond
17256 ((not (derived-mode-p 'org-mode)) ad-do-it)
17257 ((eq this-command 'cdlatex-math-symbol)
17258 (setq ad-return-value t
17259 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17261 (let ((p (org-inside-LaTeX-fragment-p)))
17262 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17263 (setq ad-return-value t
17264 texmathp-why '("Org-mode embedded math" . 0))
17265 (if p ad-do-it)))))))))
17267 (defun turn-on-org-cdlatex ()
17268 "Unconditionally turn on `org-cdlatex-mode'."
17269 (org-cdlatex-mode 1))
17271 (defun org-inside-LaTeX-fragment-p ()
17272 "Test if point is inside a LaTeX fragment.
17273 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17274 sequence appearing also before point.
17275 Even though the matchers for math are configurable, this function assumes
17276 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17277 delimiters are skipped when they have been removed by customization.
17278 The return value is nil, or a cons cell with the delimiter and the
17279 position of this delimiter.
17281 This function does a reasonably good job, but can locally be fooled by
17282 for example currency specifications. For example it will assume being in
17283 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17284 fragments that are properly closed, but during editing, we have to live
17285 with the uncertainty caused by missing closing delimiters. This function
17286 looks only before point, not after."
17287 (catch 'exit
17288 (let ((pos (point))
17289 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17290 (lim (progn
17291 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17292 (point)))
17293 dd-on str (start 0) m re)
17294 (goto-char pos)
17295 (when dodollar
17296 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17297 re (nth 1 (assoc "$" org-latex-regexps)))
17298 (while (string-match re str start)
17299 (cond
17300 ((= (match-end 0) (length str))
17301 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17302 ((= (match-end 0) (- (length str) 5))
17303 (throw 'exit nil))
17304 (t (setq start (match-end 0))))))
17305 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17306 (goto-char pos)
17307 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17308 (and (match-beginning 2) (throw 'exit nil))
17309 ;; count $$
17310 (while (re-search-backward "\\$\\$" lim t)
17311 (setq dd-on (not dd-on)))
17312 (goto-char pos)
17313 (if dd-on (cons "$$" m))))))
17315 (defun org-inside-latex-macro-p ()
17316 "Is point inside a LaTeX macro or its arguments?"
17317 (save-match-data
17318 (org-in-regexp
17319 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17321 (defun org-try-cdlatex-tab ()
17322 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17323 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17324 - inside a LaTeX fragment, or
17325 - after the first word in a line, where an abbreviation expansion could
17326 insert a LaTeX environment."
17327 (when org-cdlatex-mode
17328 (cond
17329 ;; Before any word on the line: No expansion possible.
17330 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17331 ;; Just after first word on the line: Expand it. Make sure it
17332 ;; cannot happen on headlines, though.
17333 ((save-excursion
17334 (skip-chars-backward "a-zA-Z0-9*")
17335 (skip-chars-backward " \t")
17336 (and (bolp) (not (org-at-heading-p))))
17337 (cdlatex-tab) t)
17338 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17340 (defun org-cdlatex-underscore-caret (&optional arg)
17341 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17342 Revert to the normal definition outside of these fragments."
17343 (interactive "P")
17344 (if (org-inside-LaTeX-fragment-p)
17345 (call-interactively 'cdlatex-sub-superscript)
17346 (let (org-cdlatex-mode)
17347 (call-interactively (key-binding (vector last-input-event))))))
17349 (defun org-cdlatex-math-modify (&optional arg)
17350 "Execute `cdlatex-math-modify' in LaTeX fragments.
17351 Revert to the normal definition outside of these fragments."
17352 (interactive "P")
17353 (if (org-inside-LaTeX-fragment-p)
17354 (call-interactively 'cdlatex-math-modify)
17355 (let (org-cdlatex-mode)
17356 (call-interactively (key-binding (vector last-input-event))))))
17358 (defvar org-latex-fragment-image-overlays nil
17359 "List of overlays carrying the images of latex fragments.")
17360 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17362 (defun org-remove-latex-fragment-image-overlays ()
17363 "Remove all overlays with LaTeX fragment images in current buffer."
17364 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17365 (setq org-latex-fragment-image-overlays nil))
17367 (defun org-preview-latex-fragment (&optional subtree)
17368 "Preview the LaTeX fragment at point, or all locally or globally.
17369 If the cursor is in a LaTeX fragment, create the image and overlay
17370 it over the source code. If there is no fragment at point, display
17371 all fragments in the current text, from one headline to the next. With
17372 prefix SUBTREE, display all fragments in the current subtree. With a
17373 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17374 the cursor is before the first headline,
17375 display all fragments in the buffer.
17376 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17377 (interactive "P")
17378 (unless buffer-file-name
17379 (error "Can't preview LaTeX fragment in a non-file buffer"))
17380 (org-remove-latex-fragment-image-overlays)
17381 (save-excursion
17382 (save-restriction
17383 (let (beg end at msg)
17384 (cond
17385 ((or (equal subtree '(16))
17386 (not (save-excursion
17387 (re-search-backward org-outline-regexp-bol nil t))))
17388 (setq beg (point-min) end (point-max)
17389 msg "Creating images for buffer...%s"))
17390 ((equal subtree '(4))
17391 (org-back-to-heading)
17392 (setq beg (point) end (org-end-of-subtree t)
17393 msg "Creating images for subtree...%s"))
17395 (if (setq at (org-inside-LaTeX-fragment-p))
17396 (goto-char (max (point-min) (- (cdr at) 2)))
17397 (org-back-to-heading))
17398 (setq beg (point) end (progn (outline-next-heading) (point))
17399 msg (if at "Creating image...%s"
17400 "Creating images for entry...%s"))))
17401 (message msg "")
17402 (narrow-to-region beg end)
17403 (goto-char beg)
17404 (org-format-latex
17405 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17406 (file-name-nondirectory
17407 buffer-file-name)))
17408 default-directory 'overlays msg at 'forbuffer
17409 org-latex-create-formula-image-program)
17410 (message msg "done. Use `C-c C-c' to remove images.")))))
17412 (defvar org-latex-regexps
17413 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17414 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17415 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17416 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17417 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17418 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17419 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17420 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17421 "Regular expressions for matching embedded LaTeX.")
17423 (defvar org-export-have-math nil) ;; dynamic scoping
17424 (defun org-format-latex (prefix &optional dir overlays msg at
17425 forbuffer processing-type)
17426 "Replace LaTeX fragments with links to an image, and produce images.
17427 Some of the options can be changed using the variable
17428 `org-format-latex-options'."
17429 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17430 (let* ((prefixnodir (file-name-nondirectory prefix))
17431 (absprefix (expand-file-name prefix dir))
17432 (todir (file-name-directory absprefix))
17433 (opt org-format-latex-options)
17434 (optnew org-format-latex-options)
17435 (matchers (plist-get opt :matchers))
17436 (re-list org-latex-regexps)
17437 (org-format-latex-header-extra
17438 (plist-get (org-infile-export-plist) :latex-header-extra))
17439 (cnt 0) txt hash link beg end re e checkdir
17440 string
17441 m n block-type block linkfile movefile ov)
17442 ;; Check the different regular expressions
17443 (while (setq e (pop re-list))
17444 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17445 block (if block-type "\n\n" ""))
17446 (when (member m matchers)
17447 (goto-char (point-min))
17448 (while (re-search-forward re nil t)
17449 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17450 (not (get-text-property (match-beginning n)
17451 'org-protected))
17452 (or (not overlays)
17453 (not (eq (get-char-property (match-beginning n)
17454 'org-overlay-type)
17455 'org-latex-overlay))))
17456 (setq org-export-have-math t)
17457 (cond
17458 ((eq processing-type 'verbatim)
17459 ;; Leave the text verbatim, just protect it
17460 (add-text-properties (match-beginning n) (match-end n)
17461 '(org-protected t)))
17462 ((eq processing-type 'mathjax)
17463 ;; Prepare for MathJax processing
17464 (setq string (match-string n))
17465 (if (member m '("$" "$1"))
17466 (save-excursion
17467 (delete-region (match-beginning n) (match-end n))
17468 (goto-char (match-beginning n))
17469 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17470 "\\)")
17471 '(org-protected t))))
17472 (add-text-properties (match-beginning n) (match-end n)
17473 '(org-protected t))))
17474 ((or (eq processing-type 'dvipng)
17475 (eq processing-type 'imagemagick))
17476 ;; Process to an image
17477 (setq txt (match-string n)
17478 beg (match-beginning n) end (match-end n)
17479 cnt (1+ cnt))
17480 (let ((face (face-at-point))
17481 (fg (plist-get opt :foreground))
17482 (bg (plist-get opt :background))
17483 print-length print-level) ; make sure full list is printed
17484 (when forbuffer
17485 ; Get the colors from the face at point
17486 (goto-char beg)
17487 (when (eq fg 'auto)
17488 (setq fg (face-attribute face :foreground nil 'default)))
17489 (when (eq bg 'auto)
17490 (setq bg (face-attribute face :background nil 'default)))
17491 (setq optnew (copy-sequence opt))
17492 (plist-put optnew :foreground fg)
17493 (plist-put optnew :background bg))
17494 (setq hash (sha1 (prin1-to-string
17495 (list org-format-latex-header
17496 org-format-latex-header-extra
17497 org-export-latex-default-packages-alist
17498 org-export-latex-packages-alist
17499 org-format-latex-options
17500 forbuffer txt fg bg)))
17501 linkfile (format "%s_%s.png" prefix hash)
17502 movefile (format "%s_%s.png" absprefix hash)))
17503 (setq link (concat block "[[file:" linkfile "]]" block))
17504 (if msg (message msg cnt))
17505 (goto-char beg)
17506 (unless checkdir ; make sure the directory exists
17507 (setq checkdir t)
17508 (or (file-directory-p todir) (make-directory todir t)))
17509 (org-create-formula-image
17510 txt movefile optnew forbuffer processing-type)
17511 (if overlays
17512 (progn
17513 (mapc (lambda (o)
17514 (if (eq (overlay-get o 'org-overlay-type)
17515 'org-latex-overlay)
17516 (delete-overlay o)))
17517 (overlays-in beg end))
17518 (setq ov (make-overlay beg end))
17519 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17520 (if (featurep 'xemacs)
17521 (progn
17522 (overlay-put ov 'invisible t)
17523 (overlay-put
17524 ov 'end-glyph
17525 (make-glyph (vector 'png :file movefile))))
17526 (overlay-put
17527 ov 'display
17528 (list 'image :type 'png :file movefile :ascent 'center)))
17529 (push ov org-latex-fragment-image-overlays)
17530 (goto-char end))
17531 (delete-region beg end)
17532 (insert (org-add-props link
17533 (list 'org-latex-src
17534 (replace-regexp-in-string
17535 "\"" "" txt)
17536 'org-latex-src-embed-type
17537 (if block-type 'paragraph 'character))))))
17538 ((eq processing-type 'mathml)
17539 ;; Process to MathML
17540 (unless (save-match-data (org-format-latex-mathml-available-p))
17541 (error "LaTeX to MathML converter not configured"))
17542 (setq txt (match-string n)
17543 beg (match-beginning n) end (match-end n)
17544 cnt (1+ cnt))
17545 (if msg (message msg cnt))
17546 (goto-char beg)
17547 (delete-region beg end)
17548 (insert (org-format-latex-as-mathml
17549 txt block-type prefix dir)))
17551 (error "Unknown conversion type %s for latex fragments"
17552 processing-type)))))))))
17554 (defun org-create-math-formula (latex-frag &optional mathml-file)
17555 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17556 Use `org-latex-to-mathml-convert-command'. If the conversion is
17557 sucessful, return the portion between \"<math...> </math>\"
17558 elements otherwise return nil. When MATHML-FILE is specified,
17559 write the results in to that file. When invoked as an
17560 interactive command, prompt for LATEX-FRAG, with initial value
17561 set to the current active region and echo the results for user
17562 inspection."
17563 (interactive (list (let ((frag (when (org-region-active-p)
17564 (buffer-substring-no-properties
17565 (region-beginning) (region-end)))))
17566 (read-string "LaTeX Fragment: " frag nil frag))))
17567 (unless latex-frag (error "Invalid latex-frag"))
17568 (let* ((tmp-in-file (file-relative-name
17569 (make-temp-name (expand-file-name "ltxmathml-in"))))
17570 (ignore (write-region latex-frag nil tmp-in-file))
17571 (tmp-out-file (file-relative-name
17572 (make-temp-name (expand-file-name "ltxmathml-out"))))
17573 (cmd (format-spec
17574 org-latex-to-mathml-convert-command
17575 `((?j . ,(shell-quote-argument
17576 (expand-file-name org-latex-to-mathml-jar-file)))
17577 (?I . ,(shell-quote-argument tmp-in-file))
17578 (?o . ,(shell-quote-argument tmp-out-file)))))
17579 mathml shell-command-output)
17580 (when (org-called-interactively-p 'any)
17581 (unless (org-format-latex-mathml-available-p)
17582 (error "LaTeX to MathML converter not configured")))
17583 (message "Running %s" cmd)
17584 (setq shell-command-output (shell-command-to-string cmd))
17585 (setq mathml
17586 (when (file-readable-p tmp-out-file)
17587 (with-current-buffer (find-file-noselect tmp-out-file t)
17588 (goto-char (point-min))
17589 (when (re-search-forward
17590 (concat
17591 (regexp-quote
17592 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17593 "\\(.\\|\n\\)*"
17594 (regexp-quote "</math>")) nil t)
17595 (prog1 (match-string 0) (kill-buffer))))))
17596 (cond
17597 (mathml
17598 (setq mathml
17599 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17600 (when mathml-file
17601 (write-region mathml nil mathml-file))
17602 (when (org-called-interactively-p 'any)
17603 (message mathml)))
17604 ((message "LaTeX to MathML conversion failed")
17605 (message shell-command-output)))
17606 (delete-file tmp-in-file)
17607 (when (file-exists-p tmp-out-file)
17608 (delete-file tmp-out-file))
17609 mathml))
17611 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17612 prefix &optional dir)
17613 "Use `org-create-math-formula' but check local cache first."
17614 (let* ((absprefix (expand-file-name prefix dir))
17615 (print-length nil) (print-level nil)
17616 (formula-id (concat
17617 "formula-"
17618 (sha1
17619 (prin1-to-string
17620 (list latex-frag
17621 org-latex-to-mathml-convert-command)))))
17622 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17623 (formula-cache-dir (file-name-directory formula-cache)))
17625 (unless (file-directory-p formula-cache-dir)
17626 (make-directory formula-cache-dir t))
17628 (unless (file-exists-p formula-cache)
17629 (org-create-math-formula latex-frag formula-cache))
17631 (if (file-exists-p formula-cache)
17632 ;; Successful conversion. Return the link to MathML file.
17633 (org-add-props
17634 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17635 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17636 'org-latex-src-embed-type (if latex-frag-type
17637 'paragraph 'character)))
17638 ;; Failed conversion. Return the LaTeX fragment verbatim
17639 (add-text-properties
17640 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17641 latex-frag)))
17643 (defun org-create-formula-image (string tofile options buffer &optional type)
17644 "Create an image from LaTeX source using dvipng or convert.
17645 This function calls either `org-create-formula-image-with-dvipng'
17646 or `org-create-formula-image-with-imagemagick' depending on the
17647 value of `org-latex-create-formula-image-program' or on the value
17648 of the optional TYPE variable.
17650 Note: ultimately these two function should be combined as they
17651 share a good deal of logic."
17652 (org-check-external-command
17653 "latex" "needed to convert LaTeX fragments to images")
17654 (funcall
17655 (case (or type org-latex-create-formula-image-program)
17656 ('dvipng
17657 (org-check-external-command
17658 "dvipng" "needed to convert LaTeX fragments to images")
17659 #'org-create-formula-image-with-dvipng)
17660 ('imagemagick
17661 (org-check-external-command
17662 "convert" "you need to install imagemagick")
17663 #'org-create-formula-image-with-imagemagick)
17664 (t (error
17665 "invalid value of `org-latex-create-formula-image-program'")))
17666 string tofile options buffer))
17668 ;; This function borrows from Ganesh Swami's latex2png.el
17669 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17670 "This calls dvipng."
17671 (require 'org-latex)
17672 (let* ((tmpdir (if (featurep 'xemacs)
17673 (temp-directory)
17674 temporary-file-directory))
17675 (texfilebase (make-temp-name
17676 (expand-file-name "orgtex" tmpdir)))
17677 (texfile (concat texfilebase ".tex"))
17678 (dvifile (concat texfilebase ".dvi"))
17679 (pngfile (concat texfilebase ".png"))
17680 (fnh (if (featurep 'xemacs)
17681 (font-height (face-font 'default))
17682 (face-attribute 'default :height nil)))
17683 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17684 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17685 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17686 "Black"))
17687 (bg (or (plist-get options (if buffer :background :html-background))
17688 "Transparent")))
17689 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17690 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17691 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17692 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17693 (with-temp-file texfile
17694 (insert (org-splice-latex-header
17695 org-format-latex-header
17696 org-export-latex-default-packages-alist
17697 org-export-latex-packages-alist t
17698 org-format-latex-header-extra))
17699 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17700 (require 'org-latex)
17701 (org-export-latex-fix-inputenc))
17702 (let ((dir default-directory))
17703 (condition-case nil
17704 (progn
17705 (cd tmpdir)
17706 (call-process "latex" nil nil nil texfile))
17707 (error nil))
17708 (cd dir))
17709 (if (not (file-exists-p dvifile))
17710 (progn (message "Failed to create dvi file from %s" texfile) nil)
17711 (condition-case nil
17712 (if (featurep 'xemacs)
17713 (call-process "dvipng" nil nil nil
17714 "-fg" fg "-bg" bg
17715 "-T" "tight"
17716 "-o" pngfile
17717 dvifile)
17718 (call-process "dvipng" nil nil nil
17719 "-fg" fg "-bg" bg
17720 "-D" dpi
17721 ;;"-x" scale "-y" scale
17722 "-T" "tight"
17723 "-o" pngfile
17724 dvifile))
17725 (error nil))
17726 (if (not (file-exists-p pngfile))
17727 (if org-format-latex-signal-error
17728 (error "Failed to create png file from %s" texfile)
17729 (message "Failed to create png file from %s" texfile)
17730 nil)
17731 ;; Use the requested file name and clean up
17732 (copy-file pngfile tofile 'replace)
17733 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17734 (if (file-exists-p (concat texfilebase e))
17735 (delete-file (concat texfilebase e))))
17736 pngfile))))
17738 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17739 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17740 "This calls convert, which is included into imagemagick."
17741 (require 'org-latex)
17742 (let* ((tmpdir (if (featurep 'xemacs)
17743 (temp-directory)
17744 temporary-file-directory))
17745 (texfilebase (make-temp-name
17746 (expand-file-name "orgtex" tmpdir)))
17747 (texfile (concat texfilebase ".tex"))
17748 (pdffile (concat texfilebase ".pdf"))
17749 (pngfile (concat texfilebase ".png"))
17750 (fnh (if (featurep 'xemacs)
17751 (font-height (face-font 'default))
17752 (face-attribute 'default :height nil)))
17753 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17754 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17755 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17756 "black"))
17757 (bg (or (plist-get options (if buffer :background :html-background))
17758 "white")))
17759 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17760 (setq fg (org-latex-color-format fg)))
17761 (if (eq bg 'default) (setq bg (org-latex-color :background))
17762 (setq bg (org-latex-color-format
17763 (if (string= bg "Transparent") "white" bg))))
17764 (with-temp-file texfile
17765 (insert (org-splice-latex-header
17766 org-format-latex-header
17767 org-export-latex-default-packages-alist
17768 org-export-latex-packages-alist t
17769 org-format-latex-header-extra))
17770 (insert "\n\\begin{document}\n"
17771 "\\definecolor{fg}{rgb}{" fg "}\n"
17772 "\\definecolor{bg}{rgb}{" bg "}\n"
17773 "\n\\pagecolor{bg}\n"
17774 "\n{\\color{fg}\n"
17775 string
17776 "\n}\n"
17777 "\n\\end{document}\n" )
17778 (require 'org-latex)
17779 (org-export-latex-fix-inputenc))
17780 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17781 (condition-case nil
17782 (progn
17783 (cd tmpdir)
17784 (setq cmds org-latex-to-pdf-process)
17785 (while cmds
17786 (setq latex-frags-cmds (pop cmds))
17787 (if (listp latex-frags-cmds)
17788 (setq cmds nil)
17789 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17790 (while latex-frags-cmds
17791 (setq cmd (pop latex-frags-cmds))
17792 (while (string-match "%b" cmd)
17793 (setq cmd (replace-match
17794 (save-match-data
17795 (shell-quote-argument texfile))
17796 t t cmd)))
17797 (while (string-match "%f" cmd)
17798 (setq cmd (replace-match
17799 (save-match-data
17800 (shell-quote-argument (file-name-nondirectory texfile)))
17801 t t cmd)))
17802 (while (string-match "%o" cmd)
17803 (setq cmd (replace-match
17804 (save-match-data
17805 (shell-quote-argument (file-name-directory texfile)))
17806 t t cmd)))
17807 (setq cmd (split-string cmd))
17808 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17809 (error nil))
17810 (cd dir))
17811 (if (not (file-exists-p pdffile))
17812 (progn (message "Failed to create pdf file from %s" texfile) nil)
17813 (condition-case nil
17814 (if (featurep 'xemacs)
17815 (call-process "convert" nil nil nil
17816 "-density" "96"
17817 "-trim"
17818 "-antialias"
17819 pdffile
17820 "-quality" "100"
17821 ;; "-sharpen" "0x1.0"
17822 pngfile)
17823 (call-process "convert" nil nil nil
17824 "-density" dpi
17825 "-trim"
17826 "-antialias"
17827 pdffile
17828 "-quality" "100"
17829 ; "-sharpen" "0x1.0"
17830 pngfile))
17831 (error nil))
17832 (if (not (file-exists-p pngfile))
17833 (if org-format-latex-signal-error
17834 (error "Failed to create png file from %s" texfile)
17835 (message "Failed to create png file from %s" texfile)
17836 nil)
17837 ;; Use the requested file name and clean up
17838 (copy-file pngfile tofile 'replace)
17839 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17840 (if (file-exists-p (concat texfilebase e))
17841 (delete-file (concat texfilebase e))))
17842 pngfile))))
17844 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17845 "Fill a LaTeX header template TPL.
17846 In the template, the following place holders will be recognized:
17848 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17849 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17850 [PACKAGES] \\usepackage statements for PKG
17851 [NO-PACKAGES] do not include PKG
17852 [EXTRA] the string EXTRA
17853 [NO-EXTRA] do not include EXTRA
17855 For backward compatibility, if both the positive and the negative place
17856 holder is missing, the positive one (without the \"NO-\") will be
17857 assumed to be present at the end of the template.
17858 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17859 EXTRA is a string.
17860 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17861 (let (rpl (end ""))
17862 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17863 (setq rpl (if (or (match-end 1) (not def-pkg))
17864 "" (org-latex-packages-to-string def-pkg snippets-p t))
17865 tpl (replace-match rpl t t tpl))
17866 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17868 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17869 (setq rpl (if (or (match-end 1) (not pkg))
17870 "" (org-latex-packages-to-string pkg snippets-p t))
17871 tpl (replace-match rpl t t tpl))
17872 (if pkg (setq end
17873 (concat end "\n"
17874 (org-latex-packages-to-string pkg snippets-p)))))
17876 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17877 (setq rpl (if (or (match-end 1) (not extra))
17878 "" (concat extra "\n"))
17879 tpl (replace-match rpl t t tpl))
17880 (if (and extra (string-match "\\S-" extra))
17881 (setq end (concat end "\n" extra))))
17883 (if (string-match "\\S-" end)
17884 (concat tpl "\n" end)
17885 tpl)))
17887 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17888 "Turn an alist of packages into a string with the \\usepackage macros."
17889 (setq pkg (mapconcat (lambda(p)
17890 (cond
17891 ((stringp p) p)
17892 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17893 (format "%% Package %s omitted" (cadr p)))
17894 ((equal "" (car p))
17895 (format "\\usepackage{%s}" (cadr p)))
17897 (format "\\usepackage[%s]{%s}"
17898 (car p) (cadr p)))))
17900 "\n"))
17901 (if newline (concat pkg "\n") pkg))
17903 (defun org-dvipng-color (attr)
17904 "Return a RGB color specification for dvipng."
17905 (apply 'format "rgb %s %s %s"
17906 (mapcar 'org-normalize-color
17907 (if (featurep 'xemacs)
17908 (color-rgb-components
17909 (face-property 'default
17910 (cond ((eq attr :foreground) 'foreground)
17911 ((eq attr :background) 'background))))
17912 (color-values (face-attribute 'default attr nil))))))
17914 (defun org-dvipng-color-format (color-name)
17915 "Convert COLOR-NAME to a RGB color value for dvipng."
17916 (apply 'format "rgb %s %s %s"
17917 (mapcar 'org-normalize-color
17918 (color-values color-name))))
17920 (defun org-latex-color (attr)
17921 "Return a RGB color for the LaTeX color package."
17922 (apply 'format "%s,%s,%s"
17923 (mapcar 'org-normalize-color
17924 (if (featurep 'xemacs)
17925 (color-rgb-components
17926 (face-property 'default
17927 (cond ((eq attr :foreground) 'foreground)
17928 ((eq attr :background) 'background))))
17929 (color-values (face-attribute 'default attr nil))))))
17931 (defun org-latex-color-format (color-name)
17932 "Convert COLOR-NAME to a RGB color value."
17933 (apply 'format "%s,%s,%s"
17934 (mapcar 'org-normalize-color
17935 (color-values color-name))))
17937 (defun org-normalize-color (value)
17938 "Return string to be used as color value for an RGB component."
17939 (format "%g" (/ value 65535.0)))
17941 ;; Image display
17944 (defvar org-inline-image-overlays nil)
17945 (make-variable-buffer-local 'org-inline-image-overlays)
17947 (defun org-toggle-inline-images (&optional include-linked)
17948 "Toggle the display of inline images.
17949 INCLUDE-LINKED is passed to `org-display-inline-images'."
17950 (interactive "P")
17951 (if org-inline-image-overlays
17952 (progn
17953 (org-remove-inline-images)
17954 (message "Inline image display turned off"))
17955 (org-display-inline-images include-linked)
17956 (if (and (org-called-interactively-p)
17957 org-inline-image-overlays)
17958 (message "%d images displayed inline"
17959 (length org-inline-image-overlays))
17960 (message "No images to display inline"))))
17962 (defun org-redisplay-inline-images ()
17963 "Refresh the display of inline images."
17964 (interactive)
17965 (if (not org-inline-image-overlays)
17966 (org-toggle-inline-images)
17967 (org-toggle-inline-images)
17968 (org-toggle-inline-images)))
17970 (defun org-display-inline-images (&optional include-linked refresh beg end)
17971 "Display inline images.
17972 Normally only links without a description part are inlined, because this
17973 is how it will work for export. When INCLUDE-LINKED is set, also links
17974 with a description part will be inlined. This can be nice for a quick
17975 look at those images, but it does not reflect what exported files will look
17976 like.
17977 When REFRESH is set, refresh existing images between BEG and END.
17978 This will create new image displays only if necessary.
17979 BEG and END default to the buffer boundaries."
17980 (interactive "P")
17981 (unless refresh
17982 (org-remove-inline-images)
17983 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17984 (save-excursion
17985 (save-restriction
17986 (widen)
17987 (setq beg (or beg (point-min)) end (or end (point-max)))
17988 (goto-char beg)
17989 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17990 (substring (org-image-file-name-regexp) 0 -2)
17991 "\\)\\]" (if include-linked "" "\\]")))
17992 old file ov img type attrwidth width)
17993 (while (re-search-forward re end t)
17994 (setq old (get-char-property-and-overlay (match-beginning 1)
17995 'org-image-overlay)
17996 file (expand-file-name
17997 (concat (or (match-string 3) "") (match-string 4))))
17998 (when (image-type-available-p 'imagemagick)
17999 (setq attrwidth (if (or (listp org-image-actual-width)
18000 (null org-image-actual-width))
18001 (save-excursion
18002 (save-match-data
18003 (when (re-search-backward
18004 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18005 (save-excursion
18006 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18007 (string-to-number (match-string 1))))))
18008 width (cond ((eq org-image-actual-width t) nil)
18009 ((null org-image-actual-width) attrwidth)
18010 ((numberp org-image-actual-width)
18011 org-image-actual-width)
18012 ((listp org-image-actual-width)
18013 (or attrwidth (car org-image-actual-width))))
18014 type (if width 'imagemagick)))
18015 (when (file-exists-p file)
18016 (if (and (car-safe old) refresh)
18017 (image-refresh (overlay-get (cdr old) 'display))
18018 (setq img (save-match-data (create-image file type nil :width width)))
18019 (when img
18020 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18021 (overlay-put ov 'display img)
18022 (overlay-put ov 'face 'default)
18023 (overlay-put ov 'org-image-overlay t)
18024 (overlay-put ov 'modification-hooks
18025 (list 'org-display-inline-remove-overlay))
18026 (push ov org-inline-image-overlays)))))))))
18028 (define-obsolete-function-alias
18029 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18031 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18032 "Remove inline-display overlay if a corresponding region is modified."
18033 (let ((inhibit-modification-hooks t))
18034 (when (and ov after)
18035 (delete ov org-inline-image-overlays)
18036 (delete-overlay ov))))
18038 (defun org-remove-inline-images ()
18039 "Remove inline display of images."
18040 (interactive)
18041 (mapc 'delete-overlay org-inline-image-overlays)
18042 (setq org-inline-image-overlays nil))
18044 ;;;; Key bindings
18046 ;; Outline functions from `outline-mode-prefix-map'
18047 ;; that can be remapped in Org:
18048 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18049 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18050 (define-key org-mode-map [remap outline-forward-same-level]
18051 'org-forward-heading-same-level)
18052 (define-key org-mode-map [remap outline-backward-same-level]
18053 'org-backward-heading-same-level)
18054 (define-key org-mode-map [remap show-branches]
18055 'org-kill-note-or-show-branches)
18056 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18057 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18058 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18060 ;; Outline functions from `outline-mode-prefix-map' that can not
18061 ;; be remapped in Org:
18063 ;; - the column "key binding" shows whether the Outline function is still
18064 ;; available in Org mode on the same key that it has been bound to in
18065 ;; Outline mode:
18066 ;; - "overridden": key used for a different functionality in Org mode
18067 ;; - else: key still bound to the same Outline function in Org mode
18069 ;; | Outline function | key binding | Org replacement |
18070 ;; |------------------------------------+-------------+-----------------------|
18071 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18072 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18073 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18074 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18075 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18076 ;; | `show-entry' | overridden | no replacement |
18077 ;; | `show-children' | `C-c C-i' | visibility cycling |
18078 ;; | `show-branches' | `C-c C-k' | still same function |
18079 ;; | `show-subtree' | overridden | visibility cycling |
18080 ;; | `show-all' | overridden | no replacement |
18081 ;; | `hide-subtree' | overridden | visibility cycling |
18082 ;; | `hide-body' | overridden | no replacement |
18083 ;; | `hide-entry' | overridden | visibility cycling |
18084 ;; | `hide-leaves' | overridden | no replacement |
18085 ;; | `hide-sublevels' | overridden | no replacement |
18086 ;; | `hide-other' | overridden | no replacement |
18088 ;; Make `C-c C-x' a prefix key
18089 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18091 ;; TAB key with modifiers
18092 (org-defkey org-mode-map "\C-i" 'org-cycle)
18093 (org-defkey org-mode-map [(tab)] 'org-cycle)
18094 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18095 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18096 ;; The following line is necessary under Suse GNU/Linux
18097 (unless (featurep 'xemacs)
18098 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18099 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18100 (define-key org-mode-map [backtab] 'org-shifttab)
18102 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18103 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18104 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18106 ;; Cursor keys with modifiers
18107 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18108 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18109 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18110 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18112 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18113 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18114 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18115 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18117 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18118 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18119 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18120 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18122 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18123 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18124 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18125 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18127 ;; Babel keys
18128 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18129 (mapc (lambda (pair)
18130 (define-key org-babel-map (car pair) (cdr pair)))
18131 org-babel-key-bindings)
18133 ;;; Extra keys for tty access.
18134 ;; We only set them when really needed because otherwise the
18135 ;; menus don't show the simple keys
18137 (when (or org-use-extra-keys
18138 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18139 (not window-system))
18140 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18141 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18142 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18143 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18144 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18145 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18146 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18147 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18148 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18149 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18150 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18151 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18152 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18153 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18154 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18155 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18156 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18157 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18158 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18159 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18160 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18161 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18162 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18163 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18164 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18165 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18166 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18167 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18169 ;; All the other keys
18171 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18172 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18173 (if (boundp 'narrow-map)
18174 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18175 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18176 (if (boundp 'narrow-map)
18177 (org-defkey narrow-map "b" 'org-narrow-to-block)
18178 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18179 (if (boundp 'narrow-map)
18180 (org-defkey narrow-map "e" 'org-narrow-to-element)
18181 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18182 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18183 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18184 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18185 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18186 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18187 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18188 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18189 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18190 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18191 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18192 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18193 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18194 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18195 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18196 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18197 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18198 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18199 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18200 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18201 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18202 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18203 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18204 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18205 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18206 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18207 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18208 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18209 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18210 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18211 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18212 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18213 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18214 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18215 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18216 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18217 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18218 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18219 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18220 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18221 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18222 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18223 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18224 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18225 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18226 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18227 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18228 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18229 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18230 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18231 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18232 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18233 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18234 (org-defkey org-mode-map "\C-c^" 'org-sort)
18235 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18236 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18237 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18238 (org-defkey org-mode-map "\C-m" 'org-return)
18239 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18240 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18241 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18242 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18243 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18244 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18245 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18246 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18247 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18248 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18249 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18250 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18251 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18252 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18253 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18254 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18255 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18256 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18257 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18258 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18259 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18260 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18261 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18263 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18264 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18265 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18266 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18268 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18269 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18270 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18271 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18272 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18273 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18274 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18275 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18276 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18277 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18278 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18279 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18280 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18281 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18282 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18283 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18284 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18285 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18286 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18287 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18288 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18289 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18291 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18292 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18293 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18294 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18295 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18297 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18299 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18301 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18302 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18304 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18307 (when (featurep 'xemacs)
18308 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18311 (defconst org-speed-commands-default
18313 ("Outline Navigation")
18314 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18315 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18316 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18317 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18318 ("u" . (org-speed-move-safe 'outline-up-heading))
18319 ("j" . org-goto)
18320 ("g" . (org-refile t))
18321 ("Outline Visibility")
18322 ("c" . org-cycle)
18323 ("C" . org-shifttab)
18324 (" " . org-display-outline-path)
18325 (":" . org-columns)
18326 ("Outline Structure Editing")
18327 ("U" . org-shiftmetaup)
18328 ("D" . org-shiftmetadown)
18329 ("r" . org-metaright)
18330 ("l" . org-metaleft)
18331 ("R" . org-shiftmetaright)
18332 ("L" . org-shiftmetaleft)
18333 ("i" . (progn (forward-char 1) (call-interactively
18334 'org-insert-heading-respect-content)))
18335 ("^" . org-sort)
18336 ("w" . org-refile)
18337 ("a" . org-archive-subtree-default-with-confirmation)
18338 ("." . org-mark-subtree)
18339 ("#" . org-toggle-comment)
18340 ("Clock Commands")
18341 ("I" . org-clock-in)
18342 ("O" . org-clock-out)
18343 ("Meta Data Editing")
18344 ("t" . org-todo)
18345 ("," . (org-priority))
18346 ("0" . (org-priority ?\ ))
18347 ("1" . (org-priority ?A))
18348 ("2" . (org-priority ?B))
18349 ("3" . (org-priority ?C))
18350 (";" . org-set-tags-command)
18351 ("e" . org-set-effort)
18352 ("E" . org-inc-effort)
18353 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18354 (org-entry-put (point) "APPT_WARNTIME" m)))
18355 ("Agenda Views etc")
18356 ("v" . org-agenda)
18357 ("/" . org-sparse-tree)
18358 ("Misc")
18359 ("o" . org-open-at-point)
18360 ("?" . org-speed-command-help)
18361 ("<" . (org-agenda-set-restriction-lock 'subtree))
18362 (">" . (org-agenda-remove-restriction-lock))
18364 "The default speed commands.")
18366 (defun org-print-speed-command (e)
18367 (if (> (length (car e)) 1)
18368 (progn
18369 (princ "\n")
18370 (princ (car e))
18371 (princ "\n")
18372 (princ (make-string (length (car e)) ?-))
18373 (princ "\n"))
18374 (princ (car e))
18375 (princ " ")
18376 (if (symbolp (cdr e))
18377 (princ (symbol-name (cdr e)))
18378 (prin1 (cdr e)))
18379 (princ "\n")))
18381 (defun org-speed-command-help ()
18382 "Show the available speed commands."
18383 (interactive)
18384 (if (not org-use-speed-commands)
18385 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18386 (with-output-to-temp-buffer "*Help*"
18387 (princ "User-defined Speed commands\n===========================\n")
18388 (mapc 'org-print-speed-command org-speed-commands-user)
18389 (princ "\n")
18390 (princ "Built-in Speed commands\n=======================\n")
18391 (mapc 'org-print-speed-command org-speed-commands-default))
18392 (with-current-buffer "*Help*"
18393 (setq truncate-lines t))))
18395 (defun org-speed-move-safe (cmd)
18396 "Execute CMD, but make sure that the cursor always ends up in a headline.
18397 If not, return to the original position and throw an error."
18398 (interactive)
18399 (let ((pos (point)))
18400 (call-interactively cmd)
18401 (unless (and (bolp) (org-at-heading-p))
18402 (goto-char pos)
18403 (error "Boundary reached while executing %s" cmd))))
18405 (defvar org-self-insert-command-undo-counter 0)
18407 (defvar org-table-auto-blank-field) ; defined in org-table.el
18408 (defvar org-speed-command nil)
18410 (define-obsolete-function-alias
18411 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18413 (defun org-speed-command-activate (keys)
18414 "Hook for activating single-letter speed commands.
18415 `org-speed-commands-default' specifies a minimal command set.
18416 Use `org-speed-commands-user' for further customization."
18417 (when (or (and (bolp) (looking-at org-outline-regexp))
18418 (and (functionp org-use-speed-commands)
18419 (funcall org-use-speed-commands)))
18420 (cdr (assoc keys (append org-speed-commands-user
18421 org-speed-commands-default)))))
18423 (define-obsolete-function-alias
18424 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18426 (defun org-babel-speed-command-activate (keys)
18427 "Hook for activating single-letter code block commands."
18428 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18429 (cdr (assoc keys org-babel-key-bindings))))
18431 (defcustom org-speed-command-hook
18432 '(org-speed-command-default-hook org-babel-speed-command-hook)
18433 "Hook for activating speed commands at strategic locations.
18434 Hook functions are called in sequence until a valid handler is
18435 found.
18437 Each hook takes a single argument, a user-pressed command key
18438 which is also a `self-insert-command' from the global map.
18440 Within the hook, examine the cursor position and the command key
18441 and return nil or a valid handler as appropriate. Handler could
18442 be one of an interactive command, a function, or a form.
18444 Set `org-use-speed-commands' to non-nil value to enable this
18445 hook. The default setting is `org-speed-command-activate'."
18446 :group 'org-structure
18447 :version "24.1"
18448 :type 'hook)
18450 (defun org-self-insert-command (N)
18451 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18452 If the cursor is in a table looking at whitespace, the whitespace is
18453 overwritten, and the table is not marked as requiring realignment."
18454 (interactive "p")
18455 (org-check-before-invisible-edit 'insert)
18456 (cond
18457 ((and org-use-speed-commands
18458 (setq org-speed-command
18459 (run-hook-with-args-until-success
18460 'org-speed-command-hook (this-command-keys))))
18461 (cond
18462 ((commandp org-speed-command)
18463 (setq this-command org-speed-command)
18464 (call-interactively org-speed-command))
18465 ((functionp org-speed-command)
18466 (funcall org-speed-command))
18467 ((and org-speed-command (listp org-speed-command))
18468 (eval org-speed-command))
18469 (t (let (org-use-speed-commands)
18470 (call-interactively 'org-self-insert-command)))))
18471 ((and
18472 (org-table-p)
18473 (progn
18474 ;; check if we blank the field, and if that triggers align
18475 (and (featurep 'org-table) org-table-auto-blank-field
18476 (member last-command
18477 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18478 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18479 ;; got extra space, this field does not determine column width
18480 (let (org-table-may-need-update) (org-table-blank-field))
18481 ;; no extra space, this field may determine column width
18482 (org-table-blank-field)))
18484 (eq N 1)
18485 (looking-at "[^|\n]* |"))
18486 (let (org-table-may-need-update)
18487 (goto-char (1- (match-end 0)))
18488 (backward-delete-char 1)
18489 (goto-char (match-beginning 0))
18490 (self-insert-command N)))
18492 (setq org-table-may-need-update t)
18493 (self-insert-command N)
18494 (org-fix-tags-on-the-fly)
18495 (if org-self-insert-cluster-for-undo
18496 (if (not (eq last-command 'org-self-insert-command))
18497 (setq org-self-insert-command-undo-counter 1)
18498 (if (>= org-self-insert-command-undo-counter 20)
18499 (setq org-self-insert-command-undo-counter 1)
18500 (and (> org-self-insert-command-undo-counter 0)
18501 buffer-undo-list (listp buffer-undo-list)
18502 (not (cadr buffer-undo-list)) ; remove nil entry
18503 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18504 (setq org-self-insert-command-undo-counter
18505 (1+ org-self-insert-command-undo-counter))))))))
18507 (defun org-check-before-invisible-edit (kind)
18508 "Check is editing if kind KIND would be dangerous with invisible text around.
18509 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18510 ;; First, try to get out of here as quickly as possible, to reduce overhead
18511 (if (and org-catch-invisible-edits
18512 (or (not (boundp 'visible-mode)) (not visible-mode))
18513 (or (get-char-property (point) 'invisible)
18514 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18515 ;; OK, we need to take a closer look
18516 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18517 (invisible-before-point (if (bobp) nil (get-char-property
18518 (1- (point)) 'invisible)))
18519 (border-and-ok-direction
18521 ;; Check if we are acting predictably before invisible text
18522 (and invisible-at-point (not invisible-before-point)
18523 (memq kind '(insert delete-backward)))
18524 ;; Check if we are acting predictably after invisible text
18525 ;; This works not well, and I have turned it off. It seems
18526 ;; better to always show and stop after invisible text.
18527 ;; (and (not invisible-at-point) invisible-before-point
18528 ;; (memq kind '(insert delete)))
18530 (when (or (memq invisible-at-point '(outline org-hide-block t))
18531 (memq invisible-before-point '(outline org-hide-block t)))
18532 (if (eq org-catch-invisible-edits 'error)
18533 (error "Editing in invisible areas is prohibited - make visible first"))
18534 (if (and org-custom-properties-overlays
18535 (y-or-n-p "Display invisible properties in this buffer? "))
18536 (org-toggle-custom-properties-visibility)
18537 ;; Make the area visible
18538 (save-excursion
18539 (if invisible-before-point
18540 (goto-char (previous-single-char-property-change
18541 (point) 'invisible)))
18542 (org-cycle))
18543 (cond
18544 ((eq org-catch-invisible-edits 'show)
18545 ;; That's it, we do the edit after showing
18546 (message
18547 "Unfolding invisible region around point before editing")
18548 (sit-for 1))
18549 ((and (eq org-catch-invisible-edits 'smart)
18550 border-and-ok-direction)
18551 (message "Unfolding invisible region around point before editing"))
18553 ;; Don't do the edit, make the user repeat it in full visibility
18554 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18556 (defun org-fix-tags-on-the-fly ()
18557 (when (and (equal (char-after (point-at-bol)) ?*)
18558 (org-at-heading-p))
18559 (org-align-tags-here org-tags-column)))
18561 (defun org-delete-backward-char (N)
18562 "Like `delete-backward-char', insert whitespace at field end in tables.
18563 When deleting backwards, in tables this function will insert whitespace in
18564 front of the next \"|\" separator, to keep the table aligned. The table will
18565 still be marked for re-alignment if the field did fill the entire column,
18566 because, in this case the deletion might narrow the column."
18567 (interactive "p")
18568 (org-check-before-invisible-edit 'delete-backward)
18569 (if (and (org-table-p)
18570 (eq N 1)
18571 (string-match "|" (buffer-substring (point-at-bol) (point)))
18572 (looking-at ".*?|"))
18573 (let ((pos (point))
18574 (noalign (looking-at "[^|\n\r]* |"))
18575 (c org-table-may-need-update))
18576 (backward-delete-char N)
18577 (if (not overwrite-mode)
18578 (progn
18579 (skip-chars-forward "^|")
18580 (insert " ")
18581 (goto-char (1- pos))))
18582 ;; noalign: if there were two spaces at the end, this field
18583 ;; does not determine the width of the column.
18584 (if noalign (setq org-table-may-need-update c)))
18585 (backward-delete-char N)
18586 (org-fix-tags-on-the-fly)))
18588 (defun org-delete-char (N)
18589 "Like `delete-char', but insert whitespace at field end in tables.
18590 When deleting characters, in tables this function will insert whitespace in
18591 front of the next \"|\" separator, to keep the table aligned. The table will
18592 still be marked for re-alignment if the field did fill the entire column,
18593 because, in this case the deletion might narrow the column."
18594 (interactive "p")
18595 (org-check-before-invisible-edit 'delete)
18596 (if (and (org-table-p)
18597 (not (bolp))
18598 (not (= (char-after) ?|))
18599 (eq N 1))
18600 (if (looking-at ".*?|")
18601 (let ((pos (point))
18602 (noalign (looking-at "[^|\n\r]* |"))
18603 (c org-table-may-need-update))
18604 (replace-match (concat
18605 (substring (match-string 0) 1 -1)
18606 " |"))
18607 (goto-char pos)
18608 ;; noalign: if there were two spaces at the end, this field
18609 ;; does not determine the width of the column.
18610 (if noalign (setq org-table-may-need-update c)))
18611 (delete-char N))
18612 (delete-char N)
18613 (org-fix-tags-on-the-fly)))
18615 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18616 (put 'org-self-insert-command 'delete-selection t)
18617 (put 'orgtbl-self-insert-command 'delete-selection t)
18618 (put 'org-delete-char 'delete-selection 'supersede)
18619 (put 'org-delete-backward-char 'delete-selection 'supersede)
18620 (put 'org-yank 'delete-selection 'yank)
18622 ;; Make `flyspell-mode' delay after some commands
18623 (put 'org-self-insert-command 'flyspell-delayed t)
18624 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18625 (put 'org-delete-char 'flyspell-delayed t)
18626 (put 'org-delete-backward-char 'flyspell-delayed t)
18628 ;; Make pabbrev-mode expand after org-mode commands
18629 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18630 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18632 ;; How to do this: Measure non-white length of current string
18633 ;; If equal to column width, we should realign.
18635 (defun org-remap (map &rest commands)
18636 "In MAP, remap the functions given in COMMANDS.
18637 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18638 (let (new old)
18639 (while commands
18640 (setq old (pop commands) new (pop commands))
18641 (if (fboundp 'command-remapping)
18642 (org-defkey map (vector 'remap old) new)
18643 (substitute-key-definition old new map global-map)))))
18645 (when (eq org-enable-table-editor 'optimized)
18646 ;; If the user wants maximum table support, we need to hijack
18647 ;; some standard editing functions
18648 (org-remap org-mode-map
18649 'self-insert-command 'org-self-insert-command
18650 'delete-char 'org-delete-char
18651 'delete-backward-char 'org-delete-backward-char)
18652 (org-defkey org-mode-map "|" 'org-force-self-insert))
18654 (defvar org-ctrl-c-ctrl-c-hook nil
18655 "Hook for functions attaching themselves to `C-c C-c'.
18657 This can be used to add additional functionality to the C-c C-c
18658 key which executes context-dependent commands. This hook is run
18659 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18660 run after the last test.
18662 Each function will be called with no arguments. The function
18663 must check if the context is appropriate for it to act. If yes,
18664 it should do its thing and then return a non-nil value. If the
18665 context is wrong, just do nothing and return nil.")
18667 (defvar org-ctrl-c-ctrl-c-final-hook nil
18668 "Hook for functions attaching themselves to `C-c C-c'.
18670 This can be used to add additional functionality to the C-c C-c
18671 key which executes context-dependent commands. This hook is run
18672 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18673 before the first test.
18675 Each function will be called with no arguments. The function
18676 must check if the context is appropriate for it to act. If yes,
18677 it should do its thing and then return a non-nil value. If the
18678 context is wrong, just do nothing and return nil.")
18680 (defvar org-tab-first-hook nil
18681 "Hook for functions to attach themselves to TAB.
18682 See `org-ctrl-c-ctrl-c-hook' for more information.
18683 This hook runs as the first action when TAB is pressed, even before
18684 `org-cycle' messes around with the `outline-regexp' to cater for
18685 inline tasks and plain list item folding.
18686 If any function in this hook returns t, any other actions that
18687 would have been caused by TAB (such as table field motion or visibility
18688 cycling) will not occur.")
18690 (defvar org-tab-after-check-for-table-hook nil
18691 "Hook for functions to attach themselves to TAB.
18692 See `org-ctrl-c-ctrl-c-hook' for more information.
18693 This hook runs after it has been established that the cursor is not in a
18694 table, but before checking if the cursor is in a headline or if global cycling
18695 should be done.
18696 If any function in this hook returns t, not other actions like visibility
18697 cycling will be done.")
18699 (defvar org-tab-after-check-for-cycling-hook nil
18700 "Hook for functions to attach themselves to TAB.
18701 See `org-ctrl-c-ctrl-c-hook' for more information.
18702 This hook runs after it has been established that not table field motion and
18703 not visibility should be done because of current context. This is probably
18704 the place where a package like yasnippets can hook in.")
18706 (defvar org-tab-before-tab-emulation-hook nil
18707 "Hook for functions to attach themselves to TAB.
18708 See `org-ctrl-c-ctrl-c-hook' for more information.
18709 This hook runs after every other options for TAB have been exhausted, but
18710 before indentation and \t insertion takes place.")
18712 (defvar org-metaleft-hook nil
18713 "Hook for functions attaching themselves to `M-left'.
18714 See `org-ctrl-c-ctrl-c-hook' for more information.")
18715 (defvar org-metaright-hook nil
18716 "Hook for functions attaching themselves to `M-right'.
18717 See `org-ctrl-c-ctrl-c-hook' for more information.")
18718 (defvar org-metaup-hook nil
18719 "Hook for functions attaching themselves to `M-up'.
18720 See `org-ctrl-c-ctrl-c-hook' for more information.")
18721 (defvar org-metadown-hook nil
18722 "Hook for functions attaching themselves to `M-down'.
18723 See `org-ctrl-c-ctrl-c-hook' for more information.")
18724 (defvar org-shiftmetaleft-hook nil
18725 "Hook for functions attaching themselves to `M-S-left'.
18726 See `org-ctrl-c-ctrl-c-hook' for more information.")
18727 (defvar org-shiftmetaright-hook nil
18728 "Hook for functions attaching themselves to `M-S-right'.
18729 See `org-ctrl-c-ctrl-c-hook' for more information.")
18730 (defvar org-shiftmetaup-hook nil
18731 "Hook for functions attaching themselves to `M-S-up'.
18732 See `org-ctrl-c-ctrl-c-hook' for more information.")
18733 (defvar org-shiftmetadown-hook nil
18734 "Hook for functions attaching themselves to `M-S-down'.
18735 See `org-ctrl-c-ctrl-c-hook' for more information.")
18736 (defvar org-metareturn-hook nil
18737 "Hook for functions attaching themselves to `M-RET'.
18738 See `org-ctrl-c-ctrl-c-hook' for more information.")
18739 (defvar org-shiftup-hook nil
18740 "Hook for functions attaching themselves to `S-up'.
18741 See `org-ctrl-c-ctrl-c-hook' for more information.")
18742 (defvar org-shiftup-final-hook nil
18743 "Hook for functions attaching themselves to `S-up'.
18744 This one runs after all other options except shift-select have been excluded.
18745 See `org-ctrl-c-ctrl-c-hook' for more information.")
18746 (defvar org-shiftdown-hook nil
18747 "Hook for functions attaching themselves to `S-down'.
18748 See `org-ctrl-c-ctrl-c-hook' for more information.")
18749 (defvar org-shiftdown-final-hook nil
18750 "Hook for functions attaching themselves to `S-down'.
18751 This one runs after all other options except shift-select have been excluded.
18752 See `org-ctrl-c-ctrl-c-hook' for more information.")
18753 (defvar org-shiftleft-hook nil
18754 "Hook for functions attaching themselves to `S-left'.
18755 See `org-ctrl-c-ctrl-c-hook' for more information.")
18756 (defvar org-shiftleft-final-hook nil
18757 "Hook for functions attaching themselves to `S-left'.
18758 This one runs after all other options except shift-select have been excluded.
18759 See `org-ctrl-c-ctrl-c-hook' for more information.")
18760 (defvar org-shiftright-hook nil
18761 "Hook for functions attaching themselves to `S-right'.
18762 See `org-ctrl-c-ctrl-c-hook' for more information.")
18763 (defvar org-shiftright-final-hook nil
18764 "Hook for functions attaching themselves to `S-right'.
18765 This one runs after all other options except shift-select have been excluded.
18766 See `org-ctrl-c-ctrl-c-hook' for more information.")
18768 (defun org-modifier-cursor-error ()
18769 "Throw an error, a modified cursor command was applied in wrong context."
18770 (error "This command is active in special context like tables, headlines or items"))
18772 (defun org-shiftselect-error ()
18773 "Throw an error because Shift-Cursor command was applied in wrong context."
18774 (if (and (boundp 'shift-select-mode) shift-select-mode)
18775 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18776 (error "This command works only in special context like headlines or timestamps")))
18778 (defun org-call-for-shift-select (cmd)
18779 (let ((this-command-keys-shift-translated t))
18780 (call-interactively cmd)))
18782 (defun org-shifttab (&optional arg)
18783 "Global visibility cycling or move to previous table field.
18784 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18785 on context.
18786 See the individual commands for more information."
18787 (interactive "P")
18788 (cond
18789 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18790 ((integerp arg)
18791 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18792 (message "Content view to level: %d" arg)
18793 (org-content (prefix-numeric-value arg2))
18794 (setq org-cycle-global-status 'overview)))
18795 (t (call-interactively 'org-global-cycle))))
18797 (defun org-shiftmetaleft ()
18798 "Promote subtree or delete table column.
18799 Calls `org-promote-subtree', `org-outdent-item-tree', or
18800 `org-table-delete-column', depending on context. See the
18801 individual commands for more information."
18802 (interactive)
18803 (cond
18804 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18805 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18806 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18807 ((if (not (org-region-active-p)) (org-at-item-p)
18808 (save-excursion (goto-char (region-beginning))
18809 (org-at-item-p)))
18810 (call-interactively 'org-outdent-item-tree))
18811 (t (org-modifier-cursor-error))))
18813 (defun org-shiftmetaright ()
18814 "Demote subtree or insert table column.
18815 Calls `org-demote-subtree', `org-indent-item-tree', or
18816 `org-table-insert-column', depending on context. See the
18817 individual commands for more information."
18818 (interactive)
18819 (cond
18820 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18821 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18822 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18823 ((if (not (org-region-active-p)) (org-at-item-p)
18824 (save-excursion (goto-char (region-beginning))
18825 (org-at-item-p)))
18826 (call-interactively 'org-indent-item-tree))
18827 (t (org-modifier-cursor-error))))
18829 (defun org-shiftmetaup (&optional arg)
18830 "Move subtree up or kill table row.
18831 Calls `org-move-subtree-up' or `org-table-kill-row' or
18832 `org-move-item-up' or `org-timestamp-up', depending on context.
18833 See the individual commands for more information."
18834 (interactive "P")
18835 (cond
18836 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18837 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18838 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18839 ((org-at-item-p) (call-interactively 'org-move-item-up))
18840 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18841 (call-interactively 'org-timestamp-up)))
18842 (t (org-modifier-cursor-error))))
18844 (defun org-shiftmetadown (&optional arg)
18845 "Move subtree down or insert table row.
18846 Calls `org-move-subtree-down' or `org-table-insert-row' or
18847 `org-move-item-down' or `org-timestamp-up', depending on context.
18848 See the individual commands for more information."
18849 (interactive "P")
18850 (cond
18851 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18852 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18853 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18854 ((org-at-item-p) (call-interactively 'org-move-item-down))
18855 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18856 (call-interactively 'org-timestamp-down)))
18857 (t (org-modifier-cursor-error))))
18859 (defsubst org-hidden-tree-error ()
18860 (error
18861 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18863 (defun org-metaleft (&optional arg)
18864 "Promote heading or move table column to left.
18865 Calls `org-do-promote' or `org-table-move-column', depending on context.
18866 With no specific context, calls the Emacs default `backward-word'.
18867 See the individual commands for more information."
18868 (interactive "P")
18869 (cond
18870 ((run-hook-with-args-until-success 'org-metaleft-hook))
18871 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18872 ((org-with-limited-levels
18873 (or (org-at-heading-p)
18874 (and (org-region-active-p)
18875 (save-excursion
18876 (goto-char (region-beginning))
18877 (org-at-heading-p)))))
18878 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18879 (call-interactively 'org-do-promote))
18880 ;; At an inline task.
18881 ((org-at-heading-p)
18882 (call-interactively 'org-inlinetask-promote))
18883 ((or (org-at-item-p)
18884 (and (org-region-active-p)
18885 (save-excursion
18886 (goto-char (region-beginning))
18887 (org-at-item-p))))
18888 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18889 (call-interactively 'org-outdent-item))
18890 (t (call-interactively 'backward-word))))
18892 (defun org-metaright (&optional arg)
18893 "Demote a subtree, a list item or move table column to right.
18894 In front of a drawer or a block keyword, indent it correctly.
18895 With no specific context, calls the Emacs default `forward-word'.
18896 See the individual commands for more information."
18897 (interactive "P")
18898 (cond
18899 ((run-hook-with-args-until-success 'org-metaright-hook))
18900 ((org-at-table-p) (call-interactively 'org-table-move-column))
18901 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18902 ((org-at-block-p) (call-interactively 'org-indent-block))
18903 ((org-with-limited-levels
18904 (or (org-at-heading-p)
18905 (and (org-region-active-p)
18906 (save-excursion
18907 (goto-char (region-beginning))
18908 (org-at-heading-p)))))
18909 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18910 (call-interactively 'org-do-demote))
18911 ;; At an inline task.
18912 ((org-at-heading-p)
18913 (call-interactively 'org-inlinetask-demote))
18914 ((or (org-at-item-p)
18915 (and (org-region-active-p)
18916 (save-excursion
18917 (goto-char (region-beginning))
18918 (org-at-item-p))))
18919 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18920 (call-interactively 'org-indent-item))
18921 (t (call-interactively 'forward-word))))
18923 (defun org-check-for-hidden (what)
18924 "Check if there are hidden headlines/items in the current visual line.
18925 WHAT can be either `headlines' or `items'. If the current line is
18926 an outline or item heading and it has a folded subtree below it,
18927 this function returns t, nil otherwise."
18928 (let ((re (cond
18929 ((eq what 'headlines) org-outline-regexp-bol)
18930 ((eq what 'items) (org-item-beginning-re))
18931 (t (error "This should not happen"))))
18932 beg end)
18933 (save-excursion
18934 (catch 'exit
18935 (unless (org-region-active-p)
18936 (setq beg (point-at-bol))
18937 (beginning-of-line 2)
18938 (while (and (not (eobp)) ;; this is like `next-line'
18939 (get-char-property (1- (point)) 'invisible))
18940 (beginning-of-line 2))
18941 (setq end (point))
18942 (goto-char beg)
18943 (goto-char (point-at-eol))
18944 (setq end (max end (point)))
18945 (while (re-search-forward re end t)
18946 (if (get-char-property (match-beginning 0) 'invisible)
18947 (throw 'exit t))))
18948 nil))))
18950 (autoload 'org-element-at-point "org-element")
18952 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18953 (declare-function org-element-type "org-element" (element))
18954 (declare-function org-element-context "org-element" ())
18955 (declare-function org-element-contents "org-element" (element))
18956 (declare-function org-element-property "org-element" (property element))
18957 (declare-function org-element-paragraph-parser "org-element" (limit))
18958 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18959 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18960 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18961 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18962 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18964 (defun org-metaup (&optional arg)
18965 "Move subtree up or move table row up.
18966 Calls `org-move-subtree-up' or `org-table-move-row' or
18967 `org-move-item-up', depending on context. See the individual commands
18968 for more information."
18969 (interactive "P")
18970 (cond
18971 ((run-hook-with-args-until-success 'org-metaup-hook))
18972 ((org-region-active-p)
18973 (let* ((a (min (region-beginning) (region-end)))
18974 (b (1- (max (region-beginning) (region-end))))
18975 (c (save-excursion (goto-char a)
18976 (move-beginning-of-line 0)))
18977 (d (save-excursion (goto-char a)
18978 (move-end-of-line 0) (point))))
18979 (transpose-regions a b c d)
18980 (goto-char c)))
18981 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18982 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18983 ((org-at-item-p) (call-interactively 'org-move-item-up))
18984 (t (org-drag-element-backward))))
18986 (defun org-metadown (&optional arg)
18987 "Move subtree down or move table row down.
18988 Calls `org-move-subtree-down' or `org-table-move-row' or
18989 `org-move-item-down', depending on context. See the individual
18990 commands for more information."
18991 (interactive "P")
18992 (cond
18993 ((run-hook-with-args-until-success 'org-metadown-hook))
18994 ((org-region-active-p)
18995 (let* ((a (min (region-beginning) (region-end)))
18996 (b (max (region-beginning) (region-end)))
18997 (c (save-excursion (goto-char b)
18998 (move-beginning-of-line 1)))
18999 (d (save-excursion (goto-char b)
19000 (move-end-of-line 1) (1+ (point)))))
19001 (transpose-regions a b c d)
19002 (goto-char d)))
19003 ((org-at-table-p) (call-interactively 'org-table-move-row))
19004 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19005 ((org-at-item-p) (call-interactively 'org-move-item-down))
19006 (t (org-drag-element-forward))))
19008 (defun org-shiftup (&optional arg)
19009 "Increase item in timestamp or increase priority of current headline.
19010 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19011 depending on context. See the individual commands for more information."
19012 (interactive "P")
19013 (cond
19014 ((run-hook-with-args-until-success 'org-shiftup-hook))
19015 ((and org-support-shift-select (org-region-active-p))
19016 (org-call-for-shift-select 'previous-line))
19017 ((org-at-timestamp-p t)
19018 (call-interactively (if org-edit-timestamp-down-means-later
19019 'org-timestamp-down 'org-timestamp-up)))
19020 ((and (not (eq org-support-shift-select 'always))
19021 org-enable-priority-commands
19022 (org-at-heading-p))
19023 (call-interactively 'org-priority-up))
19024 ((and (not org-support-shift-select) (org-at-item-p))
19025 (call-interactively 'org-previous-item))
19026 ((org-clocktable-try-shift 'up arg))
19027 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19028 (org-support-shift-select
19029 (org-call-for-shift-select 'previous-line))
19030 (t (org-shiftselect-error))))
19032 (defun org-shiftdown (&optional arg)
19033 "Decrease item in timestamp or decrease priority of current headline.
19034 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19035 depending on context. See the individual commands for more information."
19036 (interactive "P")
19037 (cond
19038 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19039 ((and org-support-shift-select (org-region-active-p))
19040 (org-call-for-shift-select 'next-line))
19041 ((org-at-timestamp-p t)
19042 (call-interactively (if org-edit-timestamp-down-means-later
19043 'org-timestamp-up 'org-timestamp-down)))
19044 ((and (not (eq org-support-shift-select 'always))
19045 org-enable-priority-commands
19046 (org-at-heading-p))
19047 (call-interactively 'org-priority-down))
19048 ((and (not org-support-shift-select) (org-at-item-p))
19049 (call-interactively 'org-next-item))
19050 ((org-clocktable-try-shift 'down arg))
19051 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19052 (org-support-shift-select
19053 (org-call-for-shift-select 'next-line))
19054 (t (org-shiftselect-error))))
19056 (defun org-shiftright (&optional arg)
19057 "Cycle the thing at point or in the current line, depending on context.
19058 Depending on context, this does one of the following:
19060 - switch a timestamp at point one day into the future
19061 - on a headline, switch to the next TODO keyword.
19062 - on an item, switch entire list to the next bullet type
19063 - on a property line, switch to the next allowed value
19064 - on a clocktable definition line, move time block into the future"
19065 (interactive "P")
19066 (cond
19067 ((run-hook-with-args-until-success 'org-shiftright-hook))
19068 ((and org-support-shift-select (org-region-active-p))
19069 (org-call-for-shift-select 'forward-char))
19070 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19071 ((and (not (eq org-support-shift-select 'always))
19072 (org-at-heading-p))
19073 (let ((org-inhibit-logging
19074 (not org-treat-S-cursor-todo-selection-as-state-change))
19075 (org-inhibit-blocking
19076 (not org-treat-S-cursor-todo-selection-as-state-change)))
19077 (org-call-with-arg 'org-todo 'right)))
19078 ((or (and org-support-shift-select
19079 (not (eq org-support-shift-select 'always))
19080 (org-at-item-bullet-p))
19081 (and (not org-support-shift-select) (org-at-item-p)))
19082 (org-call-with-arg 'org-cycle-list-bullet nil))
19083 ((and (not (eq org-support-shift-select 'always))
19084 (org-at-property-p))
19085 (call-interactively 'org-property-next-allowed-value))
19086 ((org-clocktable-try-shift 'right arg))
19087 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19088 (org-support-shift-select
19089 (org-call-for-shift-select 'forward-char))
19090 (t (org-shiftselect-error))))
19092 (defun org-shiftleft (&optional arg)
19093 "Cycle the thing at point or in the current line, depending on context.
19094 Depending on context, this does one of the following:
19096 - switch a timestamp at point one day into the past
19097 - on a headline, switch to the previous TODO keyword.
19098 - on an item, switch entire list to the previous bullet type
19099 - on a property line, switch to the previous allowed value
19100 - on a clocktable definition line, move time block into the past"
19101 (interactive "P")
19102 (cond
19103 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19104 ((and org-support-shift-select (org-region-active-p))
19105 (org-call-for-shift-select 'backward-char))
19106 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19107 ((and (not (eq org-support-shift-select 'always))
19108 (org-at-heading-p))
19109 (let ((org-inhibit-logging
19110 (not org-treat-S-cursor-todo-selection-as-state-change))
19111 (org-inhibit-blocking
19112 (not org-treat-S-cursor-todo-selection-as-state-change)))
19113 (org-call-with-arg 'org-todo 'left)))
19114 ((or (and org-support-shift-select
19115 (not (eq org-support-shift-select 'always))
19116 (org-at-item-bullet-p))
19117 (and (not org-support-shift-select) (org-at-item-p)))
19118 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19119 ((and (not (eq org-support-shift-select 'always))
19120 (org-at-property-p))
19121 (call-interactively 'org-property-previous-allowed-value))
19122 ((org-clocktable-try-shift 'left arg))
19123 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19124 (org-support-shift-select
19125 (org-call-for-shift-select 'backward-char))
19126 (t (org-shiftselect-error))))
19128 (defun org-shiftcontrolright ()
19129 "Switch to next TODO set."
19130 (interactive)
19131 (cond
19132 ((and org-support-shift-select (org-region-active-p))
19133 (org-call-for-shift-select 'forward-word))
19134 ((and (not (eq org-support-shift-select 'always))
19135 (org-at-heading-p))
19136 (org-call-with-arg 'org-todo 'nextset))
19137 (org-support-shift-select
19138 (org-call-for-shift-select 'forward-word))
19139 (t (org-shiftselect-error))))
19141 (defun org-shiftcontrolleft ()
19142 "Switch to previous TODO set."
19143 (interactive)
19144 (cond
19145 ((and org-support-shift-select (org-region-active-p))
19146 (org-call-for-shift-select 'backward-word))
19147 ((and (not (eq org-support-shift-select 'always))
19148 (org-at-heading-p))
19149 (org-call-with-arg 'org-todo 'previousset))
19150 (org-support-shift-select
19151 (org-call-for-shift-select 'backward-word))
19152 (t (org-shiftselect-error))))
19154 (defun org-shiftcontrolup ()
19155 "Change timestamps synchronously up in CLOCK log lines."
19156 (interactive)
19157 (cond ((and (not org-support-shift-select)
19158 (org-at-clock-log-p)
19159 (org-at-timestamp-p t))
19160 (org-clock-timestamps-up))
19161 (t (org-shiftselect-error))))
19163 (defun org-shiftcontroldown ()
19164 "Change timestamps synchronously down in CLOCK log lines."
19165 (interactive)
19166 (cond ((and (not org-support-shift-select)
19167 (org-at-clock-log-p)
19168 (org-at-timestamp-p t))
19169 (org-clock-timestamps-down))
19170 (t (org-shiftselect-error))))
19172 (defun org-ctrl-c-ret ()
19173 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19174 (interactive)
19175 (cond
19176 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19177 (t (call-interactively 'org-insert-heading))))
19179 (defun org-find-visible ()
19180 (let ((s (point)))
19181 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19182 (get-char-property s 'invisible)))
19184 (defun org-find-invisible ()
19185 (let ((s (point)))
19186 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19187 (not (get-char-property s 'invisible))))
19190 (defun org-copy-visible (beg end)
19191 "Copy the visible parts of the region."
19192 (interactive "r")
19193 (let (snippets s)
19194 (save-excursion
19195 (save-restriction
19196 (narrow-to-region beg end)
19197 (setq s (goto-char (point-min)))
19198 (while (not (= (point) (point-max)))
19199 (goto-char (org-find-invisible))
19200 (push (buffer-substring s (point)) snippets)
19201 (setq s (goto-char (org-find-visible))))))
19202 (kill-new (apply 'concat (nreverse snippets)))))
19204 (defun org-copy-special ()
19205 "Copy region in table or copy current subtree.
19206 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19207 See the individual commands for more information."
19208 (interactive)
19209 (call-interactively
19210 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19212 (defun org-cut-special ()
19213 "Cut region in table or cut current subtree.
19214 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19215 See the individual commands for more information."
19216 (interactive)
19217 (call-interactively
19218 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19220 (defun org-paste-special (arg)
19221 "Paste rectangular region into table, or past subtree relative to level.
19222 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19223 See the individual commands for more information."
19224 (interactive "P")
19225 (if (org-at-table-p)
19226 (org-table-paste-rectangle)
19227 (org-paste-subtree arg)))
19229 (defun org-edit-special (&optional arg)
19230 "Call a special editor for the stuff at point.
19231 When at a table, call the formula editor with `org-table-edit-formulas'.
19232 When at the first line of an src example, call `org-edit-src-code'.
19233 When in an #+include line, visit the include file. Otherwise call
19234 `ffap' to visit the file at point."
19235 (interactive)
19236 ;; possibly prep session before editing source
19237 (when arg
19238 (let* ((info (org-babel-get-src-block-info))
19239 (lang (nth 0 info))
19240 (params (nth 2 info))
19241 (session (cdr (assoc :session params))))
19242 (when (and info session) ;; we are in a source-code block with a session
19243 (funcall
19244 (intern (concat "org-babel-prep-session:" lang)) session params))))
19245 (cond ;; proceed with `org-edit-special'
19246 ((save-excursion
19247 (beginning-of-line 1)
19248 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19249 (find-file (org-trim (match-string 1))))
19250 ((org-edit-src-code))
19251 ((org-edit-fixed-width-region))
19252 ((org-at-table.el-p)
19253 (org-edit-src-code))
19254 ((or (org-at-table-p)
19255 (save-excursion
19256 (beginning-of-line 1)
19257 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19258 (call-interactively 'org-table-edit-formulas))
19259 (t (call-interactively 'ffap))))
19261 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19262 (defun org-ctrl-c-ctrl-c (&optional arg)
19263 "Set tags in headline, or update according to changed information at point.
19265 This command does many different things, depending on context:
19267 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19268 this is what we do.
19270 - If the cursor is on a statistics cookie, update it.
19272 - If the cursor is in a headline, prompt for tags and insert them
19273 into the current line, aligned to `org-tags-column'. When called
19274 with prefix arg, realign all tags in the current buffer.
19276 - If the cursor is in one of the special #+KEYWORD lines, this
19277 triggers scanning the buffer for these lines and updating the
19278 information.
19280 - If the cursor is inside a table, realign the table. This command
19281 works even if the automatic table editor has been turned off.
19283 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19284 the entire table.
19286 - If the cursor is at a footnote reference or definition, jump to
19287 the corresponding definition or references, respectively.
19289 - If the cursor is a the beginning of a dynamic block, update it.
19291 - If the current buffer is a capture buffer, close note and file it.
19293 - If the cursor is on a <<<target>>>, update radio targets and
19294 corresponding links in this buffer.
19296 - If the cursor is on a numbered item in a plain list, renumber the
19297 ordered list.
19299 - If the cursor is on a checkbox, toggle it.
19301 - If the cursor is on a code block, evaluate it. The variable
19302 `org-confirm-babel-evaluate' can be used to control prompting
19303 before code block evaluation, by default every code block
19304 evaluation requires confirmation. Code block evaluation can be
19305 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19306 (interactive "P")
19307 (let ((org-enable-table-editor t))
19308 (cond
19309 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19310 org-occur-highlights
19311 org-latex-fragment-image-overlays)
19312 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19313 (org-remove-occur-highlights)
19314 (org-remove-latex-fragment-image-overlays)
19315 (message "Temporary highlights/overlays removed from current buffer"))
19316 ((and (local-variable-p 'org-finish-function (current-buffer))
19317 (fboundp org-finish-function))
19318 (funcall org-finish-function))
19319 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19320 ((org-in-regexp org-ts-regexp-both)
19321 (org-timestamp-change 0 'day))
19322 ((or (looking-at org-property-start-re)
19323 (org-at-property-p))
19324 (call-interactively 'org-property-action))
19325 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19326 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19327 (or (org-at-heading-p) (org-at-item-p)))
19328 (call-interactively 'org-update-statistics-cookies))
19329 ((org-at-heading-p) (call-interactively 'org-set-tags))
19330 ((org-at-table.el-p)
19331 (message "Use C-c ' to edit table.el tables"))
19332 ((org-at-table-p)
19333 (org-table-maybe-eval-formula)
19334 (if arg
19335 (call-interactively 'org-table-recalculate)
19336 (org-table-maybe-recalculate-line))
19337 (call-interactively 'org-table-align)
19338 (orgtbl-send-table 'maybe))
19339 ((or (org-footnote-at-reference-p)
19340 (org-footnote-at-definition-p))
19341 (call-interactively 'org-footnote-action))
19342 ((org-at-item-checkbox-p)
19343 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19344 ;; list only if at top item.
19345 (let* ((cbox (match-string 1))
19346 (struct (org-list-struct))
19347 (old-struct (copy-tree struct))
19348 (parents (org-list-parents-alist struct))
19349 (orderedp (org-entry-get nil "ORDERED"))
19350 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19351 block-item)
19352 ;; Use a light version of `org-toggle-checkbox' to avoid
19353 ;; computing list structure twice.
19354 (let ((new-box (cond
19355 ((equal arg '(16)) "[-]")
19356 ((equal arg '(4)) nil)
19357 ((equal "[X]" cbox) "[ ]")
19358 (t "[X]"))))
19359 (if (and firstp arg)
19360 ;; If at first item of sub-list, remove check-box from
19361 ;; every item at the same level.
19362 (mapc
19363 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19364 (org-list-get-all-items
19365 (point-at-bol) struct (org-list-prevs-alist struct)))
19366 (org-list-set-checkbox (point-at-bol) struct new-box)))
19367 ;; Replicate `org-list-write-struct', while grabbing a return
19368 ;; value from `org-list-struct-fix-box'.
19369 (org-list-struct-fix-ind struct parents 2)
19370 (org-list-struct-fix-item-end struct)
19371 (let ((prevs (org-list-prevs-alist struct)))
19372 (org-list-struct-fix-bul struct prevs)
19373 (org-list-struct-fix-ind struct parents)
19374 (setq block-item
19375 (org-list-struct-fix-box struct parents prevs orderedp)))
19376 (org-list-struct-apply-struct struct old-struct)
19377 (org-update-checkbox-count-maybe)
19378 (when block-item
19379 (message
19380 "Checkboxes were removed due to unchecked box at line %d"
19381 (org-current-line block-item)))
19382 (when firstp (org-list-send-list 'maybe))))
19383 ((org-at-item-p)
19384 ;; Cursor at an item: repair list. Do checkbox related actions
19385 ;; only if function was called with an argument. Send list only
19386 ;; if at top item.
19387 (let* ((struct (org-list-struct))
19388 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19389 old-struct)
19390 (when arg
19391 (setq old-struct (copy-tree struct))
19392 (if firstp
19393 ;; If at first item of sub-list, add check-box to every
19394 ;; item at the same level.
19395 (mapc
19396 (lambda (pos)
19397 (unless (org-list-get-checkbox pos struct)
19398 (org-list-set-checkbox pos struct "[ ]")))
19399 (org-list-get-all-items
19400 (point-at-bol) struct (org-list-prevs-alist struct)))
19401 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19402 (org-list-write-struct
19403 struct (org-list-parents-alist struct) old-struct)
19404 (when arg (org-update-checkbox-count-maybe))
19405 (when firstp (org-list-send-list 'maybe))))
19406 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19407 ;; Dynamic block
19408 (beginning-of-line 1)
19409 (save-excursion (org-update-dblock)))
19410 ((save-excursion
19411 (let ((case-fold-search t))
19412 (beginning-of-line 1)
19413 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19414 (cond
19415 ((or (equal (match-string 1) "TBLFM")
19416 (equal (match-string 1) "tblfm"))
19417 ;; Recalculate the table before this line
19418 (save-excursion
19419 (beginning-of-line 1)
19420 (skip-chars-backward " \r\n\t")
19421 (if (org-at-table-p)
19422 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19424 (let ((org-inhibit-startup-visibility-stuff t)
19425 (org-startup-align-all-tables nil))
19426 (when (boundp 'org-table-coordinate-overlays)
19427 (mapc 'delete-overlay org-table-coordinate-overlays)
19428 (setq org-table-coordinate-overlays nil))
19429 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19430 (message "Local setup has been refreshed"))))
19431 ((org-clock-update-time-maybe))
19433 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19434 (error "C-c C-c can do nothing useful at this location"))))))
19436 (defun org-mode-restart ()
19437 "Restart Org-mode, to scan again for special lines.
19438 Also updates the keyword regular expressions."
19439 (interactive)
19440 (org-mode)
19441 (message "Org-mode restarted"))
19443 (defun org-kill-note-or-show-branches ()
19444 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19445 (interactive)
19446 (if (not org-finish-function)
19447 (progn
19448 (hide-subtree)
19449 (call-interactively 'show-branches))
19450 (let ((org-note-abort t))
19451 (funcall org-finish-function))))
19453 (defun org-return (&optional indent)
19454 "Goto next table row or insert a newline.
19455 Calls `org-table-next-row' or `newline', depending on context.
19456 See the individual commands for more information."
19457 (interactive)
19458 (let (org-ts-what)
19459 (cond
19460 ((or (bobp) (org-in-src-block-p))
19461 (if indent (newline-and-indent) (newline)))
19462 ((org-at-table-p)
19463 (org-table-justify-field-maybe)
19464 (call-interactively 'org-table-next-row))
19465 ;; when `newline-and-indent' is called within a list, make sure
19466 ;; text moved stays inside the item.
19467 ((and (org-in-item-p) indent)
19468 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19469 (progn
19470 (save-match-data (newline))
19471 (org-indent-line-to (length (match-string 0))))
19472 (let ((ind (org-get-indentation)))
19473 (newline)
19474 (if (org-looking-back org-list-end-re)
19475 (org-indent-line)
19476 (org-indent-line-to ind)))))
19477 ((and org-return-follows-link
19478 (org-at-timestamp-p t)
19479 (not (eq org-ts-what 'after)))
19480 (org-follow-timestamp-link))
19481 ((and org-return-follows-link
19482 (let ((tprop (get-text-property (point) 'face)))
19483 (or (eq tprop 'org-link)
19484 (and (listp tprop) (memq 'org-link tprop)))))
19485 (call-interactively 'org-open-at-point))
19486 ((and (org-at-heading-p)
19487 (looking-at
19488 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19489 (org-show-entry)
19490 (end-of-line 1)
19491 (newline))
19492 (t (if indent (newline-and-indent) (newline))))))
19494 (defun org-return-indent ()
19495 "Goto next table row or insert a newline and indent.
19496 Calls `org-table-next-row' or `newline-and-indent', depending on
19497 context. See the individual commands for more information."
19498 (interactive)
19499 (org-return t))
19501 (defun org-ctrl-c-star ()
19502 "Compute table, or change heading status of lines.
19503 Calls `org-table-recalculate' or `org-toggle-heading',
19504 depending on context."
19505 (interactive)
19506 (cond
19507 ((org-at-table-p)
19508 (call-interactively 'org-table-recalculate))
19510 ;; Convert all lines in region to list items
19511 (call-interactively 'org-toggle-heading))))
19513 (defun org-ctrl-c-minus ()
19514 "Insert separator line in table or modify bullet status of line.
19515 Also turns a plain line or a region of lines into list items.
19516 Calls `org-table-insert-hline', `org-toggle-item', or
19517 `org-cycle-list-bullet', depending on context."
19518 (interactive)
19519 (cond
19520 ((org-at-table-p)
19521 (call-interactively 'org-table-insert-hline))
19522 ((org-region-active-p)
19523 (call-interactively 'org-toggle-item))
19524 ((org-in-item-p)
19525 (call-interactively 'org-cycle-list-bullet))
19527 (call-interactively 'org-toggle-item))))
19529 (defun org-toggle-item (arg)
19530 "Convert headings or normal lines to items, items to normal lines.
19531 If there is no active region, only the current line is considered.
19533 If the first non blank line in the region is an headline, convert
19534 all headlines to items, shifting text accordingly.
19536 If it is an item, convert all items to normal lines.
19538 If it is normal text, change region into an item. With a prefix
19539 argument ARG, change each line in region into an item."
19540 (interactive "P")
19541 (let ((shift-text
19542 (function
19543 ;; Shift text in current section to IND, from point to END.
19544 ;; The function leaves point to END line.
19545 (lambda (ind end)
19546 (let ((min-i 1000) (end (copy-marker end)))
19547 ;; First determine the minimum indentation (MIN-I) of
19548 ;; the text.
19549 (save-excursion
19550 (catch 'exit
19551 (while (< (point) end)
19552 (let ((i (org-get-indentation)))
19553 (cond
19554 ;; Skip blank lines and inline tasks.
19555 ((looking-at "^[ \t]*$"))
19556 ((looking-at org-outline-regexp-bol))
19557 ;; We can't find less than 0 indentation.
19558 ((zerop i) (throw 'exit (setq min-i 0)))
19559 ((< i min-i) (setq min-i i))))
19560 (forward-line))))
19561 ;; Then indent each line so that a line indented to
19562 ;; MIN-I becomes indented to IND. Ignore blank lines
19563 ;; and inline tasks in the process.
19564 (let ((delta (- ind min-i)))
19565 (while (< (point) end)
19566 (unless (or (looking-at "^[ \t]*$")
19567 (looking-at org-outline-regexp-bol))
19568 (org-indent-line-to (+ (org-get-indentation) delta)))
19569 (forward-line)))))))
19570 (skip-blanks
19571 (function
19572 ;; Return beginning of first non-blank line, starting from
19573 ;; line at POS.
19574 (lambda (pos)
19575 (save-excursion
19576 (goto-char pos)
19577 (skip-chars-forward " \r\t\n")
19578 (point-at-bol)))))
19579 beg end)
19580 ;; Determine boundaries of changes.
19581 (if (org-region-active-p)
19582 (setq beg (funcall skip-blanks (region-beginning))
19583 end (copy-marker (region-end)))
19584 (setq beg (funcall skip-blanks (point-at-bol))
19585 end (copy-marker (point-at-eol))))
19586 ;; Depending on the starting line, choose an action on the text
19587 ;; between BEG and END.
19588 (org-with-limited-levels
19589 (save-excursion
19590 (goto-char beg)
19591 (cond
19592 ;; Case 1. Start at an item: de-itemize. Note that it only
19593 ;; happens when a region is active: `org-ctrl-c-minus'
19594 ;; would call `org-cycle-list-bullet' otherwise.
19595 ((org-at-item-p)
19596 (while (< (point) end)
19597 (when (org-at-item-p)
19598 (skip-chars-forward " \t")
19599 (delete-region (point) (match-end 0)))
19600 (forward-line)))
19601 ;; Case 2. Start at an heading: convert to items.
19602 ((org-at-heading-p)
19603 (let* ((bul (org-list-bullet-string "-"))
19604 (bul-len (length bul))
19605 ;; Indentation of the first heading. It should be
19606 ;; relative to the indentation of its parent, if any.
19607 (start-ind (save-excursion
19608 (cond
19609 ((not org-adapt-indentation) 0)
19610 ((not (outline-previous-heading)) 0)
19611 (t (length (match-string 0))))))
19612 ;; Level of first heading. Further headings will be
19613 ;; compared to it to determine hierarchy in the list.
19614 (ref-level (org-reduced-level (org-outline-level))))
19615 (while (< (point) end)
19616 (let* ((level (org-reduced-level (org-outline-level)))
19617 (delta (max 0 (- level ref-level))))
19618 ;; If current headline is less indented than the first
19619 ;; one, set it as reference, in order to preserve
19620 ;; subtrees.
19621 (when (< level ref-level) (setq ref-level level))
19622 (replace-match bul t t)
19623 (org-indent-line-to (+ start-ind (* delta bul-len)))
19624 ;; Ensure all text down to END (or SECTION-END) belongs
19625 ;; to the newly created item.
19626 (let ((section-end (save-excursion
19627 (or (outline-next-heading) (point)))))
19628 (forward-line)
19629 (funcall shift-text
19630 (+ start-ind (* (1+ delta) bul-len))
19631 (min end section-end)))))))
19632 ;; Case 3. Normal line with ARG: turn each non-item line into
19633 ;; an item.
19634 (arg
19635 (while (< (point) end)
19636 (unless (or (org-at-heading-p) (org-at-item-p))
19637 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19638 (replace-match
19639 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19640 (forward-line)))
19641 ;; Case 4. Normal line without ARG: make the first line of
19642 ;; region an item, and shift indentation of others
19643 ;; lines to set them as item's body.
19644 (t (let* ((bul (org-list-bullet-string "-"))
19645 (bul-len (length bul))
19646 (ref-ind (org-get-indentation)))
19647 (skip-chars-forward " \t")
19648 (insert bul)
19649 (forward-line)
19650 (while (< (point) end)
19651 ;; Ensure that lines less indented than first one
19652 ;; still get included in item body.
19653 (funcall shift-text
19654 (+ ref-ind bul-len)
19655 (min end (save-excursion (or (outline-next-heading)
19656 (point)))))
19657 (forward-line)))))))))
19659 (defun org-toggle-heading (&optional nstars)
19660 "Convert headings to normal text, or items or text to headings.
19661 If there is no active region, only the current line is considered.
19663 With a \\[universal-argument] prefix, convert the whole list at
19664 point into heading.
19666 In a region:
19668 - If the first non blank line is an headline, remove the stars
19669 from all headlines in the region.
19671 - If it is a normal line turn each and every normal line (i.e. not an
19672 heading or an item) in the region into a heading.
19674 - If it is a plain list item, turn all plain list items into headings.
19676 When converting a line into a heading, the number of stars is chosen
19677 such that the lines become children of the current entry. However,
19678 when a prefix argument is given, its value determines the number of
19679 stars to add."
19680 (interactive "P")
19681 (let ((skip-blanks
19682 (function
19683 ;; Return beginning of first non-blank line, starting from
19684 ;; line at POS.
19685 (lambda (pos)
19686 (save-excursion
19687 (goto-char pos)
19688 (while (org-at-comment-p) (forward-line))
19689 (skip-chars-forward " \r\t\n")
19690 (point-at-bol)))))
19691 beg end toggled)
19692 ;; Determine boundaries of changes. If a universal prefix has
19693 ;; been given, put the list in a region. If region ends at a bol,
19694 ;; do not consider the last line to be in the region.
19696 (when (and current-prefix-arg (org-at-item-p))
19697 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19698 (org-mark-element))
19700 (if (org-region-active-p)
19701 (setq beg (funcall skip-blanks (region-beginning))
19702 end (copy-marker (save-excursion
19703 (goto-char (region-end))
19704 (if (bolp) (point) (point-at-eol)))))
19705 (setq beg (funcall skip-blanks (point-at-bol))
19706 end (copy-marker (point-at-eol))))
19707 ;; Ensure inline tasks don't count as headings.
19708 (org-with-limited-levels
19709 (save-excursion
19710 (goto-char beg)
19711 (cond
19712 ;; Case 1. Started at an heading: de-star headings.
19713 ((org-at-heading-p)
19714 (while (< (point) end)
19715 (when (org-at-heading-p t)
19716 (looking-at org-outline-regexp) (replace-match "")
19717 (setq toggled t))
19718 (forward-line)))
19719 ;; Case 2. Started at an item: change items into headlines.
19720 ;; One star will be added by `org-list-to-subtree'.
19721 ((org-at-item-p)
19722 (let* ((stars (make-string
19723 (if nstars
19724 ;; subtract the star that will be added again by
19725 ;; `org-list-to-subtree'
19726 (1- (prefix-numeric-value current-prefix-arg))
19727 (or (org-current-level) 0))
19728 ?*))
19729 (add-stars
19730 (cond (nstars "") ; stars from prefix only
19731 ((equal stars "") "") ; before first heading
19732 (org-odd-levels-only "*") ; inside heading, odd
19733 (t "")))) ; inside heading, oddeven
19734 (while (< (point) end)
19735 (when (org-at-item-p)
19736 ;; Pay attention to cases when region ends before list.
19737 (let* ((struct (org-list-struct))
19738 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19739 (save-restriction
19740 (narrow-to-region (point) list-end)
19741 (insert
19742 (org-list-to-subtree
19743 (org-list-parse-list t)
19744 '(:istart (concat stars add-stars (funcall get-stars depth))
19745 :icount (concat stars add-stars (funcall get-stars depth)))))))
19746 (setq toggled t))
19747 (forward-line))))
19748 ;; Case 3. Started at normal text: make every line an heading,
19749 ;; skipping headlines and items.
19750 (t (let* ((stars (make-string
19751 (if nstars
19752 (prefix-numeric-value current-prefix-arg)
19753 (or (org-current-level) 0))
19754 ?*))
19755 (add-stars
19756 (cond (nstars "") ; stars from prefix only
19757 ((equal stars "") "*") ; before first heading
19758 (org-odd-levels-only "**") ; inside heading, odd
19759 (t "*"))) ; inside heading, oddeven
19760 (rpl (concat stars add-stars " ")))
19761 (while (< (point) end)
19762 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19763 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19764 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19765 (forward-line)))))))
19766 (unless toggled (message "Cannot toggle heading from here"))))
19768 (defun org-meta-return (&optional arg)
19769 "Insert a new heading or wrap a region in a table.
19770 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19771 See the individual commands for more information."
19772 (interactive "P")
19773 (cond
19774 ((run-hook-with-args-until-success 'org-metareturn-hook))
19775 ((or (org-at-drawer-p) (org-at-property-p))
19776 (newline-and-indent))
19777 ((org-at-table-p)
19778 (call-interactively 'org-table-wrap-region))
19779 (t (call-interactively 'org-insert-heading))))
19781 ;;; Menu entries
19783 (defsubst org-in-subtree-not-table-p ()
19784 "Are we in a subtree and not in a table?"
19785 (and (not (org-before-first-heading-p))
19786 (not (org-at-table-p))))
19788 ;; Define the Org-mode menus
19789 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19790 '("Tbl"
19791 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19792 ["Next Field" org-cycle (org-at-table-p)]
19793 ["Previous Field" org-shifttab (org-at-table-p)]
19794 ["Next Row" org-return (org-at-table-p)]
19795 "--"
19796 ["Blank Field" org-table-blank-field (org-at-table-p)]
19797 ["Edit Field" org-table-edit-field (org-at-table-p)]
19798 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19799 "--"
19800 ("Column"
19801 ["Move Column Left" org-metaleft (org-at-table-p)]
19802 ["Move Column Right" org-metaright (org-at-table-p)]
19803 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19804 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19805 ("Row"
19806 ["Move Row Up" org-metaup (org-at-table-p)]
19807 ["Move Row Down" org-metadown (org-at-table-p)]
19808 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19809 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19810 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19811 "--"
19812 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19813 ("Rectangle"
19814 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19815 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19816 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19817 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19818 "--"
19819 ("Calculate"
19820 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19821 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19822 ["Edit Formulas" org-edit-special (org-at-table-p)]
19823 "--"
19824 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19825 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19826 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19827 "--"
19828 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19829 "--"
19830 ["Sum Column/Rectangle" org-table-sum
19831 (or (org-at-table-p) (org-region-active-p))]
19832 ["Which Column?" org-table-current-column (org-at-table-p)])
19833 ["Debug Formulas"
19834 org-table-toggle-formula-debugger
19835 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19836 ["Show Col/Row Numbers"
19837 org-table-toggle-coordinate-overlays
19838 :style toggle
19839 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19840 "--"
19841 ["Create" org-table-create (and (not (org-at-table-p))
19842 org-enable-table-editor)]
19843 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19844 ["Import from File" org-table-import (not (org-at-table-p))]
19845 ["Export to File" org-table-export (org-at-table-p)]
19846 "--"
19847 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19849 (easy-menu-define org-org-menu org-mode-map "Org menu"
19850 '("Org"
19851 ("Show/Hide"
19852 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19853 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19854 ["Sparse Tree..." org-sparse-tree t]
19855 ["Reveal Context" org-reveal t]
19856 ["Show All" show-all t]
19857 "--"
19858 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19859 "--"
19860 ["New Heading" org-insert-heading t]
19861 ("Navigate Headings"
19862 ["Up" outline-up-heading t]
19863 ["Next" outline-next-visible-heading t]
19864 ["Previous" outline-previous-visible-heading t]
19865 ["Next Same Level" outline-forward-same-level t]
19866 ["Previous Same Level" outline-backward-same-level t]
19867 "--"
19868 ["Jump" org-goto t])
19869 ("Edit Structure"
19870 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19871 "--"
19872 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19873 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19874 "--"
19875 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19876 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19877 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19878 "--"
19879 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19880 "--"
19881 ["Copy visible text" org-copy-visible t]
19882 "--"
19883 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19884 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19885 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19886 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19887 "--"
19888 ["Sort Region/Children" org-sort t]
19889 "--"
19890 ["Convert to odd levels" org-convert-to-odd-levels t]
19891 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19892 ("Editing"
19893 ["Emphasis..." org-emphasize t]
19894 ["Edit Source Example" org-edit-special t]
19895 "--"
19896 ["Footnote new/jump" org-footnote-action t]
19897 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19898 ("Archive"
19899 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19900 "--"
19901 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19902 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19903 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19905 "--"
19906 ("Hyperlinks"
19907 ["Store Link (Global)" org-store-link t]
19908 ["Find existing link to here" org-occur-link-in-agenda-files t]
19909 ["Insert Link" org-insert-link t]
19910 ["Follow Link" org-open-at-point t]
19911 "--"
19912 ["Next link" org-next-link t]
19913 ["Previous link" org-previous-link t]
19914 "--"
19915 ["Descriptive Links"
19916 org-toggle-link-display
19917 :style radio
19918 :selected org-descriptive-links
19920 ["Literal Links"
19921 org-toggle-link-display
19922 :style radio
19923 :selected (not org-descriptive-links)])
19924 "--"
19925 ("TODO Lists"
19926 ["TODO/DONE/-" org-todo t]
19927 ("Select keyword"
19928 ["Next keyword" org-shiftright (org-at-heading-p)]
19929 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19930 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19931 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19932 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19933 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19934 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19935 "--"
19936 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19937 :selected org-enforce-todo-dependencies :style toggle :active t]
19938 "Settings for tree at point"
19939 ["Do Children sequentially" org-toggle-ordered-property :style radio
19940 :selected (org-entry-get nil "ORDERED")
19941 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19942 ["Do Children parallel" org-toggle-ordered-property :style radio
19943 :selected (not (org-entry-get nil "ORDERED"))
19944 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19945 "--"
19946 ["Set Priority" org-priority t]
19947 ["Priority Up" org-shiftup t]
19948 ["Priority Down" org-shiftdown t]
19949 "--"
19950 ["Get news from all feeds" org-feed-update-all t]
19951 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19952 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19953 ("TAGS and Properties"
19954 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19955 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19956 "--"
19957 ["Set property" org-set-property (not (org-before-first-heading-p))]
19958 ["Column view of properties" org-columns t]
19959 ["Insert Column View DBlock" org-insert-columns-dblock t])
19960 ("Dates and Scheduling"
19961 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19962 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19963 ("Change Date"
19964 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19965 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19966 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19967 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19968 ["Compute Time Range" org-evaluate-time-range t]
19969 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19970 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19971 "--"
19972 ["Custom time format" org-toggle-time-stamp-overlays
19973 :style radio :selected org-display-custom-times]
19974 "--"
19975 ["Goto Calendar" org-goto-calendar t]
19976 ["Date from Calendar" org-date-from-calendar t]
19977 "--"
19978 ["Start/Restart Timer" org-timer-start t]
19979 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19980 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19981 ["Insert Timer String" org-timer t]
19982 ["Insert Timer Item" org-timer-item t])
19983 ("Logging work"
19984 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19985 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19986 ["Clock out" org-clock-out t]
19987 ["Clock cancel" org-clock-cancel t]
19988 "--"
19989 ["Mark as default task" org-clock-mark-default-task t]
19990 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19991 ["Goto running clock" org-clock-goto t]
19992 "--"
19993 ["Display times" org-clock-display t]
19994 ["Create clock table" org-clock-report t]
19995 "--"
19996 ["Record DONE time"
19997 (progn (setq org-log-done (not org-log-done))
19998 (message "Switching to %s will %s record a timestamp"
19999 (car org-done-keywords)
20000 (if org-log-done "automatically" "not")))
20001 :style toggle :selected org-log-done])
20002 "--"
20003 ["Agenda Command..." org-agenda t]
20004 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20005 ("File List for Agenda")
20006 ("Special views current file"
20007 ["TODO Tree" org-show-todo-tree t]
20008 ["Check Deadlines" org-check-deadlines t]
20009 ["Timeline" org-timeline t]
20010 ["Tags/Property tree" org-match-sparse-tree t])
20011 "--"
20012 ["Export/Publish..." org-export t]
20013 ("LaTeX"
20014 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20015 :selected org-cdlatex-mode]
20016 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20017 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20018 ["Modify math symbol" org-cdlatex-math-modify
20019 (org-inside-LaTeX-fragment-p)]
20020 ["Insert citation" org-reftex-citation t]
20021 "--"
20022 ["Template for BEAMER" (progn (require 'org-beamer)
20023 (org-insert-beamer-options-template)) t])
20024 "--"
20025 ("MobileOrg"
20026 ["Push Files and Views" org-mobile-push t]
20027 ["Get Captured and Flagged" org-mobile-pull t]
20028 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20029 "--"
20030 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20031 "--"
20032 ("Documentation"
20033 ["Show Version" org-version t]
20034 ["Info Documentation" org-info t])
20035 ("Customize"
20036 ["Browse Org Group" org-customize t]
20037 "--"
20038 ["Expand This Menu" org-create-customize-menu
20039 (fboundp 'customize-menu-create)])
20040 ["Send bug report" org-submit-bug-report t]
20041 "--"
20042 ("Refresh/Reload"
20043 ["Refresh setup current buffer" org-mode-restart t]
20044 ["Reload Org (after update)" org-reload t]
20045 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20048 (defun org-info (&optional node)
20049 "Read documentation for Org-mode in the info system.
20050 With optional NODE, go directly to that node."
20051 (interactive)
20052 (info (format "(org)%s" (or node ""))))
20054 ;;;###autoload
20055 (defun org-submit-bug-report ()
20056 "Submit a bug report on Org-mode via mail.
20058 Don't hesitate to report any problems or inaccurate documentation.
20060 If you don't have setup sending mail from (X)Emacs, please copy the
20061 output buffer into your mail program, as it gives us important
20062 information about your Org-mode version and configuration."
20063 (interactive)
20064 (require 'reporter)
20065 (org-load-modules-maybe)
20066 (org-require-autoloaded-modules)
20067 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20068 (reporter-submit-bug-report
20069 "emacs-orgmode@gnu.org"
20070 (org-version nil 'full)
20071 (let (list)
20072 (save-window-excursion
20073 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20074 (delete-other-windows)
20075 (erase-buffer)
20076 (insert "You are about to submit a bug report to the Org-mode mailing list.
20078 We would like to add your full Org-mode and Outline configuration to the
20079 bug report. This greatly simplifies the work of the maintainer and
20080 other experts on the mailing list.
20082 HOWEVER, some variables you have customized may contain private
20083 information. The names of customers, colleagues, or friends, might
20084 appear in the form of file names, tags, todo states, or search strings.
20085 If you answer yes to the prompt, you might want to check and remove
20086 such private information before sending the email.")
20087 (add-text-properties (point-min) (point-max) '(face org-warning))
20088 (when (yes-or-no-p "Include your Org-mode configuration ")
20089 (mapatoms
20090 (lambda (v)
20091 (and (boundp v)
20092 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20093 (or (and (symbol-value v)
20094 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20095 (and
20096 (get v 'custom-type) (get v 'standard-value)
20097 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20098 (push v list)))))
20099 (kill-buffer (get-buffer "*Warn about privacy*"))
20100 list))
20101 nil nil
20102 "Remember to cover the basics, that is, what you expected to happen and
20103 what in fact did happen. You don't know how to make a good report? See
20105 http://orgmode.org/manual/Feedback.html#Feedback
20107 Your bug report will be posted to the Org-mode mailing list.
20108 ------------------------------------------------------------------------")
20109 (save-excursion
20110 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20111 (replace-match "\\1Bug: \\3 [\\2]")))))
20114 (defun org-install-agenda-files-menu ()
20115 (let ((bl (buffer-list)))
20116 (save-excursion
20117 (while bl
20118 (set-buffer (pop bl))
20119 (if (derived-mode-p 'org-mode) (setq bl nil)))
20120 (when (derived-mode-p 'org-mode)
20121 (easy-menu-change
20122 '("Org") "File List for Agenda"
20123 (append
20124 (list
20125 ["Edit File List" (org-edit-agenda-file-list) t]
20126 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20127 ["Remove Current File from List" org-remove-file t]
20128 ["Cycle through agenda files" org-cycle-agenda-files t]
20129 ["Occur in all agenda files" org-occur-in-agenda-files t]
20130 "--")
20131 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20133 ;;;; Documentation
20135 ;;;###autoload
20136 (defun org-require-autoloaded-modules ()
20137 (interactive)
20138 (mapc 'require
20139 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20140 org-docbook org-exp org-html org-icalendar
20141 org-id org-latex
20142 org-publish org-remember org-table
20143 org-timer org-xoxo)))
20145 ;;;###autoload
20146 (defun org-reload (&optional uncompiled)
20147 "Reload all org lisp files.
20148 With prefix arg UNCOMPILED, load the uncompiled versions."
20149 (interactive "P")
20150 (require 'find-func)
20151 (let* ((file-re "^org\\(-.*\\)?\\.el")
20152 (dir-org (file-name-directory (org-find-library-dir "org")))
20153 (dir-org-contrib (ignore-errors
20154 (file-name-directory
20155 (org-find-library-dir "org-contribdir"))))
20156 (babel-files
20157 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20158 (append (list nil "comint" "eval" "exp" "keys"
20159 "lob" "ref" "table" "tangle")
20160 (delq nil
20161 (mapcar
20162 (lambda (lang)
20163 (when (cdr lang) (symbol-name (car lang))))
20164 org-babel-load-languages)))))
20165 (files
20166 (append babel-files
20167 (and dir-org-contrib
20168 (directory-files dir-org-contrib t file-re))
20169 (directory-files dir-org t file-re)))
20170 (remove-re (concat (if (featurep 'xemacs)
20171 "org-colview" "org-colview-xemacs")
20172 "\\'")))
20173 (setq files (mapcar 'file-name-sans-extension files))
20174 (setq files (mapcar
20175 (lambda (x) (if (string-match remove-re x) nil x))
20176 files))
20177 (setq files (delq nil files))
20178 (mapc
20179 (lambda (f)
20180 (when (featurep (intern (file-name-nondirectory f)))
20181 (if (and (not uncompiled)
20182 (file-exists-p (concat f ".elc")))
20183 (load (concat f ".elc") nil nil 'nosuffix)
20184 (load (concat f ".el") nil nil 'nosuffix))))
20185 files)
20186 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20187 (org-version nil 'full 'message))
20189 ;;;###autoload
20190 (defun org-customize ()
20191 "Call the customize function with org as argument."
20192 (interactive)
20193 (org-load-modules-maybe)
20194 (org-require-autoloaded-modules)
20195 (customize-browse 'org))
20197 (defun org-create-customize-menu ()
20198 "Create a full customization menu for Org-mode, insert it into the menu."
20199 (interactive)
20200 (org-load-modules-maybe)
20201 (org-require-autoloaded-modules)
20202 (if (fboundp 'customize-menu-create)
20203 (progn
20204 (easy-menu-change
20205 '("Org") "Customize"
20206 `(["Browse Org group" org-customize t]
20207 "--"
20208 ,(customize-menu-create 'org)
20209 ["Set" Custom-set t]
20210 ["Save" Custom-save t]
20211 ["Reset to Current" Custom-reset-current t]
20212 ["Reset to Saved" Custom-reset-saved t]
20213 ["Reset to Standard Settings" Custom-reset-standard t]))
20214 (message "\"Org\"-menu now contains full customization menu"))
20215 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20217 ;;;; Miscellaneous stuff
20219 ;;; Generally useful functions
20221 (defun org-get-at-bol (property)
20222 "Get text property PROPERTY at beginning of line."
20223 (get-text-property (point-at-bol) property))
20225 (defun org-find-text-property-in-string (prop s)
20226 "Return the first non-nil value of property PROP in string S."
20227 (or (get-text-property 0 prop s)
20228 (get-text-property (or (next-single-property-change 0 prop s) 0)
20229 prop s)))
20231 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20232 "Display the given MESSAGE as a warning."
20233 (if (fboundp 'display-warning)
20234 (display-warning 'org message
20235 (if (featurep 'xemacs) 'warning :warning))
20236 (let ((buf (get-buffer-create "*Org warnings*")))
20237 (with-current-buffer buf
20238 (goto-char (point-max))
20239 (insert "Warning (Org): " message)
20240 (unless (bolp)
20241 (newline)))
20242 (display-buffer buf)
20243 (sit-for 0))))
20245 (defun org-eval (form)
20246 "Eval FORM and return result."
20247 (condition-case error
20248 (eval form)
20249 (error (format "%%![Error: %s]" error))))
20251 (defun org-in-clocktable-p ()
20252 "Check if the cursor is in a clocktable."
20253 (let ((pos (point)) start)
20254 (save-excursion
20255 (end-of-line 1)
20256 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20257 (setq start (match-beginning 0))
20258 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20259 (>= (match-end 0) pos)
20260 start))))
20262 (defun org-in-commented-line ()
20263 "Is point in a line starting with `#'?"
20264 (equal (char-after (point-at-bol)) ?#))
20266 (defun org-in-indented-comment-line ()
20267 "Is point in a line starting with `#' after some white space?"
20268 (save-excursion
20269 (save-match-data
20270 (goto-char (point-at-bol))
20271 (looking-at "[ \t]*#"))))
20273 (defun org-in-verbatim-emphasis ()
20274 (save-match-data
20275 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20277 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20278 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20279 (if (and marker (marker-buffer marker)
20280 (buffer-live-p (marker-buffer marker)))
20281 (progn
20282 (org-pop-to-buffer-same-window (marker-buffer marker))
20283 (if (or (> marker (point-max)) (< marker (point-min)))
20284 (widen))
20285 (goto-char marker)
20286 (org-show-context 'org-goto))
20287 (if bookmark
20288 (bookmark-jump bookmark)
20289 (error "Cannot find location"))))
20291 (defun org-quote-csv-field (s)
20292 "Quote field for inclusion in CSV material."
20293 (if (string-match "[\",]" s)
20294 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20297 (defun org-force-self-insert (N)
20298 "Needed to enforce self-insert under remapping."
20299 (interactive "p")
20300 (self-insert-command N))
20302 (defun org-string-width (s)
20303 "Compute width of string, ignoring invisible characters.
20304 This ignores character with invisibility property `org-link', and also
20305 characters with property `org-cwidth', because these will become invisible
20306 upon the next fontification round."
20307 (let (b l)
20308 (when (or (eq t buffer-invisibility-spec)
20309 (assq 'org-link buffer-invisibility-spec))
20310 (while (setq b (text-property-any 0 (length s)
20311 'invisible 'org-link s))
20312 (setq s (concat (substring s 0 b)
20313 (substring s (or (next-single-property-change
20314 b 'invisible s) (length s)))))))
20315 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20316 (setq s (concat (substring s 0 b)
20317 (substring s (or (next-single-property-change
20318 b 'org-cwidth s) (length s))))))
20319 (setq l (string-width s) b -1)
20320 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20321 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20324 (defun org-shorten-string (s maxlength)
20325 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20326 If the string is shorter or has length MAXLENGTH, just return the
20327 original string. If it is longer, the functions finds a space in the
20328 string, breaks this string off at that locations and adds three dots
20329 as ellipsis. Including the ellipsis, the string will not be longer
20330 than MAXLENGTH. If finding a good breaking point in the string does
20331 not work, the string is just chopped off in the middle of a word
20332 if necessary."
20333 (if (<= (length s) maxlength)
20335 (let* ((n (max (- maxlength 4) 1))
20336 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20337 (if (string-match re s)
20338 (concat (match-string 1 s) "...")
20339 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20341 (defun org-get-indentation (&optional line)
20342 "Get the indentation of the current line, interpreting tabs.
20343 When LINE is given, assume it represents a line and compute its indentation."
20344 (if line
20345 (if (string-match "^ *" (org-remove-tabs line))
20346 (match-end 0))
20347 (save-excursion
20348 (beginning-of-line 1)
20349 (skip-chars-forward " \t")
20350 (current-column))))
20352 (defun org-get-string-indentation (s)
20353 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20354 (let ((n -1) (i 0) (w tab-width) c)
20355 (catch 'exit
20356 (while (< (setq n (1+ n)) (length s))
20357 (setq c (aref s n))
20358 (cond ((= c ?\ ) (setq i (1+ i)))
20359 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20360 (t (throw 'exit t)))))
20363 (defun org-remove-tabs (s &optional width)
20364 "Replace tabulators in S with spaces.
20365 Assumes that s is a single line, starting in column 0."
20366 (setq width (or width tab-width))
20367 (while (string-match "\t" s)
20368 (setq s (replace-match
20369 (make-string
20370 (- (* width (/ (+ (match-beginning 0) width) width))
20371 (match-beginning 0)) ?\ )
20372 t t s)))
20375 (defun org-fix-indentation (line ind)
20376 "Fix indentation in LINE.
20377 IND is a cons cell with target and minimum indentation.
20378 If the current indentation in LINE is smaller than the minimum,
20379 leave it alone. If it is larger than ind, set it to the target."
20380 (let* ((l (org-remove-tabs line))
20381 (i (org-get-indentation l))
20382 (i1 (car ind)) (i2 (cdr ind)))
20383 (if (>= i i2) (setq l (substring line i2)))
20384 (if (> i1 0)
20385 (concat (make-string i1 ?\ ) l)
20386 l)))
20388 (defun org-remove-indentation (code &optional n)
20389 "Remove the maximum common indentation from the lines in CODE.
20390 N may optionally be the number of spaces to remove."
20391 (with-temp-buffer
20392 (insert code)
20393 (org-do-remove-indentation n)
20394 (buffer-string)))
20396 (defun org-do-remove-indentation (&optional n)
20397 "Remove the maximum common indentation from the buffer."
20398 (untabify (point-min) (point-max))
20399 (let ((min 10000) re)
20400 (if n
20401 (setq min n)
20402 (goto-char (point-min))
20403 (while (re-search-forward "^ *[^ \n]" nil t)
20404 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20405 (unless (or (= min 0) (= min 10000))
20406 (setq re (format "^ \\{%d\\}" min))
20407 (goto-char (point-min))
20408 (while (re-search-forward re nil t)
20409 (replace-match "")
20410 (end-of-line 1))
20411 min)))
20413 (defun org-fill-template (template alist)
20414 "Find each %key of ALIST in TEMPLATE and replace it."
20415 (let ((case-fold-search nil)
20416 entry key value)
20417 (setq alist (sort (copy-sequence alist)
20418 (lambda (a b) (< (length (car a)) (length (car b))))))
20419 (while (setq entry (pop alist))
20420 (setq template
20421 (replace-regexp-in-string
20422 (concat "%" (regexp-quote (car entry)))
20423 (or (cdr entry) "") template t t)))
20424 template))
20426 (defun org-base-buffer (buffer)
20427 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20428 (if (not buffer)
20429 buffer
20430 (or (buffer-base-buffer buffer)
20431 buffer)))
20433 (defun org-trim (s)
20434 "Remove whitespace at beginning and end of string."
20435 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20436 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20439 (defun org-wrap (string &optional width lines)
20440 "Wrap string to either a number of lines, or a width in characters.
20441 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20442 that costs. If there is a word longer than WIDTH, the text is actually
20443 wrapped to the length of that word.
20444 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20445 many lines, whatever width that takes.
20446 The return value is a list of lines, without newlines at the end."
20447 (let* ((words (org-split-string string "[ \t\n]+"))
20448 (maxword (apply 'max (mapcar 'org-string-width words)))
20449 w ll)
20450 (cond (width
20451 (org-do-wrap words (max maxword width)))
20452 (lines
20453 (setq w maxword)
20454 (setq ll (org-do-wrap words maxword))
20455 (if (<= (length ll) lines)
20457 (setq ll words)
20458 (while (> (length ll) lines)
20459 (setq w (1+ w))
20460 (setq ll (org-do-wrap words w)))
20461 ll))
20462 (t (error "Cannot wrap this")))))
20464 (defun org-do-wrap (words width)
20465 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20466 (let (lines line)
20467 (while words
20468 (setq line (pop words))
20469 (while (and words (< (+ (length line) (length (car words))) width))
20470 (setq line (concat line " " (pop words))))
20471 (setq lines (push line lines)))
20472 (nreverse lines)))
20474 (defun org-split-string (string &optional separators)
20475 "Splits STRING into substrings at SEPARATORS.
20476 No empty strings are returned if there are matches at the beginning
20477 and end of string."
20478 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20479 (start 0)
20480 notfirst
20481 (list nil))
20482 (while (and (string-match rexp string
20483 (if (and notfirst
20484 (= start (match-beginning 0))
20485 (< start (length string)))
20486 (1+ start) start))
20487 (< (match-beginning 0) (length string)))
20488 (setq notfirst t)
20489 (or (eq (match-beginning 0) 0)
20490 (and (eq (match-beginning 0) (match-end 0))
20491 (eq (match-beginning 0) start))
20492 (setq list
20493 (cons (substring string start (match-beginning 0))
20494 list)))
20495 (setq start (match-end 0)))
20496 (or (eq start (length string))
20497 (setq list
20498 (cons (substring string start)
20499 list)))
20500 (nreverse list)))
20502 (defun org-quote-vert (s)
20503 "Replace \"|\" with \"\\vert\"."
20504 (while (string-match "|" s)
20505 (setq s (replace-match "\\vert" t t s)))
20508 (defun org-uuidgen-p (s)
20509 "Is S an ID created by UUIDGEN?"
20510 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20512 (defun org-in-src-block-p nil
20513 "Whether point is in a code source block."
20514 (let (ov)
20515 (when (setq ov (overlays-at (point)))
20516 (memq 'org-block-background
20517 (overlay-properties
20518 (car ov))))))
20520 (defun org-context ()
20521 "Return a list of contexts of the current cursor position.
20522 If several contexts apply, all are returned.
20523 Each context entry is a list with a symbol naming the context, and
20524 two positions indicating start and end of the context. Possible
20525 contexts are:
20527 :headline anywhere in a headline
20528 :headline-stars on the leading stars in a headline
20529 :todo-keyword on a TODO keyword (including DONE) in a headline
20530 :tags on the TAGS in a headline
20531 :priority on the priority cookie in a headline
20532 :item on the first line of a plain list item
20533 :item-bullet on the bullet/number of a plain list item
20534 :checkbox on the checkbox in a plain list item
20535 :table in an org-mode table
20536 :table-special on a special filed in a table
20537 :table-table in a table.el table
20538 :clocktable in a clocktable
20539 :src-block in a source block
20540 :link on a hyperlink
20541 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20542 :target on a <<target>>
20543 :radio-target on a <<<radio-target>>>
20544 :latex-fragment on a LaTeX fragment
20545 :latex-preview on a LaTeX fragment with overlaid preview image
20547 This function expects the position to be visible because it uses font-lock
20548 faces as a help to recognize the following contexts: :table-special, :link,
20549 and :keyword."
20550 (let* ((f (get-text-property (point) 'face))
20551 (faces (if (listp f) f (list f)))
20552 (case-fold-search t)
20553 (p (point)) clist o)
20554 ;; First the large context
20555 (cond
20556 ((org-at-heading-p t)
20557 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20558 (when (progn
20559 (beginning-of-line 1)
20560 (looking-at org-todo-line-tags-regexp))
20561 (push (org-point-in-group p 1 :headline-stars) clist)
20562 (push (org-point-in-group p 2 :todo-keyword) clist)
20563 (push (org-point-in-group p 4 :tags) clist))
20564 (goto-char p)
20565 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20566 (if (looking-at "\\[#[A-Z0-9]\\]")
20567 (push (org-point-in-group p 0 :priority) clist)))
20569 ((org-at-item-p)
20570 (push (org-point-in-group p 2 :item-bullet) clist)
20571 (push (list :item (point-at-bol)
20572 (save-excursion (org-end-of-item) (point)))
20573 clist)
20574 (and (org-at-item-checkbox-p)
20575 (push (org-point-in-group p 0 :checkbox) clist)))
20577 ((org-at-table-p)
20578 (push (list :table (org-table-begin) (org-table-end)) clist)
20579 (if (memq 'org-formula faces)
20580 (push (list :table-special
20581 (previous-single-property-change p 'face)
20582 (next-single-property-change p 'face)) clist)))
20583 ((org-at-table-p 'any)
20584 (push (list :table-table) clist)))
20585 (goto-char p)
20587 (let ((case-fold-search t))
20588 ;; New the "medium" contexts: clocktables, source blocks
20589 (cond ((org-in-clocktable-p)
20590 (push (list :clocktable
20591 (and (or (looking-at "#\\+BEGIN: clocktable")
20592 (search-backward "#+BEGIN: clocktable" nil t))
20593 (match-beginning 0))
20594 (and (re-search-forward "#\\+END:?" nil t)
20595 (match-end 0))) clist))
20596 ((org-in-src-block-p)
20597 (push (list :src-block
20598 (and (or (looking-at "#\\+BEGIN_SRC")
20599 (search-backward "#+BEGIN_SRC" nil t))
20600 (match-beginning 0))
20601 (and (search-forward "#+END_SRC" nil t)
20602 (match-beginning 0))) clist))))
20603 (goto-char p)
20605 ;; Now the small context
20606 (cond
20607 ((org-at-timestamp-p)
20608 (push (org-point-in-group p 0 :timestamp) clist))
20609 ((memq 'org-link faces)
20610 (push (list :link
20611 (previous-single-property-change p 'face)
20612 (next-single-property-change p 'face)) clist))
20613 ((memq 'org-special-keyword faces)
20614 (push (list :keyword
20615 (previous-single-property-change p 'face)
20616 (next-single-property-change p 'face)) clist))
20617 ((org-at-target-p)
20618 (push (org-point-in-group p 0 :target) clist)
20619 (goto-char (1- (match-beginning 0)))
20620 (if (looking-at org-radio-target-regexp)
20621 (push (org-point-in-group p 0 :radio-target) clist))
20622 (goto-char p))
20623 ((setq o (car (delq nil
20624 (mapcar
20625 (lambda (x)
20626 (if (memq x org-latex-fragment-image-overlays) x))
20627 (overlays-at (point))))))
20628 (push (list :latex-fragment
20629 (overlay-start o) (overlay-end o)) clist)
20630 (push (list :latex-preview
20631 (overlay-start o) (overlay-end o)) clist))
20632 ((org-inside-LaTeX-fragment-p)
20633 ;; FIXME: positions wrong.
20634 (push (list :latex-fragment (point) (point)) clist)))
20636 (setq clist (nreverse (delq nil clist)))
20637 clist))
20639 ;; FIXME: Compare with at-regexp-p Do we need both?
20640 (defun org-in-regexp (re &optional nlines visually)
20641 "Check if point is inside a match of regexp.
20642 Normally only the current line is checked, but you can include NLINES extra
20643 lines both before and after point into the search.
20644 If VISUALLY is set, require that the cursor is not after the match but
20645 really on, so that the block visually is on the match."
20646 (catch 'exit
20647 (let ((pos (point))
20648 (eol (point-at-eol (+ 1 (or nlines 0))))
20649 (inc (if visually 1 0)))
20650 (save-excursion
20651 (beginning-of-line (- 1 (or nlines 0)))
20652 (while (re-search-forward re eol t)
20653 (if (and (<= (match-beginning 0) pos)
20654 (>= (+ inc (match-end 0)) pos))
20655 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20657 (defun org-at-regexp-p (regexp)
20658 "Is point inside a match of REGEXP in the current line?"
20659 (catch 'exit
20660 (save-excursion
20661 (let ((pos (point)) (end (point-at-eol)))
20662 (beginning-of-line 1)
20663 (while (re-search-forward regexp end t)
20664 (if (and (<= (match-beginning 0) pos)
20665 (>= (match-end 0) pos))
20666 (throw 'exit t)))
20667 nil))))
20669 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20670 "Non-nil when point is between matches of START-RE and END-RE.
20672 Also return a non-nil value when point is on one of the matches.
20674 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20675 buffer positions. Default values are the positions of headlines
20676 surrounding the point.
20678 The functions returns a cons cell whose car (resp. cdr) is the
20679 position before START-RE (resp. after END-RE)."
20680 (save-match-data
20681 (let ((pos (point))
20682 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20683 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20684 beg end)
20685 (save-excursion
20686 ;; Point is on a block when on START-RE or if START-RE can be
20687 ;; found before it...
20688 (and (or (org-at-regexp-p start-re)
20689 (re-search-backward start-re limit-up t))
20690 (setq beg (match-beginning 0))
20691 ;; ... and END-RE after it...
20692 (goto-char (match-end 0))
20693 (re-search-forward end-re limit-down t)
20694 (> (setq end (match-end 0)) pos)
20695 ;; ... without another START-RE in-between.
20696 (goto-char (match-beginning 0))
20697 (not (re-search-backward start-re (1+ beg) t))
20698 ;; Return value.
20699 (cons beg end))))))
20701 (defun org-in-block-p (names)
20702 "Non-nil when point belongs to a block whose name belongs to NAMES.
20704 NAMES is a list of strings containing names of blocks.
20706 Return first block name matched, or nil. Beware that in case of
20707 nested blocks, the returned name may not belong to the closest
20708 block from point."
20709 (save-match-data
20710 (catch 'exit
20711 (let ((case-fold-search t)
20712 (lim-up (save-excursion (outline-previous-heading)))
20713 (lim-down (save-excursion (outline-next-heading))))
20714 (mapc (lambda (name)
20715 (let ((n (regexp-quote name)))
20716 (when (org-between-regexps-p
20717 (concat "^[ \t]*#\\+begin_" n)
20718 (concat "^[ \t]*#\\+end_" n)
20719 lim-up lim-down)
20720 (throw 'exit n))))
20721 names))
20722 nil)))
20724 (defun org-occur-in-agenda-files (regexp &optional nlines)
20725 "Call `multi-occur' with buffers for all agenda files."
20726 (interactive "sOrg-files matching: \np")
20727 (let* ((files (org-agenda-files))
20728 (tnames (mapcar 'file-truename files))
20729 (extra org-agenda-text-search-extra-files)
20731 (when (eq (car extra) 'agenda-archives)
20732 (setq extra (cdr extra))
20733 (setq files (org-add-archive-files files)))
20734 (while (setq f (pop extra))
20735 (unless (member (file-truename f) tnames)
20736 (add-to-list 'files f 'append)
20737 (add-to-list 'tnames (file-truename f) 'append)))
20738 (multi-occur
20739 (mapcar (lambda (x)
20740 (with-current-buffer
20741 (or (get-file-buffer x) (find-file-noselect x))
20742 (widen)
20743 (current-buffer)))
20744 files)
20745 regexp)))
20747 (if (boundp 'occur-mode-find-occurrence-hook)
20748 ;; Emacs 23
20749 (add-hook 'occur-mode-find-occurrence-hook
20750 (lambda ()
20751 (when (derived-mode-p 'org-mode)
20752 (org-reveal))))
20753 ;; Emacs 22
20754 (defadvice occur-mode-goto-occurrence
20755 (after org-occur-reveal activate)
20756 (and (derived-mode-p 'org-mode) (org-reveal)))
20757 (defadvice occur-mode-goto-occurrence-other-window
20758 (after org-occur-reveal activate)
20759 (and (derived-mode-p 'org-mode) (org-reveal)))
20760 (defadvice occur-mode-display-occurrence
20761 (after org-occur-reveal activate)
20762 (when (derived-mode-p 'org-mode)
20763 (let ((pos (occur-mode-find-occurrence)))
20764 (with-current-buffer (marker-buffer pos)
20765 (save-excursion
20766 (goto-char pos)
20767 (org-reveal)))))))
20769 (defun org-occur-link-in-agenda-files ()
20770 "Create a link and search for it in the agendas.
20771 The link is not stored in `org-stored-links', it is just created
20772 for the search purpose."
20773 (interactive)
20774 (let ((link (condition-case nil
20775 (org-store-link nil)
20776 (error "Unable to create a link to here"))))
20777 (org-occur-in-agenda-files (regexp-quote link))))
20779 (defun org-uniquify (list)
20780 "Remove duplicate elements from LIST."
20781 (let (res)
20782 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20783 res))
20785 (defun org-delete-all (elts list)
20786 "Remove all elements in ELTS from LIST."
20787 (while elts
20788 (setq list (delete (pop elts) list)))
20789 list)
20791 (defun org-count (cl-item cl-seq)
20792 "Count the number of occurrences of ITEM in SEQ.
20793 Taken from `count' in cl-seq.el with all keyword arguments removed."
20794 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20795 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20796 (while (< cl-start cl-end)
20797 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20798 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20799 (setq cl-start (1+ cl-start)))
20800 cl-count))
20802 (defun org-remove-if (predicate seq)
20803 "Remove everything from SEQ that fulfills PREDICATE."
20804 (let (res e)
20805 (while seq
20806 (setq e (pop seq))
20807 (if (not (funcall predicate e)) (push e res)))
20808 (nreverse res)))
20810 (defun org-remove-if-not (predicate seq)
20811 "Remove everything from SEQ that does not fulfill PREDICATE."
20812 (let (res e)
20813 (while seq
20814 (setq e (pop seq))
20815 (if (funcall predicate e) (push e res)))
20816 (nreverse res)))
20818 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20819 "Reduce two-argument FUNCTION across SEQ.
20820 Taken from `reduce' in cl-seq.el with all keyword arguments but
20821 \":initial-value\" removed."
20822 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20823 (cadr (memq :initial-value cl-keys)))
20824 (cl-seq (pop cl-seq))
20825 (t (funcall cl-func)))))
20826 (while cl-seq
20827 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20828 cl-accum))
20830 (defun org-back-over-empty-lines ()
20831 "Move backwards over whitespace, to the beginning of the first empty line.
20832 Returns the number of empty lines passed."
20833 (let ((pos (point)))
20834 (if (cdr (assoc 'heading org-blank-before-new-entry))
20835 (skip-chars-backward " \t\n\r")
20836 (unless (eobp)
20837 (forward-line -1)))
20838 (beginning-of-line 2)
20839 (goto-char (min (point) pos))
20840 (count-lines (point) pos)))
20842 (defun org-skip-whitespace ()
20843 (skip-chars-forward " \t\n\r"))
20845 (defun org-point-in-group (point group &optional context)
20846 "Check if POINT is in match-group GROUP.
20847 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20848 match. If the match group does not exist or point is not inside it,
20849 return nil."
20850 (and (match-beginning group)
20851 (>= point (match-beginning group))
20852 (<= point (match-end group))
20853 (if context
20854 (list context (match-beginning group) (match-end group))
20855 t)))
20857 (defun org-switch-to-buffer-other-window (&rest args)
20858 "Switch to buffer in a second window on the current frame.
20859 In particular, do not allow pop-up frames.
20860 Returns the newly created buffer."
20861 (let (pop-up-frames special-display-buffer-names special-display-regexps
20862 special-display-function)
20863 (apply 'switch-to-buffer-other-window args)))
20865 (defun org-combine-plists (&rest plists)
20866 "Create a single property list from all plists in PLISTS.
20867 The process starts by copying the first list, and then setting properties
20868 from the other lists. Settings in the last list are the most significant
20869 ones and overrule settings in the other lists."
20870 (let ((rtn (copy-sequence (pop plists)))
20871 p v ls)
20872 (while plists
20873 (setq ls (pop plists))
20874 (while ls
20875 (setq p (pop ls) v (pop ls))
20876 (setq rtn (plist-put rtn p v))))
20877 rtn))
20879 (defun org-replace-escapes (string table)
20880 "Replace %-escapes in STRING with values in TABLE.
20881 TABLE is an association list with keys like \"%a\" and string values.
20882 The sequences in STRING may contain normal field width and padding information,
20883 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20884 so values can contain further %-escapes if they are define later in TABLE."
20885 (let ((tbl (copy-alist table))
20886 (case-fold-search nil)
20887 (pchg 0)
20888 e re rpl)
20889 (while (setq e (pop tbl))
20890 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20891 (when (and (cdr e) (string-match re (cdr e)))
20892 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20893 (safe "SREF"))
20894 (add-text-properties 0 3 (list 'sref sref) safe)
20895 (setcdr e (replace-match safe t t (cdr e)))))
20896 (while (string-match re string)
20897 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20898 (cdr e)))
20899 (setq string (replace-match rpl t t string))))
20900 (while (setq pchg (next-property-change pchg string))
20901 (let ((sref (get-text-property pchg 'sref string)))
20902 (when (and sref (string-match "SREF" string pchg))
20903 (setq string (replace-match sref t t string)))))
20904 string))
20906 (defun org-sublist (list start end)
20907 "Return a section of LIST, from START to END.
20908 Counting starts at 1."
20909 (let (rtn (c start))
20910 (setq list (nthcdr (1- start) list))
20911 (while (and list (<= c end))
20912 (push (pop list) rtn)
20913 (setq c (1+ c)))
20914 (nreverse rtn)))
20916 (defun org-find-base-buffer-visiting (file)
20917 "Like `find-buffer-visiting' but always return the base buffer and
20918 not an indirect buffer."
20919 (let ((buf (or (get-file-buffer file)
20920 (find-buffer-visiting file))))
20921 (if buf
20922 (or (buffer-base-buffer buf) buf)
20923 nil)))
20925 (defun org-image-file-name-regexp (&optional extensions)
20926 "Return regexp matching the file names of images.
20927 If EXTENSIONS is given, only match these."
20928 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20929 (image-file-name-regexp)
20930 (let ((image-file-name-extensions
20931 (or extensions
20932 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20933 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20934 (concat "\\."
20935 (regexp-opt (nconc (mapcar 'upcase
20936 image-file-name-extensions)
20937 image-file-name-extensions)
20939 "\\'"))))
20941 (defun org-file-image-p (file &optional extensions)
20942 "Return non-nil if FILE is an image."
20943 (save-match-data
20944 (string-match (org-image-file-name-regexp extensions) file)))
20946 (defun org-get-cursor-date ()
20947 "Return the date at cursor in as a time.
20948 This works in the calendar and in the agenda, anywhere else it just
20949 returns the current time."
20950 (let (date day defd)
20951 (cond
20952 ((eq major-mode 'calendar-mode)
20953 (setq date (calendar-cursor-to-date)
20954 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20955 ((eq major-mode 'org-agenda-mode)
20956 (setq day (get-text-property (point) 'day))
20957 (if day
20958 (setq date (calendar-gregorian-from-absolute day)
20959 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20960 (nth 2 date))))))
20961 (or defd (current-time))))
20963 (defvar org-agenda-action-marker (make-marker)
20964 "Marker pointing to the entry for the next agenda action.")
20966 (defun org-mark-entry-for-agenda-action ()
20967 "Mark the current entry as target of an agenda action.
20968 Agenda actions are actions executed from the agenda with the key `k',
20969 which make use of the date at the cursor."
20970 (interactive)
20971 (move-marker org-agenda-action-marker
20972 (save-excursion (org-back-to-heading t) (point))
20973 (current-buffer))
20974 (message
20975 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20977 (defun org-mark-subtree (&optional up)
20978 "Mark the current subtree.
20979 This puts point at the start of the current subtree, and mark at
20980 the end. If a numeric prefix UP is given, move up into the
20981 hierarchy of headlines by UP levels before marking the subtree."
20982 (interactive "P")
20983 (org-with-limited-levels
20984 (cond ((org-at-heading-p) (beginning-of-line))
20985 ((org-before-first-heading-p) (error "Not in a subtree"))
20986 (t (outline-previous-visible-heading 1))))
20987 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20988 (if (org-called-interactively-p 'any)
20989 (call-interactively 'org-mark-element)
20990 (org-mark-element)))
20993 ;;; Macros
20995 ;; Macros are expanded with `org-macro-replace-all', which relies
20996 ;; internally on `org-macro-expand'.
20998 ;; Templates for expansion are stored in the buffer-local variable
20999 ;; `org-macro-templates'. This variable is updated by
21000 ;; `org-macro-initialize-templates'.
21003 (defvar org-macro-templates nil
21004 "Alist containing all macro templates in current buffer.
21005 Associations are in the shape of (NAME . TEMPLATE) where NAME
21006 stands for macro's name and template for its replacement value,
21007 both as strings. This is an internal variable. Do not set it
21008 directly, use instead:
21010 #+MACRO: name template")
21011 (make-variable-buffer-local 'org-macro-templates)
21013 (defun org-macro-expand (macro)
21014 "Return expanded MACRO, as a string.
21015 MACRO is an object, obtained, for example, with
21016 `org-element-context'. Return nil if no template was found."
21017 (let ((template
21018 (cdr (assoc-string (org-element-property :key macro)
21019 org-macro-templates
21020 ;; Macro names are case-insensitive.
21021 t))))
21022 (when template
21023 (let ((value (replace-regexp-in-string
21024 "\\$[0-9]+"
21025 (lambda (arg)
21026 (or (nth (1- (string-to-number (substring arg 1)))
21027 (org-element-property :args macro))
21028 ;; No argument provided: remove
21029 ;; place-holder.
21030 ""))
21031 template)))
21032 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21033 (when (string-match "\\`(eval\\>" value)
21034 (setq value (eval (read value))))
21035 ;; Return string.
21036 (format "%s" (or value ""))))))
21038 (defun org-macro-replace-all ()
21039 "Replace all macros in current buffer by their expansion."
21040 (save-excursion
21041 (goto-char (point-min))
21042 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21043 (let ((object (org-element-context)))
21044 (when (eq (org-element-type object) 'macro)
21045 (let ((value (org-macro-expand object)))
21046 (when value
21047 (delete-region
21048 (org-element-property :begin object)
21049 ;; Preserve white spaces after the macro.
21050 (progn (goto-char (org-element-property :end object))
21051 (skip-chars-backward " \t")
21052 (point)))
21053 ;; Leave point before replacement in case of recursive
21054 ;; expansions.
21055 (save-excursion (insert value)))))))))
21057 (defun org-macro-initialize-templates ()
21058 "Collect macro templates defined in current buffer.
21059 Templates are stored in buffer-local variable
21060 `org-macro-templates'. In addition to buffer-defined macros, the
21061 function installs the following ones: \"property\", \"date\",
21062 \"time\". and, if appropriate, \"input-file\" and
21063 \"modification-time\"."
21064 (let ((case-fold-search t)
21065 (set-template
21066 (lambda (cell)
21067 ;; Add CELL to `org-macro-templates' if there's no
21068 ;; association matching its name already. Otherwise,
21069 ;; replace old association with the new one in that
21070 ;; variable.
21071 (let ((old-template (assoc (car cell) org-macro-templates)))
21072 (if old-template (setcdr old-template (cdr cell))
21073 (push cell org-macro-templates))))))
21074 ;; Install buffer-local macros.
21075 (org-with-wide-buffer
21076 (goto-char (point-min))
21077 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21078 (let ((element (org-element-at-point)))
21079 (when (eq (org-element-type element) 'keyword)
21080 (let ((value (org-element-property :value element)))
21081 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21082 (funcall set-template
21083 (cons (match-string 1 value)
21084 (or (match-string 2 value) "")))))))))
21085 ;; Install hard-coded macros.
21086 (mapc (lambda (cell) (funcall set-template cell))
21087 (list
21088 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21089 (cons "date" "(eval (format-time-string \"$1\"))")
21090 (cons "time" "(eval (format-time-string \"$1\"))")))
21091 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21092 (when (and visited-file (file-exists-p visited-file))
21093 (mapc (lambda (cell) (funcall set-template cell))
21094 (list
21095 (cons "input-file" (file-name-nondirectory visited-file))
21096 (cons "modification-time"
21097 (format "(eval (format-time-string \"$1\" '%s))"
21098 (prin1-to-string
21099 (nth 5 (file-attributes visited-file)))))))))))
21102 ;;; Indentation
21104 (defun org-indent-line ()
21105 "Indent line depending on context."
21106 (interactive)
21107 (let* ((pos (point))
21108 (itemp (org-at-item-p))
21109 (case-fold-search t)
21110 (org-drawer-regexp (or org-drawer-regexp "\000"))
21111 (inline-task-p (and (featurep 'org-inlinetask)
21112 (org-inlinetask-in-task-p)))
21113 (inline-re (and inline-task-p
21114 (org-inlinetask-outline-regexp)))
21115 column)
21116 (if (and orgstruct-is-++ (eq pos (point)))
21117 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21118 (indent-according-to-mode))
21119 (beginning-of-line 1)
21120 (cond
21121 ;; Headings
21122 ((looking-at org-outline-regexp) (setq column 0))
21123 ;; Included files
21124 ((looking-at "#\\+include:") (setq column 0))
21125 ;; Footnote definition
21126 ((looking-at org-footnote-definition-re) (setq column 0))
21127 ;; Literal examples
21128 ((looking-at "[ \t]*:\\( \\|$\\)")
21129 (setq column (org-get-indentation))) ; do nothing
21130 ;; Lists
21131 ((ignore-errors (goto-char (org-in-item-p)))
21132 (setq column (if itemp
21133 (org-get-indentation)
21134 (org-list-item-body-column (point))))
21135 (goto-char pos))
21136 ;; Drawers
21137 ((and (looking-at "[ \t]*:END:")
21138 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21139 (save-excursion
21140 (goto-char (1- (match-beginning 1)))
21141 (setq column (current-column))))
21142 ;; Special blocks
21143 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21144 (save-excursion
21145 (re-search-backward
21146 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21147 (setq column (org-get-indentation (match-string 0))))
21148 ((and (not (looking-at "[ \t]*#\\+begin_"))
21149 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21150 (save-excursion
21151 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21152 (setq column
21153 (cond ((equal (downcase (match-string 1)) "src")
21154 ;; src blocks: let `org-edit-src-exit' handle them
21155 (org-get-indentation))
21156 ((equal (downcase (match-string 1)) "example")
21157 (max (org-get-indentation)
21158 (org-get-indentation (match-string 0))))
21160 (org-get-indentation (match-string 0))))))
21161 ;; This line has nothing special, look at the previous relevant
21162 ;; line to compute indentation
21164 (beginning-of-line 0)
21165 (while (and (not (bobp))
21166 (not (looking-at org-drawer-regexp))
21167 ;; When point started in an inline task, do not move
21168 ;; above task starting line.
21169 (not (and inline-task-p (looking-at inline-re)))
21170 ;; Skip drawers, blocks, empty lines, verbatim,
21171 ;; comments, tables, footnotes definitions, lists,
21172 ;; inline tasks.
21173 (or (and (looking-at "[ \t]*:END:")
21174 (re-search-backward org-drawer-regexp nil t))
21175 (and (looking-at "[ \t]*#\\+end_")
21176 (re-search-backward "[ \t]*#\\+begin_"nil t))
21177 (looking-at "[ \t]*[\n:#|]")
21178 (looking-at org-footnote-definition-re)
21179 (and (ignore-errors (goto-char (org-in-item-p)))
21180 (goto-char
21181 (org-list-get-top-point (org-list-struct))))
21182 (and (not inline-task-p)
21183 (featurep 'org-inlinetask)
21184 (org-inlinetask-in-task-p)
21185 (or (org-inlinetask-goto-beginning) t))))
21186 (beginning-of-line 0))
21187 (cond
21188 ;; There was an heading above.
21189 ((looking-at "\\*+[ \t]+")
21190 (if (not org-adapt-indentation)
21191 (setq column 0)
21192 (goto-char (match-end 0))
21193 (setq column (current-column))))
21194 ;; A drawer had started and is unfinished
21195 ((looking-at org-drawer-regexp)
21196 (goto-char (1- (match-beginning 1)))
21197 (setq column (current-column)))
21198 ;; Else, nothing noticeable found: get indentation and go on.
21199 (t (setq column (org-get-indentation))))))
21200 ;; Now apply indentation and move cursor accordingly
21201 (goto-char pos)
21202 (if (<= (current-column) (current-indentation))
21203 (org-indent-line-to column)
21204 (save-excursion (org-indent-line-to column)))
21205 ;; Special polishing for properties, see `org-property-format'
21206 (setq column (current-column))
21207 (beginning-of-line 1)
21208 (if (looking-at
21209 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21210 (replace-match (concat (match-string 1)
21211 (format org-property-format
21212 (match-string 2) (match-string 3)))
21213 t t))
21214 (org-move-to-column column))))
21216 (defun org-indent-drawer ()
21217 "Indent the drawer at point."
21218 (interactive)
21219 (let ((p (point))
21220 (e (and (save-excursion (re-search-forward ":END:" nil t))
21221 (match-end 0)))
21222 (folded
21223 (save-excursion
21224 (end-of-line)
21225 (when (overlays-at (point))
21226 (member 'invisible (overlay-properties
21227 (car (overlays-at (point)))))))))
21228 (when folded (org-cycle))
21229 (indent-for-tab-command)
21230 (while (and (move-beginning-of-line 2) (< (point) e))
21231 (indent-for-tab-command))
21232 (goto-char p)
21233 (when folded (org-cycle)))
21234 (message "Drawer at point indented"))
21236 (defun org-indent-block ()
21237 "Indent the block at point."
21238 (interactive)
21239 (let ((p (point))
21240 (case-fold-search t)
21241 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21242 (match-end 0)))
21243 (folded
21244 (save-excursion
21245 (end-of-line)
21246 (when (overlays-at (point))
21247 (member 'invisible (overlay-properties
21248 (car (overlays-at (point)))))))))
21249 (when folded (org-cycle))
21250 (indent-for-tab-command)
21251 (while (and (move-beginning-of-line 2) (< (point) e))
21252 (indent-for-tab-command))
21253 (goto-char p)
21254 (when folded (org-cycle)))
21255 (message "Block at point indented"))
21257 (defun org-indent-region (start end)
21258 "Indent region."
21259 (interactive "r")
21260 (save-excursion
21261 (let ((line-end (org-current-line end)))
21262 (goto-char start)
21263 (while (< (org-current-line) line-end)
21264 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21265 (t (call-interactively 'org-indent-line)))
21266 (move-beginning-of-line 2)))))
21269 ;;; Filling
21271 ;; We use our own fill-paragraph and auto-fill functions.
21273 ;; `org-fill-paragraph' relies on adaptive filling and context
21274 ;; checking. Appropriate `fill-prefix' is computed with
21275 ;; `org-adaptive-fill-function'.
21277 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21278 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21279 ;; `org-adaptive-fill-function' value. Internally,
21280 ;; `org-comment-line-break-function' breaks the line.
21282 ;; `org-setup-filling' installs filling and auto-filling related
21283 ;; variables during `org-mode' initialization.
21285 (defun org-setup-filling ()
21286 (interactive)
21287 ;; Prevent auto-fill from inserting unwanted new items.
21288 (when (boundp 'fill-nobreak-predicate)
21289 (org-set-local
21290 'fill-nobreak-predicate
21291 (org-uniquify
21292 (append fill-nobreak-predicate
21293 '(org-fill-paragraph-separate-nobreak-p
21294 org-fill-line-break-nobreak-p)))))
21295 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21296 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21297 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21298 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21300 (defvar org-element-paragraph-separate) ; org-element.el
21301 (defun org-fill-paragraph-separate-nobreak-p ()
21302 "Non-nil when a line break at point would insert a new item."
21303 (looking-at (substring org-element-paragraph-separate 1)))
21305 (defun org-fill-line-break-nobreak-p ()
21306 "Non-nil when a line break at point would create an Org line break."
21307 (save-excursion
21308 (skip-chars-backward "[ \t]")
21309 (skip-chars-backward "\\\\")
21310 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21312 (declare-function message-in-body-p "message" ())
21313 (defvar org-element--affiliated-re) ; From org-element.el
21314 (defun org-adaptive-fill-function ()
21315 "Compute a fill prefix for the current line.
21316 Return fill prefix, as a string, or nil if current line isn't
21317 meant to be filled."
21318 (org-with-wide-buffer
21319 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21320 ;; FIXME: This is really the job of orgstruct++-mode
21321 (let* ((p (line-beginning-position))
21322 (element (save-excursion (beginning-of-line)
21323 (org-element-at-point)))
21324 (type (org-element-type element))
21325 (post-affiliated
21326 (save-excursion
21327 (goto-char (org-element-property :begin element))
21328 (while (looking-at org-element--affiliated-re) (forward-line))
21329 (point))))
21330 (unless (< p post-affiliated)
21331 (case type
21332 (comment (looking-at "[ \t]*# ?") (match-string 0))
21333 (footnote-definition "")
21334 ((item plain-list)
21335 (make-string (org-list-item-body-column post-affiliated) ? ))
21336 (paragraph
21337 ;; Fill prefix is usually the same as the current line,
21338 ;; except if the paragraph is at the beginning of an item.
21339 (let ((parent (org-element-property :parent element)))
21340 (cond ((eq (org-element-type parent) 'item)
21341 (make-string (org-list-item-body-column
21342 (org-element-property :begin parent))
21343 ? ))
21344 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21345 (match-string 0))
21346 (t ""))))
21347 (comment-block
21348 ;; Only fill contents if P is within block boundaries.
21349 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21350 (forward-line)
21351 (point)))
21352 (cend (save-excursion
21353 (goto-char (org-element-property :end element))
21354 (skip-chars-backward " \r\t\n")
21355 (line-beginning-position))))
21356 (when (and (>= p cbeg) (< p cend))
21357 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21358 (match-string 0)
21359 ""))))))))))
21361 (declare-function message-goto-body "message" ())
21362 (defvar message-cite-prefix-regexp) ; From message.el
21363 (defvar org-element-all-objects) ; From org-element.el
21364 (defun org-fill-paragraph (&optional justify)
21365 "Fill element at point, when applicable.
21367 This function only applies to comment blocks, comments, example
21368 blocks and paragraphs. Also, as a special case, re-align table
21369 when point is at one.
21371 If JUSTIFY is non-nil (interactively, with prefix argument),
21372 justify as well. If `sentence-end-double-space' is non-nil, then
21373 period followed by one space does not end a sentence, so don't
21374 break a line there. The variable `fill-column' controls the
21375 width for filling.
21377 For convenience, when point is at a plain list, an item or
21378 a footnote definition, try to fill the first paragraph within."
21379 ;; Falls back on message-fill-paragraph when necessary
21380 (interactive)
21381 (if (and (derived-mode-p 'message-mode)
21382 (or (not (message-in-body-p))
21383 (save-excursion (move-beginning-of-line 1)
21384 (looking-at message-cite-prefix-regexp))))
21385 (let ((fill-paragraph-function
21386 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21387 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21388 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21389 (paragraph-separate
21390 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21391 (fill-paragraph nil))
21392 (save-excursion
21393 ;; Move to end of line in order to get the first paragraph
21394 ;; within a plain list or a footnote definition.
21395 (end-of-line)
21396 (let ((element (org-element-at-point)))
21397 ;; First check if point is in a blank line at the beginning of
21398 ;; the buffer. In that case, ignore filling.
21399 (if (< (point) (org-element-property :begin element)) t
21400 (case (org-element-type element)
21401 ;; Align Org tables, leave table.el tables as-is.
21402 (table-row (org-table-align) t)
21403 (table
21404 (when (eq (org-element-property :type element) 'org)
21405 (org-table-align))
21407 (paragraph
21408 ;; Paragraphs may contain `line-break' type objects.
21409 (let ((beg (max (point-min)
21410 (org-element-property :contents-begin element)))
21411 (end (min (point-max)
21412 (org-element-property :contents-end element))))
21413 ;; Do nothing if point is at an affiliated keyword.
21414 (if (< (point) beg) t
21415 (when (derived-mode-p 'message-mode)
21416 ;; In `message-mode', do not fill following
21417 ;; citation in current paragraph nor text before
21418 ;; message body.
21419 (let ((body-start (save-excursion (message-goto-body))))
21420 (when body-start (setq beg (max body-start beg))))
21421 (when (save-excursion
21422 (re-search-forward
21423 (concat "^" message-cite-prefix-regexp) end t))
21424 (setq end (match-beginning 0))))
21425 ;; Fill paragraph, taking line breaks into
21426 ;; consideration. For that, slice the paragraph
21427 ;; using line breaks as separators, and fill the
21428 ;; parts in reverse order to avoid messing with
21429 ;; markers.
21430 (save-excursion
21431 (goto-char end)
21432 (mapc
21433 (lambda (pos)
21434 (fill-region-as-paragraph pos (point) justify)
21435 (goto-char pos))
21436 ;; Find the list of ending positions for line
21437 ;; breaks in the current paragraph. Add paragraph
21438 ;; beginning to include first slice.
21439 (nreverse
21440 (cons
21442 (org-element-map
21443 (org-element--parse-objects
21444 beg end nil org-element-all-objects)
21445 'line-break
21446 (lambda (lb) (org-element-property :end lb)))))))
21447 t)))
21448 ;; Contents of `comment-block' type elements should be
21449 ;; filled as plain text, but only if point is within block
21450 ;; markers.
21451 (comment-block
21452 (let* ((case-fold-search t)
21453 (beg (save-excursion
21454 (goto-char (org-element-property :begin element))
21455 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21456 (forward-line)
21457 (point)))
21458 (end (save-excursion
21459 (goto-char (org-element-property :end element))
21460 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21461 (line-beginning-position))))
21462 (when (and (>= (point) beg) (< (point) end))
21463 (fill-region-as-paragraph
21464 (save-excursion
21465 (end-of-line)
21466 (re-search-backward "^[ \t]*$" beg 'move)
21467 (line-beginning-position))
21468 (save-excursion
21469 (beginning-of-line)
21470 (re-search-forward "^[ \t]*$" end 'move)
21471 (line-beginning-position))
21472 justify)))
21474 ;; Fill comments.
21475 (comment (fill-comment-paragraph justify))
21476 ;; Ignore every other element.
21477 (otherwise t)))))))
21479 (defun org-auto-fill-function ()
21480 "Auto-fill function."
21481 ;; Check if auto-filling is meaningful.
21482 (let ((fc (current-fill-column)))
21483 (when (and fc (> (current-column) fc))
21484 (let ((fill-prefix (org-adaptive-fill-function)))
21485 (when fill-prefix (do-auto-fill))))))
21487 (defun org-comment-line-break-function (&optional soft)
21488 "Break line at point and indent, continuing comment if within one.
21489 The inserted newline is marked hard if variable
21490 `use-hard-newlines' is true, unless optional argument SOFT is
21491 non-nil."
21492 (if soft (insert-and-inherit ?\n) (newline 1))
21493 (save-excursion (forward-char -1) (delete-horizontal-space))
21494 (delete-horizontal-space)
21495 (indent-to-left-margin)
21496 (insert-before-markers-and-inherit fill-prefix))
21499 ;;; Comments
21501 ;; Org comments syntax is quite complex. It requires the entire line
21502 ;; to be just a comment. Also, even with the right syntax at the
21503 ;; beginning of line, some some elements (i.e. verse-block or
21504 ;; example-block) don't accept comments. Usual Emacs comment commands
21505 ;; cannot cope with those requirements. Therefore, Org replaces them.
21507 ;; Org still relies on `comment-dwim', but cannot trust
21508 ;; `comment-only-p'. So, `comment-region-function' and
21509 ;; `uncomment-region-function' both point
21510 ;; to`org-comment-or-uncomment-region'. Eventually,
21511 ;; `org-insert-comment' takes care of insertion of comments at the
21512 ;; beginning of line.
21514 ;; `org-setup-comments-handling' install comments related variables
21515 ;; during `org-mode' initialization.
21517 (defun org-setup-comments-handling ()
21518 (interactive)
21519 (org-set-local 'comment-use-syntax nil)
21520 (org-set-local 'comment-start "# ")
21521 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21522 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21523 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21524 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21526 (defun org-insert-comment ()
21527 "Insert an empty comment above current line.
21528 If the line is empty, insert comment at its beginning."
21529 (beginning-of-line)
21530 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21531 (org-indent-line)
21532 (insert "# "))
21534 (defvar comment-empty-lines) ; From newcomment.el.
21535 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21536 "Comment or uncomment each non-blank line in the region.
21537 Uncomment each non-blank line between BEG and END if it only
21538 contains commented lines. Otherwise, comment them."
21539 (save-restriction
21540 ;; Restrict region
21541 (narrow-to-region (save-excursion (goto-char beg)
21542 (skip-chars-forward " \r\t\n" end)
21543 (line-beginning-position))
21544 (save-excursion (goto-char end)
21545 (skip-chars-backward " \r\t\n" beg)
21546 (line-end-position)))
21547 (let ((uncommentp
21548 ;; UNCOMMENTP is non-nil when every non blank line between
21549 ;; BEG and END is a comment.
21550 (save-excursion
21551 (goto-char (point-min))
21552 (while (and (not (eobp))
21553 (let ((element (org-element-at-point)))
21554 (and (eq (org-element-type element) 'comment)
21555 (goto-char (min (point-max)
21556 (org-element-property
21557 :end element)))))))
21558 (eobp))))
21559 (if uncommentp
21560 ;; Only blank lines and comments in region: uncomment it.
21561 (save-excursion
21562 (goto-char (point-min))
21563 (while (not (eobp))
21564 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21565 (replace-match "" nil nil nil 1))
21566 (forward-line)))
21567 ;; Comment each line in region.
21568 (let ((min-indent (point-max)))
21569 ;; First find the minimum indentation across all lines.
21570 (save-excursion
21571 (goto-char (point-min))
21572 (while (and (not (eobp)) (not (zerop min-indent)))
21573 (unless (looking-at "[ \t]*$")
21574 (setq min-indent (min min-indent (current-indentation))))
21575 (forward-line)))
21576 ;; Then loop over all lines.
21577 (save-excursion
21578 (goto-char (point-min))
21579 (while (not (eobp))
21580 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21581 (org-move-to-column min-indent t)
21582 (insert comment-start))
21583 (forward-line))))))))
21586 ;;; Other stuff.
21588 (defun org-toggle-fixed-width-section (arg)
21589 "Toggle the fixed-width export.
21590 If there is no active region, the QUOTE keyword at the current headline is
21591 inserted or removed. When present, it causes the text between this headline
21592 and the next to be exported as fixed-width text, and unmodified.
21593 If there is an active region, this command adds or removes a colon as the
21594 first character of this line. If the first character of a line is a colon,
21595 this line is also exported in fixed-width font."
21596 (interactive "P")
21597 (let* ((cc 0)
21598 (regionp (org-region-active-p))
21599 (beg (if regionp (region-beginning) (point)))
21600 (end (if regionp (region-end)))
21601 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21602 (case-fold-search nil)
21603 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21604 off)
21605 (if regionp
21606 (save-excursion
21607 (goto-char beg)
21608 (setq cc (current-column))
21609 (beginning-of-line 1)
21610 (setq off (looking-at re))
21611 (while (> nlines 0)
21612 (setq nlines (1- nlines))
21613 (beginning-of-line 1)
21614 (cond
21615 (arg
21616 (org-move-to-column cc t)
21617 (insert ": \n")
21618 (forward-line -1))
21619 ((and off (looking-at re))
21620 (replace-match "" t t nil 1))
21621 ((not off) (org-move-to-column cc t) (insert ": ")))
21622 (forward-line 1)))
21623 (save-excursion
21624 (org-back-to-heading)
21625 (cond
21626 ((looking-at (format org-heading-keyword-regexp-format
21627 org-quote-string))
21628 (goto-char (match-end 1))
21629 (looking-at (concat " +" org-quote-string))
21630 (replace-match "" t t)
21631 (when (eolp) (insert " ")))
21632 ((looking-at org-outline-regexp)
21633 (goto-char (match-end 0))
21634 (insert org-quote-string " ")))))))
21636 (defun org-reftex-citation ()
21637 "Use reftex-citation to insert a citation into the buffer.
21638 This looks for a line like
21640 #+BIBLIOGRAPHY: foo plain option:-d
21642 and derives from it that foo.bib is the bibliography file relevant
21643 for this document. It then installs the necessary environment for RefTeX
21644 to work in this buffer and calls `reftex-citation' to insert a citation
21645 into the buffer.
21647 Export of such citations to both LaTeX and HTML is handled by the contributed
21648 package org-exp-bibtex by Taru Karttunen."
21649 (interactive)
21650 (let ((reftex-docstruct-symbol 'rds)
21651 (reftex-cite-format "\\cite{%l}")
21652 rds bib)
21653 (save-excursion
21654 (save-restriction
21655 (widen)
21656 (let ((case-fold-search t)
21657 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21658 (if (not (save-excursion
21659 (or (re-search-forward re nil t)
21660 (re-search-backward re nil t))))
21661 (error "No bibliography defined in file")
21662 (setq bib (concat (match-string 1) ".bib")
21663 rds (list (list 'bib bib)))))))
21664 (call-interactively 'reftex-citation)))
21666 ;;;; Functions extending outline functionality
21668 (defun org-beginning-of-line (&optional arg)
21669 "Go to the beginning of the current line. If that is invisible, continue
21670 to a visible line beginning. This makes the function of C-a more intuitive.
21671 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21672 first attempt, and only move to after the tags when the cursor is already
21673 beyond the end of the headline."
21674 (interactive "P")
21675 (let ((pos (point))
21676 (special (if (consp org-special-ctrl-a/e)
21677 (car org-special-ctrl-a/e)
21678 org-special-ctrl-a/e))
21679 refpos)
21680 (if (org-bound-and-true-p line-move-visual)
21681 (beginning-of-visual-line 1)
21682 (beginning-of-line 1))
21683 (if (and arg (fboundp 'move-beginning-of-line))
21684 (call-interactively 'move-beginning-of-line)
21685 (if (bobp)
21687 (backward-char 1)
21688 (if (org-truely-invisible-p)
21689 (while (and (not (bobp)) (org-truely-invisible-p))
21690 (backward-char 1)
21691 (beginning-of-line 1))
21692 (forward-char 1))))
21693 (when special
21694 (cond
21695 ((and (looking-at org-complex-heading-regexp)
21696 (= (char-after (match-end 1)) ?\ ))
21697 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21698 (point-at-eol)))
21699 (goto-char
21700 (if (eq special t)
21701 (cond ((> pos refpos) refpos)
21702 ((= pos (point)) refpos)
21703 (t (point)))
21704 (cond ((> pos (point)) (point))
21705 ((not (eq last-command this-command)) (point))
21706 (t refpos)))))
21707 ((org-at-item-p)
21708 ;; Being at an item and not looking at an the item means point
21709 ;; was previously moved to beginning of a visual line, which
21710 ;; doesn't contain the item. Therefore, do nothing special,
21711 ;; just stay here.
21712 (when (looking-at org-list-full-item-re)
21713 ;; Set special position at first white space character after
21714 ;; bullet, and check-box, if any.
21715 (let ((after-bullet
21716 (let ((box (match-end 3)))
21717 (if (not box) (match-end 1)
21718 (let ((after (char-after box)))
21719 (if (and after (= after ? )) (1+ box) box))))))
21720 ;; Special case: Move point to special position when
21721 ;; currently after it or at beginning of line.
21722 (if (eq special t)
21723 (when (or (> pos after-bullet) (= (point) pos))
21724 (goto-char after-bullet))
21725 ;; Reversed case: Move point to special position when
21726 ;; point was already at beginning of line and command is
21727 ;; repeated.
21728 (when (and (= (point) pos) (eq last-command this-command))
21729 (goto-char after-bullet))))))))
21730 (org-no-warnings
21731 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21733 (defun org-end-of-line (&optional arg)
21734 "Go to the end of the line.
21735 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21736 first attempt, and only move to after the tags when the cursor is already
21737 beyond the end of the headline."
21738 (interactive "P")
21739 (let ((special (if (consp org-special-ctrl-a/e)
21740 (cdr org-special-ctrl-a/e)
21741 org-special-ctrl-a/e)))
21742 (cond
21743 ((or (not special) arg
21744 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21745 (call-interactively
21746 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21747 ((fboundp 'move-end-of-line) 'move-end-of-line)
21748 (t 'end-of-line))))
21749 ((org-at-heading-p)
21750 (let ((pos (point)))
21751 (beginning-of-line 1)
21752 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21753 (if (eq special t)
21754 (if (or (< pos (match-beginning 1))
21755 (= pos (match-end 0)))
21756 (goto-char (match-beginning 1))
21757 (goto-char (match-end 0)))
21758 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21759 (goto-char (match-end 0))
21760 (goto-char (match-beginning 1))))
21761 (call-interactively (if (fboundp 'move-end-of-line)
21762 'move-end-of-line
21763 'end-of-line)))))
21764 ((org-at-drawer-p)
21765 (move-end-of-line 1)
21766 (when (overlays-at (1- (point))) (backward-char 1)))
21767 ;; At an item: Move before any hidden text.
21768 (t (call-interactively
21769 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21770 ((fboundp 'move-end-of-line) 'move-end-of-line)
21771 (t 'end-of-line)))))
21772 (org-no-warnings
21773 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21775 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21776 (define-key org-mode-map "\C-e" 'org-end-of-line)
21778 (defun org-backward-sentence (&optional arg)
21779 "Go to beginning of sentence, or beginning of table field.
21780 This will call `backward-sentence' or `org-table-beginning-of-field',
21781 depending on context."
21782 (interactive "P")
21783 (cond
21784 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21785 (t (call-interactively 'backward-sentence))))
21787 (defun org-forward-sentence (&optional arg)
21788 "Go to end of sentence, or end of table field.
21789 This will call `forward-sentence' or `org-table-end-of-field',
21790 depending on context."
21791 (interactive "P")
21792 (cond
21793 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21794 (t (call-interactively 'forward-sentence))))
21796 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21797 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21799 (defun org-kill-line (&optional arg)
21800 "Kill line, to tags or end of line."
21801 (interactive "P")
21802 (cond
21803 ((or (not org-special-ctrl-k)
21804 (bolp)
21805 (not (org-at-heading-p)))
21806 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21807 org-ctrl-k-protect-subtree)
21808 (if (or (eq org-ctrl-k-protect-subtree 'error)
21809 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21810 (error "C-k aborted - would kill hidden subtree")))
21811 (call-interactively
21812 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21813 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21814 (kill-region (point) (match-beginning 1))
21815 (org-set-tags nil t))
21816 (t (kill-region (point) (point-at-eol)))))
21818 (define-key org-mode-map "\C-k" 'org-kill-line)
21820 (defun org-yank (&optional arg)
21821 "Yank. If the kill is a subtree, treat it specially.
21822 This command will look at the current kill and check if is a single
21823 subtree, or a series of subtrees[1]. If it passes the test, and if the
21824 cursor is at the beginning of a line or after the stars of a currently
21825 empty headline, then the yank is handled specially. How exactly depends
21826 on the value of the following variables, both set by default.
21828 org-yank-folded-subtrees
21829 When set, the subtree(s) will be folded after insertion, but only
21830 if doing so would now swallow text after the yanked text.
21832 org-yank-adjusted-subtrees
21833 When set, the subtree will be promoted or demoted in order to
21834 fit into the local outline tree structure, which means that the level
21835 will be adjusted so that it becomes the smaller one of the two
21836 *visible* surrounding headings.
21838 Any prefix to this command will cause `yank' to be called directly with
21839 no special treatment. In particular, a simple \\[universal-argument] prefix \
21840 will just
21841 plainly yank the text as it is.
21843 \[1] The test checks if the first non-white line is a heading
21844 and if there are no other headings with fewer stars."
21845 (interactive "P")
21846 (org-yank-generic 'yank arg))
21848 (defun org-yank-generic (command arg)
21849 "Perform some yank-like command.
21851 This function implements the behavior described in the `org-yank'
21852 documentation. However, it has been generalized to work for any
21853 interactive command with similar behavior."
21855 ;; pretend to be command COMMAND
21856 (setq this-command command)
21858 (if arg
21859 (call-interactively command)
21861 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21862 (and (org-kill-is-subtree-p)
21863 (or (bolp)
21864 (and (looking-at "[ \t]*$")
21865 (string-match
21866 "\\`\\*+\\'"
21867 (buffer-substring (point-at-bol) (point)))))))
21868 swallowp)
21869 (cond
21870 ((and subtreep org-yank-folded-subtrees)
21871 (let ((beg (point))
21872 end)
21873 (if (and subtreep org-yank-adjusted-subtrees)
21874 (org-paste-subtree nil nil 'for-yank)
21875 (call-interactively command))
21877 (setq end (point))
21878 (goto-char beg)
21879 (when (and (bolp) subtreep
21880 (not (setq swallowp
21881 (org-yank-folding-would-swallow-text beg end))))
21882 (org-with-limited-levels
21883 (or (looking-at org-outline-regexp)
21884 (re-search-forward org-outline-regexp-bol end t))
21885 (while (and (< (point) end) (looking-at org-outline-regexp))
21886 (hide-subtree)
21887 (org-cycle-show-empty-lines 'folded)
21888 (condition-case nil
21889 (outline-forward-same-level 1)
21890 (error (goto-char end))))))
21891 (when swallowp
21892 (message
21893 "Inserted text not folded because that would swallow text"))
21895 (goto-char end)
21896 (skip-chars-forward " \t\n\r")
21897 (beginning-of-line 1)
21898 (push-mark beg 'nomsg)))
21899 ((and subtreep org-yank-adjusted-subtrees)
21900 (let ((beg (point-at-bol)))
21901 (org-paste-subtree nil nil 'for-yank)
21902 (push-mark beg 'nomsg)))
21904 (call-interactively command))))))
21906 (defun org-yank-folding-would-swallow-text (beg end)
21907 "Would hide-subtree at BEG swallow any text after END?"
21908 (let (level)
21909 (org-with-limited-levels
21910 (save-excursion
21911 (goto-char beg)
21912 (when (or (looking-at org-outline-regexp)
21913 (re-search-forward org-outline-regexp-bol end t))
21914 (setq level (org-outline-level)))
21915 (goto-char end)
21916 (skip-chars-forward " \t\r\n\v\f")
21917 (if (or (eobp)
21918 (and (bolp) (looking-at org-outline-regexp)
21919 (<= (org-outline-level) level)))
21920 nil ; Nothing would be swallowed
21921 t))))) ; something would swallow
21923 (define-key org-mode-map "\C-y" 'org-yank)
21925 (defun org-truely-invisible-p ()
21926 "Check if point is at a character currently not visible.
21927 This version does not only check the character property, but also
21928 `visible-mode'."
21929 ;; Early versions of noutline don't have `outline-invisible-p'.
21930 (if (org-bound-and-true-p visible-mode)
21932 (outline-invisible-p)))
21934 (defun org-invisible-p2 ()
21935 "Check if point is at a character currently not visible."
21936 (save-excursion
21937 (if (and (eolp) (not (bobp))) (backward-char 1))
21938 ;; Early versions of noutline don't have `outline-invisible-p'.
21939 (outline-invisible-p)))
21941 (defun org-back-to-heading (&optional invisible-ok)
21942 "Call `outline-back-to-heading', but provide a better error message."
21943 (condition-case nil
21944 (outline-back-to-heading invisible-ok)
21945 (error (error "Before first headline at position %d in buffer %s"
21946 (point) (current-buffer)))))
21948 (defun org-before-first-heading-p ()
21949 "Before first heading?"
21950 (save-excursion
21951 (end-of-line)
21952 (null (re-search-backward org-outline-regexp-bol nil t))))
21954 (defun org-at-heading-p (&optional ignored)
21955 (outline-on-heading-p t))
21956 ;; Compatibility alias with Org versions < 7.8.03
21957 (defalias 'org-on-heading-p 'org-at-heading-p)
21959 (defun org-at-comment-p nil
21960 "Is cursor in a line starting with a # character?"
21961 (save-excursion
21962 (beginning-of-line)
21963 (looking-at "^#")))
21965 (defun org-at-drawer-p nil
21966 "Is cursor at a drawer keyword?"
21967 (save-excursion
21968 (move-beginning-of-line 1)
21969 (looking-at org-drawer-regexp)))
21971 (defun org-at-block-p nil
21972 "Is cursor at a block keyword?"
21973 (save-excursion
21974 (move-beginning-of-line 1)
21975 (looking-at org-block-regexp)))
21977 (defun org-point-at-end-of-empty-headline ()
21978 "If point is at the end of an empty headline, return t, else nil.
21979 If the heading only contains a TODO keyword, it is still still considered
21980 empty."
21981 (and (looking-at "[ \t]*$")
21982 (when org-todo-line-regexp
21983 (save-excursion
21984 (beginning-of-line 1)
21985 (let ((case-fold-search nil))
21986 (looking-at org-todo-line-regexp)
21987 (string= (match-string 3) ""))))))
21989 (defun org-at-heading-or-item-p ()
21990 (or (org-at-heading-p) (org-at-item-p)))
21992 (defun org-at-target-p ()
21993 (or (org-in-regexp org-radio-target-regexp)
21994 (org-in-regexp org-target-regexp)))
21995 ;; Compatibility alias with Org versions < 7.8.03
21996 (defalias 'org-on-target-p 'org-at-target-p)
21998 (defun org-up-heading-all (arg)
21999 "Move to the heading line of which the present line is a subheading.
22000 This function considers both visible and invisible heading lines.
22001 With argument, move up ARG levels."
22002 (if (fboundp 'outline-up-heading-all)
22003 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22004 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22006 (defun org-up-heading-safe ()
22007 "Move to the heading line of which the present line is a subheading.
22008 This version will not throw an error. It will return the level of the
22009 headline found, or nil if no higher level is found.
22011 Also, this function will be a lot faster than `outline-up-heading',
22012 because it relies on stars being the outline starters. This can really
22013 make a significant difference in outlines with very many siblings."
22014 (let (start-level re)
22015 (org-back-to-heading t)
22016 (setq start-level (funcall outline-level))
22017 (if (equal start-level 1)
22019 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22020 (if (re-search-backward re nil t)
22021 (funcall outline-level)))))
22023 (defun org-first-sibling-p ()
22024 "Is this heading the first child of its parents?"
22025 (interactive)
22026 (let ((re org-outline-regexp-bol)
22027 level l)
22028 (unless (org-at-heading-p t)
22029 (error "Not at a heading"))
22030 (setq level (funcall outline-level))
22031 (save-excursion
22032 (if (not (re-search-backward re nil t))
22034 (setq l (funcall outline-level))
22035 (< l level)))))
22037 (defun org-goto-sibling (&optional previous)
22038 "Goto the next sibling, even if it is invisible.
22039 When PREVIOUS is set, go to the previous sibling instead. Returns t
22040 when a sibling was found. When none is found, return nil and don't
22041 move point."
22042 (let ((fun (if previous 're-search-backward 're-search-forward))
22043 (pos (point))
22044 (re org-outline-regexp-bol)
22045 level l)
22046 (when (condition-case nil (org-back-to-heading t) (error nil))
22047 (setq level (funcall outline-level))
22048 (catch 'exit
22049 (or previous (forward-char 1))
22050 (while (funcall fun re nil t)
22051 (setq l (funcall outline-level))
22052 (when (< l level) (goto-char pos) (throw 'exit nil))
22053 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22054 (goto-char pos)
22055 nil))))
22057 (defun org-show-siblings ()
22058 "Show all siblings of the current headline."
22059 (save-excursion
22060 (while (org-goto-sibling) (org-flag-heading nil)))
22061 (save-excursion
22062 (while (org-goto-sibling 'previous)
22063 (org-flag-heading nil))))
22065 (defun org-goto-first-child ()
22066 "Goto the first child, even if it is invisible.
22067 Return t when a child was found. Otherwise don't move point and
22068 return nil."
22069 (let (level (pos (point)) (re org-outline-regexp-bol))
22070 (when (condition-case nil (org-back-to-heading t) (error nil))
22071 (setq level (outline-level))
22072 (forward-char 1)
22073 (if (and (re-search-forward re nil t) (> (outline-level) level))
22074 (progn (goto-char (match-beginning 0)) t)
22075 (goto-char pos) nil))))
22077 (defun org-show-hidden-entry ()
22078 "Show an entry where even the heading is hidden."
22079 (save-excursion
22080 (org-show-entry)))
22082 (defun org-flag-heading (flag &optional entry)
22083 "Flag the current heading. FLAG non-nil means make invisible.
22084 When ENTRY is non-nil, show the entire entry."
22085 (save-excursion
22086 (org-back-to-heading t)
22087 ;; Check if we should show the entire entry
22088 (if entry
22089 (progn
22090 (org-show-entry)
22091 (save-excursion
22092 (and (outline-next-heading)
22093 (org-flag-heading nil))))
22094 (outline-flag-region (max (point-min) (1- (point)))
22095 (save-excursion (outline-end-of-heading) (point))
22096 flag))))
22098 (defun org-get-next-sibling ()
22099 "Move to next heading of the same level, and return point.
22100 If there is no such heading, return nil.
22101 This is like outline-next-sibling, but invisible headings are ok."
22102 (let ((level (funcall outline-level)))
22103 (outline-next-heading)
22104 (while (and (not (eobp)) (> (funcall outline-level) level))
22105 (outline-next-heading))
22106 (if (or (eobp) (< (funcall outline-level) level))
22108 (point))))
22110 (defun org-get-last-sibling ()
22111 "Move to previous heading of the same level, and return point.
22112 If there is no such heading, return nil."
22113 (let ((opoint (point))
22114 (level (funcall outline-level)))
22115 (outline-previous-heading)
22116 (when (and (/= (point) opoint) (outline-on-heading-p t))
22117 (while (and (> (funcall outline-level) level)
22118 (not (bobp)))
22119 (outline-previous-heading))
22120 (if (< (funcall outline-level) level)
22122 (point)))))
22124 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22125 "Goto to the end of a subtree."
22126 ;; This contains an exact copy of the original function, but it uses
22127 ;; `org-back-to-heading', to make it work also in invisible
22128 ;; trees. And is uses an invisible-ok argument.
22129 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22130 ;; Furthermore, when used inside Org, finding the end of a large subtree
22131 ;; with many children and grandchildren etc, this can be much faster
22132 ;; than the outline version.
22133 (org-back-to-heading invisible-ok)
22134 (let ((first t)
22135 (level (funcall outline-level)))
22136 (if (and (derived-mode-p 'org-mode) (< level 1000))
22137 ;; A true heading (not a plain list item), in Org-mode
22138 ;; This means we can easily find the end by looking
22139 ;; only for the right number of stars. Using a regexp to do
22140 ;; this is so much faster than using a Lisp loop.
22141 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22142 (forward-char 1)
22143 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22144 ;; something else, do it the slow way
22145 (while (and (not (eobp))
22146 (or first (> (funcall outline-level) level)))
22147 (setq first nil)
22148 (outline-next-heading)))
22149 (unless to-heading
22150 (if (memq (preceding-char) '(?\n ?\^M))
22151 (progn
22152 ;; Go to end of line before heading
22153 (forward-char -1)
22154 (if (memq (preceding-char) '(?\n ?\^M))
22155 ;; leave blank line before heading
22156 (forward-char -1))))))
22157 (point))
22159 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22160 "Use Org version in org-mode, for dramatic speed-up."
22161 (if (derived-mode-p 'org-mode)
22162 (progn
22163 (org-end-of-subtree nil t)
22164 (unless (eobp) (backward-char 1)))
22165 ad-do-it))
22167 (defun org-end-of-meta-data-and-drawers ()
22168 "Jump to the first text after meta data and drawers in the current entry.
22169 This will move over empty lines, lines with planning time stamps,
22170 clocking lines, and drawers."
22171 (org-back-to-heading t)
22172 (let ((end (save-excursion (outline-next-heading) (point)))
22173 (re (concat "\\(" org-drawer-regexp "\\)"
22174 "\\|" "[ \t]*" org-keyword-time-regexp)))
22175 (forward-line 1)
22176 (while (re-search-forward re end t)
22177 (if (not (match-end 1))
22178 ;; empty or planning line
22179 (forward-line 1)
22180 ;; a drawer, find the end
22181 (re-search-forward "^[ \t]*:END:" end 'move)
22182 (forward-line 1)))
22183 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22184 (point)))
22186 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22187 "Move forward to the arg'th subheading at same level as this one.
22188 Stop at the first and last subheadings of a superior heading.
22189 Normally this only looks at visible headings, but when INVISIBLE-OK is
22190 non-nil it will also look at invisible ones."
22191 (interactive "p")
22192 (org-back-to-heading invisible-ok)
22193 (org-at-heading-p)
22194 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22195 (re (format "^\\*\\{1,%d\\} " level))
22197 (forward-char 1)
22198 (while (> arg 0)
22199 (while (and (re-search-forward re nil 'move)
22200 (setq l (- (match-end 0) (match-beginning 0) 1))
22201 (= l level)
22202 (not invisible-ok)
22203 (progn (backward-char 1) (outline-invisible-p)))
22204 (if (< l level) (setq arg 1)))
22205 (setq arg (1- arg)))
22206 (beginning-of-line 1)))
22208 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22209 "Move backward to the arg'th subheading at same level as this one.
22210 Stop at the first and last subheadings of a superior heading."
22211 (interactive "p")
22212 (org-back-to-heading)
22213 (org-at-heading-p)
22214 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22215 (re (format "^\\*\\{1,%d\\} " level))
22217 (while (> arg 0)
22218 (while (and (re-search-backward re nil 'move)
22219 (setq l (- (match-end 0) (match-beginning 0) 1))
22220 (= l level)
22221 (not invisible-ok)
22222 (outline-invisible-p))
22223 (if (< l level) (setq arg 1)))
22224 (setq arg (1- arg)))))
22226 ;;;###autoload
22227 (defun org-forward-element ()
22228 "Move forward by one element.
22229 Move to the next element at the same level, when possible."
22230 (interactive)
22231 (cond ((eobp) (error "Cannot move further down"))
22232 ((org-with-limited-levels (org-at-heading-p))
22233 (let ((origin (point)))
22234 (org-forward-heading-same-level 1)
22235 (unless (org-with-limited-levels (org-at-heading-p))
22236 (goto-char origin)
22237 (error "Cannot move further down"))))
22239 (let* ((elem (org-element-at-point))
22240 (end (org-element-property :end elem))
22241 (parent (org-element-property :parent elem)))
22242 (if (and parent (= (org-element-property :contents-end parent) end))
22243 (goto-char (org-element-property :end parent))
22244 (goto-char end))))))
22246 ;;;###autoload
22247 (defun org-backward-element ()
22248 "Move backward by one element.
22249 Move to the previous element at the same level, when possible."
22250 (interactive)
22251 (cond ((bobp) (error "Cannot move further up"))
22252 ((org-with-limited-levels (org-at-heading-p))
22253 ;; At an headline, move to the previous one, if any, or stay
22254 ;; here.
22255 (let ((origin (point)))
22256 (org-backward-heading-same-level 1)
22257 (unless (org-with-limited-levels (org-at-heading-p))
22258 (goto-char origin)
22259 (error "Cannot move further up"))))
22261 (let* ((trail (org-element-at-point 'keep-trail))
22262 (elem (car trail))
22263 (prev-elem (nth 1 trail))
22264 (beg (org-element-property :begin elem)))
22265 (cond
22266 ;; Move to beginning of current element if point isn't
22267 ;; there already.
22268 ((/= (point) beg) (goto-char beg))
22269 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22270 ((org-before-first-heading-p) (goto-char (point-min)))
22271 (t (org-back-to-heading)))))))
22273 ;;;###autoload
22274 (defun org-up-element ()
22275 "Move to upper element."
22276 (interactive)
22277 (if (org-with-limited-levels (org-at-heading-p))
22278 (unless (org-up-heading-safe) (error "No surrounding element"))
22279 (let* ((elem (org-element-at-point))
22280 (parent (org-element-property :parent elem)))
22281 (if parent (goto-char (org-element-property :begin parent))
22282 (if (org-with-limited-levels (org-before-first-heading-p))
22283 (error "No surrounding element")
22284 (org-with-limited-levels (org-back-to-heading)))))))
22286 ;;;###autoload
22287 (defvar org-element-greater-elements)
22288 (defun org-down-element ()
22289 "Move to inner element."
22290 (interactive)
22291 (let ((element (org-element-at-point)))
22292 (cond
22293 ((memq (org-element-type element) '(plain-list table))
22294 (goto-char (org-element-property :contents-begin element))
22295 (forward-char))
22296 ((memq (org-element-type element) org-element-greater-elements)
22297 ;; If contents are hidden, first disclose them.
22298 (when (org-element-property :hiddenp element) (org-cycle))
22299 (goto-char (or (org-element-property :contents-begin element)
22300 (error "No content for this element"))))
22301 (t (error "No inner element")))))
22303 ;;;###autoload
22304 (defun org-drag-element-backward ()
22305 "Move backward element at point."
22306 (interactive)
22307 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22308 (let* ((trail (org-element-at-point 'keep-trail))
22309 (elem (car trail))
22310 (prev-elem (nth 1 trail)))
22311 ;; Error out if no previous element or previous element is
22312 ;; a parent of the current one.
22313 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22314 (error "Cannot drag element backward")
22315 (let ((pos (point)))
22316 (org-element-swap-A-B prev-elem elem)
22317 (goto-char (+ (org-element-property :begin prev-elem)
22318 (- pos (org-element-property :begin elem)))))))))
22320 ;;;###autoload
22321 (defun org-drag-element-forward ()
22322 "Move forward element at point."
22323 (interactive)
22324 (let* ((pos (point))
22325 (elem (org-element-at-point)))
22326 (when (= (point-max) (org-element-property :end elem))
22327 (error "Cannot drag element forward"))
22328 (goto-char (org-element-property :end elem))
22329 (let ((next-elem (org-element-at-point)))
22330 (when (or (org-element-nested-p elem next-elem)
22331 (and (eq (org-element-type next-elem) 'headline)
22332 (not (eq (org-element-type elem) 'headline))))
22333 (goto-char pos)
22334 (error "Cannot drag element forward"))
22335 ;; Compute new position of point: it's shifted by NEXT-ELEM
22336 ;; body's length (without final blanks) and by the length of
22337 ;; blanks between ELEM and NEXT-ELEM.
22338 (let ((size-next (- (save-excursion
22339 (goto-char (org-element-property :end next-elem))
22340 (skip-chars-backward " \r\t\n")
22341 (forward-line)
22342 ;; Small correction if buffer doesn't end
22343 ;; with a newline character.
22344 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22345 (org-element-property :begin next-elem)))
22346 (size-blank (- (org-element-property :end elem)
22347 (save-excursion
22348 (goto-char (org-element-property :end elem))
22349 (skip-chars-backward " \r\t\n")
22350 (forward-line)
22351 (point)))))
22352 (org-element-swap-A-B elem next-elem)
22353 (goto-char (+ pos size-next size-blank))))))
22355 ;;;###autoload
22356 (defun org-mark-element ()
22357 "Put point at beginning of this element, mark at end.
22359 Interactively, if this command is repeated or (in Transient Mark
22360 mode) if the mark is active, it marks the next element after the
22361 ones already marked."
22362 (interactive)
22363 (let (deactivate-mark)
22364 (if (and (org-called-interactively-p 'any)
22365 (or (and (eq last-command this-command) (mark t))
22366 (and transient-mark-mode mark-active)))
22367 (set-mark
22368 (save-excursion
22369 (goto-char (mark))
22370 (goto-char (org-element-property :end (org-element-at-point)))))
22371 (let ((element (org-element-at-point)))
22372 (end-of-line)
22373 (push-mark (org-element-property :end element) t t)
22374 (goto-char (org-element-property :begin element))))))
22376 ;;;###autoload
22377 (defun org-narrow-to-element ()
22378 "Narrow buffer to current element."
22379 (interactive)
22380 (let ((elem (org-element-at-point)))
22381 (cond
22382 ((eq (car elem) 'headline)
22383 (narrow-to-region
22384 (org-element-property :begin elem)
22385 (org-element-property :end elem)))
22386 ((memq (car elem) org-element-greater-elements)
22387 (narrow-to-region
22388 (org-element-property :contents-begin elem)
22389 (org-element-property :contents-end elem)))
22391 (narrow-to-region
22392 (org-element-property :begin elem)
22393 (org-element-property :end elem))))))
22395 ;;;###autoload
22396 (defun org-transpose-element ()
22397 "Transpose current and previous elements, keeping blank lines between.
22398 Point is moved after both elements."
22399 (interactive)
22400 (org-skip-whitespace)
22401 (let ((end (org-element-property :end (org-element-at-point))))
22402 (org-drag-element-backward)
22403 (goto-char end)))
22405 ;;;###autoload
22406 (defun org-unindent-buffer ()
22407 "Un-indent the visible part of the buffer.
22408 Relative indentation (between items, inside blocks, etc.) isn't
22409 modified."
22410 (interactive)
22411 (unless (eq major-mode 'org-mode)
22412 (error "Cannot un-indent a buffer not in Org mode"))
22413 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22414 unindent-tree ; For byte-compiler.
22415 (unindent-tree
22416 (function
22417 (lambda (contents)
22418 (mapc
22419 (lambda (element)
22420 (if (memq (org-element-type element) '(headline section))
22421 (funcall unindent-tree (org-element-contents element))
22422 (save-excursion
22423 (save-restriction
22424 (narrow-to-region
22425 (org-element-property :begin element)
22426 (org-element-property :end element))
22427 (org-do-remove-indentation)))))
22428 (reverse contents))))))
22429 (funcall unindent-tree (org-element-contents parse-tree))))
22431 (defun org-show-subtree ()
22432 "Show everything after this heading at deeper levels."
22433 (interactive)
22434 (outline-flag-region
22435 (point)
22436 (save-excursion
22437 (org-end-of-subtree t t))
22438 nil))
22440 (defun org-show-entry ()
22441 "Show the body directly following this heading.
22442 Show the heading too, if it is currently invisible."
22443 (interactive)
22444 (save-excursion
22445 (condition-case nil
22446 (progn
22447 (org-back-to-heading t)
22448 (outline-flag-region
22449 (max (point-min) (1- (point)))
22450 (save-excursion
22451 (if (re-search-forward
22452 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22453 (match-beginning 1)
22454 (point-max)))
22455 nil)
22456 (org-cycle-hide-drawers 'children))
22457 (error nil))))
22459 (defun org-make-options-regexp (kwds &optional extra)
22460 "Make a regular expression for keyword lines."
22461 (concat
22462 "^#\\+\\("
22463 (mapconcat 'regexp-quote kwds "\\|")
22464 (if extra (concat "\\|" extra))
22465 "\\):[ \t]*\\(.*\\)"))
22467 ;; Make isearch reveal the necessary context
22468 (defun org-isearch-end ()
22469 "Reveal context after isearch exits."
22470 (when isearch-success ; only if search was successful
22471 (if (featurep 'xemacs)
22472 ;; Under XEmacs, the hook is run in the correct place,
22473 ;; we directly show the context.
22474 (org-show-context 'isearch)
22475 ;; In Emacs the hook runs *before* restoring the overlays.
22476 ;; So we have to use a one-time post-command-hook to do this.
22477 ;; (Emacs 22 has a special variable, see function `org-mode')
22478 (unless (and (boundp 'isearch-mode-end-hook-quit)
22479 isearch-mode-end-hook-quit)
22480 ;; Only when the isearch was not quitted.
22481 (org-add-hook 'post-command-hook 'org-isearch-post-command
22482 'append 'local)))))
22484 (defun org-isearch-post-command ()
22485 "Remove self from hook, and show context."
22486 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22487 (org-show-context 'isearch))
22490 ;;;; Integration with and fixes for other packages
22492 ;;; Imenu support
22494 (defvar org-imenu-markers nil
22495 "All markers currently used by Imenu.")
22496 (make-variable-buffer-local 'org-imenu-markers)
22498 (defun org-imenu-new-marker (&optional pos)
22499 "Return a new marker for use by Imenu, and remember the marker."
22500 (let ((m (make-marker)))
22501 (move-marker m (or pos (point)))
22502 (push m org-imenu-markers)
22505 (defun org-imenu-get-tree ()
22506 "Produce the index for Imenu."
22507 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22508 (setq org-imenu-markers nil)
22509 (let* ((n org-imenu-depth)
22510 (re (concat "^" (org-get-limited-outline-regexp)))
22511 (subs (make-vector (1+ n) nil))
22512 (last-level 0)
22513 m level head)
22514 (save-excursion
22515 (save-restriction
22516 (widen)
22517 (goto-char (point-max))
22518 (while (re-search-backward re nil t)
22519 (setq level (org-reduced-level (funcall outline-level)))
22520 (when (and (<= level n)
22521 (looking-at org-complex-heading-regexp))
22522 (setq head (org-link-display-format
22523 (org-match-string-no-properties 4))
22524 m (org-imenu-new-marker))
22525 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22526 (if (>= level last-level)
22527 (push (cons head m) (aref subs level))
22528 (push (cons head (aref subs (1+ level))) (aref subs level))
22529 (loop for i from (1+ level) to n do (aset subs i nil)))
22530 (setq last-level level)))))
22531 (aref subs 1)))
22533 (eval-after-load "imenu"
22534 '(progn
22535 (add-hook 'imenu-after-jump-hook
22536 (lambda ()
22537 (if (derived-mode-p 'org-mode)
22538 (org-show-context 'org-goto))))))
22540 (defun org-link-display-format (link)
22541 "Replace a link with either the description, or the link target
22542 if no description is present"
22543 (save-match-data
22544 (if (string-match org-bracket-link-analytic-regexp link)
22545 (replace-match (if (match-end 5)
22546 (match-string 5 link)
22547 (concat (match-string 1 link)
22548 (match-string 3 link)))
22549 nil t link)
22550 link)))
22552 (defun org-toggle-link-display ()
22553 "Toggle the literal or descriptive display of links."
22554 (interactive)
22555 (if org-descriptive-links
22556 (progn (org-remove-from-invisibility-spec '(org-link))
22557 (org-restart-font-lock)
22558 (setq org-descriptive-links nil))
22559 (progn (add-to-invisibility-spec '(org-link))
22560 (org-restart-font-lock)
22561 (setq org-descriptive-links t))))
22563 ;; Speedbar support
22565 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22566 "Overlay marking the agenda restriction line in speedbar.")
22567 (overlay-put org-speedbar-restriction-lock-overlay
22568 'face 'org-agenda-restriction-lock)
22569 (overlay-put org-speedbar-restriction-lock-overlay
22570 'help-echo "Agendas are currently limited to this item.")
22571 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22573 (defun org-speedbar-set-agenda-restriction ()
22574 "Restrict future agenda commands to the location at point in speedbar.
22575 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22576 (interactive)
22577 (require 'org-agenda)
22578 (let (p m tp np dir txt)
22579 (cond
22580 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22581 'org-imenu t))
22582 (setq m (get-text-property p 'org-imenu-marker))
22583 (with-current-buffer (marker-buffer m)
22584 (goto-char m)
22585 (org-agenda-set-restriction-lock 'subtree)))
22586 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22587 'speedbar-function 'speedbar-find-file))
22588 (setq tp (previous-single-property-change
22589 (1+ p) 'speedbar-function)
22590 np (next-single-property-change
22591 tp 'speedbar-function)
22592 dir (speedbar-line-directory)
22593 txt (buffer-substring-no-properties (or tp (point-min))
22594 (or np (point-max))))
22595 (with-current-buffer (find-file-noselect
22596 (let ((default-directory dir))
22597 (expand-file-name txt)))
22598 (unless (derived-mode-p 'org-mode)
22599 (error "Cannot restrict to non-Org-mode file"))
22600 (org-agenda-set-restriction-lock 'file)))
22601 (t (error "Don't know how to restrict Org-mode's agenda")))
22602 (move-overlay org-speedbar-restriction-lock-overlay
22603 (point-at-bol) (point-at-eol))
22604 (setq current-prefix-arg nil)
22605 (org-agenda-maybe-redo)))
22607 (eval-after-load "speedbar"
22608 '(progn
22609 (speedbar-add-supported-extension ".org")
22610 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22611 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22612 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22613 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22614 (add-hook 'speedbar-visiting-tag-hook
22615 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22617 ;;; Fixes and Hacks for problems with other packages
22619 ;; Make flyspell not check words in links, to not mess up our keymap
22620 (defun org-mode-flyspell-verify ()
22621 "Don't let flyspell put overlays at active buttons, or on
22622 {todo,all-time,additional-option-like}-keywords."
22623 (let ((pos (max (1- (point)) (point-min)))
22624 (word (thing-at-point 'word)))
22625 (and (not (get-text-property pos 'keymap))
22626 (not (get-text-property pos 'org-no-flyspell))
22627 (not (member word org-todo-keywords-1))
22628 (not (member word org-all-time-keywords))
22629 (not (member word org-options-keywords))
22630 (not (member word (mapcar 'car org-startup-options)))
22631 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22633 (defun org-remove-flyspell-overlays-in (beg end)
22634 "Remove flyspell overlays in region."
22635 (and (org-bound-and-true-p flyspell-mode)
22636 (fboundp 'flyspell-delete-region-overlays)
22637 (flyspell-delete-region-overlays beg end))
22638 (add-text-properties beg end '(org-no-flyspell t)))
22640 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22641 (eval-after-load "bookmark"
22642 '(if (boundp 'bookmark-after-jump-hook)
22643 ;; We can use the hook
22644 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22645 ;; Hook not available, use advice
22646 (defadvice bookmark-jump (after org-make-visible activate)
22647 "Make the position visible."
22648 (org-bookmark-jump-unhide))))
22650 ;; Make sure saveplace shows the location if it was hidden
22651 (eval-after-load "saveplace"
22652 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22653 "Make the position visible."
22654 (org-bookmark-jump-unhide)))
22656 ;; Make sure ecb shows the location if it was hidden
22657 (eval-after-load "ecb"
22658 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22659 "Make hierarchy visible when jumping into location from ECB tree buffer."
22660 (if (derived-mode-p 'org-mode)
22661 (org-show-context))))
22663 (defun org-bookmark-jump-unhide ()
22664 "Unhide the current position, to show the bookmark location."
22665 (and (derived-mode-p 'org-mode)
22666 (or (outline-invisible-p)
22667 (save-excursion (goto-char (max (point-min) (1- (point))))
22668 (outline-invisible-p)))
22669 (org-show-context 'bookmark-jump)))
22671 ;; Make session.el ignore our circular variable
22672 (eval-after-load "session"
22673 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22675 ;;;; Experimental code
22677 (defun org-closed-in-range ()
22678 "Sparse tree of items closed in a certain time range.
22679 Still experimental, may disappear in the future."
22680 (interactive)
22681 ;; Get the time interval from the user.
22682 (let* ((time1 (org-float-time
22683 (org-read-date nil 'to-time nil "Starting date: ")))
22684 (time2 (org-float-time
22685 (org-read-date nil 'to-time nil "End date:")))
22686 ;; callback function
22687 (callback (lambda ()
22688 (let ((time
22689 (org-float-time
22690 (apply 'encode-time
22691 (org-parse-time-string
22692 (match-string 1))))))
22693 ;; check if time in interval
22694 (and (>= time time1) (<= time time2))))))
22695 ;; make tree, check each match with the callback
22696 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22698 ;;;; Finish up
22700 (provide 'org)
22702 (run-hooks 'org-load-hook)
22704 ;;; org.el ends here