Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob6f304378af545f85e60aa4ba092f275e334f8053
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-insert-diary-entry-key [?i]
3278 "The key to be installed in `calendar-mode-map' for adding diary entries.
3279 This option is irrelevant until `org-agenda-diary-file' has been configured
3280 to point to an Org-mode file. When that is the case, the command
3281 `org-agenda-diary-entry' will be bound to the key given here, by default
3282 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3283 if you want to continue doing this, you need to change this to a different
3284 key."
3285 :group 'org-agenda
3286 :type 'sexp)
3288 (defcustom org-agenda-diary-file 'diary-file
3289 "File to which to add new entries with the `i' key in agenda and calendar.
3290 When this is the symbol `diary-file', the functionality in the Emacs
3291 calendar will be used to add entries to the `diary-file'. But when this
3292 points to a file, `org-agenda-diary-entry' will be used instead."
3293 :group 'org-agenda
3294 :type '(choice
3295 (const :tag "The standard Emacs diary file" diary-file)
3296 (file :tag "Special Org file diary entries")))
3298 (eval-after-load "calendar"
3299 '(progn
3300 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3301 'org-calendar-goto-agenda)
3302 (add-hook 'calendar-mode-hook
3303 (lambda ()
3304 (unless (eq org-agenda-diary-file 'diary-file)
3305 (define-key calendar-mode-map
3306 org-calendar-insert-diary-entry-key
3307 'org-agenda-diary-entry))))))
3309 (defgroup org-latex nil
3310 "Options for embedding LaTeX code into Org-mode."
3311 :tag "Org LaTeX"
3312 :group 'org)
3314 (defcustom org-format-latex-options
3315 '(:foreground default :background default :scale 1.0
3316 :html-foreground "Black" :html-background "Transparent"
3317 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3318 "Options for creating images from LaTeX fragments.
3319 This is a property list with the following properties:
3320 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3321 `default' means use the foreground of the default face.
3322 `auto' means use the foreground from the text face.
3323 :background the background color, or \"Transparent\".
3324 `default' means use the background of the default face.
3325 `auto' means use the background from the text face.
3326 :scale a scaling factor for the size of the images, to get more pixels
3327 :html-foreground, :html-background, :html-scale
3328 the same numbers for HTML export.
3329 :matchers a list indicating which matchers should be used to
3330 find LaTeX fragments. Valid members of this list are:
3331 \"begin\" find environments
3332 \"$1\" find single characters surrounded by $.$
3333 \"$\" find math expressions surrounded by $...$
3334 \"$$\" find math expressions surrounded by $$....$$
3335 \"\\(\" find math expressions surrounded by \\(...\\)
3336 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3337 :group 'org-latex
3338 :type 'plist)
3340 (defcustom org-format-latex-signal-error t
3341 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3342 When nil, just push out a message."
3343 :group 'org-latex
3344 :version "24.1"
3345 :type 'boolean)
3347 (defcustom org-latex-to-mathml-jar-file nil
3348 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3349 Use this to specify additional executable file say a jar file.
3351 When using MathToWeb as the converter, specify the full-path to
3352 your mathtoweb.jar file."
3353 :group 'org-latex
3354 :version "24.1"
3355 :type '(choice
3356 (const :tag "None" nil)
3357 (file :tag "JAR file" :must-match t)))
3359 (defcustom org-latex-to-mathml-convert-command nil
3360 "Command to convert LaTeX fragments to MathML.
3361 Replace format-specifiers in the command as noted below and use
3362 `shell-command' to convert LaTeX to MathML.
3363 %j: Executable file in fully expanded form as specified by
3364 `org-latex-to-mathml-jar-file'.
3365 %I: Input LaTeX file in fully expanded form
3366 %o: Output MathML file
3367 This command is used by `org-create-math-formula'.
3369 When using MathToWeb as the converter, set this to
3370 \"java -jar %j -unicode -force -df %o %I\"."
3371 :group 'org-latex
3372 :version "24.1"
3373 :type '(choice
3374 (const :tag "None" nil)
3375 (string :tag "\nShell command")))
3377 (defcustom org-latex-create-formula-image-program 'dvipng
3378 "Program to convert LaTeX fragments with.
3380 dvipng Process the LaTeX fragments to dvi file, then convert
3381 dvi files to png files using dvipng.
3382 This will also include processing of non-math environments.
3383 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3384 to convert pdf files to png files"
3385 :group 'org-latex
3386 :version "24.1"
3387 :type '(choice
3388 (const :tag "dvipng" dvipng)
3389 (const :tag "imagemagick" imagemagick)))
3391 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3392 "Path to store latex preview images. A relative path here creates many
3393 directories relative to the processed org files paths. An absolute path
3394 puts all preview images at the same place."
3395 :group 'org-latex
3396 :version "24.3"
3397 :type 'string)
3399 (defun org-format-latex-mathml-available-p ()
3400 "Return t if `org-latex-to-mathml-convert-command' is usable."
3401 (save-match-data
3402 (when (and (boundp 'org-latex-to-mathml-convert-command)
3403 org-latex-to-mathml-convert-command)
3404 (let ((executable (car (split-string
3405 org-latex-to-mathml-convert-command))))
3406 (when (executable-find executable)
3407 (if (string-match
3408 "%j" org-latex-to-mathml-convert-command)
3409 (file-readable-p org-latex-to-mathml-jar-file)
3410 t))))))
3412 (defcustom org-format-latex-header "\\documentclass{article}
3413 \\usepackage[usenames]{color}
3414 \\usepackage{amsmath}
3415 \\usepackage[mathscr]{eucal}
3416 \\pagestyle{empty} % do not remove
3417 \[PACKAGES]
3418 \[DEFAULT-PACKAGES]
3419 % The settings below are copied from fullpage.sty
3420 \\setlength{\\textwidth}{\\paperwidth}
3421 \\addtolength{\\textwidth}{-3cm}
3422 \\setlength{\\oddsidemargin}{1.5cm}
3423 \\addtolength{\\oddsidemargin}{-2.54cm}
3424 \\setlength{\\evensidemargin}{\\oddsidemargin}
3425 \\setlength{\\textheight}{\\paperheight}
3426 \\addtolength{\\textheight}{-\\headheight}
3427 \\addtolength{\\textheight}{-\\headsep}
3428 \\addtolength{\\textheight}{-\\footskip}
3429 \\addtolength{\\textheight}{-3cm}
3430 \\setlength{\\topmargin}{1.5cm}
3431 \\addtolength{\\topmargin}{-2.54cm}"
3432 "The document header used for processing LaTeX fragments.
3433 It is imperative that this header make sure that no page number
3434 appears on the page. The package defined in the variables
3435 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3436 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3437 will be appended."
3438 :group 'org-latex
3439 :type 'string)
3441 (defvar org-format-latex-header-extra nil)
3443 (defun org-set-packages-alist (var val)
3444 "Set the packages alist and make sure it has 3 elements per entry."
3445 (set var (mapcar (lambda (x)
3446 (if (and (consp x) (= (length x) 2))
3447 (list (car x) (nth 1 x) t)
3449 val)))
3451 (defun org-get-packages-alist (var)
3453 "Get the packages alist and make sure it has 3 elements per entry."
3454 (mapcar (lambda (x)
3455 (if (and (consp x) (= (length x) 2))
3456 (list (car x) (nth 1 x) t)
3458 (default-value var)))
3460 ;; The following variables are defined here because is it also used
3461 ;; when formatting latex fragments. Originally it was part of the
3462 ;; LaTeX exporter, which is why the name includes "export".
3463 (defcustom org-export-latex-default-packages-alist
3464 '(("AUTO" "inputenc" t)
3465 ("T1" "fontenc" t)
3466 ("" "fixltx2e" nil)
3467 ("" "graphicx" t)
3468 ("" "longtable" nil)
3469 ("" "float" nil)
3470 ("" "wrapfig" nil)
3471 ("" "soul" t)
3472 ("" "textcomp" t)
3473 ("" "marvosym" t)
3474 ("" "wasysym" t)
3475 ("" "latexsym" t)
3476 ("" "amssymb" t)
3477 ("" "hyperref" nil)
3478 "\\tolerance=1000"
3480 "Alist of default packages to be inserted in the header.
3481 Change this only if one of the packages here causes an incompatibility
3482 with another package you are using.
3483 The packages in this list are needed by one part or another of Org-mode
3484 to function properly.
3486 - inputenc, fontenc: for basic font and character selection
3487 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3488 for interpreting the entities in `org-entities'. You can skip some of these
3489 packages if you don't use any of the symbols in it.
3490 - graphicx: for including images
3491 - float, wrapfig: for figure placement
3492 - longtable: for long tables
3493 - hyperref: for cross references
3495 Therefore you should not modify this variable unless you know what you
3496 are doing. The one reason to change it anyway is that you might be loading
3497 some other package that conflicts with one of the default packages.
3498 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3499 If SNIPPET-FLAG is t, the package also needs to be included when
3500 compiling LaTeX snippets into images for inclusion into HTML."
3501 :group 'org-export-latex
3502 :set 'org-set-packages-alist
3503 :get 'org-get-packages-alist
3504 :version "24.1"
3505 :type '(repeat
3506 (choice
3507 (list :tag "options/package pair"
3508 (string :tag "options")
3509 (string :tag "package")
3510 (boolean :tag "Snippet"))
3511 (string :tag "A line of LaTeX"))))
3513 (defcustom org-export-latex-packages-alist nil
3514 "Alist of packages to be inserted in every LaTeX header.
3515 These will be inserted after `org-export-latex-default-packages-alist'.
3516 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3517 SNIPPET-FLAG, when t, indicates that this package is also needed when
3518 turning LaTeX snippets into images for inclusion into HTML.
3519 Make sure that you only list packages here which:
3520 - you want in every file
3521 - do not conflict with the default packages in
3522 `org-export-latex-default-packages-alist'
3523 - do not conflict with the setup in `org-format-latex-header'."
3524 :group 'org-export-latex
3525 :set 'org-set-packages-alist
3526 :get 'org-get-packages-alist
3527 :type '(repeat
3528 (choice
3529 (list :tag "options/package pair"
3530 (string :tag "options")
3531 (string :tag "package")
3532 (boolean :tag "Snippet"))
3533 (string :tag "A line of LaTeX"))))
3536 (defgroup org-appearance nil
3537 "Settings for Org-mode appearance."
3538 :tag "Org Appearance"
3539 :group 'org)
3541 (defcustom org-level-color-stars-only nil
3542 "Non-nil means fontify only the stars in each headline.
3543 When nil, the entire headline is fontified.
3544 Changing it requires restart of `font-lock-mode' to become effective
3545 also in regions already fontified."
3546 :group 'org-appearance
3547 :type 'boolean)
3549 (defcustom org-hide-leading-stars nil
3550 "Non-nil means hide the first N-1 stars in a headline.
3551 This works by using the face `org-hide' for these stars. This
3552 face is white for a light background, and black for a dark
3553 background. You may have to customize the face `org-hide' to
3554 make this work.
3555 Changing it requires restart of `font-lock-mode' to become effective
3556 also in regions already fontified.
3557 You may also set this on a per-file basis by adding one of the following
3558 lines to the buffer:
3560 #+STARTUP: hidestars
3561 #+STARTUP: showstars"
3562 :group 'org-appearance
3563 :type 'boolean)
3565 (defcustom org-hidden-keywords nil
3566 "List of symbols corresponding to keywords to be hidden the org buffer.
3567 For example, a value '(title) for this list will make the document's title
3568 appear in the buffer without the initial #+TITLE: keyword."
3569 :group 'org-appearance
3570 :version "24.1"
3571 :type '(set (const :tag "#+AUTHOR" author)
3572 (const :tag "#+DATE" date)
3573 (const :tag "#+EMAIL" email)
3574 (const :tag "#+TITLE" title)))
3576 (defcustom org-custom-properties nil
3577 "List of properties (as strings) with a special meaning.
3578 The default use of these custom properties is to let the user
3579 hide them with `org-toggle-custom-properties-visibility'."
3580 :group 'org-properties
3581 :group 'org-appearance
3582 :version "24.3"
3583 :type '(repeat (string :tag "Property Name")))
3585 (defcustom org-fontify-done-headline nil
3586 "Non-nil means change the face of a headline if it is marked DONE.
3587 Normally, only the TODO/DONE keyword indicates the state of a headline.
3588 When this is non-nil, the headline after the keyword is set to the
3589 `org-headline-done' as an additional indication."
3590 :group 'org-appearance
3591 :type 'boolean)
3593 (defcustom org-fontify-emphasized-text t
3594 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3595 Changing this variable requires a restart of Emacs to take effect."
3596 :group 'org-appearance
3597 :type 'boolean)
3599 (defcustom org-fontify-whole-heading-line nil
3600 "Non-nil means fontify the whole line for headings.
3601 This is useful when setting a background color for the
3602 org-level-* faces."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-highlight-latex-fragments-and-specials nil
3607 "Non-nil means fontify what is treated specially by the exporters."
3608 :group 'org-appearance
3609 :type 'boolean)
3611 (defcustom org-hide-emphasis-markers nil
3612 "Non-nil mean font-lock should hide the emphasis marker characters."
3613 :group 'org-appearance
3614 :type 'boolean)
3616 (defcustom org-pretty-entities nil
3617 "Non-nil means show entities as UTF8 characters.
3618 When nil, the \\name form remains in the buffer."
3619 :group 'org-appearance
3620 :version "24.1"
3621 :type 'boolean)
3623 (defcustom org-pretty-entities-include-sub-superscripts t
3624 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3625 :group 'org-appearance
3626 :version "24.1"
3627 :type 'boolean)
3629 (defvar org-emph-re nil
3630 "Regular expression for matching emphasis.
3631 After a match, the match groups contain these elements:
3632 0 The match of the full regular expression, including the characters
3633 before and after the proper match
3634 1 The character before the proper match, or empty at beginning of line
3635 2 The proper match, including the leading and trailing markers
3636 3 The leading marker like * or /, indicating the type of highlighting
3637 4 The text between the emphasis markers, not including the markers
3638 5 The character after the match, empty at the end of a line")
3639 (defvar org-verbatim-re nil
3640 "Regular expression for matching verbatim text.")
3641 (defvar org-emphasis-regexp-components) ; defined just below
3642 (defvar org-emphasis-alist) ; defined just below
3643 (defun org-set-emph-re (var val)
3644 "Set variable and compute the emphasis regular expression."
3645 (set var val)
3646 (when (and (boundp 'org-emphasis-alist)
3647 (boundp 'org-emphasis-regexp-components)
3648 org-emphasis-alist org-emphasis-regexp-components)
3649 (let* ((e org-emphasis-regexp-components)
3650 (pre (car e))
3651 (post (nth 1 e))
3652 (border (nth 2 e))
3653 (body (nth 3 e))
3654 (nl (nth 4 e))
3655 (body1 (concat body "*?"))
3656 (markers (mapconcat 'car org-emphasis-alist ""))
3657 (vmarkers (mapconcat
3658 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3659 org-emphasis-alist "")))
3660 ;; make sure special characters appear at the right position in the class
3661 (if (string-match "\\^" markers)
3662 (setq markers (concat (replace-match "" t t markers) "^")))
3663 (if (string-match "-" markers)
3664 (setq markers (concat (replace-match "" t t markers) "-")))
3665 (if (string-match "\\^" vmarkers)
3666 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3667 (if (string-match "-" vmarkers)
3668 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3669 (if (> nl 0)
3670 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3671 (int-to-string nl) "\\}")))
3672 ;; Make the regexp
3673 (setq org-emph-re
3674 (concat "\\([" pre "]\\|^\\)"
3675 "\\("
3676 "\\([" markers "]\\)"
3677 "\\("
3678 "[^" border "]\\|"
3679 "[^" border "]"
3680 body1
3681 "[^" border "]"
3682 "\\)"
3683 "\\3\\)"
3684 "\\([" post "]\\|$\\)"))
3685 (setq org-verbatim-re
3686 (concat "\\([" pre "]\\|^\\)"
3687 "\\("
3688 "\\([" vmarkers "]\\)"
3689 "\\("
3690 "[^" border "]\\|"
3691 "[^" border "]"
3692 body1
3693 "[^" border "]"
3694 "\\)"
3695 "\\3\\)"
3696 "\\([" post "]\\|$\\)")))))
3698 (defcustom org-emphasis-regexp-components
3699 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3700 "Components used to build the regular expression for emphasis.
3701 This is a list with five entries. Terminology: In an emphasis string
3702 like \" *strong word* \", we call the initial space PREMATCH, the final
3703 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3704 and \"trong wor\" is the body. The different components in this variable
3705 specify what is allowed/forbidden in each part:
3707 pre Chars allowed as prematch. Beginning of line will be allowed too.
3708 post Chars allowed as postmatch. End of line will be allowed too.
3709 border The chars *forbidden* as border characters.
3710 body-regexp A regexp like \".\" to match a body character. Don't use
3711 non-shy groups here, and don't allow newline here.
3712 newline The maximum number of newlines allowed in an emphasis exp.
3714 Use customize to modify this, or restart Emacs after changing it."
3715 :group 'org-appearance
3716 :set 'org-set-emph-re
3717 :type '(list
3718 (sexp :tag "Allowed chars in pre ")
3719 (sexp :tag "Allowed chars in post ")
3720 (sexp :tag "Forbidden chars in border ")
3721 (sexp :tag "Regexp for body ")
3722 (integer :tag "number of newlines allowed")
3723 (option (boolean :tag "Please ignore this button"))))
3725 (defcustom org-emphasis-alist
3726 `(("*" bold "<b>" "</b>")
3727 ("/" italic "<i>" "</i>")
3728 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3729 ("=" org-code "<code>" "</code>" verbatim)
3730 ("~" org-verbatim "<code>" "</code>" verbatim)
3731 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3732 "<del>" "</del>")
3734 "Special syntax for emphasized text.
3735 Text starting and ending with a special character will be emphasized, for
3736 example *bold*, _underlined_ and /italic/. This variable sets the marker
3737 characters, the face to be used by font-lock for highlighting in Org-mode
3738 Emacs buffers, and the HTML tags to be used for this.
3739 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3740 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3741 Use customize to modify this, or restart Emacs after changing it."
3742 :group 'org-appearance
3743 :set 'org-set-emph-re
3744 :type '(repeat
3745 (list
3746 (string :tag "Marker character")
3747 (choice
3748 (face :tag "Font-lock-face")
3749 (plist :tag "Face property list"))
3750 (string :tag "HTML start tag")
3751 (string :tag "HTML end tag")
3752 (option (const verbatim)))))
3754 (defvar org-protecting-blocks
3755 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3756 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3757 This is needed for font-lock setup.")
3759 ;;; Miscellaneous options
3761 (defgroup org-completion nil
3762 "Completion in Org-mode."
3763 :tag "Org Completion"
3764 :group 'org)
3766 (defcustom org-completion-use-ido nil
3767 "Non-nil means use ido completion wherever possible.
3768 Note that `ido-mode' must be active for this variable to be relevant.
3769 If you decide to turn this variable on, you might well want to turn off
3770 `org-outline-path-complete-in-steps'.
3771 See also `org-completion-use-iswitchb'."
3772 :group 'org-completion
3773 :type 'boolean)
3775 (defcustom org-completion-use-iswitchb nil
3776 "Non-nil means use iswitchb completion wherever possible.
3777 Note that `iswitchb-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 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3781 :group 'org-completion
3782 :type 'boolean)
3784 (defcustom org-completion-fallback-command 'hippie-expand
3785 "The expansion command called by \\[pcomplete] in normal context.
3786 Normal means, no org-mode-specific context."
3787 :group 'org-completion
3788 :type 'function)
3790 ;;; Functions and variables from their packages
3791 ;; Declared here to avoid compiler warnings
3793 ;; XEmacs only
3794 (defvar outline-mode-menu-heading)
3795 (defvar outline-mode-menu-show)
3796 (defvar outline-mode-menu-hide)
3797 (defvar zmacs-regions) ; XEmacs regions
3799 ;; Emacs only
3800 (defvar mark-active)
3802 ;; Various packages
3803 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3804 (declare-function calendar-forward-day "cal-move" (arg))
3805 (declare-function calendar-goto-date "cal-move" (date))
3806 (declare-function calendar-goto-today "cal-move" ())
3807 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3808 (defvar calc-embedded-close-formula)
3809 (defvar calc-embedded-open-formula)
3810 (declare-function cdlatex-tab "ext:cdlatex" ())
3811 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3812 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3813 (defvar font-lock-unfontify-region-function)
3814 (declare-function iswitchb-read-buffer "iswitchb"
3815 (prompt &optional default require-match start matches-set))
3816 (defvar iswitchb-temp-buflist)
3817 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3818 (defvar org-agenda-tags-todo-honor-ignore-options)
3819 (declare-function org-agenda-skip "org-agenda" ())
3820 (declare-function
3821 org-agenda-format-item "org-agenda"
3822 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3823 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3824 (declare-function org-agenda-change-all-lines "org-agenda"
3825 (newhead hdmarker &optional fixface just-this))
3826 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3827 (declare-function org-agenda-maybe-redo "org-agenda" ())
3828 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3829 (beg end))
3830 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3831 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3832 "org-agenda" (&optional end))
3833 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3834 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3835 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3836 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3837 (declare-function org-indent-mode "org-indent" (&optional arg))
3838 (declare-function parse-time-string "parse-time" (string))
3839 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3840 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3841 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3842 (defvar remember-data-file)
3843 (defvar texmathp-why)
3844 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3845 (declare-function table--at-cell-p "table" (position &optional object at-column))
3847 (defvar w3m-current-url)
3848 (defvar w3m-current-title)
3850 (defvar org-latex-regexps)
3852 ;;; Autoload and prepare some org modules
3854 ;; Some table stuff that needs to be defined here, because it is used
3855 ;; by the functions setting up org-mode or checking for table context.
3857 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3858 "Detect an org-type or table-type table.")
3859 (defconst org-table-line-regexp "^[ \t]*|"
3860 "Detect an org-type table line.")
3861 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3862 "Detect an org-type table line.")
3863 (defconst org-table-hline-regexp "^[ \t]*|-"
3864 "Detect an org-type table hline.")
3865 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3866 "Detect a table-type table hline.")
3867 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3868 "Detect the first line outside a table when searching from within it.
3869 This works for both table types.")
3871 ;; Autoload the functions in org-table.el that are needed by functions here.
3873 (eval-and-compile
3874 (org-autoload "org-table"
3875 '(org-table-align org-table-begin org-table-blank-field
3876 org-table-convert org-table-convert-region org-table-copy-down
3877 org-table-copy-region org-table-create
3878 org-table-create-or-convert-from-region
3879 org-table-create-with-table.el org-table-current-dline
3880 org-table-cut-region org-table-delete-column org-table-edit-field
3881 org-table-edit-formulas org-table-end org-table-eval-formula
3882 org-table-export org-table-field-info
3883 org-table-get-stored-formulas org-table-goto-column
3884 org-table-hline-and-move org-table-import org-table-insert-column
3885 org-table-insert-hline org-table-insert-row org-table-iterate
3886 org-table-justify-field-maybe org-table-kill-row
3887 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3888 org-table-move-column org-table-move-column-left
3889 org-table-move-column-right org-table-move-row
3890 org-table-move-row-down org-table-move-row-up
3891 org-table-next-field org-table-next-row org-table-paste-rectangle
3892 org-table-previous-field org-table-recalculate
3893 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3894 org-table-toggle-coordinate-overlays
3895 org-table-toggle-formula-debugger org-table-wrap-region
3896 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3897 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3898 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3900 (defun org-at-table-p (&optional table-type)
3901 "Return t if the cursor is inside an org-type table.
3902 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3903 (if org-enable-table-editor
3904 (save-excursion
3905 (beginning-of-line 1)
3906 (looking-at (if table-type org-table-any-line-regexp
3907 org-table-line-regexp)))
3908 nil))
3909 (defsubst org-table-p () (org-at-table-p))
3911 (defun org-at-table.el-p ()
3912 "Return t if and only if we are at a table.el table."
3913 (and (org-at-table-p 'any)
3914 (save-excursion
3915 (goto-char (org-table-begin 'any))
3916 (looking-at org-table1-hline-regexp))))
3917 (defun org-table-recognize-table.el ()
3918 "If there is a table.el table nearby, recognize it and move into it."
3919 (if org-table-tab-recognizes-table.el
3920 (if (org-at-table.el-p)
3921 (progn
3922 (beginning-of-line 1)
3923 (if (looking-at org-table-dataline-regexp)
3925 (if (looking-at org-table1-hline-regexp)
3926 (progn
3927 (beginning-of-line 2)
3928 (if (looking-at org-table-any-border-regexp)
3929 (beginning-of-line -1)))))
3930 (if (re-search-forward "|" (org-table-end t) t)
3931 (progn
3932 (require 'table)
3933 (if (table--at-cell-p (point))
3935 (message "recognizing table.el table...")
3936 (table-recognize-table)
3937 (message "recognizing table.el table...done")))
3938 (error "This should not happen"))
3940 nil)
3941 nil))
3943 (defun org-at-table-hline-p ()
3944 "Return t if the cursor is inside a hline in a table."
3945 (if org-enable-table-editor
3946 (save-excursion
3947 (beginning-of-line 1)
3948 (looking-at org-table-hline-regexp))
3949 nil))
3951 (defvar org-table-clean-did-remove-column nil)
3953 (defun org-table-map-tables (function &optional quietly)
3954 "Apply FUNCTION to the start of all tables in the buffer."
3955 (save-excursion
3956 (save-restriction
3957 (widen)
3958 (goto-char (point-min))
3959 (while (re-search-forward org-table-any-line-regexp nil t)
3960 (unless quietly
3961 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3962 (beginning-of-line 1)
3963 (when (and (looking-at org-table-line-regexp)
3964 ;; Exclude tables in src/example/verbatim/clocktable blocks
3965 (not (org-in-block-p '("src" "example"))))
3966 (save-excursion (funcall function))
3967 (or (looking-at org-table-line-regexp)
3968 (forward-char 1)))
3969 (re-search-forward org-table-any-border-regexp nil 1))))
3970 (unless quietly (message "Mapping tables: done")))
3972 ;; Declare and autoload functions from org-exp.el & Co
3974 (declare-function org-default-export-plist "org-exp")
3975 (declare-function org-infile-export-plist "org-exp")
3976 (declare-function org-get-current-options "org-exp")
3977 (eval-and-compile
3978 (org-autoload "org-exp"
3979 '(org-export org-export-visible
3980 org-insert-export-options-template
3981 org-table-clean-before-export))
3982 (org-autoload "org-ascii"
3983 '(org-export-as-ascii org-export-ascii-preprocess
3984 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3985 org-export-region-as-ascii))
3986 (org-autoload "org-latex"
3987 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3988 org-replace-region-by-latex org-export-region-as-latex
3989 org-export-as-latex org-export-as-pdf
3990 org-export-as-pdf-and-open))
3991 (org-autoload "org-html"
3992 '(org-export-as-html-and-open
3993 org-export-as-html-batch org-export-as-html-to-buffer
3994 org-replace-region-by-html org-export-region-as-html
3995 org-export-as-html))
3996 (org-autoload "org-docbook"
3997 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3998 org-replace-region-by-docbook org-export-region-as-docbook
3999 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4000 org-export-as-docbook))
4001 (org-autoload "org-icalendar"
4002 '(org-export-icalendar-this-file
4003 org-export-icalendar-all-agenda-files
4004 org-export-icalendar-combine-agenda-files))
4005 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4006 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4008 ;; Declare and autoload functions from org-agenda.el
4010 (eval-and-compile
4011 (org-autoload "org-agenda"
4012 '(org-agenda org-agenda-list org-search-view
4013 org-todo-list org-tags-view org-agenda-list-stuck-projects
4014 org-diary org-agenda-to-appt
4015 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4017 ;; Autoload org-remember
4019 (eval-and-compile
4020 (org-autoload "org-remember"
4021 '(org-remember-insinuate org-remember-annotation
4022 org-remember-apply-template org-remember org-remember-handler)))
4024 (eval-and-compile
4025 (org-autoload "org-capture"
4026 '(org-capture org-capture-insert-template-here
4027 org-capture-import-remember-templates)))
4029 ;; Autoload org-clock.el
4031 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4032 (beg end))
4033 (declare-function org-clock-update-mode-line "org-clock" ())
4034 (declare-function org-resolve-clocks "org-clock"
4035 (&optional also-non-dangling-p prompt last-valid))
4036 (defvar org-clock-start-time)
4037 (defvar org-clock-marker (make-marker)
4038 "Marker recording the last clock-in.")
4039 (defvar org-clock-hd-marker (make-marker)
4040 "Marker recording the last clock-in, but the headline position.")
4041 (defvar org-clock-heading ""
4042 "The heading of the current clock entry.")
4043 (defun org-clock-is-active ()
4044 "Return non-nil if clock is currently running.
4045 The return value is actually the clock marker."
4046 (marker-buffer org-clock-marker))
4048 (eval-and-compile
4049 (org-autoload
4050 "org-clock"
4051 '(org-clock-in org-clock-out org-clock-cancel
4052 org-clock-goto org-clock-sum org-clock-display
4053 org-clock-remove-overlays org-clock-report
4054 org-clocktable-shift org-dblock-write:clocktable
4055 org-get-clocktable org-resolve-clocks)))
4057 (defun org-clock-update-time-maybe ()
4058 "If this is a CLOCK line, update it and return t.
4059 Otherwise, return nil."
4060 (interactive)
4061 (save-excursion
4062 (beginning-of-line 1)
4063 (skip-chars-forward " \t")
4064 (when (looking-at org-clock-string)
4065 (let ((re (concat "[ \t]*" org-clock-string
4066 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4067 "\\([ \t]*=>.*\\)?\\)?"))
4068 ts te h m s neg)
4069 (cond
4070 ((not (looking-at re))
4071 nil)
4072 ((not (match-end 2))
4073 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4074 (> org-clock-marker (point))
4075 (<= org-clock-marker (point-at-eol)))
4076 ;; The clock is running here
4077 (setq org-clock-start-time
4078 (apply 'encode-time
4079 (org-parse-time-string (match-string 1))))
4080 (org-clock-update-mode-line)))
4082 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4083 (end-of-line 1)
4084 (setq ts (match-string 1)
4085 te (match-string 3))
4086 (setq s (- (org-float-time
4087 (apply 'encode-time (org-parse-time-string te)))
4088 (org-float-time
4089 (apply 'encode-time (org-parse-time-string ts))))
4090 neg (< s 0)
4091 s (abs s)
4092 h (floor (/ s 3600))
4093 s (- s (* 3600 h))
4094 m (floor (/ s 60))
4095 s (- s (* 60 s)))
4096 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4097 t))))))
4099 (defun org-check-running-clock ()
4100 "Check if the current buffer contains the running clock.
4101 If yes, offer to stop it and to save the buffer with the changes."
4102 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4103 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4104 (buffer-name))))
4105 (org-clock-out)
4106 (when (y-or-n-p "Save changed buffer?")
4107 (save-buffer))))
4109 (defun org-clocktable-try-shift (dir n)
4110 "Check if this line starts a clock table, if yes, shift the time block."
4111 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4112 (org-clocktable-shift dir n)))
4114 ;; Autoload org-timer.el
4116 (eval-and-compile
4117 (org-autoload
4118 "org-timer"
4119 '(org-timer-start org-timer org-timer-item
4120 org-timer-change-times-in-region
4121 org-timer-set-timer
4122 org-timer-reset-timers
4123 org-timer-show-remaining-time)))
4125 ;; Autoload org-feed.el
4127 (eval-and-compile
4128 (org-autoload
4129 "org-feed"
4130 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4133 ;; Autoload org-indent.el
4135 ;; Define the variable already here, to make sure we have it.
4136 (defvar org-indent-mode nil
4137 "Non-nil if Org-Indent mode is enabled.
4138 Use the command `org-indent-mode' to change this variable.")
4140 (eval-and-compile
4141 (org-autoload
4142 "org-indent"
4143 '(org-indent-mode)))
4145 ;; Autoload org-mobile.el
4147 (eval-and-compile
4148 (org-autoload
4149 "org-mobile"
4150 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4152 ;; Autoload archiving code
4153 ;; The stuff that is needed for cycling and tags has to be defined here.
4155 (defgroup org-archive nil
4156 "Options concerning archiving in Org-mode."
4157 :tag "Org Archive"
4158 :group 'org-structure)
4160 (defcustom org-archive-location "%s_archive::"
4161 "The location where subtrees should be archived.
4163 The value of this variable is a string, consisting of two parts,
4164 separated by a double-colon. The first part is a filename and
4165 the second part is a headline.
4167 When the filename is omitted, archiving happens in the same file.
4168 %s in the filename will be replaced by the current file
4169 name (without the directory part). Archiving to a different file
4170 is useful to keep archived entries from contributing to the
4171 Org-mode Agenda.
4173 The archived entries will be filed as subtrees of the specified
4174 headline. When the headline is omitted, the subtrees are simply
4175 filed away at the end of the file, as top-level entries. Also in
4176 the heading you can use %s to represent the file name, this can be
4177 useful when using the same archive for a number of different files.
4179 Here are a few examples:
4180 \"%s_archive::\"
4181 If the current file is Projects.org, archive in file
4182 Projects.org_archive, as top-level trees. This is the default.
4184 \"::* Archived Tasks\"
4185 Archive in the current file, under the top-level headline
4186 \"* Archived Tasks\".
4188 \"~/org/archive.org::\"
4189 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4191 \"~/org/archive.org::* From %s\"
4192 Archive in file ~/org/archive.org (absolute path), under headlines
4193 \"From FILENAME\" where file name is the current file name.
4195 \"~/org/datetree.org::datetree/* Finished Tasks\"
4196 The \"datetree/\" string is special, signifying to archive
4197 items to the datetree. Items are placed in either the CLOSED
4198 date of the item, or the current date if there is no CLOSED date.
4199 The heading will be a subentry to the current date. There doesn't
4200 need to be a heading, but there always needs to be a slash after
4201 datetree. For example, to store archived items directly in the
4202 datetree, use \"~/org/datetree.org::datetree/\".
4204 \"basement::** Finished Tasks\"
4205 Archive in file ./basement (relative path), as level 3 trees
4206 below the level 2 heading \"** Finished Tasks\".
4208 You may set this option on a per-file basis by adding to the buffer a
4209 line like
4211 #+ARCHIVE: basement::** Finished Tasks
4213 You may also define it locally for a subtree by setting an ARCHIVE property
4214 in the entry. If such a property is found in an entry, or anywhere up
4215 the hierarchy, it will be used."
4216 :group 'org-archive
4217 :type 'string)
4219 (defcustom org-archive-tag "ARCHIVE"
4220 "The tag that marks a subtree as archived.
4221 An archived subtree does not open during visibility cycling, and does
4222 not contribute to the agenda listings.
4223 After changing this, font-lock must be restarted in the relevant buffers to
4224 get the proper fontification."
4225 :group 'org-archive
4226 :group 'org-keywords
4227 :type 'string)
4229 (defcustom org-agenda-skip-archived-trees t
4230 "Non-nil means the agenda will skip any items located in archived trees.
4231 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4232 variable is no longer recommended, you should leave it at the value t.
4233 Instead, use the key `v' to cycle the archives-mode in the agenda."
4234 :group 'org-archive
4235 :group 'org-agenda-skip
4236 :type 'boolean)
4238 (defcustom org-columns-skip-archived-trees t
4239 "Non-nil means ignore archived trees when creating column view."
4240 :group 'org-archive
4241 :group 'org-properties
4242 :type 'boolean)
4244 (defcustom org-cycle-open-archived-trees nil
4245 "Non-nil means `org-cycle' will open archived trees.
4246 An archived tree is a tree marked with the tag ARCHIVE.
4247 When nil, archived trees will stay folded. You can still open them with
4248 normal outline commands like `show-all', but not with the cycling commands."
4249 :group 'org-archive
4250 :group 'org-cycle
4251 :type 'boolean)
4253 (defcustom org-sparse-tree-open-archived-trees nil
4254 "Non-nil means sparse tree construction shows matches in archived trees.
4255 When nil, matches in these trees are highlighted, but the trees are kept in
4256 collapsed state."
4257 :group 'org-archive
4258 :group 'org-sparse-trees
4259 :type 'boolean)
4261 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4262 "The default date type when building a sparse tree.
4263 When this is nil, a date is a scheduled or a deadline timestamp.
4264 Otherwise, these types are allowed:
4266 all: all timestamps
4267 active: only active timestamps (<...>)
4268 inactive: only inactive timestamps (<...)
4269 scheduled: only scheduled timestamps
4270 deadline: only deadline timestamps"
4271 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4272 (const :tag "All timestamps" all)
4273 (const :tag "Only active timestamps" active)
4274 (const :tag "Only inactive timestamps" inactive)
4275 (const :tag "Only scheduled timestamps" scheduled)
4276 (const :tag "Only deadline timestamps" deadline))
4277 :version "24.3"
4278 :group 'org-sparse-trees)
4280 (defun org-cycle-hide-archived-subtrees (state)
4281 "Re-hide all archived subtrees after a visibility state change."
4282 (when (and (not org-cycle-open-archived-trees)
4283 (not (memq state '(overview folded))))
4284 (save-excursion
4285 (let* ((globalp (memq state '(contents all)))
4286 (beg (if globalp (point-min) (point)))
4287 (end (if globalp (point-max) (org-end-of-subtree t))))
4288 (org-hide-archived-subtrees beg end)
4289 (goto-char beg)
4290 (if (looking-at (concat ".*:" org-archive-tag ":"))
4291 (message "%s" (substitute-command-keys
4292 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4294 (defun org-force-cycle-archived ()
4295 "Cycle subtree even if it is archived."
4296 (interactive)
4297 (setq this-command 'org-cycle)
4298 (let ((org-cycle-open-archived-trees t))
4299 (call-interactively 'org-cycle)))
4301 (defun org-hide-archived-subtrees (beg end)
4302 "Re-hide all archived subtrees after a visibility state change."
4303 (save-excursion
4304 (let* ((re (concat ":" org-archive-tag ":")))
4305 (goto-char beg)
4306 (while (re-search-forward re end t)
4307 (when (org-at-heading-p)
4308 (org-flag-subtree t)
4309 (org-end-of-subtree t))))))
4311 (declare-function outline-end-of-heading "outline" ())
4312 (declare-function outline-flag-region "outline" (from to flag))
4313 (defun org-flag-subtree (flag)
4314 (save-excursion
4315 (org-back-to-heading t)
4316 (outline-end-of-heading)
4317 (outline-flag-region (point)
4318 (progn (org-end-of-subtree t) (point))
4319 flag)))
4321 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4323 (eval-and-compile
4324 (org-autoload "org-archive"
4325 '(org-add-archive-files org-archive-subtree
4326 org-archive-to-archive-sibling org-toggle-archive-tag
4327 org-archive-subtree-default
4328 org-archive-subtree-default-with-confirmation)))
4330 ;; Autoload Column View Code
4332 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4333 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4334 (declare-function org-columns-compute "org-colview" (property))
4336 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4337 '(org-columns-number-to-string org-columns-get-format-and-top-level
4338 org-columns-compute org-agenda-columns org-columns-remove-overlays
4339 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4341 ;; Autoload ID code
4343 (declare-function org-id-store-link "org-id")
4344 (declare-function org-id-locations-load "org-id")
4345 (declare-function org-id-locations-save "org-id")
4346 (defvar org-id-track-globally)
4347 (org-autoload "org-id"
4348 '(org-id-get-create org-id-new org-id-copy org-id-get
4349 org-id-get-with-outline-path-completion
4350 org-id-get-with-outline-drilling org-id-store-link
4351 org-id-goto org-id-find org-id-store-link))
4353 ;; Autoload Plotting Code
4355 (org-autoload "org-plot"
4356 '(org-plot/gnuplot))
4358 ;;; Variables for pre-computed regular expressions, all buffer local
4360 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4361 "Matches first line of a hidden block.")
4362 (make-variable-buffer-local 'org-drawer-regexp)
4363 (defvar org-todo-regexp nil
4364 "Matches any of the TODO state keywords.")
4365 (make-variable-buffer-local 'org-todo-regexp)
4366 (defvar org-not-done-regexp nil
4367 "Matches any of the TODO state keywords except the last one.")
4368 (make-variable-buffer-local 'org-not-done-regexp)
4369 (defvar org-not-done-heading-regexp nil
4370 "Matches a TODO headline that is not done.")
4371 (make-variable-buffer-local 'org-not-done-regexp)
4372 (defvar org-todo-line-regexp nil
4373 "Matches a headline and puts TODO state into group 2 if present.")
4374 (make-variable-buffer-local 'org-todo-line-regexp)
4375 (defvar org-complex-heading-regexp nil
4376 "Matches a headline and puts everything into groups:
4377 group 1: the stars
4378 group 2: The todo keyword, maybe
4379 group 3: Priority cookie
4380 group 4: True headline
4381 group 5: Tags")
4382 (make-variable-buffer-local 'org-complex-heading-regexp)
4383 (defvar org-complex-heading-regexp-format nil
4384 "Printf format to make regexp to match an exact headline.
4385 This regexp will match the headline of any node which has the
4386 exact headline text that is put into the format, but may have any
4387 TODO state, priority and tags.")
4388 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4389 (defvar org-todo-line-tags-regexp nil
4390 "Matches a headline and puts TODO state into group 2 if present.
4391 Also put tags into group 4 if tags are present.")
4392 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4393 (defvar org-ds-keyword-length 12
4394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4395 (make-variable-buffer-local 'org-ds-keyword-length)
4396 (defvar org-deadline-regexp nil
4397 "Matches the DEADLINE keyword.")
4398 (make-variable-buffer-local 'org-deadline-regexp)
4399 (defvar org-deadline-time-regexp nil
4400 "Matches the DEADLINE keyword together with a time stamp.")
4401 (make-variable-buffer-local 'org-deadline-time-regexp)
4402 (defvar org-deadline-line-regexp nil
4403 "Matches the DEADLINE keyword and the rest of the line.")
4404 (make-variable-buffer-local 'org-deadline-line-regexp)
4405 (defvar org-scheduled-regexp nil
4406 "Matches the SCHEDULED keyword.")
4407 (make-variable-buffer-local 'org-scheduled-regexp)
4408 (defvar org-scheduled-time-regexp nil
4409 "Matches the SCHEDULED keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-scheduled-time-regexp)
4411 (defvar org-closed-time-regexp nil
4412 "Matches the CLOSED keyword together with a time stamp.")
4413 (make-variable-buffer-local 'org-closed-time-regexp)
4415 (defvar org-keyword-time-regexp nil
4416 "Matches any of the 4 keywords, together with the time stamp.")
4417 (make-variable-buffer-local 'org-keyword-time-regexp)
4418 (defvar org-keyword-time-not-clock-regexp nil
4419 "Matches any of the 3 keywords, together with the time stamp.")
4420 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4421 (defvar org-maybe-keyword-time-regexp nil
4422 "Matches a timestamp, possibly preceded by a keyword.")
4423 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4424 (defvar org-all-time-keywords nil
4425 "List of time keywords.")
4426 (make-variable-buffer-local 'org-all-time-keywords)
4428 (defconst org-plain-time-of-day-regexp
4429 (concat
4430 "\\(\\<[012]?[0-9]"
4431 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4432 "\\(--?"
4433 "\\(\\<[012]?[0-9]"
4434 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4435 "\\)?")
4436 "Regular expression to match a plain time or time range.
4437 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4438 groups carry important information:
4439 0 the full match
4440 1 the first time, range or not
4441 8 the second time, if it is a range.")
4443 (defconst org-plain-time-extension-regexp
4444 (concat
4445 "\\(\\<[012]?[0-9]"
4446 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4447 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4448 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4449 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4450 groups carry important information:
4451 0 the full match
4452 7 hours of duration
4453 9 minutes of duration")
4455 (defconst org-stamp-time-of-day-regexp
4456 (concat
4457 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4458 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4459 "\\(--?"
4460 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4461 "Regular expression to match a timestamp time or time range.
4462 After a match, the following groups carry important information:
4463 0 the full match
4464 1 date plus weekday, for back referencing to make sure both times are on the same day
4465 2 the first time, range or not
4466 4 the second time, if it is a range.")
4468 (defconst org-startup-options
4469 '(("fold" org-startup-folded t)
4470 ("overview" org-startup-folded t)
4471 ("nofold" org-startup-folded nil)
4472 ("showall" org-startup-folded nil)
4473 ("showeverything" org-startup-folded showeverything)
4474 ("content" org-startup-folded content)
4475 ("indent" org-startup-indented t)
4476 ("noindent" org-startup-indented nil)
4477 ("hidestars" org-hide-leading-stars t)
4478 ("showstars" org-hide-leading-stars nil)
4479 ("odd" org-odd-levels-only t)
4480 ("oddeven" org-odd-levels-only nil)
4481 ("align" org-startup-align-all-tables t)
4482 ("noalign" org-startup-align-all-tables nil)
4483 ("inlineimages" org-startup-with-inline-images t)
4484 ("noinlineimages" org-startup-with-inline-images nil)
4485 ("customtime" org-display-custom-times t)
4486 ("logdone" org-log-done time)
4487 ("lognotedone" org-log-done note)
4488 ("nologdone" org-log-done nil)
4489 ("lognoteclock-out" org-log-note-clock-out t)
4490 ("nolognoteclock-out" org-log-note-clock-out nil)
4491 ("logrepeat" org-log-repeat state)
4492 ("lognoterepeat" org-log-repeat note)
4493 ("nologrepeat" org-log-repeat nil)
4494 ("logreschedule" org-log-reschedule time)
4495 ("lognotereschedule" org-log-reschedule note)
4496 ("nologreschedule" org-log-reschedule nil)
4497 ("logredeadline" org-log-redeadline time)
4498 ("lognoteredeadline" org-log-redeadline note)
4499 ("nologredeadline" org-log-redeadline nil)
4500 ("logrefile" org-log-refile time)
4501 ("lognoterefile" org-log-refile note)
4502 ("nologrefile" org-log-refile nil)
4503 ("fninline" org-footnote-define-inline t)
4504 ("nofninline" org-footnote-define-inline nil)
4505 ("fnlocal" org-footnote-section nil)
4506 ("fnauto" org-footnote-auto-label t)
4507 ("fnprompt" org-footnote-auto-label nil)
4508 ("fnconfirm" org-footnote-auto-label confirm)
4509 ("fnplain" org-footnote-auto-label plain)
4510 ("fnadjust" org-footnote-auto-adjust t)
4511 ("nofnadjust" org-footnote-auto-adjust nil)
4512 ("constcgs" constants-unit-system cgs)
4513 ("constSI" constants-unit-system SI)
4514 ("noptag" org-tag-persistent-alist nil)
4515 ("hideblocks" org-hide-block-startup t)
4516 ("nohideblocks" org-hide-block-startup nil)
4517 ("beamer" org-startup-with-beamer-mode t)
4518 ("entitiespretty" org-pretty-entities t)
4519 ("entitiesplain" org-pretty-entities nil))
4520 "Variable associated with STARTUP options for org-mode.
4521 Each element is a list of three items: the startup options (as written
4522 in the #+STARTUP line), the corresponding variable, and the value to set
4523 this variable to if the option is found. An optional forth element PUSH
4524 means to push this value onto the list in the variable.")
4526 (defun org-update-property-plist (key val props)
4527 "Update PROPS with KEY and VAL."
4528 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4529 (key (if appending (substring key 0 (- (length key) 1)) key))
4530 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4531 (previous (cdr (assoc key props))))
4532 (if appending
4533 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4534 (cons (cons key val) remainder))))
4536 (defconst org-block-regexp
4537 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4538 "Regular expression for hiding blocks.")
4539 (defconst org-heading-keyword-regexp-format
4540 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4541 "Printf format for a regexp matching an headline with some keyword.
4542 This regexp will match the headline of any node which has the
4543 exact keyword that is put into the format. The keyword isn't in
4544 any group by default, but the stars and the body are.")
4545 (defconst org-heading-keyword-maybe-regexp-format
4546 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4547 "Printf format for a regexp matching an headline, possibly with some keyword.
4548 This regexp can match any headline with the specified keyword, or
4549 without a keyword. The keyword isn't in any group by default,
4550 but the stars and the body are.")
4552 (defun org-set-regexps-and-options ()
4553 "Precompute regular expressions for current buffer."
4554 (when (derived-mode-p 'org-mode)
4555 (org-set-local 'org-todo-kwd-alist nil)
4556 (org-set-local 'org-todo-key-alist nil)
4557 (org-set-local 'org-todo-key-trigger nil)
4558 (org-set-local 'org-todo-keywords-1 nil)
4559 (org-set-local 'org-done-keywords nil)
4560 (org-set-local 'org-todo-heads nil)
4561 (org-set-local 'org-todo-sets nil)
4562 (org-set-local 'org-todo-log-states nil)
4563 (org-set-local 'org-file-properties nil)
4564 (org-set-local 'org-file-tags nil)
4565 (let ((re (org-make-options-regexp
4566 '("CATEGORY" "TODO" "COLUMNS"
4567 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4568 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4569 "OPTIONS")
4570 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4571 (splitre "[ \t]+")
4572 (scripts org-use-sub-superscripts)
4573 kwds kws0 kwsa key log value cat arch tags const links hw dws
4574 tail sep kws1 prio props ftags drawers beamer-p
4575 ext-setup-or-nil setup-contents (start 0))
4576 (save-excursion
4577 (save-restriction
4578 (widen)
4579 (goto-char (point-min))
4580 (while (or (and ext-setup-or-nil
4581 (string-match re ext-setup-or-nil start)
4582 (setq start (match-end 0)))
4583 (and (setq ext-setup-or-nil nil start 0)
4584 (re-search-forward re nil t)))
4585 (setq key (upcase (match-string 1 ext-setup-or-nil))
4586 value (org-match-string-no-properties 2 ext-setup-or-nil))
4587 (if (stringp value) (setq value (org-trim value)))
4588 (cond
4589 ((equal key "CATEGORY")
4590 (setq cat value))
4591 ((member key '("SEQ_TODO" "TODO"))
4592 (push (cons 'sequence (org-split-string value splitre)) kwds))
4593 ((equal key "TYP_TODO")
4594 (push (cons 'type (org-split-string value splitre)) kwds))
4595 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4596 ;; general TODO-like setup
4597 (push (cons (intern (downcase (match-string 1 key)))
4598 (org-split-string value splitre)) kwds))
4599 ((equal key "TAGS")
4600 (setq tags (append tags (if tags '("\\n") nil)
4601 (org-split-string value splitre))))
4602 ((equal key "COLUMNS")
4603 (org-set-local 'org-columns-default-format value))
4604 ((equal key "LINK")
4605 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4606 (push (cons (match-string 1 value)
4607 (org-trim (match-string 2 value)))
4608 links)))
4609 ((equal key "PRIORITIES")
4610 (setq prio (org-split-string value " +")))
4611 ((equal key "PROPERTY")
4612 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4613 (setq props (org-update-property-plist (match-string 1 value)
4614 (match-string 2 value)
4615 props))))
4616 ((equal key "FILETAGS")
4617 (when (string-match "\\S-" value)
4618 (setq ftags
4619 (append
4620 ftags
4621 (apply 'append
4622 (mapcar (lambda (x) (org-split-string x ":"))
4623 (org-split-string value)))))))
4624 ((equal key "DRAWERS")
4625 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4626 ((equal key "CONSTANTS")
4627 (setq const (append const (org-split-string value splitre))))
4628 ((equal key "STARTUP")
4629 (let ((opts (org-split-string value splitre))
4630 l var val)
4631 (while (setq l (pop opts))
4632 (when (setq l (assoc l org-startup-options))
4633 (setq var (nth 1 l) val (nth 2 l))
4634 (if (not (nth 3 l))
4635 (set (make-local-variable var) val)
4636 (if (not (listp (symbol-value var)))
4637 (set (make-local-variable var) nil))
4638 (set (make-local-variable var) (symbol-value var))
4639 (add-to-list var val))))))
4640 ((equal key "ARCHIVE")
4641 (setq arch value)
4642 (remove-text-properties 0 (length arch)
4643 '(face t fontified t) arch))
4644 ((equal key "LATEX_CLASS")
4645 (setq beamer-p (equal value "beamer")))
4646 ((equal key "OPTIONS")
4647 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4648 (setq scripts (read (match-string 2 value)))))
4649 ((equal key "SETUPFILE")
4650 (setq setup-contents (org-file-contents
4651 (expand-file-name
4652 (org-remove-double-quotes value))
4653 'noerror))
4654 (if (not ext-setup-or-nil)
4655 (setq ext-setup-or-nil setup-contents start 0)
4656 (setq ext-setup-or-nil
4657 (concat (substring ext-setup-or-nil 0 start)
4658 "\n" setup-contents "\n"
4659 (substring ext-setup-or-nil start)))))))
4660 ;; search for property blocks
4661 (goto-char (point-min))
4662 (while (re-search-forward org-block-regexp nil t)
4663 (when (equal "PROPERTY" (upcase (match-string 1)))
4664 (setq value (replace-regexp-in-string
4665 "[\n\r]" " " (match-string 4)))
4666 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4667 (setq props (org-update-property-plist (match-string 1 value)
4668 (match-string 2 value)
4669 props)))))))
4670 (org-set-local 'org-use-sub-superscripts scripts)
4671 (when cat
4672 (org-set-local 'org-category (intern cat))
4673 (push (cons "CATEGORY" cat) props))
4674 (when prio
4675 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4676 (setq prio (mapcar 'string-to-char prio))
4677 (org-set-local 'org-highest-priority (nth 0 prio))
4678 (org-set-local 'org-lowest-priority (nth 1 prio))
4679 (org-set-local 'org-default-priority (nth 2 prio)))
4680 (and props (org-set-local 'org-file-properties (nreverse props)))
4681 (and ftags (org-set-local 'org-file-tags
4682 (mapcar 'org-add-prop-inherited ftags)))
4683 (and drawers (org-set-local 'org-drawers drawers))
4684 (and arch (org-set-local 'org-archive-location arch))
4685 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4686 ;; Process the TODO keywords
4687 (unless kwds
4688 ;; Use the global values as if they had been given locally.
4689 (setq kwds (default-value 'org-todo-keywords))
4690 (if (stringp (car kwds))
4691 (setq kwds (list (cons org-todo-interpretation
4692 (default-value 'org-todo-keywords)))))
4693 (setq kwds (reverse kwds)))
4694 (setq kwds (nreverse kwds))
4695 (let (inter kws kw)
4696 (while (setq kws (pop kwds))
4697 (let ((kws (or
4698 (run-hook-with-args-until-success
4699 'org-todo-setup-filter-hook kws)
4700 kws)))
4701 (setq inter (pop kws) sep (member "|" kws)
4702 kws0 (delete "|" (copy-sequence kws))
4703 kwsa nil
4704 kws1 (mapcar
4705 (lambda (x)
4706 ;; 1 2
4707 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4708 (progn
4709 (setq kw (match-string 1 x)
4710 key (and (match-end 2) (match-string 2 x))
4711 log (org-extract-log-state-settings x))
4712 (push (cons kw (and key (string-to-char key))) kwsa)
4713 (and log (push log org-todo-log-states))
4715 (error "Invalid TODO keyword %s" x)))
4716 kws0)
4717 kwsa (if kwsa (append '((:startgroup))
4718 (nreverse kwsa)
4719 '((:endgroup))))
4720 hw (car kws1)
4721 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4722 tail (list inter hw (car dws) (org-last dws))))
4723 (add-to-list 'org-todo-heads hw 'append)
4724 (push kws1 org-todo-sets)
4725 (setq org-done-keywords (append org-done-keywords dws nil))
4726 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4727 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4728 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4729 (setq org-todo-sets (nreverse org-todo-sets)
4730 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4731 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4732 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4733 ;; Process the constants
4734 (when const
4735 (let (e cst)
4736 (while (setq e (pop const))
4737 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4738 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4739 (setq org-table-formula-constants-local cst)))
4741 ;; Process the tags.
4742 (when tags
4743 (let (e tgs)
4744 (while (setq e (pop tags))
4745 (cond
4746 ((equal e "{") (push '(:startgroup) tgs))
4747 ((equal e "}") (push '(:endgroup) tgs))
4748 ((equal e "\\n") (push '(:newline) tgs))
4749 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4750 (push (cons (match-string 1 e)
4751 (string-to-char (match-string 2 e)))
4752 tgs))
4753 (t (push (list e) tgs))))
4754 (org-set-local 'org-tag-alist nil)
4755 (while (setq e (pop tgs))
4756 (or (and (stringp (car e))
4757 (assoc (car e) org-tag-alist))
4758 (push e org-tag-alist)))))
4760 ;; Compute the regular expressions and other local variables.
4761 ;; Using `org-outline-regexp-bol' would complicate them much,
4762 ;; because of the fixed white space at the end of that string.
4763 (if (not org-done-keywords)
4764 (setq org-done-keywords (and org-todo-keywords-1
4765 (list (org-last org-todo-keywords-1)))))
4766 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4767 (length org-scheduled-string)
4768 (length org-clock-string)
4769 (length org-closed-string)))
4770 org-drawer-regexp
4771 (concat "^[ \t]*:\\("
4772 (mapconcat 'regexp-quote org-drawers "\\|")
4773 "\\):[ \t]*$")
4774 org-not-done-keywords
4775 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4776 org-todo-regexp
4777 (concat "\\("
4778 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4779 "\\)")
4780 org-not-done-regexp
4781 (concat "\\("
4782 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4783 "\\)")
4784 org-not-done-heading-regexp
4785 (format org-heading-keyword-regexp-format org-not-done-regexp)
4786 org-todo-line-regexp
4787 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4788 org-complex-heading-regexp
4789 (concat "^\\(\\*+\\)"
4790 "\\(?: +" org-todo-regexp "\\)?"
4791 "\\(?: +\\(\\[#.\\]\\)\\)?"
4792 "\\(?: +\\(.*?\\)\\)??"
4793 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4794 "[ \t]*$")
4795 org-complex-heading-regexp-format
4796 (concat "^\\(\\*+\\)"
4797 "\\(?: +" org-todo-regexp "\\)?"
4798 "\\(?: +\\(\\[#.\\]\\)\\)?"
4799 "\\(?: +"
4800 ;; Stats cookies can be stuck to body.
4801 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4802 "\\(%s\\)"
4803 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4804 "\\)"
4805 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4806 "[ \t]*$")
4807 org-todo-line-tags-regexp
4808 (concat "^\\(\\*+\\)"
4809 "\\(?: +" org-todo-regexp "\\)?"
4810 "\\(?: +\\(.*?\\)\\)??"
4811 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4812 "[ \t]*$")
4813 org-deadline-regexp (concat "\\<" org-deadline-string)
4814 org-deadline-time-regexp
4815 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4816 org-deadline-line-regexp
4817 (concat "\\<\\(" org-deadline-string "\\).*")
4818 org-scheduled-regexp
4819 (concat "\\<" org-scheduled-string)
4820 org-scheduled-time-regexp
4821 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4822 org-closed-time-regexp
4823 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4824 org-keyword-time-regexp
4825 (concat "\\<\\(" org-scheduled-string
4826 "\\|" org-deadline-string
4827 "\\|" org-closed-string
4828 "\\|" org-clock-string "\\)"
4829 " *[[<]\\([^]>]+\\)[]>]")
4830 org-keyword-time-not-clock-regexp
4831 (concat "\\<\\(" org-scheduled-string
4832 "\\|" org-deadline-string
4833 "\\|" org-closed-string
4834 "\\)"
4835 " *[[<]\\([^]>]+\\)[]>]")
4836 org-maybe-keyword-time-regexp
4837 (concat "\\(\\<\\(" org-scheduled-string
4838 "\\|" org-deadline-string
4839 "\\|" org-closed-string
4840 "\\|" org-clock-string "\\)\\)?"
4841 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4842 org-all-time-keywords
4843 (mapcar (lambda (w) (substring w 0 -1))
4844 (list org-scheduled-string org-deadline-string
4845 org-clock-string org-closed-string))
4847 (org-compute-latex-and-specials-regexp)
4848 (org-set-font-lock-defaults))))
4850 (defun org-file-contents (file &optional noerror)
4851 "Return the contents of FILE, as a string."
4852 (if (or (not file)
4853 (not (file-readable-p file)))
4854 (if noerror
4855 (progn
4856 (message "Cannot read file \"%s\"" file)
4857 (ding) (sit-for 2)
4859 (error "Cannot read file \"%s\"" file))
4860 (with-temp-buffer
4861 (insert-file-contents file)
4862 (buffer-string))))
4864 (defun org-extract-log-state-settings (x)
4865 "Extract the log state setting from a TODO keyword string.
4866 This will extract info from a string like \"WAIT(w@/!)\"."
4867 (let (kw key log1 log2)
4868 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4869 (setq kw (match-string 1 x)
4870 key (and (match-end 2) (match-string 2 x))
4871 log1 (and (match-end 3) (match-string 3 x))
4872 log2 (and (match-end 4) (match-string 4 x)))
4873 (and (or log1 log2)
4874 (list kw
4875 (and log1 (if (equal log1 "!") 'time 'note))
4876 (and log2 (if (equal log2 "!") 'time 'note)))))))
4878 (defun org-remove-keyword-keys (list)
4879 "Remove a pair of parenthesis at the end of each string in LIST."
4880 (mapcar (lambda (x)
4881 (if (string-match "(.*)$" x)
4882 (substring x 0 (match-beginning 0))
4884 list))
4886 (defun org-assign-fast-keys (alist)
4887 "Assign fast keys to a keyword-key alist.
4888 Respect keys that are already there."
4889 (let (new e (alt ?0))
4890 (while (setq e (pop alist))
4891 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4892 (cdr e)) ;; Key already assigned.
4893 (push e new)
4894 (let ((clist (string-to-list (downcase (car e))))
4895 (used (append new alist)))
4896 (when (= (car clist) ?@)
4897 (pop clist))
4898 (while (and clist (rassoc (car clist) used))
4899 (pop clist))
4900 (unless clist
4901 (while (rassoc alt used)
4902 (incf alt)))
4903 (push (cons (car e) (or (car clist) alt)) new))))
4904 (nreverse new)))
4906 ;;; Some variables used in various places
4908 (defvar org-window-configuration nil
4909 "Used in various places to store a window configuration.")
4910 (defvar org-selected-window nil
4911 "Used in various places to store a window configuration.")
4912 (defvar org-finish-function nil
4913 "Function to be called when `C-c C-c' is used.
4914 This is for getting out of special buffers like capture.")
4917 ;; FIXME: Occasionally check by commenting these, to make sure
4918 ;; no other functions uses these, forgetting to let-bind them.
4919 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4920 (defvar org-last-state)
4921 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4923 ;; Defined somewhere in this file, but used before definition.
4924 (defvar org-entities) ;; defined in org-entities.el
4925 (defvar org-struct-menu)
4926 (defvar org-org-menu)
4927 (defvar org-tbl-menu)
4929 ;;;; Define the Org-mode
4931 ;; We use a before-change function to check if a table might need
4932 ;; an update.
4933 (defvar org-table-may-need-update t
4934 "Indicates that a table might need an update.
4935 This variable is set by `org-before-change-function'.
4936 `org-table-align' sets it back to nil.")
4937 (defun org-before-change-function (beg end)
4938 "Every change indicates that a table might need an update."
4939 (setq org-table-may-need-update t))
4940 (defvar org-mode-map)
4941 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4942 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4943 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4944 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4945 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4946 (defvar org-table-buffer-is-an nil)
4948 (defvar bidi-paragraph-direction)
4949 (defvar buffer-face-mode-face)
4951 (require 'outline)
4952 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4953 (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"))
4954 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4956 ;; Other stuff we need.
4957 (require 'time-date)
4958 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4959 (require 'easymenu)
4960 (require 'overlay)
4962 (require 'org-macs)
4963 (require 'org-entities)
4964 ;; (require 'org-compat) moved higher up in the file before it is first used
4965 (require 'org-faces)
4966 (require 'org-list)
4967 (require 'org-pcomplete)
4968 (require 'org-src)
4969 (require 'org-footnote)
4971 ;; babel
4972 (require 'ob)
4973 (require 'ob-table)
4974 (require 'ob-lob)
4975 (require 'ob-ref)
4976 (require 'ob-tangle)
4977 (require 'ob-comint)
4978 (require 'ob-keys)
4980 ;;;###autoload
4981 (define-derived-mode org-mode outline-mode "Org"
4982 "Outline-based notes management and organizer, alias
4983 \"Carsten's outline-mode for keeping track of everything.\"
4985 Org-mode develops organizational tasks around a NOTES file which
4986 contains information about projects as plain text. Org-mode is
4987 implemented on top of outline-mode, which is ideal to keep the content
4988 of large files well structured. It supports ToDo items, deadlines and
4989 time stamps, which magically appear in the diary listing of the Emacs
4990 calendar. Tables are easily created with a built-in table editor.
4991 Plain text URL-like links connect to websites, emails (VM), Usenet
4992 messages (Gnus), BBDB entries, and any files related to the project.
4993 For printing and sharing of notes, an Org-mode file (or a part of it)
4994 can be exported as a structured ASCII or HTML file.
4996 The following commands are available:
4998 \\{org-mode-map}"
5000 ;; Get rid of Outline menus, they are not needed
5001 ;; Need to do this here because define-derived-mode sets up
5002 ;; the keymap so late. Still, it is a waste to call this each time
5003 ;; we switch another buffer into org-mode.
5004 (if (featurep 'xemacs)
5005 (when (boundp 'outline-mode-menu-heading)
5006 ;; Assume this is Greg's port, it uses easymenu
5007 (easy-menu-remove outline-mode-menu-heading)
5008 (easy-menu-remove outline-mode-menu-show)
5009 (easy-menu-remove outline-mode-menu-hide))
5010 (define-key org-mode-map [menu-bar headings] 'undefined)
5011 (define-key org-mode-map [menu-bar hide] 'undefined)
5012 (define-key org-mode-map [menu-bar show] 'undefined))
5014 (org-load-modules-maybe)
5015 (easy-menu-add org-org-menu)
5016 (easy-menu-add org-tbl-menu)
5017 (org-install-agenda-files-menu)
5018 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5019 (add-to-invisibility-spec '(org-cwidth))
5020 (add-to-invisibility-spec '(org-hide-block . t))
5021 (when (featurep 'xemacs)
5022 (org-set-local 'line-move-ignore-invisible t))
5023 (org-set-local 'outline-regexp org-outline-regexp)
5024 (org-set-local 'outline-level 'org-outline-level)
5025 (setq bidi-paragraph-direction 'left-to-right)
5026 (when (and org-ellipsis
5027 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5028 (fboundp 'make-glyph-code))
5029 (unless org-display-table
5030 (setq org-display-table (make-display-table)))
5031 (set-display-table-slot
5032 org-display-table 4
5033 (vconcat (mapcar
5034 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5035 org-ellipsis)))
5036 (if (stringp org-ellipsis) org-ellipsis "..."))))
5037 (setq buffer-display-table org-display-table))
5038 (org-set-regexps-and-options)
5039 (when (and org-tag-faces (not org-tags-special-faces-re))
5040 ;; tag faces set outside customize.... force initialization.
5041 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5042 ;; Calc embedded
5043 (org-set-local 'calc-embedded-open-mode "# ")
5044 (modify-syntax-entry ?@ "w")
5045 (modify-syntax-entry ?\" "\"")
5046 (if org-startup-truncated (setq truncate-lines t))
5047 (org-set-local 'font-lock-unfontify-region-function
5048 'org-unfontify-region)
5049 ;; Activate before-change-function
5050 (org-set-local 'org-table-may-need-update t)
5051 (org-add-hook 'before-change-functions 'org-before-change-function nil
5052 'local)
5053 ;; Check for running clock before killing a buffer
5054 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5055 ;; Initialize macros templates.
5056 (org-macro-initialize-templates)
5057 ;; Initialize radio targets.
5058 (org-update-radio-target-regexp)
5059 ;; Indentation.
5060 (org-set-local 'indent-line-function 'org-indent-line)
5061 (org-set-local 'indent-region-function 'org-indent-region)
5062 ;; Filling and auto-filling.
5063 (org-setup-filling)
5064 ;; Comments.
5065 (org-setup-comments-handling)
5066 ;; Beginning/end of defun
5067 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5068 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5069 ;; Next error for sparse trees
5070 (org-set-local 'next-error-function 'org-occur-next-match)
5071 ;; Make sure dependence stuff works reliably, even for users who set it
5072 ;; too late :-(
5073 (if org-enforce-todo-dependencies
5074 (add-hook 'org-blocker-hook
5075 'org-block-todo-from-children-or-siblings-or-parent)
5076 (remove-hook 'org-blocker-hook
5077 'org-block-todo-from-children-or-siblings-or-parent))
5078 (if org-enforce-todo-checkbox-dependencies
5079 (add-hook 'org-blocker-hook
5080 'org-block-todo-from-checkboxes)
5081 (remove-hook 'org-blocker-hook
5082 'org-block-todo-from-checkboxes))
5084 ;; Align options lines
5085 (org-set-local
5086 'align-mode-rules-list
5087 '((org-in-buffer-settings
5088 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5089 (modes . '(org-mode)))))
5091 ;; Imenu
5092 (org-set-local 'imenu-create-index-function
5093 'org-imenu-get-tree)
5095 ;; Make isearch reveal context
5096 (if (or (featurep 'xemacs)
5097 (not (boundp 'outline-isearch-open-invisible-function)))
5098 ;; Emacs 21 and XEmacs make use of the hook
5099 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5100 ;; Emacs 22 deals with this through a special variable
5101 (org-set-local 'outline-isearch-open-invisible-function
5102 (lambda (&rest ignore) (org-show-context 'isearch))))
5104 ;; Turn on org-beamer-mode?
5105 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5107 ;; Setup the pcomplete hooks
5108 (set (make-local-variable 'pcomplete-command-completion-function)
5109 'org-pcomplete-initial)
5110 (set (make-local-variable 'pcomplete-command-name-function)
5111 'org-command-at-point)
5112 (set (make-local-variable 'pcomplete-default-completion-function)
5113 'ignore)
5114 (set (make-local-variable 'pcomplete-parse-arguments-function)
5115 'org-parse-arguments)
5116 (set (make-local-variable 'pcomplete-termination-string) "")
5117 (when (>= emacs-major-version 23)
5118 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5120 ;; If empty file that did not turn on org-mode automatically, make it to.
5121 (if (and org-insert-mode-line-in-empty-file
5122 (org-called-interactively-p 'any)
5123 (= (point-min) (point-max)))
5124 (insert "# -*- mode: org -*-\n\n"))
5125 (unless org-inhibit-startup
5126 (when org-startup-align-all-tables
5127 (let ((bmp (buffer-modified-p)))
5128 (org-table-map-tables 'org-table-align 'quietly)
5129 (set-buffer-modified-p bmp)))
5130 (when org-startup-with-inline-images
5131 (org-display-inline-images))
5132 (when org-startup-indented
5133 (require 'org-indent)
5134 (org-indent-mode 1))
5135 (unless org-inhibit-startup-visibility-stuff
5136 (org-set-startup-visibility)))
5137 ;; Try to set org-hide correctly
5138 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5140 (when (fboundp 'abbrev-table-put)
5141 (abbrev-table-put org-mode-abbrev-table
5142 :parents (list text-mode-abbrev-table)))
5144 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5147 (defun org-find-invisible-foreground ()
5148 (let ((candidates (remove
5149 "unspecified-bg"
5150 (list
5151 (face-background 'default)
5152 (face-background 'org-default)
5153 (cdr (assoc 'background-color default-frame-alist))
5154 (cdr (assoc 'background-color initial-frame-alist))
5155 (cdr (assoc 'background-color window-system-default-frame-alist))
5156 (face-foreground 'org-hide)))))
5157 (car (remove nil candidates))))
5159 (defun org-current-time ()
5160 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5161 (if (> (car org-time-stamp-rounding-minutes) 1)
5162 (let ((r (car org-time-stamp-rounding-minutes))
5163 (time (decode-time)))
5164 (apply 'encode-time
5165 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5166 (nthcdr 2 time))))
5167 (current-time)))
5169 (defun org-today ()
5170 "Return today date, considering `org-extend-today-until'."
5171 (time-to-days
5172 (time-subtract (current-time)
5173 (list 0 (* 3600 org-extend-today-until) 0))))
5175 ;;;; Font-Lock stuff, including the activators
5177 (defvar org-mouse-map (make-sparse-keymap))
5178 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5179 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5180 (when org-mouse-1-follows-link
5181 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5182 (when org-tab-follows-link
5183 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5184 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5186 (require 'font-lock)
5188 (defconst org-non-link-chars "]\t\n\r<>")
5189 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5190 "shell" "elisp" "doi" "message"))
5191 (defvar org-link-types-re nil
5192 "Matches a link that has a url-like prefix like \"http:\"")
5193 (defvar org-link-re-with-space nil
5194 "Matches a link with spaces, optional angular brackets around it.")
5195 (defvar org-link-re-with-space2 nil
5196 "Matches a link with spaces, optional angular brackets around it.")
5197 (defvar org-link-re-with-space3 nil
5198 "Matches a link with spaces, only for internal part in bracket links.")
5199 (defvar org-angle-link-re nil
5200 "Matches link with angular brackets, spaces are allowed.")
5201 (defvar org-plain-link-re nil
5202 "Matches plain link, without spaces.")
5203 (defvar org-bracket-link-regexp nil
5204 "Matches a link in double brackets.")
5205 (defvar org-bracket-link-analytic-regexp nil
5206 "Regular expression used to analyze links.
5207 Here is what the match groups contain after a match:
5208 1: http:
5209 2: http
5210 3: path
5211 4: [desc]
5212 5: desc")
5213 (defvar org-bracket-link-analytic-regexp++ nil
5214 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5215 (defvar org-any-link-re nil
5216 "Regular expression matching any link.")
5218 (defcustom org-match-sexp-depth 3
5219 "Number of stacked braces for sub/superscript matching.
5220 This has to be set before loading org.el to be effective."
5221 :group 'org-export-translation ; ??????????????????????????/
5222 :type 'integer)
5224 (defun org-create-multibrace-regexp (left right n)
5225 "Create a regular expression which will match a balanced sexp.
5226 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5227 as single character strings.
5228 The regexp returned will match the entire expression including the
5229 delimiters. It will also define a single group which contains the
5230 match except for the outermost delimiters. The maximum depth of
5231 stacked delimiters is N. Escaping delimiters is not possible."
5232 (let* ((nothing (concat "[^" left right "]*?"))
5233 (or "\\|")
5234 (re nothing)
5235 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5236 (while (> n 1)
5237 (setq n (1- n)
5238 re (concat re or next)
5239 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5240 (concat left "\\(" re "\\)" right)))
5242 (defvar org-match-substring-regexp
5243 (concat
5244 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5245 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5246 "\\|"
5247 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5248 "\\|"
5249 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5250 "The regular expression matching a sub- or superscript.")
5252 (defvar org-match-substring-with-braces-regexp
5253 (concat
5254 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5255 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5256 "\\)")
5257 "The regular expression matching a sub- or superscript, forcing braces.")
5259 (defun org-make-link-regexps ()
5260 "Update the link regular expressions.
5261 This should be called after the variable `org-link-types' has changed."
5262 (setq org-link-types-re
5263 (concat
5264 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5265 org-link-re-with-space
5266 (concat
5267 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5268 "\\([^" org-non-link-chars " ]"
5269 "[^" org-non-link-chars "]*"
5270 "[^" org-non-link-chars " ]\\)>?")
5271 org-link-re-with-space2
5272 (concat
5273 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5274 "\\([^" org-non-link-chars " ]"
5275 "[^\t\n\r]*"
5276 "[^" org-non-link-chars " ]\\)>?")
5277 org-link-re-with-space3
5278 (concat
5279 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5280 "\\([^" org-non-link-chars " ]"
5281 "[^\t\n\r]*\\)")
5282 org-angle-link-re
5283 (concat
5284 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5285 "\\([^" org-non-link-chars " ]"
5286 "[^" org-non-link-chars "]*"
5287 "\\)>")
5288 org-plain-link-re
5289 (concat
5290 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5291 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5292 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5293 org-bracket-link-regexp
5294 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5295 org-bracket-link-analytic-regexp
5296 (concat
5297 "\\[\\["
5298 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5299 "\\([^]]+\\)"
5300 "\\]"
5301 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5302 "\\]")
5303 org-bracket-link-analytic-regexp++
5304 (concat
5305 "\\[\\["
5306 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5307 "\\([^]]+\\)"
5308 "\\]"
5309 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5310 "\\]")
5311 org-any-link-re
5312 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5313 org-angle-link-re "\\)\\|\\("
5314 org-plain-link-re "\\)")))
5316 (org-make-link-regexps)
5318 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5319 "Regular expression for fast time stamp matching.")
5320 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5321 "Regular expression for fast time stamp matching.")
5322 (defconst org-ts-regexp0
5323 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5324 "Regular expression matching time strings for analysis.
5325 This one does not require the space after the date, so it can be used
5326 on a string that terminates immediately after the date.")
5327 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5328 "Regular expression matching time strings for analysis.")
5329 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5330 "Regular expression matching time stamps, with groups.")
5331 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5332 "Regular expression matching time stamps (also [..]), with groups.")
5333 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5334 "Regular expression matching a time stamp range.")
5335 (defconst org-tr-regexp-both
5336 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5337 "Regular expression matching a time stamp range.")
5338 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5339 org-ts-regexp "\\)?")
5340 "Regular expression matching a time stamp or time stamp range.")
5341 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5342 org-ts-regexp-both "\\)?")
5343 "Regular expression matching a time stamp or time stamp range.
5344 The time stamps may be either active or inactive.")
5346 (defvar org-emph-face nil)
5348 (defun org-do-emphasis-faces (limit)
5349 "Run through the buffer and add overlays to emphasized strings."
5350 (let (rtn a)
5351 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5352 (if (not (= (char-after (match-beginning 3))
5353 (char-after (match-beginning 4))))
5354 (progn
5355 (setq rtn t)
5356 (setq a (assoc (match-string 3) org-emphasis-alist))
5357 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5358 'face
5359 (nth 1 a))
5360 (and (nth 4 a)
5361 (org-remove-flyspell-overlays-in
5362 (match-beginning 0) (match-end 0)))
5363 (add-text-properties (match-beginning 2) (match-end 2)
5364 '(font-lock-multiline t org-emphasis t))
5365 (when org-hide-emphasis-markers
5366 (add-text-properties (match-end 4) (match-beginning 5)
5367 '(invisible org-link))
5368 (add-text-properties (match-beginning 3) (match-end 3)
5369 '(invisible org-link)))))
5370 (backward-char 1))
5371 rtn))
5373 (defun org-emphasize (&optional char)
5374 "Insert or change an emphasis, i.e. a font like bold or italic.
5375 If there is an active region, change that region to a new emphasis.
5376 If there is no region, just insert the marker characters and position
5377 the cursor between them.
5378 CHAR should be either the marker character, or the first character of the
5379 HTML tag associated with that emphasis. If CHAR is a space, the means
5380 to remove the emphasis of the selected region.
5381 If char is not given (for example in an interactive call) it
5382 will be prompted for."
5383 (interactive)
5384 (let ((eal org-emphasis-alist) e det
5385 (erc org-emphasis-regexp-components)
5386 (prompt "")
5387 (string "") beg end move tag c s)
5388 (if (org-region-active-p)
5389 (setq beg (region-beginning) end (region-end)
5390 string (buffer-substring beg end))
5391 (setq move t))
5393 (while (setq e (pop eal))
5394 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5395 c (aref tag 0))
5396 (push (cons c (string-to-char (car e))) det)
5397 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5398 (substring tag 1)))))
5399 (setq det (nreverse det))
5400 (unless char
5401 (message "%s" (concat "Emphasis marker or tag:" prompt))
5402 (setq char (read-char-exclusive)))
5403 (setq char (or (cdr (assoc char det)) char))
5404 (if (equal char ?\ )
5405 (setq s "" move nil)
5406 (unless (assoc (char-to-string char) org-emphasis-alist)
5407 (error "No such emphasis marker: \"%c\"" char))
5408 (setq s (char-to-string char)))
5409 (while (and (> (length string) 1)
5410 (equal (substring string 0 1) (substring string -1))
5411 (assoc (substring string 0 1) org-emphasis-alist))
5412 (setq string (substring string 1 -1)))
5413 (setq string (concat s string s))
5414 (if beg (delete-region beg end))
5415 (unless (or (bolp)
5416 (string-match (concat "[" (nth 0 erc) "\n]")
5417 (char-to-string (char-before (point)))))
5418 (insert " "))
5419 (unless (or (eobp)
5420 (string-match (concat "[" (nth 1 erc) "\n]")
5421 (char-to-string (char-after (point)))))
5422 (insert " ") (backward-char 1))
5423 (insert string)
5424 (and move (backward-char 1))))
5426 (defconst org-nonsticky-props
5427 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5429 (defsubst org-rear-nonsticky-at (pos)
5430 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5432 (defun org-activate-plain-links (limit)
5433 "Run through the buffer and add overlays to links."
5434 (catch 'exit
5435 (let (f hl)
5436 (when (re-search-forward (concat org-plain-link-re) limit t)
5437 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5438 (setq f (get-text-property (match-beginning 0) 'face))
5439 (setq hl (org-match-string-no-properties 0))
5440 (if (or (eq f 'org-tag)
5441 (and (listp f) (memq 'org-tag f)))
5443 (add-text-properties (match-beginning 0) (match-end 0)
5444 (list 'mouse-face 'highlight
5445 'face 'org-link
5446 'htmlize-link `(:uri ,hl)
5447 'keymap org-mouse-map))
5448 (org-rear-nonsticky-at (match-end 0)))
5449 t))))
5451 (defun org-activate-code (limit)
5452 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5453 (progn
5454 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5455 (remove-text-properties (match-beginning 0) (match-end 0)
5456 '(display t invisible t intangible t))
5457 t)))
5459 (defcustom org-src-fontify-natively nil
5460 "When non-nil, fontify code in code blocks."
5461 :type 'boolean
5462 :version "24.1"
5463 :group 'org-appearance
5464 :group 'org-babel)
5466 (defcustom org-allow-promoting-top-level-subtree nil
5467 "When non-nil, allow promoting a top level subtree.
5468 The leading star of the top level headline will be replaced
5469 by a #."
5470 :type 'boolean
5471 :version "24.1"
5472 :group 'org-appearance)
5474 (defun org-fontify-meta-lines-and-blocks (limit)
5475 (condition-case nil
5476 (org-fontify-meta-lines-and-blocks-1 limit)
5477 (error (message "org-mode fontification error"))))
5479 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5480 "Fontify #+ lines and blocks, in the correct ways."
5481 (let ((case-fold-search t))
5482 (if (re-search-forward
5483 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5484 limit t)
5485 (let ((beg (match-beginning 0))
5486 (block-start (match-end 0))
5487 (block-end nil)
5488 (lang (match-string 7))
5489 (beg1 (line-beginning-position 2))
5490 (dc1 (downcase (match-string 2)))
5491 (dc3 (downcase (match-string 3)))
5492 end end1 quoting block-type ovl)
5493 (cond
5494 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5495 ;; a single line of backend-specific content
5496 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5497 (remove-text-properties (match-beginning 0) (match-end 0)
5498 '(display t invisible t intangible t))
5499 (add-text-properties (match-beginning 1) (match-end 3)
5500 '(font-lock-fontified t face org-meta-line))
5501 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5502 '(font-lock-fontified t face org-block))
5503 ; for backend-specific code
5505 ((and (match-end 4) (equal dc3 "+begin"))
5506 ;; Truly a block
5507 (setq block-type (downcase (match-string 5))
5508 quoting (member block-type org-protecting-blocks))
5509 (when (re-search-forward
5510 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5511 nil t) ;; on purpose, we look further than LIMIT
5512 (setq end (min (point-max) (match-end 0))
5513 end1 (min (point-max) (1- (match-beginning 0))))
5514 (setq block-end (match-beginning 0))
5515 (when quoting
5516 (remove-text-properties beg end
5517 '(display t invisible t intangible t)))
5518 (add-text-properties
5519 beg end
5520 '(font-lock-fontified t font-lock-multiline t))
5521 (add-text-properties beg beg1 '(face org-meta-line))
5522 (add-text-properties end1 (min (point-max) (1+ end))
5523 '(face org-meta-line)) ; for end_src
5524 (cond
5525 ((and lang (not (string= lang "")) org-src-fontify-natively)
5526 (org-src-font-lock-fontify-block lang block-start block-end)
5527 ;; remove old background overlays
5528 (mapc (lambda (ov)
5529 (if (eq (overlay-get ov 'face) 'org-block-background)
5530 (delete-overlay ov)))
5531 (overlays-at (/ (+ beg1 block-end) 2)))
5532 ;; add a background overlay
5533 (setq ovl (make-overlay beg1 block-end))
5534 (overlay-put ovl 'face 'org-block-background)
5535 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5536 (quoting
5537 (add-text-properties beg1 (min (point-max) (1+ end1))
5538 '(face org-block))) ; end of source block
5539 ((not org-fontify-quote-and-verse-blocks))
5540 ((string= block-type "quote")
5541 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5542 ((string= block-type "verse")
5543 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5544 (add-text-properties beg beg1 '(face org-block-begin-line))
5545 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5546 '(face org-block-end-line))
5548 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5549 (add-text-properties
5550 beg (match-end 3)
5551 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5552 '(font-lock-fontified t invisible t)
5553 '(font-lock-fontified t face org-document-info-keyword)))
5554 (add-text-properties
5555 (match-beginning 6) (match-end 6)
5556 (if (string-equal dc1 "+title:")
5557 '(font-lock-fontified t face org-document-title)
5558 '(font-lock-fontified t face org-document-info))))
5559 ((or (equal dc1 "+results")
5560 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5561 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5562 "+call:" "+header:" "+headers:" "+name:"))
5563 (and (match-end 4) (equal dc3 "+attr")))
5564 (add-text-properties
5565 beg (match-end 0)
5566 '(font-lock-fontified t face org-meta-line))
5568 ((member dc3 '(" " ""))
5569 (add-text-properties
5570 beg (match-end 0)
5571 '(font-lock-fontified t face font-lock-comment-face)))
5572 ((not (member (char-after beg) '(?\ ?\t)))
5573 ;; just any other in-buffer setting, but not indented
5574 (add-text-properties
5575 beg (match-end 0)
5576 '(font-lock-fontified t face org-meta-line))
5578 (t nil))))))
5580 (defun org-activate-angle-links (limit)
5581 "Run through the buffer and add overlays to links."
5582 (if (re-search-forward org-angle-link-re limit t)
5583 (progn
5584 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5585 (add-text-properties (match-beginning 0) (match-end 0)
5586 (list 'mouse-face 'highlight
5587 'keymap org-mouse-map))
5588 (org-rear-nonsticky-at (match-end 0))
5589 t)))
5591 (defun org-activate-footnote-links (limit)
5592 "Run through the buffer and add overlays to footnotes."
5593 (let ((fn (org-footnote-next-reference-or-definition limit)))
5594 (when fn
5595 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5596 (org-remove-flyspell-overlays-in beg end)
5597 (add-text-properties beg end
5598 (list 'mouse-face 'highlight
5599 'keymap org-mouse-map
5600 'help-echo
5601 (if (= (point-at-bol) beg)
5602 "Footnote definition"
5603 "Footnote reference")
5604 'font-lock-fontified t
5605 'font-lock-multiline t
5606 'face 'org-footnote))))))
5608 (defun org-activate-bracket-links (limit)
5609 "Run through the buffer and add overlays to bracketed links."
5610 (if (re-search-forward org-bracket-link-regexp limit t)
5611 (let* ((hl (org-match-string-no-properties 1))
5612 (help (concat "LINK: " hl))
5613 ;; FIXME: Above we should remove the escapes. But that
5614 ;; requires another match, protecting match data, a lot
5615 ;; of overhead for font-lock.
5616 (ip (org-maybe-intangible
5617 (list 'invisible 'org-link
5618 'keymap org-mouse-map 'mouse-face 'highlight
5619 'font-lock-multiline t 'help-echo help
5620 'htmlize-link `(:uri ,hl))))
5621 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5622 'font-lock-multiline t 'help-echo help
5623 'htmlize-link `(:uri ,hl))))
5624 ;; We need to remove the invisible property here. Table narrowing
5625 ;; may have made some of this invisible.
5626 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5627 (remove-text-properties (match-beginning 0) (match-end 0)
5628 '(invisible nil))
5629 (if (match-end 3)
5630 (progn
5631 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5632 (org-rear-nonsticky-at (match-beginning 3))
5633 (add-text-properties (match-beginning 3) (match-end 3) vp)
5634 (org-rear-nonsticky-at (match-end 3))
5635 (add-text-properties (match-end 3) (match-end 0) ip)
5636 (org-rear-nonsticky-at (match-end 0)))
5637 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5638 (org-rear-nonsticky-at (match-beginning 1))
5639 (add-text-properties (match-beginning 1) (match-end 1) vp)
5640 (org-rear-nonsticky-at (match-end 1))
5641 (add-text-properties (match-end 1) (match-end 0) ip)
5642 (org-rear-nonsticky-at (match-end 0)))
5643 t)))
5645 (defun org-activate-dates (limit)
5646 "Run through the buffer and add overlays to dates."
5647 (if (re-search-forward org-tsr-regexp-both limit t)
5648 (progn
5649 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5650 (add-text-properties (match-beginning 0) (match-end 0)
5651 (list 'mouse-face 'highlight
5652 'keymap org-mouse-map))
5653 (org-rear-nonsticky-at (match-end 0))
5654 (when org-display-custom-times
5655 (if (match-end 3)
5656 (org-display-custom-time (match-beginning 3) (match-end 3)))
5657 (org-display-custom-time (match-beginning 1) (match-end 1)))
5658 t)))
5660 (defvar org-target-link-regexp nil
5661 "Regular expression matching radio targets in plain text.")
5662 (make-variable-buffer-local 'org-target-link-regexp)
5663 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5664 "Regular expression matching a link target.")
5665 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5666 "Regular expression matching a radio target.")
5667 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5668 "Regular expression matching any target.")
5670 (defun org-activate-target-links (limit)
5671 "Run through the buffer and add overlays to target matches."
5672 (when org-target-link-regexp
5673 (let ((case-fold-search t))
5674 (if (re-search-forward org-target-link-regexp limit t)
5675 (progn
5676 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5677 (add-text-properties (match-beginning 0) (match-end 0)
5678 (list 'mouse-face 'highlight
5679 'keymap org-mouse-map
5680 'help-echo "Radio target link"
5681 'org-linked-text t))
5682 (org-rear-nonsticky-at (match-end 0))
5683 t)))))
5685 (defun org-update-radio-target-regexp ()
5686 "Find all radio targets in this file and update the regular expression."
5687 (interactive)
5688 (when (memq 'radio org-activate-links)
5689 (setq org-target-link-regexp
5690 (org-make-target-link-regexp (org-all-targets 'radio)))
5691 (org-restart-font-lock)))
5693 (defun org-hide-wide-columns (limit)
5694 (let (s e)
5695 (setq s (text-property-any (point) (or limit (point-max))
5696 'org-cwidth t))
5697 (when s
5698 (setq e (next-single-property-change s 'org-cwidth))
5699 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5700 (goto-char e)
5701 t)))
5703 (defvar org-latex-and-specials-regexp nil
5704 "Regular expression for highlighting export special stuff.")
5705 (defvar org-match-substring-regexp)
5706 (defvar org-match-substring-with-braces-regexp)
5708 ;; This should be with the exporter code, but we also use if for font-locking
5709 (defconst org-export-html-special-string-regexps
5710 '(("\\\\-" . "&shy;")
5711 ("---\\([^-]\\)" . "&mdash;\\1")
5712 ("--\\([^-]\\)" . "&ndash;\\1")
5713 ("\\.\\.\\." . "&hellip;"))
5714 "Regular expressions for special string conversion.")
5717 (defun org-compute-latex-and-specials-regexp ()
5718 "Compute regular expression for stuff treated specially by exporters."
5719 (if (not org-highlight-latex-fragments-and-specials)
5720 (org-set-local 'org-latex-and-specials-regexp nil)
5721 (require 'org-exp)
5722 (let*
5723 ((matchers (plist-get org-format-latex-options :matchers))
5724 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5725 org-latex-regexps)))
5726 (org-export-allow-BIND nil)
5727 (options (org-combine-plists (org-default-export-plist)
5728 (org-infile-export-plist)))
5729 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5730 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5731 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5732 (org-export-html-expand (plist-get options :expand-quoted-html))
5733 (org-export-with-special-strings (plist-get options :special-strings))
5734 (re-sub
5735 (cond
5736 ((equal org-export-with-sub-superscripts '{})
5737 (list org-match-substring-with-braces-regexp))
5738 (org-export-with-sub-superscripts
5739 (list org-match-substring-regexp))))
5740 (re-latex
5741 (if org-export-with-LaTeX-fragments
5742 (mapcar (lambda (x) (nth 1 x)) latexs)))
5743 (re-macros
5744 (if org-export-with-TeX-macros
5745 (list (concat "\\\\"
5746 (regexp-opt
5747 (append
5749 (delq nil
5750 (mapcar 'car-safe
5751 (append org-entities-user
5752 org-entities)))
5753 (if (boundp 'org-latex-entities)
5754 (mapcar (lambda (x)
5755 (or (car-safe x) x))
5756 org-latex-entities)
5757 nil))
5758 'words))) ; FIXME
5760 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5761 (re-special (if org-export-with-special-strings
5762 (mapcar (lambda (x) (car x))
5763 org-export-html-special-string-regexps)))
5764 (re-rest
5765 (delq nil
5766 (list
5767 (if org-export-html-expand "@<[^>\n]+>")
5768 ))))
5769 (org-set-local
5770 'org-latex-and-specials-regexp
5771 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5772 re-rest) "\\|")))))
5774 (defun org-do-latex-and-special-faces (limit)
5775 "Run through the buffer and add overlays to links."
5776 (when org-latex-and-specials-regexp
5777 (let (rtn d)
5778 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5779 limit t))
5780 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5781 'face))
5782 '(org-code org-verbatim underline)))
5783 (progn
5784 (setq rtn t
5785 d (cond ((member (char-after (1+ (match-beginning 0)))
5786 '(?_ ?^)) 1)
5787 (t 0)))
5788 (font-lock-prepend-text-property
5789 (+ d (match-beginning 0)) (match-end 0)
5790 'face 'org-latex-and-export-specials)
5791 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5792 '(font-lock-multiline t)))))
5793 rtn)))
5795 (defun org-restart-font-lock ()
5796 "Restart `font-lock-mode', to force refontification."
5797 (when (and (boundp 'font-lock-mode) font-lock-mode)
5798 (font-lock-mode -1)
5799 (font-lock-mode 1)))
5801 (defun org-all-targets (&optional radio)
5802 "Return a list of all targets in this file.
5803 With optional argument RADIO, only find radio targets."
5804 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5805 rtn)
5806 (save-excursion
5807 (goto-char (point-min))
5808 (while (re-search-forward re nil t)
5809 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5810 rtn)))
5812 (defun org-make-target-link-regexp (targets)
5813 "Make regular expression matching all strings in TARGETS.
5814 The regular expression finds the targets also if there is a line break
5815 between words."
5816 (and targets
5817 (concat
5818 "\\<\\("
5819 (mapconcat
5820 (lambda (x)
5821 (setq x (regexp-quote x))
5822 (while (string-match " +" x)
5823 (setq x (replace-match "\\s-+" t t x)))
5825 targets
5826 "\\|")
5827 "\\)\\>")))
5829 (defun org-activate-tags (limit)
5830 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5831 (progn
5832 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5833 (add-text-properties (match-beginning 1) (match-end 1)
5834 (list 'mouse-face 'highlight
5835 'keymap org-mouse-map))
5836 (org-rear-nonsticky-at (match-end 1))
5837 t)))
5839 (defun org-outline-level ()
5840 "Compute the outline level of the heading at point.
5841 If this is called at a normal headline, the level is the number of stars.
5842 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5843 (save-excursion
5844 (if (not (condition-case nil
5845 (org-back-to-heading t)
5846 (error nil)))
5848 (looking-at org-outline-regexp)
5849 (1- (- (match-end 0) (match-beginning 0))))))
5851 (defvar org-font-lock-keywords nil)
5853 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5854 "Regular expression matching a property line.")
5856 (defvar org-font-lock-hook nil
5857 "Functions to be called for special font lock stuff.")
5859 (defvar org-font-lock-set-keywords-hook nil
5860 "Functions that can manipulate `org-font-lock-extra-keywords'.
5861 This is called after `org-font-lock-extra-keywords' is defined, but before
5862 it is installed to be used by font lock. This can be useful if something
5863 needs to be inserted at a specific position in the font-lock sequence.")
5865 (defun org-font-lock-hook (limit)
5866 "Run `org-font-lock-hook' within LIMIT."
5867 (run-hook-with-args 'org-font-lock-hook limit))
5869 (defun org-set-font-lock-defaults ()
5870 "Set font lock defaults for the current buffer."
5871 (let* ((em org-fontify-emphasized-text)
5872 (lk org-activate-links)
5873 (org-font-lock-extra-keywords
5874 (list
5875 ;; Call the hook
5876 '(org-font-lock-hook)
5877 ;; Headlines
5878 `(,(if org-fontify-whole-heading-line
5879 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5880 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5881 (1 (org-get-level-face 1))
5882 (2 (org-get-level-face 2))
5883 (3 (org-get-level-face 3)))
5884 ;; Table lines
5885 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5886 (1 'org-table t))
5887 ;; Table internals
5888 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5889 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5890 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5891 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5892 ;; Drawers
5893 (list org-drawer-regexp '(0 'org-special-keyword t))
5894 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5895 ;; Properties
5896 (list org-property-re
5897 '(1 'org-special-keyword t)
5898 '(3 'org-property-value t))
5899 ;; Links
5900 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5901 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5902 (if (memq 'plain lk) '(org-activate-plain-links))
5903 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5904 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5905 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5906 (if (memq 'footnote lk) '(org-activate-footnote-links))
5907 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5908 '(org-hide-wide-columns (0 nil append))
5909 ;; TODO keyword
5910 (list (format org-heading-keyword-regexp-format
5911 org-todo-regexp)
5912 '(2 (org-get-todo-face 2) t))
5913 ;; DONE
5914 (if org-fontify-done-headline
5915 (list (format org-heading-keyword-regexp-format
5916 (concat
5917 "\\(?:"
5918 (mapconcat 'regexp-quote org-done-keywords "\\|")
5919 "\\)"))
5920 '(2 'org-headline-done t))
5921 nil)
5922 ;; Priorities
5923 '(org-font-lock-add-priority-faces)
5924 ;; Tags
5925 '(org-font-lock-add-tag-faces)
5926 ;; Special keywords
5927 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5928 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5929 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5930 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5931 ;; Emphasis
5932 (if em
5933 (if (featurep 'xemacs)
5934 '(org-do-emphasis-faces (0 nil append))
5935 '(org-do-emphasis-faces)))
5936 ;; Checkboxes
5937 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5938 1 'org-checkbox prepend)
5939 (if (cdr (assq 'checkbox org-list-automatic-rules))
5940 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5941 (0 (org-get-checkbox-statistics-face) t)))
5942 ;; Description list items
5943 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5944 1 'org-list-dt prepend)
5945 ;; ARCHIVEd headings
5946 (list (concat
5947 org-outline-regexp-bol
5948 "\\(.*:" org-archive-tag ":.*\\)")
5949 '(1 'org-archived prepend))
5950 ;; Specials
5951 '(org-do-latex-and-special-faces)
5952 '(org-fontify-entities)
5953 '(org-raise-scripts)
5954 ;; Code
5955 '(org-activate-code (1 'org-code t))
5956 ;; COMMENT
5957 (list (format org-heading-keyword-regexp-format
5958 (concat "\\("
5959 org-comment-string "\\|" org-quote-string
5960 "\\)"))
5961 '(2 'org-special-keyword t))
5962 ;; Blocks and meta lines
5963 '(org-fontify-meta-lines-and-blocks)
5965 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5966 (run-hooks 'org-font-lock-set-keywords-hook)
5967 ;; Now set the full font-lock-keywords
5968 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5969 (org-set-local 'font-lock-defaults
5970 '(org-font-lock-keywords t nil nil backward-paragraph))
5971 (kill-local-variable 'font-lock-keywords) nil))
5973 (defun org-toggle-pretty-entities ()
5974 "Toggle the composition display of entities as UTF8 characters."
5975 (interactive)
5976 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5977 (org-restart-font-lock)
5978 (if org-pretty-entities
5979 (message "Entities are displayed as UTF8 characters")
5980 (save-restriction
5981 (widen)
5982 (org-decompose-region (point-min) (point-max))
5983 (message "Entities are displayed plain"))))
5985 (defvar org-custom-properties-overlays nil
5986 "List of overlays used for custom properties.")
5987 (make-variable-buffer-local 'org-custom-properties-overlays)
5989 (defun org-toggle-custom-properties-visibility ()
5990 "Display or hide properties in `org-custom-properties'."
5991 (interactive)
5992 (if org-custom-properties-overlays
5993 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5994 (setq org-custom-properties-overlays nil))
5995 (unless (not org-custom-properties)
5996 (save-excursion
5997 (save-restriction
5998 (widen)
5999 (goto-char (point-min))
6000 (while (re-search-forward org-property-re nil t)
6001 (mapc (lambda(p)
6002 (when (equal p (substring (match-string 1) 1 -1))
6003 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6004 (overlay-put o 'invisible t)
6005 (overlay-put o 'org-custom-property t)
6006 (push o org-custom-properties-overlays))))
6007 org-custom-properties)))))))
6009 (defun org-fontify-entities (limit)
6010 "Find an entity to fontify."
6011 (let (ee)
6012 (when org-pretty-entities
6013 (catch 'match
6014 (while (re-search-forward
6015 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6016 limit t)
6017 (if (and (not (org-in-indented-comment-line))
6018 (setq ee (org-entity-get (match-string 1)))
6019 (= (length (nth 6 ee)) 1))
6020 (let*
6021 ((end (if (equal (match-string 2) "{}")
6022 (match-end 2)
6023 (match-end 1))))
6024 (add-text-properties
6025 (match-beginning 0) end
6026 (list 'font-lock-fontified t))
6027 (compose-region (match-beginning 0) end
6028 (nth 6 ee) nil)
6029 (backward-char 1)
6030 (throw 'match t))))
6031 nil))))
6033 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6034 "Fontify string S like in Org-mode."
6035 (with-temp-buffer
6036 (insert s)
6037 (let ((org-odd-levels-only odd-levels))
6038 (org-mode)
6039 (font-lock-fontify-buffer)
6040 (buffer-string))))
6042 (defvar org-m nil)
6043 (defvar org-l nil)
6044 (defvar org-f nil)
6045 (defun org-get-level-face (n)
6046 "Get the right face for match N in font-lock matching of headlines."
6047 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6048 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6049 (if org-cycle-level-faces
6050 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6051 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6052 (cond
6053 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6054 ((eq n 2) org-f)
6055 (t (if org-level-color-stars-only nil org-f))))
6058 (defun org-get-todo-face (kwd)
6059 "Get the right face for a TODO keyword KWD.
6060 If KWD is a number, get the corresponding match group."
6061 (if (numberp kwd) (setq kwd (match-string kwd)))
6062 (or (org-face-from-face-or-color
6063 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6064 (and (member kwd org-done-keywords) 'org-done)
6065 'org-todo))
6067 (defun org-face-from-face-or-color (context inherit face-or-color)
6068 "Create a face list that inherits INHERIT, but sets the foreground color.
6069 When FACE-OR-COLOR is not a string, just return it."
6070 (if (stringp face-or-color)
6071 (list :inherit inherit
6072 (cdr (assoc context org-faces-easy-properties))
6073 face-or-color)
6074 face-or-color))
6076 (defun org-font-lock-add-tag-faces (limit)
6077 "Add the special tag faces."
6078 (when (and org-tag-faces org-tags-special-faces-re)
6079 (while (re-search-forward org-tags-special-faces-re limit t)
6080 (add-text-properties (match-beginning 1) (match-end 1)
6081 (list 'face (org-get-tag-face 1)
6082 'font-lock-fontified t))
6083 (backward-char 1))))
6085 (defun org-font-lock-add-priority-faces (limit)
6086 "Add the special priority faces."
6087 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6088 (when (save-match-data (org-at-heading-p))
6089 (add-text-properties
6090 (match-beginning 0) (match-end 0)
6091 (list 'face (or (org-face-from-face-or-color
6092 'priority 'org-special-keyword
6093 (cdr (assoc (char-after (match-beginning 1))
6094 org-priority-faces)))
6095 'org-special-keyword)
6096 'font-lock-fontified t)))))
6098 (defun org-get-tag-face (kwd)
6099 "Get the right face for a TODO keyword KWD.
6100 If KWD is a number, get the corresponding match group."
6101 (if (numberp kwd) (setq kwd (match-string kwd)))
6102 (or (org-face-from-face-or-color
6103 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6104 'org-tag))
6106 (defun org-unfontify-region (beg end &optional maybe_loudly)
6107 "Remove fontification and activation overlays from links."
6108 (font-lock-default-unfontify-region beg end)
6109 (let* ((buffer-undo-list t)
6110 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6111 (inhibit-modification-hooks t)
6112 deactivate-mark buffer-file-name buffer-file-truename)
6113 (org-decompose-region beg end)
6114 (remove-text-properties beg end
6115 '(mouse-face t keymap t org-linked-text t
6116 invisible t intangible t
6117 org-no-flyspell t org-emphasis t))
6118 (org-remove-font-lock-display-properties beg end)))
6120 (defconst org-script-display '(((raise -0.3) (height 0.7))
6121 ((raise 0.3) (height 0.7))
6122 ((raise -0.5))
6123 ((raise 0.5)))
6124 "Display properties for showing superscripts and subscripts.")
6126 (defun org-remove-font-lock-display-properties (beg end)
6127 "Remove specific display properties that have been added by font lock.
6128 The will remove the raise properties that are used to show superscripts
6129 and subscripts."
6130 (let (next prop)
6131 (while (< beg end)
6132 (setq next (next-single-property-change beg 'display nil end)
6133 prop (get-text-property beg 'display))
6134 (if (member prop org-script-display)
6135 (put-text-property beg next 'display nil))
6136 (setq beg next))))
6138 (defun org-raise-scripts (limit)
6139 "Add raise properties to sub/superscripts."
6140 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6141 (if (re-search-forward
6142 (if (eq org-use-sub-superscripts t)
6143 org-match-substring-regexp
6144 org-match-substring-with-braces-regexp)
6145 limit t)
6146 (let* ((pos (point)) table-p comment-p
6147 (mpos (match-beginning 3))
6148 (emph-p (get-text-property mpos 'org-emphasis))
6149 (link-p (get-text-property mpos 'mouse-face))
6150 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6151 (goto-char (point-at-bol))
6152 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6153 comment-p (org-looking-at-p "[ \t]*#"))
6154 (goto-char pos)
6155 ;; FIXME: Should we go back one character here, for a_b^c
6156 ;; (goto-char (1- pos)) ;????????????????????
6157 (if (or comment-p emph-p link-p keyw-p)
6159 (put-text-property (match-beginning 3) (match-end 0)
6160 'display
6161 (if (equal (char-after (match-beginning 2)) ?^)
6162 (nth (if table-p 3 1) org-script-display)
6163 (nth (if table-p 2 0) org-script-display)))
6164 (add-text-properties (match-beginning 2) (match-end 2)
6165 (list 'invisible t
6166 'org-dwidth t 'org-dwidth-n 1))
6167 (if (and (eq (char-after (match-beginning 3)) ?{)
6168 (eq (char-before (match-end 3)) ?}))
6169 (progn
6170 (add-text-properties
6171 (match-beginning 3) (1+ (match-beginning 3))
6172 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6173 (add-text-properties
6174 (1- (match-end 3)) (match-end 3)
6175 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6176 t)))))
6178 ;;;; Visibility cycling, including org-goto and indirect buffer
6180 ;;; Cycling
6182 (defvar org-cycle-global-status nil)
6183 (make-variable-buffer-local 'org-cycle-global-status)
6184 (defvar org-cycle-subtree-status nil)
6185 (make-variable-buffer-local 'org-cycle-subtree-status)
6187 (defvar org-inlinetask-min-level)
6189 ;;;###autoload
6190 (defun org-cycle (&optional arg)
6191 "TAB-action and visibility cycling for Org-mode.
6193 This is the command invoked in Org-mode by the TAB key. Its main purpose
6194 is outline visibility cycling, but it also invokes other actions
6195 in special contexts.
6197 - When this function is called with a prefix argument, rotate the entire
6198 buffer through 3 states (global cycling)
6199 1. OVERVIEW: Show only top-level headlines.
6200 2. CONTENTS: Show all headlines of all levels, but no body text.
6201 3. SHOW ALL: Show everything.
6202 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6203 determined by the variable `org-startup-folded', and by any VISIBILITY
6204 properties in the buffer.
6205 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6206 including any drawers.
6208 - When inside a table, re-align the table and move to the next field.
6210 - When point is at the beginning of a headline, rotate the subtree started
6211 by this line through 3 different states (local cycling)
6212 1. FOLDED: Only the main headline is shown.
6213 2. CHILDREN: The main headline and the direct children are shown.
6214 From this state, you can move to one of the children
6215 and zoom in further.
6216 3. SUBTREE: Show the entire subtree, including body text.
6217 If there is no subtree, switch directly from CHILDREN to FOLDED.
6219 - When point is at the beginning of an empty headline and the variable
6220 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6221 of the headline by demoting and promoting it to likely levels. This
6222 speeds up creation document structure by pressing TAB once or several
6223 times right after creating a new headline.
6225 - When there is a numeric prefix, go up to a heading with level ARG, do
6226 a `show-subtree' and return to the previous cursor position. If ARG
6227 is negative, go up that many levels.
6229 - When point is not at the beginning of a headline, execute the global
6230 binding for TAB, which is re-indenting the line. See the option
6231 `org-cycle-emulate-tab' for details.
6233 - Special case: if point is at the beginning of the buffer and there is
6234 no headline in line 1, this function will act as if called with prefix arg
6235 (C-u TAB, same as S-TAB) also when called without prefix arg.
6236 But only if also the variable `org-cycle-global-at-bob' is t."
6237 (interactive "P")
6238 (org-load-modules-maybe)
6239 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6240 (and org-cycle-level-after-item/entry-creation
6241 (or (org-cycle-level)
6242 (org-cycle-item-indentation))))
6243 (let* ((limit-level
6244 (or org-cycle-max-level
6245 (and (boundp 'org-inlinetask-min-level)
6246 org-inlinetask-min-level
6247 (1- org-inlinetask-min-level))))
6248 (nstars (and limit-level
6249 (if org-odd-levels-only
6250 (and limit-level (1- (* limit-level 2)))
6251 limit-level)))
6252 (org-outline-regexp
6253 (if (not (derived-mode-p 'org-mode))
6254 outline-regexp
6255 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6256 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6257 (not (looking-at org-outline-regexp))))
6258 (org-cycle-hook
6259 (if bob-special
6260 (delq 'org-optimize-window-after-visibility-change
6261 (copy-sequence org-cycle-hook))
6262 org-cycle-hook))
6263 (pos (point)))
6265 (if (or bob-special (equal arg '(4)))
6266 ;; special case: use global cycling
6267 (setq arg t))
6269 (cond
6271 ((equal arg '(16))
6272 (setq last-command 'dummy)
6273 (org-set-startup-visibility)
6274 (message "Startup visibility, plus VISIBILITY properties"))
6276 ((equal arg '(64))
6277 (show-all)
6278 (message "Entire buffer visible, including drawers"))
6280 ;; Table: enter it or move to the next field.
6281 ((org-at-table-p 'any)
6282 (if (org-at-table.el-p)
6283 (message "Use C-c ' to edit table.el tables")
6284 (if arg (org-table-edit-field t)
6285 (org-table-justify-field-maybe)
6286 (call-interactively 'org-table-next-field))))
6288 ((run-hook-with-args-until-success
6289 'org-tab-after-check-for-table-hook))
6291 ;; Global cycling: delegate to `org-cycle-internal-global'.
6292 ((eq arg t) (org-cycle-internal-global))
6294 ;; Drawers: delegate to `org-flag-drawer'.
6295 ((and org-drawers org-drawer-regexp
6296 (save-excursion
6297 (beginning-of-line 1)
6298 (looking-at org-drawer-regexp)))
6299 (org-flag-drawer ; toggle block visibility
6300 (not (get-char-property (match-end 0) 'invisible))))
6302 ;; Show-subtree, ARG levels up from here.
6303 ((integerp arg)
6304 (save-excursion
6305 (org-back-to-heading)
6306 (outline-up-heading (if (< arg 0) (- arg)
6307 (- (funcall outline-level) arg)))
6308 (org-show-subtree)))
6310 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6311 ((and (featurep 'org-inlinetask)
6312 (org-inlinetask-at-task-p)
6313 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6314 (org-inlinetask-toggle-visibility))
6316 ((org-try-cdlatex-tab))
6318 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6319 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6320 (save-excursion (beginning-of-line 1)
6321 (looking-at org-outline-regexp)))
6322 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6323 (org-cycle-internal-local))
6325 ;; From there: TAB emulation and template completion.
6326 (buffer-read-only (org-back-to-heading))
6328 ((run-hook-with-args-until-success
6329 'org-tab-after-check-for-cycling-hook))
6331 ((org-try-structure-completion))
6333 ((run-hook-with-args-until-success
6334 'org-tab-before-tab-emulation-hook))
6336 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6337 (or (not (bolp))
6338 (not (looking-at org-outline-regexp))))
6339 (call-interactively (global-key-binding "\t")))
6341 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6342 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6343 (or (and (eq org-cycle-emulate-tab 'white)
6344 (= (match-end 0) (point-at-eol)))
6345 (and (eq org-cycle-emulate-tab 'whitestart)
6346 (>= (match-end 0) pos))))
6348 (eq org-cycle-emulate-tab t))
6349 (call-interactively (global-key-binding "\t")))
6351 (t (save-excursion
6352 (org-back-to-heading)
6353 (org-cycle)))))))
6355 (defun org-cycle-internal-global ()
6356 "Do the global cycling action."
6357 ;; Hack to avoid display of messages for .org attachments in Gnus
6358 (let ((ga (string-match "\\*fontification" (buffer-name))))
6359 (cond
6360 ((and (eq last-command this-command)
6361 (eq org-cycle-global-status 'overview))
6362 ;; We just created the overview - now do table of contents
6363 ;; This can be slow in very large buffers, so indicate action
6364 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6365 (unless ga (message "CONTENTS..."))
6366 (org-content)
6367 (unless ga (message "CONTENTS...done"))
6368 (setq org-cycle-global-status 'contents)
6369 (run-hook-with-args 'org-cycle-hook 'contents))
6371 ((and (eq last-command this-command)
6372 (eq org-cycle-global-status 'contents))
6373 ;; We just showed the table of contents - now show everything
6374 (run-hook-with-args 'org-pre-cycle-hook 'all)
6375 (show-all)
6376 (unless ga (message "SHOW ALL"))
6377 (setq org-cycle-global-status 'all)
6378 (run-hook-with-args 'org-cycle-hook 'all))
6381 ;; Default action: go to overview
6382 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6383 (org-overview)
6384 (unless ga (message "OVERVIEW"))
6385 (setq org-cycle-global-status 'overview)
6386 (run-hook-with-args 'org-cycle-hook 'overview)))))
6388 (defun org-cycle-internal-local ()
6389 "Do the local cycling action."
6390 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6391 ;; First, determine end of headline (EOH), end of subtree or item
6392 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6393 (save-excursion
6394 (if (org-at-item-p)
6395 (progn
6396 (beginning-of-line)
6397 (setq struct (org-list-struct))
6398 (setq eoh (point-at-eol))
6399 (setq eos (org-list-get-item-end-before-blank (point) struct))
6400 (setq has-children (org-list-has-child-p (point) struct)))
6401 (org-back-to-heading)
6402 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6403 (setq eos (save-excursion
6404 (org-end-of-subtree t)
6405 (unless (eobp)
6406 (skip-chars-forward " \t\n"))
6407 (if (eobp) (point) (1- (point)))))
6408 (setq has-children
6409 (or (save-excursion
6410 (let ((level (funcall outline-level)))
6411 (outline-next-heading)
6412 (and (org-at-heading-p t)
6413 (> (funcall outline-level) level))))
6414 (save-excursion
6415 (org-list-search-forward (org-item-beginning-re) eos t)))))
6416 ;; Determine end invisible part of buffer (EOL)
6417 (beginning-of-line 2)
6418 ;; XEmacs doesn't have `next-single-char-property-change'
6419 (if (featurep 'xemacs)
6420 (while (and (not (eobp)) ;; this is like `next-line'
6421 (get-char-property (1- (point)) 'invisible))
6422 (beginning-of-line 2))
6423 (while (and (not (eobp)) ;; this is like `next-line'
6424 (get-char-property (1- (point)) 'invisible))
6425 (goto-char (next-single-char-property-change (point) 'invisible))
6426 (and (eolp) (beginning-of-line 2))))
6427 (setq eol (point)))
6428 ;; Find out what to do next and set `this-command'
6429 (cond
6430 ((= eos eoh)
6431 ;; Nothing is hidden behind this heading
6432 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6433 (message "EMPTY ENTRY")
6434 (setq org-cycle-subtree-status nil)
6435 (save-excursion
6436 (goto-char eos)
6437 (outline-next-heading)
6438 (if (outline-invisible-p) (org-flag-heading nil))))
6439 ((and (or (>= eol eos)
6440 (not (string-match "\\S-" (buffer-substring eol eos))))
6441 (or has-children
6442 (not (setq children-skipped
6443 org-cycle-skip-children-state-if-no-children))))
6444 ;; Entire subtree is hidden in one line: children view
6445 (run-hook-with-args 'org-pre-cycle-hook 'children)
6446 (if (org-at-item-p)
6447 (org-list-set-item-visibility (point-at-bol) struct 'children)
6448 (org-show-entry)
6449 (org-with-limited-levels (show-children))
6450 ;; FIXME: This slows down the func way too much.
6451 ;; How keep drawers hidden in subtree anyway?
6452 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6453 ;; (org-cycle-hide-drawers 'subtree))
6455 ;; Fold every list in subtree to top-level items.
6456 (when (eq org-cycle-include-plain-lists 'integrate)
6457 (save-excursion
6458 (org-back-to-heading)
6459 (while (org-list-search-forward (org-item-beginning-re) eos t)
6460 (beginning-of-line 1)
6461 (let* ((struct (org-list-struct))
6462 (prevs (org-list-prevs-alist struct))
6463 (end (org-list-get-bottom-point struct)))
6464 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6465 (org-list-get-all-items (point) struct prevs))
6466 (goto-char end))))))
6467 (message "CHILDREN")
6468 (save-excursion
6469 (goto-char eos)
6470 (outline-next-heading)
6471 (if (outline-invisible-p) (org-flag-heading nil)))
6472 (setq org-cycle-subtree-status 'children)
6473 (run-hook-with-args 'org-cycle-hook 'children))
6474 ((or children-skipped
6475 (and (eq last-command this-command)
6476 (eq org-cycle-subtree-status 'children)))
6477 ;; We just showed the children, or no children are there,
6478 ;; now show everything.
6479 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6480 (outline-flag-region eoh eos nil)
6481 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6482 (setq org-cycle-subtree-status 'subtree)
6483 (run-hook-with-args 'org-cycle-hook 'subtree))
6485 ;; Default action: hide the subtree.
6486 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6487 (outline-flag-region eoh eos t)
6488 (message "FOLDED")
6489 (setq org-cycle-subtree-status 'folded)
6490 (run-hook-with-args 'org-cycle-hook 'folded)))))
6492 ;;;###autoload
6493 (defun org-global-cycle (&optional arg)
6494 "Cycle the global visibility. For details see `org-cycle'.
6495 With \\[universal-argument] prefix arg, switch to startup visibility.
6496 With a numeric prefix, show all headlines up to that level."
6497 (interactive "P")
6498 (let ((org-cycle-include-plain-lists
6499 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6500 (cond
6501 ((integerp arg)
6502 (show-all)
6503 (hide-sublevels arg)
6504 (setq org-cycle-global-status 'contents))
6505 ((equal arg '(4))
6506 (org-set-startup-visibility)
6507 (message "Startup visibility, plus VISIBILITY properties."))
6509 (org-cycle '(4))))))
6511 (defun org-set-startup-visibility ()
6512 "Set the visibility required by startup options and properties."
6513 (cond
6514 ((eq org-startup-folded t)
6515 (org-cycle '(4)))
6516 ((eq org-startup-folded 'content)
6517 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6518 (org-cycle '(4)) (org-cycle '(4)))))
6519 (unless (eq org-startup-folded 'showeverything)
6520 (if org-hide-block-startup (org-hide-block-all))
6521 (org-set-visibility-according-to-property 'no-cleanup)
6522 (org-cycle-hide-archived-subtrees 'all)
6523 (org-cycle-hide-drawers 'all)
6524 (org-cycle-show-empty-lines t)))
6526 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6527 "Switch subtree visibilities according to :VISIBILITY: property."
6528 (interactive)
6529 (let (org-show-entry-below state)
6530 (save-excursion
6531 (goto-char (point-min))
6532 (while (re-search-forward
6533 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6534 nil t)
6535 (setq state (match-string 1))
6536 (save-excursion
6537 (org-back-to-heading t)
6538 (hide-subtree)
6539 (org-reveal)
6540 (cond
6541 ((equal state '("fold" "folded"))
6542 (hide-subtree))
6543 ((equal state "children")
6544 (org-show-hidden-entry)
6545 (show-children))
6546 ((equal state "content")
6547 (save-excursion
6548 (save-restriction
6549 (org-narrow-to-subtree)
6550 (org-content))))
6551 ((member state '("all" "showall"))
6552 (show-subtree)))))
6553 (unless no-cleanup
6554 (org-cycle-hide-archived-subtrees 'all)
6555 (org-cycle-hide-drawers 'all)
6556 (org-cycle-show-empty-lines 'all)))))
6558 ;; This function uses outline-regexp instead of the more fundamental
6559 ;; org-outline-regexp so that org-cycle-global works outside of Org
6560 ;; buffers, where outline-regexp is needed.
6561 (defun org-overview ()
6562 "Switch to overview mode, showing only top-level headlines.
6563 Really, this shows all headlines with level equal or greater than the level
6564 of the first headline in the buffer. This is important, because if the
6565 first headline is not level one, then (hide-sublevels 1) gives confusing
6566 results."
6567 (interactive)
6568 (let ((level (save-excursion
6569 (goto-char (point-min))
6570 (if (re-search-forward (concat "^" outline-regexp) nil t)
6571 (progn
6572 (goto-char (match-beginning 0))
6573 (funcall outline-level))))))
6574 (and level (hide-sublevels level))))
6576 (defun org-content (&optional arg)
6577 "Show all headlines in the buffer, like a table of contents.
6578 With numerical argument N, show content up to level N."
6579 (interactive "P")
6580 (save-excursion
6581 ;; Visit all headings and show their offspring
6582 (and (integerp arg) (org-overview))
6583 (goto-char (point-max))
6584 (catch 'exit
6585 (while (and (progn (condition-case nil
6586 (outline-previous-visible-heading 1)
6587 (error (goto-char (point-min))))
6589 (looking-at org-outline-regexp))
6590 (if (integerp arg)
6591 (show-children (1- arg))
6592 (show-branches))
6593 (if (bobp) (throw 'exit nil))))))
6596 (defun org-optimize-window-after-visibility-change (state)
6597 "Adjust the window after a change in outline visibility.
6598 This function is the default value of the hook `org-cycle-hook'."
6599 (when (get-buffer-window (current-buffer))
6600 (cond
6601 ((eq state 'content) nil)
6602 ((eq state 'all) nil)
6603 ((eq state 'folded) nil)
6604 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6605 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6607 (defun org-remove-empty-overlays-at (pos)
6608 "Remove outline overlays that do not contain non-white stuff."
6609 (mapc
6610 (lambda (o)
6611 (and (eq 'outline (overlay-get o 'invisible))
6612 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6613 (overlay-end o))))
6614 (delete-overlay o)))
6615 (overlays-at pos)))
6617 (defun org-clean-visibility-after-subtree-move ()
6618 "Fix visibility issues after moving a subtree."
6619 ;; First, find a reasonable region to look at:
6620 ;; Start two siblings above, end three below
6621 (let* ((beg (save-excursion
6622 (and (org-get-last-sibling)
6623 (org-get-last-sibling))
6624 (point)))
6625 (end (save-excursion
6626 (and (org-get-next-sibling)
6627 (org-get-next-sibling)
6628 (org-get-next-sibling))
6629 (if (org-at-heading-p)
6630 (point-at-eol)
6631 (point))))
6632 (level (looking-at "\\*+"))
6633 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6634 (save-excursion
6635 (save-restriction
6636 (narrow-to-region beg end)
6637 (when re
6638 ;; Properly fold already folded siblings
6639 (goto-char (point-min))
6640 (while (re-search-forward re nil t)
6641 (if (and (not (outline-invisible-p))
6642 (save-excursion
6643 (goto-char (point-at-eol)) (outline-invisible-p)))
6644 (hide-entry))))
6645 (org-cycle-show-empty-lines 'overview)
6646 (org-cycle-hide-drawers 'overview)))))
6648 (defun org-cycle-show-empty-lines (state)
6649 "Show empty lines above all visible headlines.
6650 The region to be covered depends on STATE when called through
6651 `org-cycle-hook'. Lisp program can use t for STATE to get the
6652 entire buffer covered. Note that an empty line is only shown if there
6653 are at least `org-cycle-separator-lines' empty lines before the headline."
6654 (when (not (= org-cycle-separator-lines 0))
6655 (save-excursion
6656 (let* ((n (abs org-cycle-separator-lines))
6657 (re (cond
6658 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6659 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6660 (t (let ((ns (number-to-string (- n 2))))
6661 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6662 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6663 beg end b e)
6664 (cond
6665 ((memq state '(overview contents t))
6666 (setq beg (point-min) end (point-max)))
6667 ((memq state '(children folded))
6668 (setq beg (point) end (progn (org-end-of-subtree t t)
6669 (beginning-of-line 2)
6670 (point)))))
6671 (when beg
6672 (goto-char beg)
6673 (while (re-search-forward re end t)
6674 (unless (get-char-property (match-end 1) 'invisible)
6675 (setq e (match-end 1))
6676 (if (< org-cycle-separator-lines 0)
6677 (setq b (save-excursion
6678 (goto-char (match-beginning 0))
6679 (org-back-over-empty-lines)
6680 (if (save-excursion
6681 (goto-char (max (point-min) (1- (point))))
6682 (org-at-heading-p))
6683 (1- (point))
6684 (point))))
6685 (setq b (match-beginning 1)))
6686 (outline-flag-region b e nil)))))))
6687 ;; Never hide empty lines at the end of the file.
6688 (save-excursion
6689 (goto-char (point-max))
6690 (outline-previous-heading)
6691 (outline-end-of-heading)
6692 (if (and (looking-at "[ \t\n]+")
6693 (= (match-end 0) (point-max)))
6694 (outline-flag-region (point) (match-end 0) nil))))
6696 (defun org-show-empty-lines-in-parent ()
6697 "Move to the parent and re-show empty lines before visible headlines."
6698 (save-excursion
6699 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6700 (org-cycle-show-empty-lines context))))
6702 (defun org-files-list ()
6703 "Return `org-agenda-files' list, plus all open org-mode files.
6704 This is useful for operations that need to scan all of a user's
6705 open and agenda-wise Org files."
6706 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6707 (dolist (buf (buffer-list))
6708 (with-current-buffer buf
6709 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6710 (let ((file (expand-file-name (buffer-file-name))))
6711 (unless (member file files)
6712 (push file files))))))
6713 files))
6715 (defsubst org-entry-beginning-position ()
6716 "Return the beginning position of the current entry."
6717 (save-excursion (outline-back-to-heading t) (point)))
6719 (defsubst org-entry-end-position ()
6720 "Return the end position of the current entry."
6721 (save-excursion (outline-next-heading) (point)))
6723 (defun org-cycle-hide-drawers (state)
6724 "Re-hide all drawers after a visibility state change."
6725 (when (and (derived-mode-p 'org-mode)
6726 (not (memq state '(overview folded contents))))
6727 (save-excursion
6728 (let* ((globalp (memq state '(contents all)))
6729 (beg (if globalp (point-min) (point)))
6730 (end (if globalp (point-max)
6731 (if (eq state 'children)
6732 (save-excursion (outline-next-heading) (point))
6733 (org-end-of-subtree t)))))
6734 (goto-char beg)
6735 (while (re-search-forward org-drawer-regexp end t)
6736 (org-flag-drawer t))))))
6738 (defun org-cycle-hide-inline-tasks (state)
6739 "Re-hide inline task when switching to 'contents visibility state."
6740 (when (and (eq state 'contents)
6741 (boundp 'org-inlinetask-min-level)
6742 org-inlinetask-min-level)
6743 (hide-sublevels (1- org-inlinetask-min-level))))
6745 (defun org-flag-drawer (flag)
6746 "When FLAG is non-nil, hide the drawer we are within.
6747 Otherwise make it visible."
6748 (save-excursion
6749 (beginning-of-line 1)
6750 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6751 (let ((b (match-end 0)))
6752 (if (re-search-forward
6753 "^[ \t]*:END:"
6754 (save-excursion (outline-next-heading) (point)) t)
6755 (outline-flag-region b (point-at-eol) flag)
6756 (error ":END: line missing at position %s" b))))))
6758 (defun org-subtree-end-visible-p ()
6759 "Is the end of the current subtree visible?"
6760 (pos-visible-in-window-p
6761 (save-excursion (org-end-of-subtree t) (point))))
6763 (defun org-first-headline-recenter (&optional N)
6764 "Move cursor to the first headline and recenter the headline.
6765 Optional argument N means put the headline into the Nth line of the window."
6766 (goto-char (point-min))
6767 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6768 (beginning-of-line)
6769 (recenter (prefix-numeric-value N))))
6771 ;;; Saving and restoring visibility
6773 (defun org-outline-overlay-data (&optional use-markers)
6774 "Return a list of the locations of all outline overlays.
6775 These are overlays with the `invisible' property value `outline'.
6776 The return value is a list of cons cells, with start and stop
6777 positions for each overlay.
6778 If USE-MARKERS is set, return the positions as markers."
6779 (let (beg end)
6780 (save-excursion
6781 (save-restriction
6782 (widen)
6783 (delq nil
6784 (mapcar (lambda (o)
6785 (when (eq (overlay-get o 'invisible) 'outline)
6786 (setq beg (overlay-start o)
6787 end (overlay-end o))
6788 (and beg end (> end beg)
6789 (if use-markers
6790 (cons (move-marker (make-marker) beg)
6791 (move-marker (make-marker) end))
6792 (cons beg end)))))
6793 (overlays-in (point-min) (point-max))))))))
6795 (defun org-set-outline-overlay-data (data)
6796 "Create visibility overlays for all positions in DATA.
6797 DATA should have been made by `org-outline-overlay-data'."
6798 (let (o)
6799 (save-excursion
6800 (save-restriction
6801 (widen)
6802 (show-all)
6803 (mapc (lambda (c)
6804 (outline-flag-region (car c) (cdr c) t))
6805 data)))))
6807 ;;; Folding of blocks
6809 (defvar org-hide-block-overlays nil
6810 "Overlays hiding blocks.")
6811 (make-variable-buffer-local 'org-hide-block-overlays)
6813 (defun org-block-map (function &optional start end)
6814 "Call FUNCTION at the head of all source blocks in the current buffer.
6815 Optional arguments START and END can be used to limit the range."
6816 (let ((start (or start (point-min)))
6817 (end (or end (point-max))))
6818 (save-excursion
6819 (goto-char start)
6820 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6821 (save-excursion
6822 (save-match-data
6823 (goto-char (match-beginning 0))
6824 (funcall function)))))))
6826 (defun org-hide-block-toggle-all ()
6827 "Toggle the visibility of all blocks in the current buffer."
6828 (org-block-map #'org-hide-block-toggle))
6830 (defun org-hide-block-all ()
6831 "Fold all blocks in the current buffer."
6832 (interactive)
6833 (org-show-block-all)
6834 (org-block-map #'org-hide-block-toggle-maybe))
6836 (defun org-show-block-all ()
6837 "Unfold all blocks in the current buffer."
6838 (interactive)
6839 (mapc 'delete-overlay org-hide-block-overlays)
6840 (setq org-hide-block-overlays nil))
6842 (defun org-hide-block-toggle-maybe ()
6843 "Toggle visibility of block at point."
6844 (interactive)
6845 (let ((case-fold-search t))
6846 (if (save-excursion
6847 (beginning-of-line 1)
6848 (looking-at org-block-regexp))
6849 (progn (org-hide-block-toggle)
6850 t) ;; to signal that we took action
6851 nil))) ;; to signal that we did not
6853 (defun org-hide-block-toggle (&optional force)
6854 "Toggle the visibility of the current block."
6855 (interactive)
6856 (save-excursion
6857 (beginning-of-line)
6858 (if (re-search-forward org-block-regexp nil t)
6859 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6860 (end (match-end 0)) ;; end of entire body
6862 (if (memq t (mapcar (lambda (overlay)
6863 (eq (overlay-get overlay 'invisible)
6864 'org-hide-block))
6865 (overlays-at start)))
6866 (if (or (not force) (eq force 'off))
6867 (mapc (lambda (ov)
6868 (when (member ov org-hide-block-overlays)
6869 (setq org-hide-block-overlays
6870 (delq ov org-hide-block-overlays)))
6871 (when (eq (overlay-get ov 'invisible)
6872 'org-hide-block)
6873 (delete-overlay ov)))
6874 (overlays-at start)))
6875 (setq ov (make-overlay start end))
6876 (overlay-put ov 'invisible 'org-hide-block)
6877 ;; make the block accessible to isearch
6878 (overlay-put
6879 ov 'isearch-open-invisible
6880 (lambda (ov)
6881 (when (member ov org-hide-block-overlays)
6882 (setq org-hide-block-overlays
6883 (delq ov org-hide-block-overlays)))
6884 (when (eq (overlay-get ov 'invisible)
6885 'org-hide-block)
6886 (delete-overlay ov))))
6887 (push ov org-hide-block-overlays)))
6888 (error "Not looking at a source block"))))
6890 ;; org-tab-after-check-for-cycling-hook
6891 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6892 ;; Remove overlays when changing major mode
6893 (add-hook 'org-mode-hook
6894 (lambda () (org-add-hook 'change-major-mode-hook
6895 'org-show-block-all 'append 'local)))
6897 ;;; Org-goto
6899 (defvar org-goto-window-configuration nil)
6900 (defvar org-goto-marker nil)
6901 (defvar org-goto-map
6902 (let ((map (make-sparse-keymap)))
6903 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6904 (while (setq cmd (pop cmds))
6905 (substitute-key-definition cmd cmd map global-map)))
6906 (suppress-keymap map)
6907 (org-defkey map "\C-m" 'org-goto-ret)
6908 (org-defkey map [(return)] 'org-goto-ret)
6909 (org-defkey map [(left)] 'org-goto-left)
6910 (org-defkey map [(right)] 'org-goto-right)
6911 (org-defkey map [(control ?g)] 'org-goto-quit)
6912 (org-defkey map "\C-i" 'org-cycle)
6913 (org-defkey map [(tab)] 'org-cycle)
6914 (org-defkey map [(down)] 'outline-next-visible-heading)
6915 (org-defkey map [(up)] 'outline-previous-visible-heading)
6916 (if org-goto-auto-isearch
6917 (if (fboundp 'define-key-after)
6918 (define-key-after map [t] 'org-goto-local-auto-isearch)
6919 nil)
6920 (org-defkey map "q" 'org-goto-quit)
6921 (org-defkey map "n" 'outline-next-visible-heading)
6922 (org-defkey map "p" 'outline-previous-visible-heading)
6923 (org-defkey map "f" 'outline-forward-same-level)
6924 (org-defkey map "b" 'outline-backward-same-level)
6925 (org-defkey map "u" 'outline-up-heading))
6926 (org-defkey map "/" 'org-occur)
6927 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6928 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6929 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6930 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6931 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6932 map))
6934 (defconst org-goto-help
6935 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6936 RET=jump to location [Q]uit and return to previous location
6937 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6939 (defvar org-goto-start-pos) ; dynamically scoped parameter
6941 ;; FIXME: Docstring does not mention both interfaces
6942 (defun org-goto (&optional alternative-interface)
6943 "Look up a different location in the current file, keeping current visibility.
6945 When you want look-up or go to a different location in a
6946 document, the fastest way is often to fold the entire buffer and
6947 then dive into the tree. This method has the disadvantage, that
6948 the previous location will be folded, which may not be what you
6949 want.
6951 This command works around this by showing a copy of the current
6952 buffer in an indirect buffer, in overview mode. You can dive
6953 into the tree in that copy, use org-occur and incremental search
6954 to find a location. When pressing RET or `Q', the command
6955 returns to the original buffer in which the visibility is still
6956 unchanged. After RET it will also jump to the location selected
6957 in the indirect buffer and expose the headline hierarchy above.
6959 With a prefix argument, use the alternative interface: e.g. if
6960 `org-goto-interface' is 'outline use 'outline-path-completion."
6961 (interactive "P")
6962 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6963 (org-refile-use-outline-path t)
6964 (org-refile-target-verify-function nil)
6965 (interface
6966 (if (not alternative-interface)
6967 org-goto-interface
6968 (if (eq org-goto-interface 'outline)
6969 'outline-path-completion
6970 'outline)))
6971 (org-goto-start-pos (point))
6972 (selected-point
6973 (if (eq interface 'outline)
6974 (car (org-get-location (current-buffer) org-goto-help))
6975 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6976 (org-refile-check-position pa)
6977 (nth 3 pa)))))
6978 (if selected-point
6979 (progn
6980 (org-mark-ring-push org-goto-start-pos)
6981 (goto-char selected-point)
6982 (if (or (outline-invisible-p) (org-invisible-p2))
6983 (org-show-context 'org-goto)))
6984 (message "Quit"))))
6986 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6987 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6988 (defvar org-goto-local-auto-isearch-map) ; defined below
6990 (defun org-get-location (buf help)
6991 "Let the user select a location in the Org-mode buffer BUF.
6992 This function uses a recursive edit. It returns the selected position
6993 or nil."
6994 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6995 (isearch-hide-immediately nil)
6996 (isearch-search-fun-function
6997 (lambda () 'org-goto-local-search-headings))
6998 (org-goto-selected-point org-goto-exit-command)
6999 (pop-up-frames nil)
7000 (special-display-buffer-names nil)
7001 (special-display-regexps nil)
7002 (special-display-function nil))
7003 (save-excursion
7004 (save-window-excursion
7005 (delete-other-windows)
7006 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7007 (org-pop-to-buffer-same-window
7008 (condition-case nil
7009 (make-indirect-buffer (current-buffer) "*org-goto*")
7010 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7011 (with-output-to-temp-buffer "*Help*"
7012 (princ help))
7013 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7014 (setq buffer-read-only nil)
7015 (let ((org-startup-truncated t)
7016 (org-startup-folded nil)
7017 (org-startup-align-all-tables nil))
7018 (org-mode)
7019 (org-overview))
7020 (setq buffer-read-only t)
7021 (if (and (boundp 'org-goto-start-pos)
7022 (integer-or-marker-p org-goto-start-pos))
7023 (let ((org-show-hierarchy-above t)
7024 (org-show-siblings t)
7025 (org-show-following-heading t))
7026 (goto-char org-goto-start-pos)
7027 (and (outline-invisible-p) (org-show-context)))
7028 (goto-char (point-min)))
7029 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7030 (message "Select location and press RET")
7031 (use-local-map org-goto-map)
7032 (recursive-edit)
7034 (kill-buffer "*org-goto*")
7035 (cons org-goto-selected-point org-goto-exit-command)))
7037 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7038 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7039 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7040 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7042 (defun org-goto-local-search-headings (string bound noerror)
7043 "Search and make sure that any matches are in headlines."
7044 (catch 'return
7045 (while (if isearch-forward
7046 (search-forward string bound noerror)
7047 (search-backward string bound noerror))
7048 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7049 (and (member :headline context)
7050 (not (member :tags context))))
7051 (throw 'return (point))))))
7053 (defun org-goto-local-auto-isearch ()
7054 "Start isearch."
7055 (interactive)
7056 (goto-char (point-min))
7057 (let ((keys (this-command-keys)))
7058 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7059 (isearch-mode t)
7060 (isearch-process-search-char (string-to-char keys)))))
7062 (defun org-goto-ret (&optional arg)
7063 "Finish `org-goto' by going to the new location."
7064 (interactive "P")
7065 (setq org-goto-selected-point (point)
7066 org-goto-exit-command 'return)
7067 (throw 'exit nil))
7069 (defun org-goto-left ()
7070 "Finish `org-goto' by going to the new location."
7071 (interactive)
7072 (if (org-at-heading-p)
7073 (progn
7074 (beginning-of-line 1)
7075 (setq org-goto-selected-point (point)
7076 org-goto-exit-command 'left)
7077 (throw 'exit nil))
7078 (error "Not on a heading")))
7080 (defun org-goto-right ()
7081 "Finish `org-goto' by going to the new location."
7082 (interactive)
7083 (if (org-at-heading-p)
7084 (progn
7085 (setq org-goto-selected-point (point)
7086 org-goto-exit-command 'right)
7087 (throw 'exit nil))
7088 (error "Not on a heading")))
7090 (defun org-goto-quit ()
7091 "Finish `org-goto' without cursor motion."
7092 (interactive)
7093 (setq org-goto-selected-point nil)
7094 (setq org-goto-exit-command 'quit)
7095 (throw 'exit nil))
7097 ;;; Indirect buffer display of subtrees
7099 (defvar org-indirect-dedicated-frame nil
7100 "This is the frame being used for indirect tree display.")
7101 (defvar org-last-indirect-buffer nil)
7103 (defun org-tree-to-indirect-buffer (&optional arg)
7104 "Create indirect buffer and narrow it to current subtree.
7105 With a numerical prefix ARG, go up to this level and then take that tree.
7106 If ARG is negative, go up that many levels.
7108 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7109 indirect buffer previously made with this command, to avoid proliferation of
7110 indirect buffers. However, when you call the command with a \
7111 \\[universal-argument] prefix, or
7112 when `org-indirect-buffer-display' is `new-frame', the last buffer
7113 is kept so that you can work with several indirect buffers at the same time.
7114 If `org-indirect-buffer-display' is `dedicated-frame', the \
7115 \\[universal-argument] prefix also
7116 requests that a new frame be made for the new buffer, so that the dedicated
7117 frame is not changed."
7118 (interactive "P")
7119 (let ((cbuf (current-buffer))
7120 (cwin (selected-window))
7121 (pos (point))
7122 beg end level heading ibuf)
7123 (save-excursion
7124 (org-back-to-heading t)
7125 (when (numberp arg)
7126 (setq level (org-outline-level))
7127 (if (< arg 0) (setq arg (+ level arg)))
7128 (while (> (setq level (org-outline-level)) arg)
7129 (org-up-heading-safe)))
7130 (setq beg (point)
7131 heading (org-get-heading))
7132 (org-end-of-subtree t t)
7133 (if (org-at-heading-p) (backward-char 1))
7134 (setq end (point)))
7135 (if (and (buffer-live-p org-last-indirect-buffer)
7136 (not (eq org-indirect-buffer-display 'new-frame))
7137 (not arg))
7138 (kill-buffer org-last-indirect-buffer))
7139 (setq ibuf (org-get-indirect-buffer cbuf)
7140 org-last-indirect-buffer ibuf)
7141 (cond
7142 ((or (eq org-indirect-buffer-display 'new-frame)
7143 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7144 (select-frame (make-frame))
7145 (delete-other-windows)
7146 (org-pop-to-buffer-same-window ibuf)
7147 (org-set-frame-title heading))
7148 ((eq org-indirect-buffer-display 'dedicated-frame)
7149 (raise-frame
7150 (select-frame (or (and org-indirect-dedicated-frame
7151 (frame-live-p org-indirect-dedicated-frame)
7152 org-indirect-dedicated-frame)
7153 (setq org-indirect-dedicated-frame (make-frame)))))
7154 (delete-other-windows)
7155 (org-pop-to-buffer-same-window ibuf)
7156 (org-set-frame-title (concat "Indirect: " heading)))
7157 ((eq org-indirect-buffer-display 'current-window)
7158 (org-pop-to-buffer-same-window ibuf))
7159 ((eq org-indirect-buffer-display 'other-window)
7160 (pop-to-buffer ibuf))
7161 (t (error "Invalid value")))
7162 (if (featurep 'xemacs)
7163 (save-excursion (org-mode) (turn-on-font-lock)))
7164 (narrow-to-region beg end)
7165 (show-all)
7166 (goto-char pos)
7167 (run-hook-with-args 'org-cycle-hook 'all)
7168 (and (window-live-p cwin) (select-window cwin))))
7170 (defun org-get-indirect-buffer (&optional buffer)
7171 (setq buffer (or buffer (current-buffer)))
7172 (let ((n 1) (base (buffer-name buffer)) bname)
7173 (while (buffer-live-p
7174 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7175 (setq n (1+ n)))
7176 (condition-case nil
7177 (make-indirect-buffer buffer bname 'clone)
7178 (error (make-indirect-buffer buffer bname)))))
7180 (defun org-set-frame-title (title)
7181 "Set the title of the current frame to the string TITLE."
7182 ;; FIXME: how to name a single frame in XEmacs???
7183 (unless (featurep 'xemacs)
7184 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7186 ;;;; Structure editing
7188 ;;; Inserting headlines
7190 (defun org-previous-line-empty-p ()
7191 (save-excursion
7192 (and (not (bobp))
7193 (or (beginning-of-line 0) t)
7194 (save-match-data
7195 (looking-at "[ \t]*$")))))
7197 (defun org-insert-heading (&optional force-heading invisible-ok)
7198 "Insert a new heading or item with same depth at point.
7199 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7200 If point is at the beginning of a headline, insert a sibling before the
7201 current headline. If point is not at the beginning, split the line,
7202 create the new headline with the text in the current line after point
7203 \(but see also the variable `org-M-RET-may-split-line').
7205 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7206 This is important for non-interactive uses of the command."
7207 (interactive "P")
7208 (if (or (= (buffer-size) 0)
7209 (and (not (save-excursion
7210 (and (ignore-errors (org-back-to-heading invisible-ok))
7211 (org-at-heading-p))))
7212 (or force-heading (not (org-in-item-p)))))
7213 (progn
7214 (insert "\n* ")
7215 (run-hooks 'org-insert-heading-hook))
7216 (when (or force-heading (not (org-insert-item)))
7217 (let* ((empty-line-p nil)
7218 (level nil)
7219 (on-heading (org-at-heading-p))
7220 (head (save-excursion
7221 (condition-case nil
7222 (progn
7223 (org-back-to-heading invisible-ok)
7224 (when (and (not on-heading)
7225 (featurep 'org-inlinetask)
7226 (integerp org-inlinetask-min-level)
7227 (>= (length (match-string 0))
7228 org-inlinetask-min-level))
7229 ;; Find a heading level before the inline task
7230 (while (and (setq level (org-up-heading-safe))
7231 (>= level org-inlinetask-min-level)))
7232 (if (org-at-heading-p)
7233 (org-back-to-heading invisible-ok)
7234 (error "This should not happen")))
7235 (setq empty-line-p (org-previous-line-empty-p))
7236 (match-string 0))
7237 (error "*"))))
7238 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7239 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7240 pos hide-previous previous-pos)
7241 (cond
7242 ((and (org-at-heading-p) (bolp)
7243 (or (bobp)
7244 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7245 ;; insert before the current line
7246 (open-line (if blank 2 1)))
7247 ((and (bolp)
7248 (not org-insert-heading-respect-content)
7249 (or (bobp)
7250 (save-excursion
7251 (backward-char 1) (not (outline-invisible-p)))))
7252 ;; insert right here
7253 nil)
7255 ;; somewhere in the line
7256 (save-excursion
7257 (setq previous-pos (point-at-bol))
7258 (end-of-line)
7259 (setq hide-previous (outline-invisible-p)))
7260 (and org-insert-heading-respect-content (org-show-subtree))
7261 (let ((split
7262 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7263 (save-excursion
7264 (let ((p (point)))
7265 (goto-char (point-at-bol))
7266 (and (looking-at org-complex-heading-regexp)
7267 (match-beginning 4)
7268 (> p (match-beginning 4)))))))
7269 tags pos)
7270 (cond
7271 (org-insert-heading-respect-content
7272 (org-end-of-subtree nil t)
7273 (when (featurep 'org-inlinetask)
7274 (while (and (not (eobp))
7275 (looking-at "\\(\\*+\\)[ \t]+")
7276 (>= (length (match-string 1))
7277 org-inlinetask-min-level))
7278 (org-end-of-subtree nil t)))
7279 (or (bolp) (newline))
7280 (or (org-previous-line-empty-p)
7281 (and blank (newline)))
7282 (open-line 1))
7283 ((org-at-heading-p)
7284 (when hide-previous
7285 (show-children)
7286 (org-show-entry))
7287 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7288 (setq tags (and (match-end 2) (match-string 2)))
7289 (and (match-end 1)
7290 (delete-region (match-beginning 1) (match-end 1)))
7291 (setq pos (point-at-bol))
7292 (or split (end-of-line 1))
7293 (delete-horizontal-space)
7294 (if (string-match "\\`\\*+\\'"
7295 (buffer-substring (point-at-bol) (point)))
7296 (insert " "))
7297 (newline (if blank 2 1))
7298 (when tags
7299 (save-excursion
7300 (goto-char pos)
7301 (end-of-line 1)
7302 (insert " " tags)
7303 (org-set-tags nil 'align))))
7305 (or split (end-of-line 1))
7306 (newline (if blank 2 1)))))))
7307 (insert head) (just-one-space)
7308 (setq pos (point))
7309 (end-of-line 1)
7310 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7311 (when (and org-insert-heading-respect-content hide-previous)
7312 (save-excursion
7313 (goto-char previous-pos)
7314 (hide-subtree)))
7315 (run-hooks 'org-insert-heading-hook)))))
7317 (defun org-get-heading (&optional no-tags no-todo)
7318 "Return the heading of the current entry, without the stars.
7319 When NO-TAGS is non-nil, don't include tags.
7320 When NO-TODO is non-nil, don't include TODO keywords."
7321 (save-excursion
7322 (org-back-to-heading t)
7323 (cond
7324 ((and no-tags no-todo)
7325 (looking-at org-complex-heading-regexp)
7326 (match-string 4))
7327 (no-tags
7328 (looking-at (concat org-outline-regexp
7329 "\\(.*?\\)"
7330 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7331 (match-string 1))
7332 (no-todo
7333 (looking-at org-todo-line-regexp)
7334 (match-string 3))
7335 (t (looking-at org-heading-regexp)
7336 (match-string 2)))))
7338 (defun org-heading-components ()
7339 "Return the components of the current heading.
7340 This is a list with the following elements:
7341 - the level as an integer
7342 - the reduced level, different if `org-odd-levels-only' is set.
7343 - the TODO keyword, or nil
7344 - the priority character, like ?A, or nil if no priority is given
7345 - the headline text itself, or the tags string if no headline text
7346 - the tags string, or nil."
7347 (save-excursion
7348 (org-back-to-heading t)
7349 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7350 (list (length (match-string 1))
7351 (org-reduced-level (length (match-string 1)))
7352 (org-match-string-no-properties 2)
7353 (and (match-end 3) (aref (match-string 3) 2))
7354 (org-match-string-no-properties 4)
7355 (org-match-string-no-properties 5)))))
7357 (defun org-get-entry ()
7358 "Get the entry text, after heading, entire subtree."
7359 (save-excursion
7360 (org-back-to-heading t)
7361 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7363 (defun org-insert-heading-after-current ()
7364 "Insert a new heading with same level as current, after current subtree."
7365 (interactive)
7366 (org-back-to-heading)
7367 (org-insert-heading)
7368 (org-move-subtree-down)
7369 (end-of-line 1))
7371 (defun org-insert-heading-respect-content ()
7372 (interactive)
7373 (let ((org-insert-heading-respect-content t))
7374 (org-insert-heading t)))
7376 (defun org-insert-todo-heading-respect-content (&optional force-state)
7377 (interactive "P")
7378 (let ((org-insert-heading-respect-content t))
7379 (org-insert-todo-heading force-state t)))
7381 (defun org-insert-todo-heading (arg &optional force-heading)
7382 "Insert a new heading with the same level and TODO state as current heading.
7383 If the heading has no TODO state, or if the state is DONE, use the first
7384 state (TODO by default). Also with prefix arg, force first state."
7385 (interactive "P")
7386 (when (or force-heading (not (org-insert-item 'checkbox)))
7387 (org-insert-heading force-heading)
7388 (save-excursion
7389 (org-back-to-heading)
7390 (outline-previous-heading)
7391 (looking-at org-todo-line-regexp))
7392 (let*
7393 ((new-mark-x
7394 (if (or arg
7395 (not (match-beginning 2))
7396 (member (match-string 2) org-done-keywords))
7397 (car org-todo-keywords-1)
7398 (match-string 2)))
7399 (new-mark
7401 (run-hook-with-args-until-success
7402 'org-todo-get-default-hook new-mark-x nil)
7403 new-mark-x)))
7404 (beginning-of-line 1)
7405 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7406 (if org-treat-insert-todo-heading-as-state-change
7407 (org-todo new-mark)
7408 (insert new-mark " "))))
7409 (when org-provide-todo-statistics
7410 (org-update-parent-todo-statistics))))
7412 (defun org-insert-subheading (arg)
7413 "Insert a new subheading and demote it.
7414 Works for outline headings and for plain lists alike."
7415 (interactive "P")
7416 (org-insert-heading arg)
7417 (cond
7418 ((org-at-heading-p) (org-do-demote))
7419 ((org-at-item-p) (org-indent-item))))
7421 (defun org-insert-todo-subheading (arg)
7422 "Insert a new subheading with TODO keyword or checkbox and demote it.
7423 Works for outline headings and for plain lists alike."
7424 (interactive "P")
7425 (org-insert-todo-heading arg)
7426 (cond
7427 ((org-at-heading-p) (org-do-demote))
7428 ((org-at-item-p) (org-indent-item))))
7430 ;;; Promotion and Demotion
7432 (defvar org-after-demote-entry-hook nil
7433 "Hook run after an entry has been demoted.
7434 The cursor will be at the beginning of the entry.
7435 When a subtree is being demoted, the hook will be called for each node.")
7437 (defvar org-after-promote-entry-hook nil
7438 "Hook run after an entry has been promoted.
7439 The cursor will be at the beginning of the entry.
7440 When a subtree is being promoted, the hook will be called for each node.")
7442 (defun org-promote-subtree ()
7443 "Promote the entire subtree.
7444 See also `org-promote'."
7445 (interactive)
7446 (save-excursion
7447 (org-with-limited-levels (org-map-tree 'org-promote)))
7448 (org-fix-position-after-promote))
7450 (defun org-demote-subtree ()
7451 "Demote the entire subtree. See `org-demote'.
7452 See also `org-promote'."
7453 (interactive)
7454 (save-excursion
7455 (org-with-limited-levels (org-map-tree 'org-demote)))
7456 (org-fix-position-after-promote))
7459 (defun org-do-promote ()
7460 "Promote the current heading higher up the tree.
7461 If the region is active in `transient-mark-mode', promote all headings
7462 in the region."
7463 (interactive)
7464 (save-excursion
7465 (if (org-region-active-p)
7466 (org-map-region 'org-promote (region-beginning) (region-end))
7467 (org-promote)))
7468 (org-fix-position-after-promote))
7470 (defun org-do-demote ()
7471 "Demote the current heading lower down the tree.
7472 If the region is active in `transient-mark-mode', demote all headings
7473 in the region."
7474 (interactive)
7475 (save-excursion
7476 (if (org-region-active-p)
7477 (org-map-region 'org-demote (region-beginning) (region-end))
7478 (org-demote)))
7479 (org-fix-position-after-promote))
7481 (defun org-fix-position-after-promote ()
7482 "Make sure that after pro/demotion cursor position is right."
7483 (let ((pos (point)))
7484 (when (save-excursion
7485 (beginning-of-line 1)
7486 (looking-at org-todo-line-regexp)
7487 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7488 (cond ((eobp) (insert " "))
7489 ((eolp) (insert " "))
7490 ((equal (char-after) ?\ ) (forward-char 1))))))
7492 (defun org-current-level ()
7493 "Return the level of the current entry, or nil if before the first headline.
7494 The level is the number of stars at the beginning of the headline."
7495 (save-excursion
7496 (org-with-limited-levels
7497 (if (ignore-errors (org-back-to-heading t))
7498 (funcall outline-level)))))
7500 (defun org-get-previous-line-level ()
7501 "Return the outline depth of the last headline before the current line.
7502 Returns 0 for the first headline in the buffer, and nil if before the
7503 first headline."
7504 (let ((current-level (org-current-level))
7505 (prev-level (when (> (line-number-at-pos) 1)
7506 (save-excursion
7507 (beginning-of-line 0)
7508 (org-current-level)))))
7509 (cond ((null current-level) nil) ; Before first headline
7510 ((null prev-level) 0) ; At first headline
7511 (prev-level))))
7513 (defun org-reduced-level (l)
7514 "Compute the effective level of a heading.
7515 This takes into account the setting of `org-odd-levels-only'."
7516 (cond
7517 ((zerop l) 0)
7518 (org-odd-levels-only (1+ (floor (/ l 2))))
7519 (t l)))
7521 (defun org-level-increment ()
7522 "Return the number of stars that will be added or removed at a
7523 time to headlines when structure editing, based on the value of
7524 `org-odd-levels-only'."
7525 (if org-odd-levels-only 2 1))
7527 (defun org-get-valid-level (level &optional change)
7528 "Rectify a level change under the influence of `org-odd-levels-only'
7529 LEVEL is a current level, CHANGE is by how much the level should be
7530 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7531 even level numbers will become the next higher odd number."
7532 (if org-odd-levels-only
7533 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7534 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7535 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7536 (max 1 (+ level (or change 0)))))
7538 (if (boundp 'define-obsolete-function-alias)
7539 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7540 (define-obsolete-function-alias 'org-get-legal-level
7541 'org-get-valid-level)
7542 (define-obsolete-function-alias 'org-get-legal-level
7543 'org-get-valid-level "23.1")))
7545 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7546 ;; ̀org-with-limited-levels'
7547 (defun org-promote ()
7548 "Promote the current heading higher up the tree.
7549 If the region is active in `transient-mark-mode', promote all headings
7550 in the region."
7551 (org-back-to-heading t)
7552 (let* ((level (save-match-data (funcall outline-level)))
7553 (after-change-functions (remove 'flyspell-after-change-function
7554 after-change-functions))
7555 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7556 (diff (abs (- level (length up-head) -1))))
7557 (cond ((and (= level 1) org-called-with-limited-levels
7558 org-allow-promoting-top-level-subtree)
7559 (replace-match "# " nil t))
7560 ((= level 1)
7561 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7562 (t (replace-match up-head nil t)))
7563 ;; Fixup tag positioning
7564 (unless (= level 1)
7565 (and org-auto-align-tags (org-set-tags nil t))
7566 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7567 (run-hooks 'org-after-promote-entry-hook)))
7569 (defun org-demote ()
7570 "Demote the current heading lower down the tree.
7571 If the region is active in `transient-mark-mode', demote all headings
7572 in the region."
7573 (org-back-to-heading t)
7574 (let* ((level (save-match-data (funcall outline-level)))
7575 (after-change-functions (remove 'flyspell-after-change-function
7576 after-change-functions))
7577 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7578 (diff (abs (- level (length down-head) -1))))
7579 (replace-match down-head nil t)
7580 ;; Fixup tag positioning
7581 (and org-auto-align-tags (org-set-tags nil t))
7582 (if org-adapt-indentation (org-fixup-indentation diff))
7583 (run-hooks 'org-after-demote-entry-hook)))
7585 (defun org-cycle-level ()
7586 "Cycle the level of an empty headline through possible states.
7587 This goes first to child, then to parent, level, then up the hierarchy.
7588 After top level, it switches back to sibling level."
7589 (interactive)
7590 (let ((org-adapt-indentation nil))
7591 (when (org-point-at-end-of-empty-headline)
7592 (setq this-command 'org-cycle-level) ; Only needed for caching
7593 (let ((cur-level (org-current-level))
7594 (prev-level (org-get-previous-line-level)))
7595 (cond
7596 ;; If first headline in file, promote to top-level.
7597 ((= prev-level 0)
7598 (loop repeat (/ (- cur-level 1) (org-level-increment))
7599 do (org-do-promote)))
7600 ;; If same level as prev, demote one.
7601 ((= prev-level cur-level)
7602 (org-do-demote))
7603 ;; If parent is top-level, promote to top level if not already.
7604 ((= prev-level 1)
7605 (loop repeat (/ (- cur-level 1) (org-level-increment))
7606 do (org-do-promote)))
7607 ;; If top-level, return to prev-level.
7608 ((= cur-level 1)
7609 (loop repeat (/ (- prev-level 1) (org-level-increment))
7610 do (org-do-demote)))
7611 ;; If less than prev-level, promote one.
7612 ((< cur-level prev-level)
7613 (org-do-promote))
7614 ;; If deeper than prev-level, promote until higher than
7615 ;; prev-level.
7616 ((> cur-level prev-level)
7617 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7618 do (org-do-promote))))
7619 t))))
7621 (defun org-map-tree (fun)
7622 "Call FUN for every heading underneath the current one."
7623 (org-back-to-heading)
7624 (let ((level (funcall outline-level)))
7625 (save-excursion
7626 (funcall fun)
7627 (while (and (progn
7628 (outline-next-heading)
7629 (> (funcall outline-level) level))
7630 (not (eobp)))
7631 (funcall fun)))))
7633 (defun org-map-region (fun beg end)
7634 "Call FUN for every heading between BEG and END."
7635 (let ((org-ignore-region t))
7636 (save-excursion
7637 (setq end (copy-marker end))
7638 (goto-char beg)
7639 (if (and (re-search-forward org-outline-regexp-bol nil t)
7640 (< (point) end))
7641 (funcall fun))
7642 (while (and (progn
7643 (outline-next-heading)
7644 (< (point) end))
7645 (not (eobp)))
7646 (funcall fun)))))
7648 (defvar org-property-end-re) ; silence byte-compiler
7649 (defun org-fixup-indentation (diff)
7650 "Change the indentation in the current entry by DIFF.
7651 However, if any line in the current entry has no indentation, or if it
7652 would end up with no indentation after the change, nothing at all is done."
7653 (save-excursion
7654 (let ((end (save-excursion (outline-next-heading)
7655 (point-marker)))
7656 (prohibit (if (> diff 0)
7657 "^\\S-"
7658 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7659 col)
7660 (unless (save-excursion (end-of-line 1)
7661 (re-search-forward prohibit end t))
7662 (while (and (< (point) end)
7663 (re-search-forward "^[ \t]+" end t))
7664 (goto-char (match-end 0))
7665 (setq col (current-column))
7666 (if (< diff 0) (replace-match ""))
7667 (org-indent-to-column (+ diff col))))
7668 (move-marker end nil))))
7670 (defun org-convert-to-odd-levels ()
7671 "Convert an org-mode file with all levels allowed to one with odd levels.
7672 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7673 level 5 etc."
7674 (interactive)
7675 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7676 (let ((outline-level 'org-outline-level)
7677 (org-odd-levels-only nil) n)
7678 (save-excursion
7679 (goto-char (point-min))
7680 (while (re-search-forward "^\\*\\*+ " nil t)
7681 (setq n (- (length (match-string 0)) 2))
7682 (while (>= (setq n (1- n)) 0)
7683 (org-demote))
7684 (end-of-line 1))))))
7686 (defun org-convert-to-oddeven-levels ()
7687 "Convert an org-mode file with only odd levels to one with odd/even levels.
7688 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7689 file contains a section with an even level, conversion would
7690 destroy the structure of the file. An error is signaled in this
7691 case."
7692 (interactive)
7693 (goto-char (point-min))
7694 ;; First check if there are no even levels
7695 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7696 (org-show-context t)
7697 (error "Not all levels are odd in this file. Conversion not possible"))
7698 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7699 (let ((outline-regexp org-outline-regexp)
7700 (outline-level 'org-outline-level)
7701 (org-odd-levels-only nil) n)
7702 (save-excursion
7703 (goto-char (point-min))
7704 (while (re-search-forward "^\\*\\*+ " nil t)
7705 (setq n (/ (1- (length (match-string 0))) 2))
7706 (while (>= (setq n (1- n)) 0)
7707 (org-promote))
7708 (end-of-line 1))))))
7710 (defun org-tr-level (n)
7711 "Make N odd if required."
7712 (if org-odd-levels-only (1+ (/ n 2)) n))
7714 ;;; Vertical tree motion, cutting and pasting of subtrees
7716 (defun org-move-subtree-up (&optional arg)
7717 "Move the current subtree up past ARG headlines of the same level."
7718 (interactive "p")
7719 (org-move-subtree-down (- (prefix-numeric-value arg))))
7721 (defun org-move-subtree-down (&optional arg)
7722 "Move the current subtree down past ARG headlines of the same level."
7723 (interactive "p")
7724 (setq arg (prefix-numeric-value arg))
7725 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7726 'org-get-last-sibling))
7727 (ins-point (make-marker))
7728 (cnt (abs arg))
7729 (col (current-column))
7730 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7731 ;; Select the tree
7732 (org-back-to-heading)
7733 (setq beg0 (point))
7734 (save-excursion
7735 (setq ne-beg (org-back-over-empty-lines))
7736 (setq beg (point)))
7737 (save-match-data
7738 (save-excursion (outline-end-of-heading)
7739 (setq folded (outline-invisible-p)))
7740 (outline-end-of-subtree))
7741 (outline-next-heading)
7742 (setq ne-end (org-back-over-empty-lines))
7743 (setq end (point))
7744 (goto-char beg0)
7745 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7746 ;; include less whitespace
7747 (save-excursion
7748 (goto-char beg)
7749 (forward-line (- ne-beg ne-end))
7750 (setq beg (point))))
7751 ;; Find insertion point, with error handling
7752 (while (> cnt 0)
7753 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7754 (progn (goto-char beg0)
7755 (error "Cannot move past superior level or buffer limit")))
7756 (setq cnt (1- cnt)))
7757 (if (> arg 0)
7758 ;; Moving forward - still need to move over subtree
7759 (progn (org-end-of-subtree t t)
7760 (save-excursion
7761 (org-back-over-empty-lines)
7762 (or (bolp) (newline)))))
7763 (setq ne-ins (org-back-over-empty-lines))
7764 (move-marker ins-point (point))
7765 (setq txt (buffer-substring beg end))
7766 (org-save-markers-in-region beg end)
7767 (delete-region beg end)
7768 (org-remove-empty-overlays-at beg)
7769 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7770 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7771 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7772 (let ((bbb (point)))
7773 (insert-before-markers txt)
7774 (org-reinstall-markers-in-region bbb)
7775 (move-marker ins-point bbb))
7776 (or (bolp) (insert "\n"))
7777 (setq ins-end (point))
7778 (goto-char ins-point)
7779 (org-skip-whitespace)
7780 (when (and (< arg 0)
7781 (org-first-sibling-p)
7782 (> ne-ins ne-beg))
7783 ;; Move whitespace back to beginning
7784 (save-excursion
7785 (goto-char ins-end)
7786 (let ((kill-whole-line t))
7787 (kill-line (- ne-ins ne-beg)) (point)))
7788 (insert (make-string (- ne-ins ne-beg) ?\n)))
7789 (move-marker ins-point nil)
7790 (if folded
7791 (hide-subtree)
7792 (org-show-entry)
7793 (show-children)
7794 (org-cycle-hide-drawers 'children))
7795 (org-clean-visibility-after-subtree-move)
7796 ;; move back to the initial column we were at
7797 (move-to-column col)))
7799 (defvar org-subtree-clip ""
7800 "Clipboard for cut and paste of subtrees.
7801 This is actually only a copy of the kill, because we use the normal kill
7802 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7804 (defvar org-subtree-clip-folded nil
7805 "Was the last copied subtree folded?
7806 This is used to fold the tree back after pasting.")
7808 (defun org-cut-subtree (&optional n)
7809 "Cut the current subtree into the clipboard.
7810 With prefix arg N, cut this many sequential subtrees.
7811 This is a short-hand for marking the subtree and then cutting it."
7812 (interactive "p")
7813 (org-copy-subtree n 'cut))
7815 (defun org-copy-subtree (&optional n cut force-store-markers)
7816 "Cut the current subtree into the clipboard.
7817 With prefix arg N, cut this many sequential subtrees.
7818 This is a short-hand for marking the subtree and then copying it.
7819 If CUT is non-nil, actually cut the subtree.
7820 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7821 of some markers in the region, even if CUT is non-nil. This is
7822 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7823 (interactive "p")
7824 (let (beg end folded (beg0 (point)))
7825 (if (org-called-interactively-p 'any)
7826 (org-back-to-heading nil) ; take what looks like a subtree
7827 (org-back-to-heading t)) ; take what is really there
7828 (org-back-over-empty-lines)
7829 (setq beg (point))
7830 (skip-chars-forward " \t\r\n")
7831 (save-match-data
7832 (save-excursion (outline-end-of-heading)
7833 (setq folded (outline-invisible-p)))
7834 (condition-case nil
7835 (org-forward-heading-same-level (1- n) t)
7836 (error nil))
7837 (org-end-of-subtree t t))
7838 (org-back-over-empty-lines)
7839 (setq end (point))
7840 (goto-char beg0)
7841 (when (> end beg)
7842 (setq org-subtree-clip-folded folded)
7843 (when (or cut force-store-markers)
7844 (org-save-markers-in-region beg end))
7845 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7846 (setq org-subtree-clip (current-kill 0))
7847 (message "%s: Subtree(s) with %d characters"
7848 (if cut "Cut" "Copied")
7849 (length org-subtree-clip)))))
7851 (defun org-paste-subtree (&optional level tree for-yank)
7852 "Paste the clipboard as a subtree, with modification of headline level.
7853 The entire subtree is promoted or demoted in order to match a new headline
7854 level.
7856 If the cursor is at the beginning of a headline, the same level as
7857 that headline is used to paste the tree
7859 If not, the new level is derived from the *visible* headings
7860 before and after the insertion point, and taken to be the inferior headline
7861 level of the two. So if the previous visible heading is level 3 and the
7862 next is level 4 (or vice versa), level 4 will be used for insertion.
7863 This makes sure that the subtree remains an independent subtree and does
7864 not swallow low level entries.
7866 You can also force a different level, either by using a numeric prefix
7867 argument, or by inserting the heading marker by hand. For example, if the
7868 cursor is after \"*****\", then the tree will be shifted to level 5.
7870 If optional TREE is given, use this text instead of the kill ring.
7872 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7873 move back over whitespace before inserting, and move point to the end of
7874 the inserted text when done."
7875 (interactive "P")
7876 (setq tree (or tree (and kill-ring (current-kill 0))))
7877 (unless (org-kill-is-subtree-p tree)
7878 (error "%s"
7879 (substitute-command-keys
7880 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7881 (org-with-limited-levels
7882 (let* ((visp (not (outline-invisible-p)))
7883 (txt tree)
7884 (^re_ "\\(\\*+\\)[ \t]*")
7885 (old-level (if (string-match org-outline-regexp-bol txt)
7886 (- (match-end 0) (match-beginning 0) 1)
7887 -1))
7888 (force-level (cond (level (prefix-numeric-value level))
7889 ((and (looking-at "[ \t]*$")
7890 (string-match
7891 "^\\*+$" (buffer-substring
7892 (point-at-bol) (point))))
7893 (- (match-end 1) (match-beginning 1)))
7894 ((and (bolp)
7895 (looking-at org-outline-regexp))
7896 (- (match-end 0) (point) 1))))
7897 (previous-level (save-excursion
7898 (condition-case nil
7899 (progn
7900 (outline-previous-visible-heading 1)
7901 (if (looking-at ^re_)
7902 (- (match-end 0) (match-beginning 0) 1)
7904 (error 1))))
7905 (next-level (save-excursion
7906 (condition-case nil
7907 (progn
7908 (or (looking-at org-outline-regexp)
7909 (outline-next-visible-heading 1))
7910 (if (looking-at ^re_)
7911 (- (match-end 0) (match-beginning 0) 1)
7913 (error 1))))
7914 (new-level (or force-level (max previous-level next-level)))
7915 (shift (if (or (= old-level -1)
7916 (= new-level -1)
7917 (= old-level new-level))
7919 (- new-level old-level)))
7920 (delta (if (> shift 0) -1 1))
7921 (func (if (> shift 0) 'org-demote 'org-promote))
7922 (org-odd-levels-only nil)
7923 beg end newend)
7924 ;; Remove the forced level indicator
7925 (if force-level
7926 (delete-region (point-at-bol) (point)))
7927 ;; Paste
7928 (beginning-of-line (if (bolp) 1 2))
7929 (unless for-yank (org-back-over-empty-lines))
7930 (setq beg (point))
7931 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7932 (insert-before-markers txt)
7933 (unless (string-match "\n\\'" txt) (insert "\n"))
7934 (setq newend (point))
7935 (org-reinstall-markers-in-region beg)
7936 (setq end (point))
7937 (goto-char beg)
7938 (skip-chars-forward " \t\n\r")
7939 (setq beg (point))
7940 (if (and (outline-invisible-p) visp)
7941 (save-excursion (outline-show-heading)))
7942 ;; Shift if necessary
7943 (unless (= shift 0)
7944 (save-restriction
7945 (narrow-to-region beg end)
7946 (while (not (= shift 0))
7947 (org-map-region func (point-min) (point-max))
7948 (setq shift (+ delta shift)))
7949 (goto-char (point-min))
7950 (setq newend (point-max))))
7951 (when (or (org-called-interactively-p 'interactive) for-yank)
7952 (message "Clipboard pasted as level %d subtree" new-level))
7953 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7954 kill-ring
7955 (eq org-subtree-clip (current-kill 0))
7956 org-subtree-clip-folded)
7957 ;; The tree was folded before it was killed/copied
7958 (hide-subtree))
7959 (and for-yank (goto-char newend)))))
7961 (defun org-kill-is-subtree-p (&optional txt)
7962 "Check if the current kill is an outline subtree, or a set of trees.
7963 Returns nil if kill does not start with a headline, or if the first
7964 headline level is not the largest headline level in the tree.
7965 So this will actually accept several entries of equal levels as well,
7966 which is OK for `org-paste-subtree'.
7967 If optional TXT is given, check this string instead of the current kill."
7968 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7969 (re (org-get-limited-outline-regexp))
7970 (^re (concat "^" re))
7971 (start-level (and kill
7972 (string-match
7973 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7974 kill)
7975 (- (match-end 2) (match-beginning 2) 1)))
7976 (start (1+ (or (match-beginning 2) -1))))
7977 (if (not start-level)
7978 (progn
7979 nil) ;; does not even start with a heading
7980 (catch 'exit
7981 (while (setq start (string-match ^re kill (1+ start)))
7982 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7983 (throw 'exit nil)))
7984 t))))
7986 (defvar org-markers-to-move nil
7987 "Markers that should be moved with a cut-and-paste operation.
7988 Those markers are stored together with their positions relative to
7989 the start of the region.")
7991 (defun org-save-markers-in-region (beg end)
7992 "Check markers in region.
7993 If these markers are between BEG and END, record their position relative
7994 to BEG, so that after moving the block of text, we can put the markers back
7995 into place.
7996 This function gets called just before an entry or tree gets cut from the
7997 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7998 called immediately, to move the markers with the entries."
7999 (setq org-markers-to-move nil)
8000 (when (featurep 'org-clock)
8001 (org-clock-save-markers-for-cut-and-paste beg end))
8002 (when (featurep 'org-agenda)
8003 (org-agenda-save-markers-for-cut-and-paste beg end)))
8005 (defun org-check-and-save-marker (marker beg end)
8006 "Check if MARKER is between BEG and END.
8007 If yes, remember the marker and the distance to BEG."
8008 (when (and (marker-buffer marker)
8009 (equal (marker-buffer marker) (current-buffer)))
8010 (if (and (>= marker beg) (< marker end))
8011 (push (cons marker (- marker beg)) org-markers-to-move))))
8013 (defun org-reinstall-markers-in-region (beg)
8014 "Move all remembered markers to their position relative to BEG."
8015 (mapc (lambda (x)
8016 (move-marker (car x) (+ beg (cdr x))))
8017 org-markers-to-move)
8018 (setq org-markers-to-move nil))
8020 (defun org-narrow-to-subtree ()
8021 "Narrow buffer to the current subtree."
8022 (interactive)
8023 (save-excursion
8024 (save-match-data
8025 (org-with-limited-levels
8026 (narrow-to-region
8027 (progn (org-back-to-heading t) (point))
8028 (progn (org-end-of-subtree t t)
8029 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8030 (point)))))))
8032 (defun org-narrow-to-block ()
8033 "Narrow buffer to the current block."
8034 (interactive)
8035 (let* ((case-fold-search t)
8036 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8037 "^[ \t]*#\\+end_.*")))
8038 (if blockp
8039 (narrow-to-region (car blockp) (cdr blockp))
8040 (error "Not in a block"))))
8042 (eval-when-compile
8043 (defvar org-property-drawer-re))
8045 (defvar org-property-start-re) ;; defined below
8046 (defun org-clone-subtree-with-time-shift (n &optional shift)
8047 "Clone the task (subtree) at point N times.
8048 The clones will be inserted as siblings.
8050 In interactive use, the user will be prompted for the number of
8051 clones to be produced, and for a time SHIFT, which may be a
8052 repeater as used in time stamps, for example `+3d'.
8054 When a valid repeater is given and the entry contains any time
8055 stamps, the clones will become a sequence in time, with time
8056 stamps in the subtree shifted for each clone produced. If SHIFT
8057 is nil or the empty string, time stamps will be left alone. The
8058 ID property of the original subtree is removed.
8060 If the original subtree did contain time stamps with a repeater,
8061 the following will happen:
8062 - the repeater will be removed in each clone
8063 - an additional clone will be produced, with the current, unshifted
8064 date(s) in the entry.
8065 - the original entry will be placed *after* all the clones, with
8066 repeater intact.
8067 - the start days in the repeater in the original entry will be shifted
8068 to past the last clone.
8069 In this way you can spell out a number of instances of a repeating task,
8070 and still retain the repeater to cover future instances of the task."
8071 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8072 (let (beg end template task idprop
8073 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8074 (drawer-re org-drawer-regexp))
8075 (if (not (and (integerp n) (> n 0)))
8076 (error "Invalid number of replications %s" n))
8077 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8078 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8079 shift)))
8080 (error "Invalid shift specification %s" shift))
8081 (when doshift
8082 (setq shift-n (string-to-number (match-string 1 shift))
8083 shift-what (cdr (assoc (match-string 2 shift)
8084 '(("d" . day) ("w" . week)
8085 ("m" . month) ("y" . year))))))
8086 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8087 (setq nmin 1 nmax n)
8088 (org-back-to-heading t)
8089 (setq beg (point))
8090 (setq idprop (org-entry-get nil "ID"))
8091 (org-end-of-subtree t t)
8092 (or (bolp) (insert "\n"))
8093 (setq end (point))
8094 (setq template (buffer-substring beg end))
8095 (when (and doshift
8096 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8097 (delete-region beg end)
8098 (setq end beg)
8099 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8100 (goto-char end)
8101 (loop for n from nmin to nmax do
8102 ;; prepare clone
8103 (with-temp-buffer
8104 (insert template)
8105 (org-mode)
8106 (goto-char (point-min))
8107 (org-show-subtree)
8108 (and idprop (if org-clone-delete-id
8109 (org-entry-delete nil "ID")
8110 (org-id-get-create t)))
8111 (unless (= n 0)
8112 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8113 (kill-whole-line))
8114 (goto-char (point-min))
8115 (while (re-search-forward drawer-re nil t)
8116 (mapc (lambda (d)
8117 (org-remove-empty-drawer-at d (point))) org-drawers)))
8118 (goto-char (point-min))
8119 (when doshift
8120 (while (re-search-forward org-ts-regexp-both nil t)
8121 (org-timestamp-change (* n shift-n) shift-what))
8122 (unless (= n n-no-remove)
8123 (goto-char (point-min))
8124 (while (re-search-forward org-ts-regexp nil t)
8125 (save-excursion
8126 (goto-char (match-beginning 0))
8127 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8128 (delete-region (match-beginning 1) (match-end 1)))))))
8129 (setq task (buffer-string)))
8130 (insert task))
8131 (goto-char beg)))
8133 ;;; Outline Sorting
8135 (defun org-sort (with-case)
8136 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8137 Optional argument WITH-CASE means sort case-sensitively."
8138 (interactive "P")
8139 (cond
8140 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8141 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8143 (org-call-with-arg 'org-sort-entries with-case))))
8145 (defun org-sort-remove-invisible (s)
8146 (remove-text-properties 0 (length s) org-rm-props s)
8147 (while (string-match org-bracket-link-regexp s)
8148 (setq s (replace-match (if (match-end 2)
8149 (match-string 3 s)
8150 (match-string 1 s)) t t s)))
8153 (defvar org-priority-regexp) ; defined later in the file
8155 (defvar org-after-sorting-entries-or-items-hook nil
8156 "Hook that is run after a bunch of entries or items have been sorted.
8157 When children are sorted, the cursor is in the parent line when this
8158 hook gets called. When a region or a plain list is sorted, the cursor
8159 will be in the first entry of the sorted region/list.")
8161 (defun org-sort-entries
8162 (&optional with-case sorting-type getkey-func compare-func property)
8163 "Sort entries on a certain level of an outline tree.
8164 If there is an active region, the entries in the region are sorted.
8165 Else, if the cursor is before the first entry, sort the top-level items.
8166 Else, the children of the entry at point are sorted.
8168 Sorting can be alphabetically, numerically, by date/time as given by
8169 a time stamp, by a property or by priority.
8171 The command prompts for the sorting type unless it has been given to the
8172 function through the SORTING-TYPE argument, which needs to be a character,
8173 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8174 precise meaning of each character:
8176 n Numerically, by converting the beginning of the entry/item to a number.
8177 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8178 t By date/time, either the first active time stamp in the entry, or, if
8179 none exist, by the first inactive one.
8180 s By the scheduled date/time.
8181 d By deadline date/time.
8182 c By creation time, which is assumed to be the first inactive time stamp
8183 at the beginning of a line.
8184 p By priority according to the cookie.
8185 r By the value of a property.
8187 Capital letters will reverse the sort order.
8189 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8190 called with point at the beginning of the record. It must return either
8191 a string or a number that should serve as the sorting key for that record.
8193 Comparing entries ignores case by default. However, with an optional argument
8194 WITH-CASE, the sorting considers case as well."
8195 (interactive "P")
8196 (let ((case-func (if with-case 'identity 'downcase))
8197 start beg end stars re re2
8198 txt what tmp)
8199 ;; Find beginning and end of region to sort
8200 (cond
8201 ((org-region-active-p)
8202 ;; we will sort the region
8203 (setq end (region-end)
8204 what "region")
8205 (goto-char (region-beginning))
8206 (if (not (org-at-heading-p)) (outline-next-heading))
8207 (setq start (point)))
8208 ((or (org-at-heading-p)
8209 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8210 ;; we will sort the children of the current headline
8211 (org-back-to-heading)
8212 (setq start (point)
8213 end (progn (org-end-of-subtree t t)
8214 (or (bolp) (insert "\n"))
8215 (org-back-over-empty-lines)
8216 (point))
8217 what "children")
8218 (goto-char start)
8219 (show-subtree)
8220 (outline-next-heading))
8222 ;; we will sort the top-level entries in this file
8223 (goto-char (point-min))
8224 (or (org-at-heading-p) (outline-next-heading))
8225 (setq start (point))
8226 (goto-char (point-max))
8227 (beginning-of-line 1)
8228 (when (looking-at ".*?\\S-")
8229 ;; File ends in a non-white line
8230 (end-of-line 1)
8231 (insert "\n"))
8232 (setq end (point-max))
8233 (setq what "top-level")
8234 (goto-char start)
8235 (show-all)))
8237 (setq beg (point))
8238 (if (>= beg end) (error "Nothing to sort"))
8240 (looking-at "\\(\\*+\\)")
8241 (setq stars (match-string 1)
8242 re (concat "^" (regexp-quote stars) " +")
8243 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8244 txt (buffer-substring beg end))
8245 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8246 (if (and (not (equal stars "*")) (string-match re2 txt))
8247 (error "Region to sort contains a level above the first entry"))
8249 (unless sorting-type
8250 (message
8251 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8252 [t]ime [s]cheduled [d]eadline [c]reated
8253 A/N/T/S/D/C/P/O/F means reversed:"
8254 what)
8255 (setq sorting-type (read-char-exclusive))
8257 (and (= (downcase sorting-type) ?f)
8258 (setq getkey-func
8259 (org-icompleting-read "Sort using function: "
8260 obarray 'fboundp t nil nil))
8261 (setq getkey-func (intern getkey-func)))
8263 (and (= (downcase sorting-type) ?r)
8264 (setq property
8265 (org-icompleting-read "Property: "
8266 (mapcar 'list (org-buffer-property-keys t))
8267 nil t))))
8269 (message "Sorting entries...")
8271 (save-restriction
8272 (narrow-to-region start end)
8273 (let ((dcst (downcase sorting-type))
8274 (case-fold-search nil)
8275 (now (current-time)))
8276 (sort-subr
8277 (/= dcst sorting-type)
8278 ;; This function moves to the beginning character of the "record" to
8279 ;; be sorted.
8280 (lambda nil
8281 (if (re-search-forward re nil t)
8282 (goto-char (match-beginning 0))
8283 (goto-char (point-max))))
8284 ;; This function moves to the last character of the "record" being
8285 ;; sorted.
8286 (lambda nil
8287 (save-match-data
8288 (condition-case nil
8289 (outline-forward-same-level 1)
8290 (error
8291 (goto-char (point-max))))))
8292 ;; This function returns the value that gets sorted against.
8293 (lambda nil
8294 (cond
8295 ((= dcst ?n)
8296 (if (looking-at org-complex-heading-regexp)
8297 (string-to-number (match-string 4))
8298 nil))
8299 ((= dcst ?a)
8300 (if (looking-at org-complex-heading-regexp)
8301 (funcall case-func (match-string 4))
8302 nil))
8303 ((= dcst ?t)
8304 (let ((end (save-excursion (outline-next-heading) (point))))
8305 (if (or (re-search-forward org-ts-regexp end t)
8306 (re-search-forward org-ts-regexp-both end t))
8307 (org-time-string-to-seconds (match-string 0))
8308 (org-float-time now))))
8309 ((= dcst ?c)
8310 (let ((end (save-excursion (outline-next-heading) (point))))
8311 (if (re-search-forward
8312 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8313 end t)
8314 (org-time-string-to-seconds (match-string 0))
8315 (org-float-time now))))
8316 ((= dcst ?s)
8317 (let ((end (save-excursion (outline-next-heading) (point))))
8318 (if (re-search-forward org-scheduled-time-regexp end t)
8319 (org-time-string-to-seconds (match-string 1))
8320 (org-float-time now))))
8321 ((= dcst ?d)
8322 (let ((end (save-excursion (outline-next-heading) (point))))
8323 (if (re-search-forward org-deadline-time-regexp end t)
8324 (org-time-string-to-seconds (match-string 1))
8325 (org-float-time now))))
8326 ((= dcst ?p)
8327 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8328 (string-to-char (match-string 2))
8329 org-default-priority))
8330 ((= dcst ?r)
8331 (or (org-entry-get nil property) ""))
8332 ((= dcst ?o)
8333 (if (looking-at org-complex-heading-regexp)
8334 (- 9999 (length (member (match-string 2)
8335 org-todo-keywords-1)))))
8336 ((= dcst ?f)
8337 (if getkey-func
8338 (progn
8339 (setq tmp (funcall getkey-func))
8340 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8341 tmp)
8342 (error "Invalid key function `%s'" getkey-func)))
8343 (t (error "Invalid sorting type `%c'" sorting-type))))
8345 (cond
8346 ((= dcst ?a) 'string<)
8347 ((= dcst ?f) compare-func)
8348 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8349 (run-hooks 'org-after-sorting-entries-or-items-hook)
8350 (message "Sorting entries...done")))
8352 (defun org-do-sort (table what &optional with-case sorting-type)
8353 "Sort TABLE of WHAT according to SORTING-TYPE.
8354 The user will be prompted for the SORTING-TYPE if the call to this
8355 function does not specify it. WHAT is only for the prompt, to indicate
8356 what is being sorted. The sorting key will be extracted from
8357 the car of the elements of the table.
8358 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8359 (unless sorting-type
8360 (message
8361 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8362 what)
8363 (setq sorting-type (read-char-exclusive)))
8364 (let ((dcst (downcase sorting-type))
8365 extractfun comparefun)
8366 ;; Define the appropriate functions
8367 (cond
8368 ((= dcst ?n)
8369 (setq extractfun 'string-to-number
8370 comparefun (if (= dcst sorting-type) '< '>)))
8371 ((= dcst ?a)
8372 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8373 (lambda(x) (downcase (org-sort-remove-invisible x))))
8374 comparefun (if (= dcst sorting-type)
8375 'string<
8376 (lambda (a b) (and (not (string< a b))
8377 (not (string= a b)))))))
8378 ((= dcst ?t)
8379 (setq extractfun
8380 (lambda (x)
8381 (if (or (string-match org-ts-regexp x)
8382 (string-match org-ts-regexp-both x))
8383 (org-float-time
8384 (org-time-string-to-time (match-string 0 x)))
8386 comparefun (if (= dcst sorting-type) '< '>)))
8387 (t (error "Invalid sorting type `%c'" sorting-type)))
8389 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8390 table)
8391 (lambda (a b) (funcall comparefun (car a) (car b))))))
8394 ;;; The orgstruct minor mode
8396 ;; Define a minor mode which can be used in other modes in order to
8397 ;; integrate the org-mode structure editing commands.
8399 ;; This is really a hack, because the org-mode structure commands use
8400 ;; keys which normally belong to the major mode. Here is how it
8401 ;; works: The minor mode defines all the keys necessary to operate the
8402 ;; structure commands, but wraps the commands into a function which
8403 ;; tests if the cursor is currently at a headline or a plain list
8404 ;; item. If that is the case, the structure command is used,
8405 ;; temporarily setting many Org-mode variables like regular
8406 ;; expressions for filling etc. However, when any of those keys is
8407 ;; used at a different location, function uses `key-binding' to look
8408 ;; up if the key has an associated command in another currently active
8409 ;; keymap (minor modes, major mode, global), and executes that
8410 ;; command. There might be problems if any of the keys is otherwise
8411 ;; used as a prefix key.
8413 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8414 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8415 ;; addresses this by checking explicitly for both bindings.
8417 (defvar orgstruct-mode-map (make-sparse-keymap)
8418 "Keymap for the minor `orgstruct-mode'.")
8420 (defvar org-local-vars nil
8421 "List of local variables, for use by `orgstruct-mode'.")
8423 ;;;###autoload
8424 (define-minor-mode orgstruct-mode
8425 "Toggle the minor mode `orgstruct-mode'.
8426 This mode is for using Org-mode structure commands in other
8427 modes. The following keys behave as if Org-mode were active, if
8428 the cursor is on a headline, or on a plain list item (both as
8429 defined by Org-mode).
8431 M-up Move entry/item up
8432 M-down Move entry/item down
8433 M-left Promote
8434 M-right Demote
8435 M-S-up Move entry/item up
8436 M-S-down Move entry/item down
8437 M-S-left Promote subtree
8438 M-S-right Demote subtree
8439 M-q Fill paragraph and items like in Org-mode
8440 C-c ^ Sort entries
8441 C-c - Cycle list bullet
8442 TAB Cycle item visibility
8443 M-RET Insert new heading/item
8444 S-M-RET Insert new TODO heading / Checkbox item
8445 C-c C-c Set tags / toggle checkbox"
8446 nil " OrgStruct" nil
8447 (org-load-modules-maybe)
8448 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8450 ;;;###autoload
8451 (defun turn-on-orgstruct ()
8452 "Unconditionally turn on `orgstruct-mode'."
8453 (orgstruct-mode 1))
8455 (defvar org-fb-vars nil)
8456 (make-variable-buffer-local 'org-fb-vars)
8457 (defun orgstruct++-mode (&optional arg)
8458 "Toggle `orgstruct-mode', the enhanced version of it.
8459 In addition to setting orgstruct-mode, this also exports all
8460 indentation and autofilling variables from org-mode into the
8461 buffer. It will also recognize item context in multiline items."
8462 (interactive "P")
8463 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8464 (if (< arg 1)
8465 (progn (orgstruct-mode -1)
8466 (mapc (lambda(v)
8467 (org-set-local (car v)
8468 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8469 org-fb-vars))
8470 (orgstruct-mode 1)
8471 (setq org-fb-vars nil)
8472 (let (var val)
8473 (mapc
8474 (lambda (x)
8475 (when (string-match
8476 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8477 (symbol-name (car x)))
8478 (setq var (car x) val (nth 1 x))
8479 (push (list var `(quote ,(eval var))) org-fb-vars)
8480 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8481 org-local-vars)
8482 (org-set-local 'orgstruct-is-++ t))))
8484 (defvar orgstruct-is-++ nil
8485 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8486 (make-variable-buffer-local 'orgstruct-is-++)
8488 ;;;###autoload
8489 (defun turn-on-orgstruct++ ()
8490 "Unconditionally turn on `orgstruct++-mode'."
8491 (orgstruct++-mode 1))
8493 (defun orgstruct-error ()
8494 "Error when there is no default binding for a structure key."
8495 (interactive)
8496 (error "This key has no function outside structure elements"))
8498 (defun orgstruct-setup ()
8499 "Setup orgstruct keymaps."
8500 (let ((nfunc 0)
8501 (bindings
8502 (list
8503 '([(meta up)] org-metaup)
8504 '([(meta down)] org-metadown)
8505 '([(meta left)] org-metaleft)
8506 '([(meta right)] org-metaright)
8507 '([(meta shift up)] org-shiftmetaup)
8508 '([(meta shift down)] org-shiftmetadown)
8509 '([(meta shift left)] org-shiftmetaleft)
8510 '([(meta shift right)] org-shiftmetaright)
8511 '([?\e (up)] org-metaup)
8512 '([?\e (down)] org-metadown)
8513 '([?\e (left)] org-metaleft)
8514 '([?\e (right)] org-metaright)
8515 '([?\e (shift up)] org-shiftmetaup)
8516 '([?\e (shift down)] org-shiftmetadown)
8517 '([?\e (shift left)] org-shiftmetaleft)
8518 '([?\e (shift right)] org-shiftmetaright)
8519 '([(shift up)] org-shiftup)
8520 '([(shift down)] org-shiftdown)
8521 '([(shift left)] org-shiftleft)
8522 '([(shift right)] org-shiftright)
8523 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8524 '("\M-q" fill-paragraph)
8525 '("\C-c^" org-sort)
8526 '("\C-c-" org-cycle-list-bullet)))
8527 elt key fun cmd)
8528 (while (setq elt (pop bindings))
8529 (setq nfunc (1+ nfunc))
8530 (setq key (org-key (car elt))
8531 fun (nth 1 elt)
8532 cmd (orgstruct-make-binding fun nfunc key))
8533 (org-defkey orgstruct-mode-map key cmd))
8535 ;; Prevent an error for users who forgot to make autoloads
8536 (require 'org-element)
8538 ;; Special treatment needed for TAB and RET
8539 (org-defkey orgstruct-mode-map [(tab)]
8540 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8541 (org-defkey orgstruct-mode-map "\C-i"
8542 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8544 (org-defkey orgstruct-mode-map "\M-\C-m"
8545 (orgstruct-make-binding 'org-insert-heading 105
8546 "\M-\C-m" [(meta return)]))
8547 (org-defkey orgstruct-mode-map [(meta return)]
8548 (orgstruct-make-binding 'org-insert-heading 106
8549 [(meta return)] "\M-\C-m"))
8551 (org-defkey orgstruct-mode-map [(shift meta return)]
8552 (orgstruct-make-binding 'org-insert-todo-heading 107
8553 [(meta return)] "\M-\C-m"))
8555 (org-defkey orgstruct-mode-map "\e\C-m"
8556 (orgstruct-make-binding 'org-insert-heading 108
8557 "\e\C-m" [?\e (return)]))
8558 (org-defkey orgstruct-mode-map [?\e (return)]
8559 (orgstruct-make-binding 'org-insert-heading 109
8560 [?\e (return)] "\e\C-m"))
8561 (org-defkey orgstruct-mode-map [?\e (shift return)]
8562 (orgstruct-make-binding 'org-insert-todo-heading 110
8563 [?\e (return)] "\e\C-m"))
8565 (unless org-local-vars
8566 (setq org-local-vars (org-get-local-variables)))
8570 (defun orgstruct-make-binding (fun n &rest keys)
8571 "Create a function for binding in the structure minor mode.
8572 FUN is the command to call inside a table. N is used to create a unique
8573 command name. KEYS are keys that should be checked in for a command
8574 to execute outside of tables."
8575 (eval
8576 (list 'defun
8577 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8578 '(arg)
8579 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8580 "Outside of structure, run the binding of `"
8581 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8582 "'.")
8583 '(interactive "p")
8584 (list 'if
8585 `(org-context-p 'headline 'item
8586 (and orgstruct-is-++
8587 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8588 'item-body))
8589 (list 'org-run-like-in-org-mode (list 'quote fun))
8590 (list 'let '(orgstruct-mode)
8591 (list 'call-interactively
8592 (append '(or)
8593 (mapcar (lambda (k)
8594 (list 'key-binding k))
8595 keys)
8596 '('orgstruct-error))))))))
8598 (defun org-contextualize-keys (alist contexts)
8599 "Return valid elements in ALIST depending on CONTEXTS.
8601 `org-agenda-custom-commands' or `org-capture-templates' are the
8602 values used for ALIST, and `org-agenda-custom-commands-contexts'
8603 or `org-capture-templates-contexts' are the associated contexts
8604 definitions."
8605 (let ((contexts
8606 ;; normalize contexts
8607 (mapcar
8608 (lambda(c) (cond ((listp (cadr c))
8609 (list (car c) (car c) (cadr c)))
8610 ((string= "" (cadr c))
8611 (list (car c) (car c) (caddr c)))
8612 (t c))) contexts))
8613 (a alist) c r s)
8614 ;; loop over all commands or templates
8615 (while (setq c (pop a))
8616 (let (vrules repl)
8617 (cond
8618 ((not (assoc (car c) contexts))
8619 (push c r))
8620 ((and (assoc (car c) contexts)
8621 (setq vrules (org-contextualize-validate-key
8622 (car c) contexts)))
8623 (mapc (lambda (vr)
8624 (when (not (equal (car vr) (cadr vr)))
8625 (setq repl vr))) vrules)
8626 (if (not repl) (push c r)
8627 (push (cadr repl) s)
8628 (push
8629 (cons (car c)
8630 (cdr (or (assoc (cadr repl) alist)
8631 (error "Undefined key `%s' as contextual replacement for `%s'"
8632 (cadr repl) (car c)))))
8633 r))))))
8634 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8635 (delq
8637 (delete-dups
8638 (mapcar (lambda (x)
8639 (let ((tpl (car x)))
8640 (when (not (delq
8642 (mapcar (lambda(y)
8643 (equal y tpl)) s))) x)))
8644 (reverse r))))))
8646 (defun org-contextualize-validate-key (key contexts)
8647 "Check CONTEXTS for agenda or capture KEY."
8648 (let (r rr res)
8649 (while (setq r (pop contexts))
8650 (mapc
8651 (lambda (rr)
8652 (when
8653 (and (equal key (car r))
8654 (if (functionp rr) (funcall rr)
8655 (or (and (eq (car rr) 'in-file)
8656 (buffer-file-name)
8657 (string-match (cdr rr) (buffer-file-name)))
8658 (and (eq (car rr) 'in-mode)
8659 (string-match (cdr rr) (symbol-name major-mode)))
8660 (when (and (eq (car rr) 'not-in-file)
8661 (buffer-file-name))
8662 (not (string-match (cdr rr) (buffer-file-name))))
8663 (when (eq (car rr) 'not-in-mode)
8664 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8665 (push r res)))
8666 (car (last r))))
8667 (delete-dups (delq nil res))))
8669 (defun org-context-p (&rest contexts)
8670 "Check if local context is any of CONTEXTS.
8671 Possible values in the list of contexts are `table', `headline', and `item'."
8672 (let ((pos (point)))
8673 (goto-char (point-at-bol))
8674 (prog1 (or (and (memq 'table contexts)
8675 (looking-at "[ \t]*|"))
8676 (and (memq 'headline contexts)
8677 (looking-at org-outline-regexp))
8678 (and (memq 'item contexts)
8679 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8680 (and (memq 'item-body contexts)
8681 (org-in-item-p)))
8682 (goto-char pos))))
8684 (defun org-get-local-variables ()
8685 "Return a list of all local variables in an Org mode buffer."
8686 (let (varlist)
8687 (with-current-buffer (get-buffer-create "*Org tmp*")
8688 (erase-buffer)
8689 (org-mode)
8690 (setq varlist (buffer-local-variables)))
8691 (kill-buffer "*Org tmp*")
8692 (delq nil
8693 (mapcar
8694 (lambda (x)
8695 (setq x
8696 (if (symbolp x)
8697 (list x)
8698 (list (car x) (list 'quote (cdr x)))))
8699 (if (string-match
8700 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8701 (symbol-name (car x)))
8702 x nil))
8703 varlist))))
8705 (defun org-clone-local-variables (from-buffer &optional regexp)
8706 "Clone local variables from FROM-BUFFER.
8707 Optional argument REGEXP selects variables to clone."
8708 (mapc
8709 (lambda (pair)
8710 (and (symbolp (car pair))
8711 (or (null regexp)
8712 (string-match regexp (symbol-name (car pair))))
8713 (set (make-local-variable (car pair))
8714 (cdr pair))))
8715 (buffer-local-variables from-buffer)))
8717 ;;;###autoload
8718 (defun org-run-like-in-org-mode (cmd)
8719 "Run a command, pretending that the current buffer is in Org-mode.
8720 This will temporarily bind local variables that are typically bound in
8721 Org-mode to the values they have in Org-mode, and then interactively
8722 call CMD."
8723 (org-load-modules-maybe)
8724 (unless org-local-vars
8725 (setq org-local-vars (org-get-local-variables)))
8726 (eval (list 'let org-local-vars
8727 (list 'call-interactively (list 'quote cmd)))))
8729 ;;;; Archiving
8731 (defun org-get-category (&optional pos force-refresh)
8732 "Get the category applying to position POS."
8733 (save-match-data
8734 (if force-refresh (org-refresh-category-properties))
8735 (let ((pos (or pos (point))))
8736 (or (get-text-property pos 'org-category)
8737 (progn (org-refresh-category-properties)
8738 (get-text-property pos 'org-category))))))
8740 (defun org-refresh-category-properties ()
8741 "Refresh category text properties in the buffer."
8742 (let ((case-fold-search t)
8743 (inhibit-read-only t)
8744 (def-cat (cond
8745 ((null org-category)
8746 (if buffer-file-name
8747 (file-name-sans-extension
8748 (file-name-nondirectory buffer-file-name))
8749 "???"))
8750 ((symbolp org-category) (symbol-name org-category))
8751 (t org-category)))
8752 beg end cat pos optionp)
8753 (org-unmodified
8754 (save-excursion
8755 (save-restriction
8756 (widen)
8757 (goto-char (point-min))
8758 (put-text-property (point) (point-max) 'org-category def-cat)
8759 (while (re-search-forward
8760 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8761 (setq pos (match-end 0)
8762 optionp (equal (char-after (match-beginning 0)) ?#)
8763 cat (org-trim (match-string 2)))
8764 (if optionp
8765 (setq beg (point-at-bol) end (point-max))
8766 (org-back-to-heading t)
8767 (setq beg (point) end (org-end-of-subtree t t)))
8768 (put-text-property beg end 'org-category cat)
8769 (put-text-property beg end 'org-category-position beg)
8770 (goto-char pos)))))))
8773 ;;;; Link Stuff
8775 ;;; Link abbreviations
8777 (defun org-link-expand-abbrev (link)
8778 "Apply replacements as defined in `org-link-abbrev-alist'."
8779 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8780 (let* ((key (match-string 1 link))
8781 (as (or (assoc key org-link-abbrev-alist-local)
8782 (assoc key org-link-abbrev-alist)))
8783 (tag (and (match-end 2) (match-string 3 link)))
8784 rpl)
8785 (if (not as)
8786 link
8787 (setq rpl (cdr as))
8788 (cond
8789 ((symbolp rpl) (funcall rpl tag))
8790 ((string-match "%(\\([^)]+\\))" rpl)
8791 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8792 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8793 ((string-match "%h" rpl)
8794 (replace-match (url-hexify-string (or tag "")) t t rpl))
8795 (t (concat rpl tag)))))
8796 link))
8798 ;;; Storing and inserting links
8800 (defvar org-insert-link-history nil
8801 "Minibuffer history for links inserted with `org-insert-link'.")
8803 (defvar org-stored-links nil
8804 "Contains the links stored with `org-store-link'.")
8806 (defvar org-store-link-plist nil
8807 "Plist with info about the most recently link created with `org-store-link'.")
8809 (defvar org-link-protocols nil
8810 "Link protocols added to Org-mode using `org-add-link-type'.")
8812 (defvar org-store-link-functions nil
8813 "List of functions that are called to create and store a link.
8814 Each function will be called in turn until one returns a non-nil
8815 value. Each function should check if it is responsible for creating
8816 this link (for example by looking at the major mode).
8817 If not, it must exit and return nil.
8818 If yes, it should return a non-nil value after a calling
8819 `org-store-link-props' with a list of properties and values.
8820 Special properties are:
8822 :type The link prefix, like \"http\". This must be given.
8823 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8824 This is obligatory as well.
8825 :description Optional default description for the second pair
8826 of brackets in an Org-mode link. The user can still change
8827 this when inserting this link into an Org-mode buffer.
8829 In addition to these, any additional properties can be specified
8830 and then used in capture templates.")
8832 (defun org-add-link-type (type &optional follow export)
8833 "Add TYPE to the list of `org-link-types'.
8834 Re-compute all regular expressions depending on `org-link-types'
8836 FOLLOW and EXPORT are two functions.
8838 FOLLOW should take the link path as the single argument and do whatever
8839 is necessary to follow the link, for example find a file or display
8840 a mail message.
8842 EXPORT should format the link path for export to one of the export formats.
8843 It should be a function accepting three arguments:
8845 path the path of the link, the text after the prefix (like \"http:\")
8846 desc the description of the link, if any, or a description added by
8847 org-export-normalize-links if there is none
8848 format the export format, a symbol like `html' or `latex' or `ascii'..
8850 The function may use the FORMAT information to return different values
8851 depending on the format. The return value will be put literally into
8852 the exported file. If the return value is nil, this means Org should
8853 do what it normally does with links which do not have EXPORT defined.
8855 Org-mode has a built-in default for exporting links. If you are happy with
8856 this default, there is no need to define an export function for the link
8857 type. For a simple example of an export function, see `org-bbdb.el'."
8858 (add-to-list 'org-link-types type t)
8859 (org-make-link-regexps)
8860 (if (assoc type org-link-protocols)
8861 (setcdr (assoc type org-link-protocols) (list follow export))
8862 (push (list type follow export) org-link-protocols)))
8864 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8865 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8867 ;;;###autoload
8868 (defun org-store-link (arg)
8869 "\\<org-mode-map>Store an org-link to the current location.
8870 This link is added to `org-stored-links' and can later be inserted
8871 into an org-buffer with \\[org-insert-link].
8873 For some link types, a prefix arg is interpreted:
8874 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8875 For file links, arg negates `org-context-in-file-links'."
8876 (interactive "P")
8877 (org-load-modules-maybe)
8878 (setq org-store-link-plist nil) ; reset
8879 (org-with-limited-levels
8880 (let (link cpltxt desc description search txt custom-id agenda-link)
8881 (cond
8883 ((run-hook-with-args-until-success 'org-store-link-functions)
8884 (setq link (plist-get org-store-link-plist :link)
8885 desc (or (plist-get org-store-link-plist :description) link)))
8887 ((org-src-edit-buffer-p)
8888 (let (label gc)
8889 (while (or (not label)
8890 (save-excursion
8891 (save-restriction
8892 (widen)
8893 (goto-char (point-min))
8894 (re-search-forward
8895 (regexp-quote (format org-coderef-label-format label))
8896 nil t))))
8897 (when label (message "Label exists already") (sit-for 2))
8898 (setq label (read-string "Code line label: " label)))
8899 (end-of-line 1)
8900 (setq link (format org-coderef-label-format label))
8901 (setq gc (- 79 (length link)))
8902 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8903 (insert link)
8904 (setq link (concat "(" label ")") desc nil)))
8906 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8907 ;; We are in the agenda, link to referenced location
8908 (let ((m (or (get-text-property (point) 'org-hd-marker)
8909 (get-text-property (point) 'org-marker))))
8910 (when m
8911 (org-with-point-at m
8912 (setq agenda-link
8913 (if (org-called-interactively-p 'any)
8914 (call-interactively 'org-store-link)
8915 (org-store-link nil)))))))
8917 ((eq major-mode 'calendar-mode)
8918 (let ((cd (calendar-cursor-to-date)))
8919 (setq link
8920 (format-time-string
8921 (car org-time-stamp-formats)
8922 (apply 'encode-time
8923 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8924 nil nil nil))))
8925 (org-store-link-props :type "calendar" :date cd)))
8927 ((eq major-mode 'help-mode)
8928 (setq link (concat "help:" (save-excursion
8929 (goto-char (point-min))
8930 (looking-at "^[^ ]+")
8931 (match-string 0))))
8932 (org-store-link-props :type "help"))
8934 ((eq major-mode 'w3-mode)
8935 (setq cpltxt (if (and (buffer-name)
8936 (not (string-match "Untitled" (buffer-name))))
8937 (buffer-name)
8938 (url-view-url t))
8939 link (url-view-url t))
8940 (org-store-link-props :type "w3" :url (url-view-url t)))
8942 ((eq major-mode 'w3m-mode)
8943 (setq cpltxt (or w3m-current-title w3m-current-url)
8944 link w3m-current-url)
8945 (org-store-link-props :type "w3m" :url (url-view-url t)))
8947 ((setq search (run-hook-with-args-until-success
8948 'org-create-file-search-functions))
8949 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8950 "::" search))
8951 (setq cpltxt (or description link)))
8953 ((eq major-mode 'image-mode)
8954 (setq cpltxt (concat "file:"
8955 (abbreviate-file-name buffer-file-name))
8956 link cpltxt)
8957 (org-store-link-props :type "image" :file buffer-file-name))
8959 ((eq major-mode 'dired-mode)
8960 ;; link to the file in the current line
8961 (let ((file (dired-get-filename nil t)))
8962 (setq file (if file
8963 (abbreviate-file-name
8964 (expand-file-name (dired-get-filename nil t)))
8965 ;; otherwise, no file so use current directory.
8966 default-directory))
8967 (setq cpltxt (concat "file:" file)
8968 link cpltxt)))
8970 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8971 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8972 (cond
8973 ((org-in-regexp "<<\\(.*?\\)>>")
8974 (setq cpltxt
8975 (concat "file:"
8976 (abbreviate-file-name
8977 (buffer-file-name (buffer-base-buffer)))
8978 "::" (match-string 1))
8979 link cpltxt))
8980 ((and (featurep 'org-id)
8981 (or (eq org-link-to-org-use-id t)
8982 (and (org-called-interactively-p 'any)
8983 (or (eq org-link-to-org-use-id 'create-if-interactive)
8984 (and (eq org-link-to-org-use-id
8985 'create-if-interactive-and-no-custom-id)
8986 (not custom-id))))
8987 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8988 ;; We can make a link using the ID.
8989 (setq link (condition-case nil
8990 (prog1 (org-id-store-link)
8991 (setq desc (plist-get org-store-link-plist :description)))
8992 (error
8993 ;; probably before first headline, link to file only
8994 (concat "file:"
8995 (abbreviate-file-name
8996 (buffer-file-name (buffer-base-buffer))))))))
8998 ;; Just link to current headline
8999 (setq cpltxt (concat "file:"
9000 (abbreviate-file-name
9001 (buffer-file-name (buffer-base-buffer)))))
9002 ;; Add a context search string
9003 (when (org-xor org-context-in-file-links arg)
9004 (setq txt (cond
9005 ((org-at-heading-p) nil)
9006 ((org-region-active-p)
9007 (buffer-substring (region-beginning) (region-end)))))
9008 (when (or (null txt) (string-match "\\S-" txt))
9009 (setq cpltxt
9010 (concat cpltxt "::"
9011 (condition-case nil
9012 (org-make-org-heading-search-string txt)
9013 (error "")))
9014 desc (or (nth 4 (ignore-errors
9015 (org-heading-components))) "NONE"))))
9016 (if (string-match "::\\'" cpltxt)
9017 (setq cpltxt (substring cpltxt 0 -2)))
9018 (setq link cpltxt))))
9020 ((buffer-file-name (buffer-base-buffer))
9021 ;; Just link to this file here.
9022 (setq cpltxt (concat "file:"
9023 (abbreviate-file-name
9024 (buffer-file-name (buffer-base-buffer)))))
9025 ;; Add a context string
9026 (when (org-xor org-context-in-file-links arg)
9027 (setq txt (if (org-region-active-p)
9028 (buffer-substring (region-beginning) (region-end))
9029 (buffer-substring (point-at-bol) (point-at-eol))))
9030 ;; Only use search option if there is some text.
9031 (when (string-match "\\S-" txt)
9032 (setq cpltxt
9033 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9034 desc "NONE")))
9035 (setq link cpltxt))
9037 ((org-called-interactively-p 'interactive)
9038 (error "Cannot link to a buffer which is not visiting a file"))
9040 (t (setq link nil)))
9042 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9043 (setq link (or link cpltxt)
9044 desc (or desc cpltxt))
9045 (if (equal desc "NONE") (setq desc nil))
9047 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9048 (progn
9049 (setq org-stored-links
9050 (cons (list link desc) org-stored-links))
9051 (message "Stored: %s" (or desc link))
9052 (when custom-id
9053 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9054 "::#" custom-id))
9055 (setq org-stored-links
9056 (cons (list link desc) org-stored-links))))
9057 (or agenda-link (and link (org-make-link-string link desc)))))))
9059 (defun org-store-link-props (&rest plist)
9060 "Store link properties, extract names and addresses."
9061 (let (x adr)
9062 (when (setq x (plist-get plist :from))
9063 (setq adr (mail-extract-address-components x))
9064 (setq plist (plist-put plist :fromname (car adr)))
9065 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9066 (when (setq x (plist-get plist :to))
9067 (setq adr (mail-extract-address-components x))
9068 (setq plist (plist-put plist :toname (car adr)))
9069 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9070 (let ((from (plist-get plist :from))
9071 (to (plist-get plist :to)))
9072 (when (and from to org-from-is-user-regexp)
9073 (setq plist
9074 (plist-put plist :fromto
9075 (if (string-match org-from-is-user-regexp from)
9076 (concat "to %t")
9077 (concat "from %f"))))))
9078 (setq org-store-link-plist plist))
9080 (defun org-add-link-props (&rest plist)
9081 "Add these properties to the link property list."
9082 (let (key value)
9083 (while plist
9084 (setq key (pop plist) value (pop plist))
9085 (setq org-store-link-plist
9086 (plist-put org-store-link-plist key value)))))
9088 (defun org-email-link-description (&optional fmt)
9089 "Return the description part of an email link.
9090 This takes information from `org-store-link-plist' and formats it
9091 according to FMT (default from `org-email-link-description-format')."
9092 (setq fmt (or fmt org-email-link-description-format))
9093 (let* ((p org-store-link-plist)
9094 (to (plist-get p :toaddress))
9095 (from (plist-get p :fromaddress))
9096 (table
9097 (list
9098 (cons "%c" (plist-get p :fromto))
9099 (cons "%F" (plist-get p :from))
9100 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9101 (cons "%T" (plist-get p :to))
9102 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9103 (cons "%s" (plist-get p :subject))
9104 (cons "%d" (plist-get p :date))
9105 (cons "%m" (plist-get p :message-id)))))
9106 (when (string-match "%c" fmt)
9107 ;; Check if the user wrote this message
9108 (if (and org-from-is-user-regexp from to
9109 (save-match-data (string-match org-from-is-user-regexp from)))
9110 (setq fmt (replace-match "to %t" t t fmt))
9111 (setq fmt (replace-match "from %f" t t fmt))))
9112 (org-replace-escapes fmt table)))
9114 (defun org-make-org-heading-search-string (&optional string heading)
9115 "Make search string for STRING or current headline."
9116 (interactive)
9117 (let ((s (or string (org-get-heading)))
9118 (lines org-context-in-file-links))
9119 (unless (and string (not heading))
9120 ;; We are using a headline, clean up garbage in there.
9121 (if (string-match org-todo-regexp s)
9122 (setq s (replace-match "" t t s)))
9123 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9124 (setq s (replace-match "" t t s)))
9125 (setq s (org-trim s))
9126 (if (string-match (concat "^\\(" org-quote-string "\\|"
9127 org-comment-string "\\)") s)
9128 (setq s (replace-match "" t t s)))
9129 (while (string-match org-ts-regexp s)
9130 (setq s (replace-match "" t t s))))
9131 (or string (setq s (concat "*" s))) ; Add * for headlines
9132 (when (and string (integerp lines) (> lines 0))
9133 (let ((slines (org-split-string s "\n")))
9134 (when (< lines (length slines))
9135 (setq s (mapconcat
9136 'identity
9137 (reverse (nthcdr (- (length slines) lines)
9138 (reverse slines))) "\n")))))
9139 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9141 (defun org-make-link-string (link &optional description)
9142 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9143 (unless (string-match "\\S-" link)
9144 (error "Empty link"))
9145 (when (and description
9146 (stringp description)
9147 (not (string-match "\\S-" description)))
9148 (setq description nil))
9149 (when (stringp description)
9150 ;; Remove brackets from the description, they are fatal.
9151 (while (string-match "\\[" description)
9152 (setq description (replace-match "{" t t description)))
9153 (while (string-match "\\]" description)
9154 (setq description (replace-match "}" t t description))))
9155 (when (equal link description)
9156 ;; No description needed, it is identical
9157 (setq description nil))
9158 (when (and (not description)
9159 (not (string-match (org-image-file-name-regexp) link))
9160 (not (equal link (org-link-escape link))))
9161 (setq description (org-extract-attributes link)))
9162 (setq link
9163 (cond ((string-match (org-image-file-name-regexp) link) link)
9164 ((string-match org-link-types-re link)
9165 (concat (match-string 1 link)
9166 (org-link-escape (substring link (match-end 1)))))
9167 (t (org-link-escape link))))
9168 (concat "[[" link "]"
9169 (if description (concat "[" description "]") "")
9170 "]"))
9172 (defconst org-link-escape-chars
9173 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9174 "List of characters that should be escaped in link.
9175 This is the list that is used for internal purposes.")
9177 (defconst org-link-escape-chars-browser
9178 '(?\ )
9179 "List of escapes for characters that are problematic in links.
9180 This is the list that is used before handing over to the browser.")
9182 (defun org-link-escape (text &optional table merge)
9183 "Return percent escaped representation of TEXT.
9184 TEXT is a string with the text to escape.
9185 Optional argument TABLE is a list with characters that should be
9186 escaped. When nil, `org-link-escape-chars' is used.
9187 If optional argument MERGE is set, merge TABLE into
9188 `org-link-escape-chars'."
9189 (cond
9190 ((and table merge)
9191 (mapc (lambda (defchr)
9192 (unless (member defchr table)
9193 (setq table (cons defchr table)))) org-link-escape-chars))
9194 ((null table)
9195 (setq table org-link-escape-chars)))
9196 (mapconcat
9197 (lambda (char)
9198 (if (or (member char table)
9199 (and (or (< char 32) (= char 37) (> char 126))
9200 org-url-hexify-p))
9201 (mapconcat (lambda (sequence-element)
9202 (format "%%%.2X" sequence-element))
9203 (or (encode-coding-char char 'utf-8)
9204 (error "Unable to percent escape character: %s"
9205 (char-to-string char))) "")
9206 (char-to-string char))) text ""))
9208 (defun org-link-unescape (str)
9209 "Unhex hexified Unicode strings as returned from the JavaScript function
9210 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9211 (unless (and (null str) (string= "" str))
9212 (let ((pos 0) (case-fold-search t) unhexed)
9213 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9214 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9215 (setq str (replace-match unhexed t t str))
9216 (setq pos (+ pos (length unhexed))))))
9217 str)
9219 (defun org-link-unescape-compound (hex)
9220 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9221 Note: this function also decodes single byte encodings like
9222 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9223 (save-match-data
9224 (let* ((bytes (cdr (split-string hex "%")))
9225 (ret "")
9226 (eat 0)
9227 (sum 0))
9228 (while bytes
9229 (let* ((val (string-to-number (pop bytes) 16))
9230 (shift-xor
9231 (if (= 0 eat)
9232 (cond
9233 ((>= val 252) (cons 6 252))
9234 ((>= val 248) (cons 5 248))
9235 ((>= val 240) (cons 4 240))
9236 ((>= val 224) (cons 3 224))
9237 ((>= val 192) (cons 2 192))
9238 (t (cons 0 0)))
9239 (cons 6 128))))
9240 (if (>= val 192) (setq eat (car shift-xor)))
9241 (setq val (logxor val (cdr shift-xor)))
9242 (setq sum (+ (lsh sum (car shift-xor)) val))
9243 (if (> eat 0) (setq eat (- eat 1)))
9244 (cond
9245 ((= 0 eat) ;multi byte
9246 (setq ret (concat ret (org-char-to-string sum)))
9247 (setq sum 0))
9248 ((not bytes) ; single byte(s)
9249 (setq ret (org-link-unescape-single-byte-sequence hex))))
9250 )) ;; end (while bytes
9251 ret )))
9253 (defun org-link-unescape-single-byte-sequence (hex)
9254 "Unhexify hex-encoded single byte character sequences."
9255 (mapconcat (lambda (byte)
9256 (char-to-string (string-to-number byte 16)))
9257 (cdr (split-string hex "%")) ""))
9259 (defun org-xor (a b)
9260 "Exclusive or."
9261 (if a (not b) b))
9263 (defun org-fixup-message-id-for-http (s)
9264 "Replace special characters in a message id, so it can be used in an http query."
9265 (when (string-match "%" s)
9266 (setq s (mapconcat (lambda (c)
9267 (if (eq c ?%)
9268 "%25"
9269 (char-to-string c)))
9270 s "")))
9271 (while (string-match "<" s)
9272 (setq s (replace-match "%3C" t t s)))
9273 (while (string-match ">" s)
9274 (setq s (replace-match "%3E" t t s)))
9275 (while (string-match "@" s)
9276 (setq s (replace-match "%40" t t s)))
9279 (defun org-link-prettify (link)
9280 "Return a human-readable representation of LINK.
9281 The car of LINK must be a raw link the cdr of LINK must be either
9282 a link description or nil."
9283 (let ((desc (or (cadr link) "<no description>")))
9284 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9285 "<" (car link) ">")))
9287 ;;;###autoload
9288 (defun org-insert-link-global ()
9289 "Insert a link like Org-mode does.
9290 This command can be called in any mode to insert a link in Org-mode syntax."
9291 (interactive)
9292 (org-load-modules-maybe)
9293 (org-run-like-in-org-mode 'org-insert-link))
9295 (defun org-insert-all-links (&optional keep)
9296 "Insert all links in `org-stored-links'."
9297 (interactive "P")
9298 (let ((links (copy-sequence org-stored-links)) l)
9299 (while (setq l (if keep (pop links) (pop org-stored-links)))
9300 (insert "- ")
9301 (org-insert-link nil (car l) (cadr l))
9302 (insert "\n"))))
9304 (defun org-link-fontify-links-to-this-file ()
9305 "Fontify links to the current file in `org-stored-links'."
9306 (let ((f (buffer-file-name)) a b)
9307 (setq a (mapcar (lambda(l)
9308 (let ((ll (car l)))
9309 (when (and (string-match "^file:\\(.+\\)::" ll)
9310 (equal f (expand-file-name (match-string 1 ll))))
9311 ll)))
9312 org-stored-links))
9313 (when (featurep 'org-id)
9314 (setq b (mapcar (lambda(l)
9315 (let ((ll (car l)))
9316 (when (and (string-match "^id:\\(.+\\)$" ll)
9317 (equal f (expand-file-name
9318 (or (org-id-find-id-file
9319 (match-string 1 ll)) ""))))
9320 ll)))
9321 org-stored-links)))
9322 (mapcar (lambda(l)
9323 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9324 (delq nil (append a b)))))
9326 (defvar org-link-links-in-this-file nil)
9327 (defun org-insert-link (&optional complete-file link-location default-description)
9328 "Insert a link. At the prompt, enter the link.
9330 Completion can be used to insert any of the link protocol prefixes like
9331 http or ftp in use.
9333 The history can be used to select a link previously stored with
9334 `org-store-link'. When the empty string is entered (i.e. if you just
9335 press RET at the prompt), the link defaults to the most recently
9336 stored link. As SPC triggers completion in the minibuffer, you need to
9337 use M-SPC or C-q SPC to force the insertion of a space character.
9339 You will also be prompted for a description, and if one is given, it will
9340 be displayed in the buffer instead of the link.
9342 If there is already a link at point, this command will allow you to edit link
9343 and description parts.
9345 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9346 be selected using completion. The path to the file will be relative to the
9347 current directory if the file is in the current directory or a subdirectory.
9348 Otherwise, the link will be the absolute path as completed in the minibuffer
9349 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9350 option `org-link-file-path-type'.
9352 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9353 the current directory or below.
9355 With three \\[universal-argument] prefixes, negate the meaning of
9356 `org-keep-stored-link-after-insertion'.
9358 If `org-make-link-description-function' is non-nil, this function will be
9359 called with the link target, and the result will be the default
9360 link description.
9362 If the LINK-LOCATION parameter is non-nil, this value will be
9363 used as the link location instead of reading one interactively.
9365 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9366 be used as the default description."
9367 (interactive "P")
9368 (let* ((wcf (current-window-configuration))
9369 (origbuf (current-buffer))
9370 (region (if (org-region-active-p)
9371 (buffer-substring (region-beginning) (region-end))))
9372 (remove (and region (list (region-beginning) (region-end))))
9373 (desc region)
9374 tmphist ; byte-compile incorrectly complains about this
9375 (link link-location)
9376 (abbrevs org-link-abbrev-alist-local)
9377 entry file all-prefixes auto-desc)
9378 (cond
9379 (link-location) ; specified by arg, just use it.
9380 ((org-in-regexp org-bracket-link-regexp 1)
9381 ;; We do have a link at point, and we are going to edit it.
9382 (setq remove (list (match-beginning 0) (match-end 0)))
9383 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9384 (setq link (read-string "Link: "
9385 (org-link-unescape
9386 (org-match-string-no-properties 1)))))
9387 ((or (org-in-regexp org-angle-link-re)
9388 (org-in-regexp org-plain-link-re))
9389 ;; Convert to bracket link
9390 (setq remove (list (match-beginning 0) (match-end 0))
9391 link (read-string "Link: "
9392 (org-remove-angle-brackets (match-string 0)))))
9393 ((member complete-file '((4) (16)))
9394 ;; Completing read for file names.
9395 (setq link (org-file-complete-link complete-file)))
9397 ;; Read link, with completion for stored links.
9398 (org-link-fontify-links-to-this-file)
9399 (org-switch-to-buffer-other-window "*Org Links*")
9400 (with-current-buffer "*Org Links*"
9401 (erase-buffer)
9402 (insert "Insert a link.
9403 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9404 (when org-stored-links
9405 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9406 (insert (mapconcat 'org-link-prettify
9407 (reverse org-stored-links) "\n")))
9408 (goto-char (point-min)))
9409 (let ((cw (selected-window)))
9410 (select-window (get-buffer-window "*Org Links*" 'visible))
9411 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9412 (unless (pos-visible-in-window-p (point-max))
9413 (org-fit-window-to-buffer))
9414 (and (window-live-p cw) (select-window cw)))
9415 ;; Fake a link history, containing the stored links.
9416 (setq tmphist (append (mapcar 'car org-stored-links)
9417 org-insert-link-history))
9418 (setq all-prefixes (append (mapcar 'car abbrevs)
9419 (mapcar 'car org-link-abbrev-alist)
9420 org-link-types))
9421 (unwind-protect
9422 (progn
9423 (setq link
9424 (let ((org-completion-use-ido nil)
9425 (org-completion-use-iswitchb nil))
9426 (org-completing-read
9427 "Link: "
9428 (append
9429 (mapcar (lambda (x) (list (concat x ":")))
9430 all-prefixes)
9431 (mapcar 'car org-stored-links)
9432 (mapcar 'cadr org-stored-links))
9433 nil nil nil
9434 'tmphist
9435 (caar org-stored-links))))
9436 (if (not (string-match "\\S-" link))
9437 (error "No link selected"))
9438 (mapc (lambda(l)
9439 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9440 org-stored-links)
9441 (if (or (member link all-prefixes)
9442 (and (equal ":" (substring link -1))
9443 (member (substring link 0 -1) all-prefixes)
9444 (setq link (substring link 0 -1))))
9445 (setq link (with-current-buffer origbuf
9446 (org-link-try-special-completion link)))))
9447 (set-window-configuration wcf)
9448 (kill-buffer "*Org Links*"))
9449 (setq entry (assoc link org-stored-links))
9450 (or entry (push link org-insert-link-history))
9451 (setq desc (or desc (nth 1 entry)))))
9453 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9454 (not org-keep-stored-link-after-insertion))
9455 (setq org-stored-links (delq (assoc link org-stored-links)
9456 org-stored-links)))
9458 (if (string-match org-plain-link-re link)
9459 ;; URL-like link, normalize the use of angular brackets.
9460 (setq link (org-remove-angle-brackets link)))
9462 ;; Check if we are linking to the current file with a search option
9463 ;; If yes, simplify the link by using only the search option.
9464 (when (and buffer-file-name
9465 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9466 (let* ((path (match-string 1 link))
9467 (case-fold-search nil)
9468 (search (match-string 2 link)))
9469 (save-match-data
9470 (if (equal (file-truename buffer-file-name) (file-truename path))
9471 ;; We are linking to this same file, with a search option
9472 (setq link search)))))
9474 ;; Check if we can/should use a relative path. If yes, simplify the link
9475 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9476 (let* ((type (match-string 1 link))
9477 (path (match-string 2 link))
9478 (origpath path)
9479 (case-fold-search nil))
9480 (cond
9481 ((or (eq org-link-file-path-type 'absolute)
9482 (equal complete-file '(16)))
9483 (setq path (abbreviate-file-name (expand-file-name path))))
9484 ((eq org-link-file-path-type 'noabbrev)
9485 (setq path (expand-file-name path)))
9486 ((eq org-link-file-path-type 'relative)
9487 (setq path (file-relative-name path)))
9489 (save-match-data
9490 (if (string-match (concat "^" (regexp-quote
9491 (expand-file-name
9492 (file-name-as-directory
9493 default-directory))))
9494 (expand-file-name path))
9495 ;; We are linking a file with relative path name.
9496 (setq path (substring (expand-file-name path)
9497 (match-end 0)))
9498 (setq path (abbreviate-file-name (expand-file-name path)))))))
9499 (setq link (concat type path))
9500 (if (equal desc origpath)
9501 (setq desc path))))
9503 (if org-make-link-description-function
9504 (setq desc
9505 (or (condition-case nil
9506 (funcall org-make-link-description-function link desc)
9507 (error (progn (message "Can't get link description from `%s'"
9508 (symbol-name org-make-link-description-function))
9509 (sit-for 2) nil)))
9510 (read-string "Description: " default-description)))
9511 (if default-description (setq desc default-description)
9512 (setq desc (or (and auto-desc desc)
9513 (read-string "Description: " desc)))))
9515 (unless (string-match "\\S-" desc) (setq desc nil))
9516 (if remove (apply 'delete-region remove))
9517 (insert (org-make-link-string link desc))))
9519 (defun org-link-try-special-completion (type)
9520 "If there is completion support for link type TYPE, offer it."
9521 (let ((fun (intern (concat "org-" type "-complete-link"))))
9522 (if (functionp fun)
9523 (funcall fun)
9524 (read-string "Link (no completion support): " (concat type ":")))))
9526 (defun org-file-complete-link (&optional arg)
9527 "Create a file link using completion."
9528 (let (file link)
9529 (setq file (read-file-name "File: "))
9530 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9531 (pwd1 (file-name-as-directory (abbreviate-file-name
9532 (expand-file-name ".")))))
9533 (cond
9534 ((equal arg '(16))
9535 (setq link (concat
9536 "file:"
9537 (abbreviate-file-name (expand-file-name file)))))
9538 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9539 (setq link (concat "file:" (match-string 1 file))))
9540 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9541 (expand-file-name file))
9542 (setq link (concat
9543 "file:" (match-string 1 (expand-file-name file)))))
9544 (t (setq link (concat "file:" file)))))
9545 link))
9547 (defun org-completing-read (&rest args)
9548 "Completing-read with SPACE being a normal character."
9549 (let ((enable-recursive-minibuffers t)
9550 (minibuffer-local-completion-map
9551 (copy-keymap minibuffer-local-completion-map)))
9552 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9553 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9554 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9555 (apply 'org-icompleting-read args)))
9557 (defun org-completing-read-no-i (&rest args)
9558 (let (org-completion-use-ido org-completion-use-iswitchb)
9559 (apply 'org-completing-read args)))
9561 (defun org-iswitchb-completing-read (prompt choices &rest args)
9562 "Use iswitch as a completing-read replacement to choose from choices.
9563 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9564 from."
9565 (let* ((iswitchb-use-virtual-buffers nil)
9566 (iswitchb-make-buflist-hook
9567 (lambda ()
9568 (setq iswitchb-temp-buflist choices))))
9569 (iswitchb-read-buffer prompt)))
9571 (defun org-icompleting-read (&rest args)
9572 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9573 (org-without-partial-completion
9574 (if (and org-completion-use-ido
9575 (fboundp 'ido-completing-read)
9576 (boundp 'ido-mode) ido-mode
9577 (listp (second args)))
9578 (let ((ido-enter-matching-directory nil))
9579 (apply 'ido-completing-read (concat (car args))
9580 (if (consp (car (nth 1 args)))
9581 (mapcar 'car (nth 1 args))
9582 (nth 1 args))
9583 (cddr args)))
9584 (if (and org-completion-use-iswitchb
9585 (boundp 'iswitchb-mode) iswitchb-mode
9586 (listp (second args)))
9587 (apply 'org-iswitchb-completing-read (concat (car args))
9588 (if (consp (car (nth 1 args)))
9589 (mapcar 'car (nth 1 args))
9590 (nth 1 args))
9591 (cddr args))
9592 (apply 'completing-read args)))))
9594 (defun org-extract-attributes (s)
9595 "Extract the attributes cookie from a string and set as text property."
9596 (let (a attr (start 0) key value)
9597 (save-match-data
9598 (when (string-match "{{\\([^}]+\\)}}$" s)
9599 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9600 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9601 (setq key (match-string 1 a) value (match-string 2 a)
9602 start (match-end 0)
9603 attr (plist-put attr (intern key) value))))
9604 (org-add-props s nil 'org-attr attr))
9607 (defun org-extract-attributes-from-string (tag)
9608 (let (key value attr)
9609 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9610 (setq key (match-string 1 tag) value (match-string 2 tag)
9611 tag (replace-match "" t t tag)
9612 attr (plist-put attr (intern key) value)))
9613 (cons tag attr)))
9615 (defun org-attributes-to-string (plist)
9616 "Format a property list into an HTML attribute list."
9617 (let ((s "") key value)
9618 (while plist
9619 (setq key (pop plist) value (pop plist))
9620 (and value
9621 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9624 ;;; Opening/following a link
9626 (defvar org-link-search-failed nil)
9628 (defvar org-open-link-functions nil
9629 "Hook for functions finding a plain text link.
9630 These functions must take a single argument, the link content.
9631 They will be called for links that look like [[link text][description]]
9632 when LINK TEXT does not have a protocol like \"http:\" and does not look
9633 like a filename (e.g. \"./blue.png\").
9635 These functions will be called *before* Org attempts to resolve the
9636 link by doing text searches in the current buffer - so if you want a
9637 link \"[[target]]\" to still find \"<<target>>\", your function should
9638 handle this as a special case.
9640 When the function does handle the link, it must return a non-nil value.
9641 If it decides that it is not responsible for this link, it must return
9642 nil to indicate that that Org-mode can continue with other options
9643 like exact and fuzzy text search.")
9645 (defun org-next-link ()
9646 "Move forward to the next link.
9647 If the link is in hidden text, expose it."
9648 (interactive)
9649 (when (and org-link-search-failed (eq this-command last-command))
9650 (goto-char (point-min))
9651 (message "Link search wrapped back to beginning of buffer"))
9652 (setq org-link-search-failed nil)
9653 (let* ((pos (point))
9654 (ct (org-context))
9655 (a (assoc :link ct)))
9656 (if a (goto-char (nth 2 a)))
9657 (if (re-search-forward org-any-link-re nil t)
9658 (progn
9659 (goto-char (match-beginning 0))
9660 (if (outline-invisible-p) (org-show-context)))
9661 (goto-char pos)
9662 (setq org-link-search-failed t)
9663 (error "No further link found"))))
9665 (defun org-previous-link ()
9666 "Move backward to the previous link.
9667 If the link is in hidden text, expose it."
9668 (interactive)
9669 (when (and org-link-search-failed (eq this-command last-command))
9670 (goto-char (point-max))
9671 (message "Link search wrapped back to end of buffer"))
9672 (setq org-link-search-failed nil)
9673 (let* ((pos (point))
9674 (ct (org-context))
9675 (a (assoc :link ct)))
9676 (if a (goto-char (nth 1 a)))
9677 (if (re-search-backward org-any-link-re nil t)
9678 (progn
9679 (goto-char (match-beginning 0))
9680 (if (outline-invisible-p) (org-show-context)))
9681 (goto-char pos)
9682 (setq org-link-search-failed t)
9683 (error "No further link found"))))
9685 (defun org-translate-link (s)
9686 "Translate a link string if a translation function has been defined."
9687 (if (and org-link-translation-function
9688 (fboundp org-link-translation-function)
9689 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9690 (progn
9691 (setq s (funcall org-link-translation-function
9692 (match-string 1 s) (match-string 2 s)))
9693 (concat (car s) ":" (cdr s)))
9696 (defun org-translate-link-from-planner (type path)
9697 "Translate a link from Emacs Planner syntax so that Org can follow it.
9698 This is still an experimental function, your mileage may vary."
9699 (cond
9700 ((member type '("http" "https" "news" "ftp"))
9701 ;; standard Internet links are the same.
9702 nil)
9703 ((and (equal type "irc") (string-match "^//" path))
9704 ;; Planner has two / at the beginning of an irc link, we have 1.
9705 ;; We should have zero, actually....
9706 (setq path (substring path 1)))
9707 ((and (equal type "lisp") (string-match "^/" path))
9708 ;; Planner has a slash, we do not.
9709 (setq type "elisp" path (substring path 1)))
9710 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9711 ;; A typical message link. Planner has the id after the final slash,
9712 ;; we separate it with a hash mark
9713 (setq path (concat (match-string 1 path) "#"
9714 (org-remove-angle-brackets (match-string 2 path)))))
9716 (cons type path))
9718 (defun org-find-file-at-mouse (ev)
9719 "Open file link or URL at mouse."
9720 (interactive "e")
9721 (mouse-set-point ev)
9722 (org-open-at-point 'in-emacs))
9724 (defun org-open-at-mouse (ev)
9725 "Open file link or URL at mouse.
9726 See the docstring of `org-open-file' for details."
9727 (interactive "e")
9728 (mouse-set-point ev)
9729 (if (eq major-mode 'org-agenda-mode)
9730 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9731 (org-open-at-point))
9733 (defvar org-window-config-before-follow-link nil
9734 "The window configuration before following a link.
9735 This is saved in case the need arises to restore it.")
9737 (defvar org-open-link-marker (make-marker)
9738 "Marker pointing to the location where `org-open-at-point; was called.")
9740 ;;;###autoload
9741 (defun org-open-at-point-global ()
9742 "Follow a link like Org-mode does.
9743 This command can be called in any mode to follow a link that has
9744 Org-mode syntax."
9745 (interactive)
9746 (org-run-like-in-org-mode 'org-open-at-point))
9748 ;;;###autoload
9749 (defun org-open-link-from-string (s &optional arg reference-buffer)
9750 "Open a link in the string S, as if it was in Org-mode."
9751 (interactive "sLink: \nP")
9752 (let ((reference-buffer (or reference-buffer (current-buffer))))
9753 (with-temp-buffer
9754 (let ((org-inhibit-startup (not reference-buffer)))
9755 (org-mode)
9756 (insert s)
9757 (goto-char (point-min))
9758 (when reference-buffer
9759 (setq org-link-abbrev-alist-local
9760 (with-current-buffer reference-buffer
9761 org-link-abbrev-alist-local)))
9762 (org-open-at-point arg reference-buffer)))))
9764 (defvar org-open-at-point-functions nil
9765 "Hook that is run when following a link at point.
9767 Functions in this hook must return t if they identify and follow
9768 a link at point. If they don't find anything interesting at point,
9769 they must return nil.")
9771 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9772 (defun org-open-at-point (&optional arg reference-buffer)
9773 "Open link at or after point.
9774 If there is no link at point, this function will search forward up to
9775 the end of the current line.
9776 Normally, files will be opened by an appropriate application. If the
9777 optional prefix argument ARG is non-nil, Emacs will visit the file.
9778 With a double prefix argument, try to open outside of Emacs, in the
9779 application the system uses for this file type."
9780 (interactive "P")
9781 ;; if in a code block, then open the block's results
9782 (unless (call-interactively #'org-babel-open-src-block-result)
9783 (org-load-modules-maybe)
9784 (move-marker org-open-link-marker (point))
9785 (setq org-window-config-before-follow-link (current-window-configuration))
9786 (org-remove-occur-highlights nil nil t)
9787 (cond
9788 ((and (org-at-heading-p)
9789 (not (org-at-timestamp-p t))
9790 (not (org-in-regexp
9791 (concat org-plain-link-re "\\|"
9792 org-bracket-link-regexp "\\|"
9793 org-angle-link-re "\\|"
9794 "[ \t]:[^ \t\n]+:[ \t]*$")))
9795 (not (get-text-property (point) 'org-linked-text)))
9796 (or (org-offer-links-in-entry arg)
9797 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9798 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9799 ((and (org-at-timestamp-p t)
9800 (not (org-in-regexp org-bracket-link-regexp)))
9801 (org-follow-timestamp-link))
9802 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9803 (not (org-in-regexp org-bracket-link-regexp)))
9804 (org-footnote-action))
9806 (let (type path link line search (pos (point)))
9807 (catch 'match
9808 (save-excursion
9809 (skip-chars-forward "^]\n\r")
9810 (when (org-in-regexp org-bracket-link-regexp 1)
9811 (setq link (org-extract-attributes
9812 (org-link-unescape (org-match-string-no-properties 1))))
9813 (while (string-match " *\n *" link)
9814 (setq link (replace-match " " t t link)))
9815 (setq link (org-link-expand-abbrev link))
9816 (cond
9817 ((or (file-name-absolute-p link)
9818 (string-match "^\\.\\.?/" link))
9819 (setq type "file" path link))
9820 ((string-match org-link-re-with-space3 link)
9821 (setq type (match-string 1 link) path (match-string 2 link)))
9822 ((string-match "^help:+\\(.+\\)" link)
9823 (setq type "help" path (match-string 1 link)))
9824 (t (setq type "thisfile" path link)))
9825 (throw 'match t)))
9827 (when (get-text-property (point) 'org-linked-text)
9828 (setq type "thisfile"
9829 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9830 (1+ (point)) (point))
9831 path (buffer-substring
9832 (or (previous-single-property-change pos 'org-linked-text)
9833 (point-min))
9834 (or (next-single-property-change pos 'org-linked-text)
9835 (point-max))))
9836 (throw 'match t))
9838 (save-excursion
9839 (when (or (org-in-regexp org-angle-link-re)
9840 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9841 (save-match-data (not (looking-back "\\[\\[")))))
9842 (setq type (match-string 1)
9843 path (org-link-unescape (match-string 2)))
9844 (throw 'match t)))
9845 (save-excursion
9846 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9847 (setq type "tags"
9848 path (match-string 1))
9849 (while (string-match ":" path)
9850 (setq path (replace-match "+" t t path)))
9851 (throw 'match t)))
9852 (when (org-in-regexp "<\\([^><\n]+\\)>")
9853 (setq type "tree-match"
9854 path (match-string 1))
9855 (throw 'match t)))
9856 (unless path
9857 (error "No link found"))
9859 ;; switch back to reference buffer
9860 ;; needed when if called in a temporary buffer through
9861 ;; org-open-link-from-string
9862 (with-current-buffer (or reference-buffer (current-buffer))
9864 ;; Remove any trailing spaces in path
9865 (if (string-match " +\\'" path)
9866 (setq path (replace-match "" t t path)))
9867 (if (and org-link-translation-function
9868 (fboundp org-link-translation-function))
9869 ;; Check if we need to translate the link
9870 (let ((tmp (funcall org-link-translation-function type path)))
9871 (setq type (car tmp) path (cdr tmp))))
9873 (cond
9875 ((assoc type org-link-protocols)
9876 (funcall (nth 1 (assoc type org-link-protocols)) path))
9878 ((equal type "help")
9879 (let ((f-or-v (intern path)))
9880 (cond ((fboundp f-or-v)
9881 (describe-function f-or-v))
9882 ((boundp f-or-v)
9883 (describe-variable f-or-v))
9884 (t (error "Not a known function or variable")))))
9886 ((equal type "mailto")
9887 (let ((cmd (car org-link-mailto-program))
9888 (args (cdr org-link-mailto-program)) args1
9889 (address path) (subject "") a)
9890 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9891 (setq address (match-string 1 path)
9892 subject (org-link-escape (match-string 2 path))))
9893 (while args
9894 (cond
9895 ((not (stringp (car args))) (push (pop args) args1))
9896 (t (setq a (pop args))
9897 (if (string-match "%a" a)
9898 (setq a (replace-match address t t a)))
9899 (if (string-match "%s" a)
9900 (setq a (replace-match subject t t a)))
9901 (push a args1))))
9902 (apply cmd (nreverse args1))))
9904 ((member type '("http" "https" "ftp" "news"))
9905 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9906 (org-link-escape
9907 path org-link-escape-chars-browser)
9908 path))))
9910 ((string= type "doi")
9911 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9912 (org-link-escape
9913 path org-link-escape-chars-browser)
9914 path))))
9916 ((member type '("message"))
9917 (browse-url (concat type ":" path)))
9919 ((string= type "tags")
9920 (org-tags-view arg path))
9922 ((string= type "tree-match")
9923 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9925 ((string= type "file")
9926 (if (string-match "::\\([0-9]+\\)\\'" path)
9927 (setq line (string-to-number (match-string 1 path))
9928 path (substring path 0 (match-beginning 0)))
9929 (if (string-match "::\\(.+\\)\\'" path)
9930 (setq search (match-string 1 path)
9931 path (substring path 0 (match-beginning 0)))))
9932 (if (string-match "[*?{]" (file-name-nondirectory path))
9933 (dired path)
9934 (org-open-file path arg line search)))
9936 ((string= type "shell")
9937 (let ((buf (generate-new-buffer "*Org Shell Output"))
9938 (cmd path))
9939 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9940 (string-match org-confirm-shell-link-not-regexp cmd))
9941 (not org-confirm-shell-link-function)
9942 (funcall org-confirm-shell-link-function
9943 (format "Execute \"%s\" in shell? "
9944 (org-add-props cmd nil
9945 'face 'org-warning))))
9946 (progn
9947 (message "Executing %s" cmd)
9948 (shell-command cmd buf)
9949 (if (featurep 'midnight)
9950 (setq clean-buffer-list-kill-buffer-names
9951 (cons buf clean-buffer-list-kill-buffer-names))))
9952 (error "Abort"))))
9954 ((string= type "elisp")
9955 (let ((cmd path))
9956 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9957 (string-match org-confirm-elisp-link-not-regexp cmd))
9958 (not org-confirm-elisp-link-function)
9959 (funcall org-confirm-elisp-link-function
9960 (format "Execute \"%s\" as elisp? "
9961 (org-add-props cmd nil
9962 'face 'org-warning))))
9963 (message "%s => %s" cmd
9964 (if (equal (string-to-char cmd) ?\()
9965 (eval (read cmd))
9966 (call-interactively (read cmd))))
9967 (error "Abort"))))
9969 ((and (string= type "thisfile")
9970 (run-hook-with-args-until-success
9971 'org-open-link-functions path)))
9973 ((string= type "thisfile")
9974 (if arg
9975 (switch-to-buffer-other-window
9976 (org-get-buffer-for-internal-link (current-buffer)))
9977 (org-mark-ring-push))
9978 (let ((cmd `(org-link-search
9979 ,path
9980 ,(cond ((equal arg '(4)) ''occur)
9981 ((equal arg '(16)) ''org-occur))
9982 ,pos)))
9983 (condition-case nil (let ((org-link-search-inhibit-query t))
9984 (eval cmd))
9985 (error (progn (widen) (eval cmd))))))
9987 (t (browse-url-at-point)))))))
9988 (move-marker org-open-link-marker nil)
9989 (run-hook-with-args 'org-follow-link-hook)))
9991 (defun org-offer-links-in-entry (&optional nth zero)
9992 "Offer links in the current entry and follow the selected link.
9993 If there is only one link, follow it immediately as well.
9994 If NTH is an integer, immediately pick the NTH link found.
9995 If ZERO is a string, check also this string for a link, and if
9996 there is one, offer it as link number zero."
9997 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9998 "\\(" org-angle-link-re "\\)\\|"
9999 "\\(" org-plain-link-re "\\)"))
10000 (cnt ?0)
10001 (in-emacs (if (integerp nth) nil nth))
10002 have-zero end links link c)
10003 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10004 (push (match-string 0 zero) links)
10005 (setq cnt (1- cnt) have-zero t))
10006 (save-excursion
10007 (org-back-to-heading t)
10008 (setq end (save-excursion (outline-next-heading) (point)))
10009 (while (re-search-forward re end t)
10010 (push (match-string 0) links))
10011 (setq links (org-uniquify (reverse links))))
10013 (cond
10014 ((null links)
10015 (message "No links"))
10016 ((equal (length links) 1)
10017 (setq link (list (car links))))
10018 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10019 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10020 (t ; we have to select a link
10021 (save-excursion
10022 (save-window-excursion
10023 (delete-other-windows)
10024 (with-output-to-temp-buffer "*Select Link*"
10025 (mapc (lambda (l)
10026 (if (not (string-match org-bracket-link-regexp l))
10027 (princ (format "[%c] %s\n" (incf cnt)
10028 (org-remove-angle-brackets l)))
10029 (if (match-end 3)
10030 (princ (format "[%c] %s (%s)\n" (incf cnt)
10031 (match-string 3 l) (match-string 1 l)))
10032 (princ (format "[%c] %s\n" (incf cnt)
10033 (match-string 1 l))))))
10034 links))
10035 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10036 (message "Select link to open, RET to open all:")
10037 (setq c (read-char-exclusive))
10038 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10039 (when (equal c ?q) (error "Abort"))
10040 (if (equal c ?\C-m)
10041 (setq link links)
10042 (setq nth (- c ?0))
10043 (if have-zero (setq nth (1+ nth)))
10044 (unless (and (integerp nth) (>= (length links) nth))
10045 (error "Invalid link selection"))
10046 (setq link (list (nth (1- nth) links))))))
10047 (if link
10048 (let ((buf (current-buffer)))
10049 (dolist (l link)
10050 (org-open-link-from-string l in-emacs buf))
10052 nil)))
10054 ;; Add special file links that specify the way of opening
10056 (org-add-link-type "file+sys" 'org-open-file-with-system)
10057 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10058 (defun org-open-file-with-system (path)
10059 "Open file at PATH using the system way of opening it."
10060 (org-open-file path 'system))
10061 (defun org-open-file-with-emacs (path)
10062 "Open file at PATH in Emacs."
10063 (org-open-file path 'emacs))
10064 (defun org-remove-file-link-modifiers ()
10065 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10066 (goto-char (point-min))
10067 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10068 (org-if-unprotected
10069 (replace-match "file:" t t))))
10070 (eval-after-load "org-exp"
10071 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10072 'org-remove-file-link-modifiers))
10074 ;;;; Time estimates
10076 (defun org-get-effort (&optional pom)
10077 "Get the effort estimate for the current entry."
10078 (org-entry-get pom org-effort-property))
10080 ;;; File search
10082 (defvar org-create-file-search-functions nil
10083 "List of functions to construct the right search string for a file link.
10084 These functions are called in turn with point at the location to
10085 which the link should point.
10087 A function in the hook should first test if it would like to
10088 handle this file type, for example by checking the `major-mode'
10089 or the file extension. If it decides not to handle this file, it
10090 should just return nil to give other functions a chance. If it
10091 does handle the file, it must return the search string to be used
10092 when following the link. The search string will be part of the
10093 file link, given after a double colon, and `org-open-at-point'
10094 will automatically search for it. If special measures must be
10095 taken to make the search successful, another function should be
10096 added to the companion hook `org-execute-file-search-functions',
10097 which see.
10099 A function in this hook may also use `setq' to set the variable
10100 `description' to provide a suggestion for the descriptive text to
10101 be used for this link when it gets inserted into an Org-mode
10102 buffer with \\[org-insert-link].")
10104 (defvar org-execute-file-search-functions nil
10105 "List of functions to execute a file search triggered by a link.
10107 Functions added to this hook must accept a single argument, the
10108 search string that was part of the file link, the part after the
10109 double colon. The function must first check if it would like to
10110 handle this search, for example by checking the `major-mode' or
10111 the file extension. If it decides not to handle this search, it
10112 should just return nil to give other functions a chance. If it
10113 does handle the search, it must return a non-nil value to keep
10114 other functions from trying.
10116 Each function can access the current prefix argument through the
10117 variable `current-prefix-argument'. Note that a single prefix is
10118 used to force opening a link in Emacs, so it may be good to only
10119 use a numeric or double prefix to guide the search function.
10121 In case this is needed, a function in this hook can also restore
10122 the window configuration before `org-open-at-point' was called using:
10124 (set-window-configuration org-window-config-before-follow-link)")
10126 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10127 (defun org-link-search (s &optional type avoid-pos stealth)
10128 "Search for a link search option.
10129 If S is surrounded by forward slashes, it is interpreted as a
10130 regular expression. In org-mode files, this will create an `org-occur'
10131 sparse tree. In ordinary files, `occur' will be used to list matches.
10132 If the current buffer is in `dired-mode', grep will be used to search
10133 in all files. If AVOID-POS is given, ignore matches near that position.
10135 When optional argument STEALTH is non-nil, do not modify
10136 visibility around point, thus ignoring
10137 `org-show-hierarchy-above', `org-show-following-heading' and
10138 `org-show-siblings' variables."
10139 (let ((case-fold-search t)
10140 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10141 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10142 (append '(("") (" ") ("\t") ("\n"))
10143 org-emphasis-alist)
10144 "\\|") "\\)"))
10145 (pos (point))
10146 (pre nil) (post nil)
10147 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10148 (cond
10149 ;; First check if there are any special search functions
10150 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10151 ;; Now try the builtin stuff
10152 ((and (equal (string-to-char s0) ?#)
10153 (> (length s0) 1)
10154 (save-excursion
10155 (goto-char (point-min))
10156 (and
10157 (re-search-forward
10158 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10159 (setq type 'dedicated
10160 pos (match-beginning 0))))
10161 ;; There is an exact target for this
10162 (goto-char pos)
10163 (org-back-to-heading t)))
10164 ((save-excursion
10165 (goto-char (point-min))
10166 (and
10167 (re-search-forward
10168 (concat "<<" (regexp-quote s0) ">>") nil t)
10169 (setq type 'dedicated
10170 pos (match-beginning 0))))
10171 ;; There is an exact target for this
10172 (goto-char pos))
10173 ((save-excursion
10174 (goto-char (point-min))
10175 (and
10176 (re-search-forward
10177 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10178 (setq type 'dedicated pos (match-beginning 0))))
10179 ;; Found an invisible target.
10180 (goto-char pos))
10181 ((save-excursion
10182 (goto-char (point-min))
10183 (and
10184 (re-search-forward
10185 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10186 (setq type 'dedicated pos (match-beginning 0))))
10187 ;; Found an element with a matching #+name affiliated keyword.
10188 (goto-char pos))
10189 ((and (string-match "^(\\(.*\\))$" s0)
10190 (save-excursion
10191 (goto-char (point-min))
10192 (and
10193 (re-search-forward
10194 (concat "[^[]" (regexp-quote
10195 (format org-coderef-label-format
10196 (match-string 1 s0))))
10197 nil t)
10198 (setq type 'dedicated
10199 pos (1+ (match-beginning 0))))))
10200 ;; There is a coderef target for this
10201 (goto-char pos))
10202 ((string-match "^/\\(.*\\)/$" s)
10203 ;; A regular expression
10204 (cond
10205 ((derived-mode-p 'org-mode)
10206 (org-occur (match-string 1 s)))
10207 ;;((eq major-mode 'dired-mode)
10208 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10209 (t (org-do-occur (match-string 1 s)))))
10210 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10211 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10212 (goto-char (point-min))
10213 (cond
10214 ((let (case-fold-search)
10215 (re-search-forward (format org-complex-heading-regexp-format
10216 (regexp-quote s))
10217 nil t))
10218 ;; OK, found a match
10219 (setq type 'dedicated)
10220 (goto-char (match-beginning 0)))
10221 ((and (not org-link-search-inhibit-query)
10222 (eq org-link-search-must-match-exact-headline 'query-to-create)
10223 (y-or-n-p "No match - create this as a new heading? "))
10224 (goto-char (point-max))
10225 (or (bolp) (newline))
10226 (insert "* " s "\n")
10227 (beginning-of-line 0))
10229 (goto-char pos)
10230 (error "No match"))))
10232 ;; A normal search string
10233 (when (equal (string-to-char s) ?*)
10234 ;; Anchor on headlines, post may include tags.
10235 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10236 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10237 s (substring s 1)))
10238 (remove-text-properties
10239 0 (length s)
10240 '(face nil mouse-face nil keymap nil fontified nil) s)
10241 ;; Make a series of regular expressions to find a match
10242 (setq words (org-split-string s "[ \n\r\t]+")
10244 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10245 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10246 "\\)" markers)
10247 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10248 re2a (concat "[ \t\r\n]" re2a_)
10249 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10250 re4 (concat "[^a-zA-Z_]" re4_)
10252 re1 (concat pre re2 post)
10253 re3 (concat pre (if pre re4_ re4) post)
10254 re5 (concat pre ".*" re4)
10255 re2 (concat pre re2)
10256 re2a (concat pre (if pre re2a_ re2a))
10257 re4 (concat pre (if pre re4_ re4))
10258 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10259 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10260 re5 "\\)"
10262 (cond
10263 ((eq type 'org-occur) (org-occur reall))
10264 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10265 (t (goto-char (point-min))
10266 (setq type 'fuzzy)
10267 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10268 (org-search-not-self 1 re1 nil t)
10269 (org-search-not-self 1 re2 nil t)
10270 (org-search-not-self 1 re2a nil t)
10271 (org-search-not-self 1 re3 nil t)
10272 (org-search-not-self 1 re4 nil t)
10273 (org-search-not-self 1 re5 nil t)
10275 (goto-char (match-beginning 1))
10276 (goto-char pos)
10277 (error "No match"))))))
10278 (and (derived-mode-p 'org-mode)
10279 (not stealth)
10280 (org-show-context 'link-search))
10281 type))
10283 (defun org-search-not-self (group &rest args)
10284 "Execute `re-search-forward', but only accept matches that do not
10285 enclose the position of `org-open-link-marker'."
10286 (let ((m org-open-link-marker))
10287 (catch 'exit
10288 (while (apply 're-search-forward args)
10289 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10290 (goto-char (match-end group))
10291 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10292 (> (match-beginning 0) (marker-position m))
10293 (< (match-end 0) (marker-position m)))
10294 (save-match-data
10295 (or (not (org-in-regexp
10296 org-bracket-link-analytic-regexp 1))
10297 (not (match-end 4)) ; no description
10298 (and (<= (match-beginning 4) (point))
10299 (>= (match-end 4) (point))))))
10300 (throw 'exit (point))))))))
10302 (defun org-get-buffer-for-internal-link (buffer)
10303 "Return a buffer to be used for displaying the link target of internal links."
10304 (cond
10305 ((not org-display-internal-link-with-indirect-buffer)
10306 buffer)
10307 ((string-match "(Clone)$" (buffer-name buffer))
10308 (message "Buffer is already a clone, not making another one")
10309 ;; we also do not modify visibility in this case
10310 buffer)
10311 (t ; make a new indirect buffer for displaying the link
10312 (let* ((bn (buffer-name buffer))
10313 (ibn (concat bn "(Clone)"))
10314 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10315 (with-current-buffer ib (org-overview))
10316 ib))))
10318 (defun org-do-occur (regexp &optional cleanup)
10319 "Call the Emacs command `occur'.
10320 If CLEANUP is non-nil, remove the printout of the regular expression
10321 in the *Occur* buffer. This is useful if the regex is long and not useful
10322 to read."
10323 (occur regexp)
10324 (when cleanup
10325 (let ((cwin (selected-window)) win beg end)
10326 (when (setq win (get-buffer-window "*Occur*"))
10327 (select-window win))
10328 (goto-char (point-min))
10329 (when (re-search-forward "match[a-z]+" nil t)
10330 (setq beg (match-end 0))
10331 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10332 (setq end (1- (match-beginning 0)))))
10333 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10334 (goto-char (point-min))
10335 (select-window cwin))))
10337 ;;; The mark ring for links jumps
10339 (defvar org-mark-ring nil
10340 "Mark ring for positions before jumps in Org-mode.")
10341 (defvar org-mark-ring-last-goto nil
10342 "Last position in the mark ring used to go back.")
10343 ;; Fill and close the ring
10344 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10345 (loop for i from 1 to org-mark-ring-length do
10346 (push (make-marker) org-mark-ring))
10347 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10348 org-mark-ring)
10350 (defun org-mark-ring-push (&optional pos buffer)
10351 "Put the current position or POS into the mark ring and rotate it."
10352 (interactive)
10353 (setq pos (or pos (point)))
10354 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10355 (move-marker (car org-mark-ring)
10356 (or pos (point))
10357 (or buffer (current-buffer)))
10358 (message "%s"
10359 (substitute-command-keys
10360 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10362 (defun org-mark-ring-goto (&optional n)
10363 "Jump to the previous position in the mark ring.
10364 With prefix arg N, jump back that many stored positions. When
10365 called several times in succession, walk through the entire ring.
10366 Org-mode commands jumping to a different position in the current file,
10367 or to another Org-mode file, automatically push the old position
10368 onto the ring."
10369 (interactive "p")
10370 (let (p m)
10371 (if (eq last-command this-command)
10372 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10373 (setq p org-mark-ring))
10374 (setq org-mark-ring-last-goto p)
10375 (setq m (car p))
10376 (org-pop-to-buffer-same-window (marker-buffer m))
10377 (goto-char m)
10378 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10380 (defun org-remove-angle-brackets (s)
10381 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10382 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10384 (defun org-add-angle-brackets (s)
10385 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10386 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10388 (defun org-remove-double-quotes (s)
10389 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10390 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10393 ;;; Following specific links
10395 (defun org-follow-timestamp-link ()
10396 "Open an agenda view for the time-stamp date/range at point."
10397 (cond
10398 ((org-at-date-range-p t)
10399 (let ((org-agenda-start-on-weekday)
10400 (t1 (match-string 1))
10401 (t2 (match-string 2)) tt1 tt2)
10402 (setq tt1 (time-to-days (org-time-string-to-time t1))
10403 tt2 (time-to-days (org-time-string-to-time t2)))
10404 (let ((org-agenda-buffer-tmp-name
10405 (format "*Org Agenda(a:%s)"
10406 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10407 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10408 ((org-at-timestamp-p t)
10409 (let ((org-agenda-buffer-tmp-name
10410 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10411 (org-agenda-list nil (time-to-days (org-time-string-to-time
10412 (substring (match-string 1) 0 10)))
10413 1)))
10414 (t (error "This should not happen"))))
10417 ;;; Following file links
10418 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10419 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10420 (declare-function mailcap-mime-info
10421 "mailcap" (string &optional request no-decode))
10422 (defvar org-wait nil)
10423 (defun org-open-file (path &optional in-emacs line search)
10424 "Open the file at PATH.
10425 First, this expands any special file name abbreviations. Then the
10426 configuration variable `org-file-apps' is checked if it contains an
10427 entry for this file type, and if yes, the corresponding command is launched.
10429 If no application is found, Emacs simply visits the file.
10431 With optional prefix argument IN-EMACS, Emacs will visit the file.
10432 With a double \\[universal-argument] \\[universal-argument] \
10433 prefix arg, Org tries to avoid opening in Emacs
10434 and to use an external application to visit the file.
10436 Optional LINE specifies a line to go to, optional SEARCH a string
10437 to search for. If LINE or SEARCH is given, the file will be
10438 opened in Emacs, unless an entry from org-file-apps that makes
10439 use of groups in a regexp matches.
10441 If you want to change the way frames are used when following a
10442 link, please customize `org-link-frame-setup'.
10444 If the file does not exist, an error is thrown."
10445 (let* ((file (if (equal path "")
10446 buffer-file-name
10447 (substitute-in-file-name (expand-file-name path))))
10448 (file-apps (append org-file-apps (org-default-apps)))
10449 (apps (org-remove-if
10450 'org-file-apps-entry-match-against-dlink-p file-apps))
10451 (apps-dlink (org-remove-if-not
10452 'org-file-apps-entry-match-against-dlink-p file-apps))
10453 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10454 (dirp (if remp nil (file-directory-p file)))
10455 (file (if (and dirp org-open-directory-means-index-dot-org)
10456 (concat (file-name-as-directory file) "index.org")
10457 file))
10458 (a-m-a-p (assq 'auto-mode apps))
10459 (dfile (downcase file))
10460 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10461 (link (cond ((and (eq line nil)
10462 (eq search nil))
10463 file)
10464 (line
10465 (concat file "::" (number-to-string line)))
10466 (search
10467 (concat file "::" search))))
10468 (dlink (downcase link))
10469 (old-buffer (current-buffer))
10470 (old-pos (point))
10471 (old-mode major-mode)
10472 ext cmd link-match-data)
10473 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10474 (setq ext (match-string 1 dfile))
10475 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10476 (setq ext (match-string 1 dfile))))
10477 (cond
10478 ((member in-emacs '((16) system))
10479 (setq cmd (cdr (assoc 'system apps))))
10480 (in-emacs (setq cmd 'emacs))
10482 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10483 (and dirp (cdr (assoc 'directory apps)))
10484 ; first, try matching against apps-dlink
10485 ; if we get a match here, store the match data for later
10486 (let ((match (assoc-default dlink apps-dlink
10487 'string-match)))
10488 (if match
10489 (progn (setq link-match-data (match-data))
10490 match)
10491 (progn (setq in-emacs (or in-emacs line search))
10492 nil))) ; if we have no match in apps-dlink,
10493 ; always open the file in emacs if line or search
10494 ; is given (for backwards compatibility)
10495 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10496 'string-match)
10497 (cdr (assoc ext apps))
10498 (cdr (assoc t apps))))))
10499 (when (eq cmd 'system)
10500 (setq cmd (cdr (assoc 'system apps))))
10501 (when (eq cmd 'default)
10502 (setq cmd (cdr (assoc t apps))))
10503 (when (eq cmd 'mailcap)
10504 (require 'mailcap)
10505 (mailcap-parse-mailcaps)
10506 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10507 (command (mailcap-mime-info mime-type)))
10508 (if (stringp command)
10509 (setq cmd command)
10510 (setq cmd 'emacs))))
10511 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10512 (not (file-exists-p file))
10513 (not org-open-non-existing-files))
10514 (error "No such file: %s" file))
10515 (cond
10516 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10517 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10518 (while (string-match "['\"]%s['\"]" cmd)
10519 (setq cmd (replace-match "%s" t t cmd)))
10520 (while (string-match "%s" cmd)
10521 (setq cmd (replace-match
10522 (save-match-data
10523 (shell-quote-argument
10524 (convert-standard-filename file)))
10525 t t cmd)))
10527 ;; Replace "%1", "%2" etc. in command with group matches from regex
10528 (save-match-data
10529 (let ((match-index 1)
10530 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10531 (set-match-data link-match-data)
10532 (while (<= match-index number-of-groups)
10533 (let ((regex (concat "%" (number-to-string match-index)))
10534 (replace-with (match-string match-index dlink)))
10535 (while (string-match regex cmd)
10536 (setq cmd (replace-match replace-with t t cmd))))
10537 (setq match-index (+ match-index 1)))))
10539 (save-window-excursion
10540 (message "Running %s...done" cmd)
10541 (start-process-shell-command cmd nil cmd)
10542 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10543 ((or (stringp cmd)
10544 (eq cmd 'emacs))
10545 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10546 (widen)
10547 (if line (org-goto-line line)
10548 (if search (org-link-search search))))
10549 ((consp cmd)
10550 (let ((file (convert-standard-filename file)))
10551 (save-match-data
10552 (set-match-data link-match-data)
10553 (eval cmd))))
10554 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10555 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10556 (or (not (equal old-buffer (current-buffer)))
10557 (not (equal old-pos (point))))
10558 (org-mark-ring-push old-pos old-buffer))))
10560 (defun org-file-apps-entry-match-against-dlink-p (entry)
10561 "This function returns non-nil if `entry' uses a regular
10562 expression which should be matched against the whole link by
10563 org-open-file.
10565 It assumes that is the case when the entry uses a regular
10566 expression which has at least one grouping construct and the
10567 action is either a lisp form or a command string containing
10568 '%1', i.e. using at least one subexpression match as a
10569 parameter."
10570 (let ((selector (car entry))
10571 (action (cdr entry)))
10572 (if (stringp selector)
10573 (and (> (regexp-opt-depth selector) 0)
10574 (or (and (stringp action)
10575 (string-match "%[0-9]" action))
10576 (consp action)))
10577 nil)))
10579 (defun org-default-apps ()
10580 "Return the default applications for this operating system."
10581 (cond
10582 ((eq system-type 'darwin)
10583 org-file-apps-defaults-macosx)
10584 ((eq system-type 'windows-nt)
10585 org-file-apps-defaults-windowsnt)
10586 (t org-file-apps-defaults-gnu)))
10588 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10589 "Convert extensions to regular expressions in the cars of LIST.
10590 Also, weed out any non-string entries, because the return value is used
10591 only for regexp matching.
10592 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10593 point to the symbol `emacs', indicating that the file should
10594 be opened in Emacs."
10595 (append
10596 (delq nil
10597 (mapcar (lambda (x)
10598 (if (not (stringp (car x)))
10600 (if (string-match "\\W" (car x))
10602 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10603 list))
10604 (if add-auto-mode
10605 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10607 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10608 (defun org-file-remote-p (file)
10609 "Test whether FILE specifies a location on a remote system.
10610 Return non-nil if the location is indeed remote.
10612 For example, the filename \"/user@host:/foo\" specifies a location
10613 on the system \"/user@host:\"."
10614 (cond ((fboundp 'file-remote-p)
10615 (file-remote-p file))
10616 ((fboundp 'tramp-handle-file-remote-p)
10617 (tramp-handle-file-remote-p file))
10618 ((and (boundp 'ange-ftp-name-format)
10619 (string-match (car ange-ftp-name-format) file))
10620 t)))
10623 ;;;; Refiling
10625 (defun org-get-org-file ()
10626 "Read a filename, with default directory `org-directory'."
10627 (let ((default (or org-default-notes-file remember-data-file)))
10628 (read-file-name (format "File name [%s]: " default)
10629 (file-name-as-directory org-directory)
10630 default)))
10632 (defun org-notes-order-reversed-p ()
10633 "Check if the current file should receive notes in reversed order."
10634 (cond
10635 ((not org-reverse-note-order) nil)
10636 ((eq t org-reverse-note-order) t)
10637 ((not (listp org-reverse-note-order)) nil)
10638 (t (catch 'exit
10639 (let ((all org-reverse-note-order)
10640 entry)
10641 (while (setq entry (pop all))
10642 (if (string-match (car entry) buffer-file-name)
10643 (throw 'exit (cdr entry))))
10644 nil)))))
10646 (defvar org-refile-target-table nil
10647 "The list of refile targets, created by `org-refile'.")
10649 (defvar org-agenda-new-buffers nil
10650 "Buffers created to visit agenda files.")
10652 (defvar org-refile-cache nil
10653 "Cache for refile targets.")
10655 (defvar org-refile-markers nil
10656 "All the markers used for caching refile locations.")
10658 (defun org-refile-marker (pos)
10659 "Get a new refile marker, but only if caching is in use."
10660 (if (not org-refile-use-cache)
10662 (let ((m (make-marker)))
10663 (move-marker m pos)
10664 (push m org-refile-markers)
10665 m)))
10667 (defun org-refile-cache-clear ()
10668 "Clear the refile cache and disable all the markers."
10669 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10670 (setq org-refile-markers nil)
10671 (setq org-refile-cache nil)
10672 (message "Refile cache has been cleared"))
10674 (defun org-refile-cache-check-set (set)
10675 "Check if all the markers in the cache still have live buffers."
10676 (let (marker)
10677 (catch 'exit
10678 (while (and set (setq marker (nth 3 (pop set))))
10679 ;; if org-refile-use-outline-path is 'file, marker may be nil
10680 (when (and marker (null (marker-buffer marker)))
10681 (message "not found") (sit-for 3)
10682 (throw 'exit nil)))
10683 t)))
10685 (defun org-refile-cache-put (set &rest identifiers)
10686 "Push the refile targets SET into the cache, under IDENTIFIERS."
10687 (let* ((key (sha1 (prin1-to-string identifiers)))
10688 (entry (assoc key org-refile-cache)))
10689 (if entry
10690 (setcdr entry set)
10691 (push (cons key set) org-refile-cache))))
10693 (defun org-refile-cache-get (&rest identifiers)
10694 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10695 (cond
10696 ((not org-refile-cache) nil)
10697 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10699 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10700 org-refile-cache))))
10701 (and set (org-refile-cache-check-set set) set)))))
10703 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10704 "Produce a table with refile targets."
10705 (let ((case-fold-search nil)
10706 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10707 (entries (or org-refile-targets '((nil . (:level . 1)))))
10708 targets tgs txt re files f desc descre fast-path-p level pos0)
10709 (message "Getting targets...")
10710 (with-current-buffer (or default-buffer (current-buffer))
10711 (while (setq entry (pop entries))
10712 (setq files (car entry) desc (cdr entry))
10713 (setq fast-path-p nil)
10714 (cond
10715 ((null files) (setq files (list (current-buffer))))
10716 ((eq files 'org-agenda-files)
10717 (setq files (org-agenda-files 'unrestricted)))
10718 ((and (symbolp files) (fboundp files))
10719 (setq files (funcall files)))
10720 ((and (symbolp files) (boundp files))
10721 (setq files (symbol-value files))))
10722 (if (stringp files) (setq files (list files)))
10723 (cond
10724 ((eq (car desc) :tag)
10725 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10726 ((eq (car desc) :todo)
10727 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10728 ((eq (car desc) :regexp)
10729 (setq descre (cdr desc)))
10730 ((eq (car desc) :level)
10731 (setq descre (concat "^\\*\\{" (number-to-string
10732 (if org-odd-levels-only
10733 (1- (* 2 (cdr desc)))
10734 (cdr desc)))
10735 "\\}[ \t]")))
10736 ((eq (car desc) :maxlevel)
10737 (setq fast-path-p t)
10738 (setq descre (concat "^\\*\\{1," (number-to-string
10739 (if org-odd-levels-only
10740 (1- (* 2 (cdr desc)))
10741 (cdr desc)))
10742 "\\}[ \t]")))
10743 (t (error "Bad refiling target description %s" desc)))
10744 (while (setq f (pop files))
10745 (with-current-buffer
10746 (if (bufferp f) f (org-get-agenda-file-buffer f))
10748 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10749 (progn
10750 (if (bufferp f) (setq f (buffer-file-name
10751 (buffer-base-buffer f))))
10752 (setq f (and f (expand-file-name f)))
10753 (if (eq org-refile-use-outline-path 'file)
10754 (push (list (file-name-nondirectory f) f nil nil) tgs))
10755 (save-excursion
10756 (save-restriction
10757 (widen)
10758 (goto-char (point-min))
10759 (while (re-search-forward descre nil t)
10760 (goto-char (setq pos0 (point-at-bol)))
10761 (catch 'next
10762 (when org-refile-target-verify-function
10763 (save-match-data
10764 (or (funcall org-refile-target-verify-function)
10765 (throw 'next t))))
10766 (when (and (looking-at org-complex-heading-regexp)
10767 (not (member (match-string 4) excluded-entries))
10768 (match-string 4))
10769 (setq level (org-reduced-level
10770 (- (match-end 1) (match-beginning 1)))
10771 txt (org-link-display-format (match-string 4))
10772 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10773 re (format org-complex-heading-regexp-format
10774 (regexp-quote (match-string 4))))
10775 (when org-refile-use-outline-path
10776 (setq txt (mapconcat
10777 'org-protect-slash
10778 (append
10779 (if (eq org-refile-use-outline-path
10780 'file)
10781 (list (file-name-nondirectory
10782 (buffer-file-name
10783 (buffer-base-buffer))))
10784 (if (eq org-refile-use-outline-path
10785 'full-file-path)
10786 (list (buffer-file-name
10787 (buffer-base-buffer)))))
10788 (org-get-outline-path fast-path-p
10789 level txt)
10790 (list txt))
10791 "/")))
10792 (push (list txt f re (org-refile-marker (point)))
10793 tgs)))
10794 (when (= (point) pos0)
10795 ;; verification function has not moved point
10796 (goto-char (point-at-eol))))))))
10797 (when org-refile-use-cache
10798 (org-refile-cache-put tgs (buffer-file-name) descre))
10799 (setq targets (append tgs targets))
10800 ))))
10801 (message "Getting targets...done")
10802 (nreverse targets)))
10804 (defun org-protect-slash (s)
10805 (while (string-match "/" s)
10806 (setq s (replace-match "\\" t t s)))
10809 (defvar org-olpa (make-vector 20 nil))
10811 (defun org-get-outline-path (&optional fastp level heading)
10812 "Return the outline path to the current entry, as a list.
10814 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10815 routine which makes outline path derivations for an entire file,
10816 avoiding backtracing. Refile target collection makes use of that."
10817 (if fastp
10818 (progn
10819 (if (> level 19)
10820 (error "Outline path failure, more than 19 levels"))
10821 (loop for i from level upto 19 do
10822 (aset org-olpa i nil))
10823 (prog1
10824 (delq nil (append org-olpa nil))
10825 (aset org-olpa level heading)))
10826 (let (rtn case-fold-search)
10827 (save-excursion
10828 (save-restriction
10829 (widen)
10830 (while (org-up-heading-safe)
10831 (when (looking-at org-complex-heading-regexp)
10832 (push (org-match-string-no-properties 4) rtn)))
10833 rtn)))))
10835 (defun org-format-outline-path (path &optional width prefix separator)
10836 "Format the outline path PATH for display.
10837 WIDTH is the maximum number of characters that is available.
10838 PREFIX is a prefix to be included in the returned string,
10839 such as the file name.
10840 SEPARATOR is inserted between the different parts of the path,
10841 the default is \"/\"."
10842 (setq width (or width 79))
10843 (if prefix (setq width (- width (length prefix))))
10844 (if (not path)
10845 (or prefix "")
10846 (let* ((nsteps (length path))
10847 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10848 (maxwidth (if (<= total-width width)
10849 10000 ;; everything fits
10850 ;; we need to shorten the level headings
10851 (/ (- width nsteps) nsteps)))
10852 (org-odd-levels-only nil)
10853 (n 0)
10854 (total (1+ (length prefix))))
10855 (setq maxwidth (max maxwidth 10))
10856 (concat prefix
10857 (if prefix (or separator "/"))
10858 (mapconcat
10859 (lambda (h)
10860 (setq n (1+ n))
10861 (if (and (= n nsteps) (< maxwidth 10000))
10862 (setq maxwidth (- total-width total)))
10863 (if (< (length h) maxwidth)
10864 (progn (setq total (+ total (length h) 1)) h)
10865 (setq h (substring h 0 (- maxwidth 2))
10866 total (+ total maxwidth 1))
10867 (if (string-match "[ \t]+\\'" h)
10868 (setq h (substring h 0 (match-beginning 0))))
10869 (setq h (concat h "..")))
10870 (org-add-props h nil 'face
10871 (nth (% (1- n) org-n-level-faces)
10872 org-level-faces))
10874 path (or separator "/"))))))
10876 (defun org-display-outline-path (&optional file current separator just-return-string)
10877 "Display the current outline path in the echo area.
10879 If FILE is non-nil, prepend the output with the file name.
10880 If CURRENT is non-nil, append the current heading to the output.
10881 SEPARATOR is passed through to `org-format-outline-path'. It separates
10882 the different parts of the path and defaults to \"/\".
10883 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10884 (interactive "P")
10885 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10886 (case-fold-search nil)
10887 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10888 res)
10889 (if current (setq path (append path
10890 (save-excursion
10891 (org-back-to-heading t)
10892 (if (looking-at org-complex-heading-regexp)
10893 (list (match-string 4)))))))
10894 (setq res
10895 (org-format-outline-path
10896 path
10897 (1- (frame-width))
10898 (and file bfn (concat (file-name-nondirectory bfn) separator))
10899 separator))
10900 (if just-return-string
10901 (org-no-properties res)
10902 (message "%s" res))))
10904 (defvar org-refile-history nil
10905 "History for refiling operations.")
10907 (defvar org-after-refile-insert-hook nil
10908 "Hook run after `org-refile' has inserted its stuff at the new location.
10909 Note that this is still *before* the stuff will be removed from
10910 the *old* location.")
10912 (defvar org-capture-last-stored-marker)
10913 (defvar org-refile-keep nil
10914 "Non-nil means `org-refile' will copy instead of refile.")
10916 (defun org-copy ()
10917 "Like `org-refile', but copy."
10918 (interactive)
10919 (let ((org-refile-keep t))
10920 (funcall 'org-refile nil nil nil "Copy")))
10922 (defun org-refile (&optional goto default-buffer rfloc msg)
10923 "Move the entry or entries at point to another heading.
10924 The list of target headings is compiled using the information in
10925 `org-refile-targets', which see.
10927 At the target location, the entry is filed as a subitem of the target
10928 heading. Depending on `org-reverse-note-order', the new subitem will
10929 either be the first or the last subitem.
10931 If there is an active region, all entries in that region will be moved.
10932 However, the region must fulfill the requirement that the first heading
10933 is the first one sets the top-level of the moved text - at most siblings
10934 below it are allowed.
10936 With prefix arg GOTO, the command will only visit the target location
10937 and not actually move anything.
10939 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10940 go to the location where the last refiling operation has put the subtree.
10941 With a prefix argument of `2', refile to the running clock.
10943 RFLOC can be a refile location obtained in a different way.
10945 MSG is a string to replace \"Refile\" in the default prompt with
10946 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10948 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10950 If you are using target caching (see `org-refile-use-cache'),
10951 you have to clear the target cache in order to find new targets.
10952 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10953 prefix argument (`C-u C-u C-u C-c C-w')."
10955 (interactive "P")
10956 (if (member goto '(0 (64)))
10957 (org-refile-cache-clear)
10958 (let* ((actionmsg (or msg "Refile"))
10959 (cbuf (current-buffer))
10960 (regionp (org-region-active-p))
10961 (region-start (and regionp (region-beginning)))
10962 (region-end (and regionp (region-end)))
10963 (region-length (and regionp (- region-end region-start)))
10964 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10965 pos it nbuf file re level reversed)
10966 (setq last-command nil)
10967 (when regionp
10968 (goto-char region-start)
10969 (or (bolp) (goto-char (point-at-bol)))
10970 (setq region-start (point))
10971 (unless (or (org-kill-is-subtree-p
10972 (buffer-substring region-start region-end))
10973 (prog1 org-refile-active-region-within-subtree
10974 (org-toggle-heading)))
10975 (error "The region is not a (sequence of) subtree(s)")))
10976 (if (equal goto '(16))
10977 (org-refile-goto-last-stored)
10978 (when (or
10979 (and (equal goto 2)
10980 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10981 (prog1
10982 (setq it (list (or org-clock-heading "running clock")
10983 (buffer-file-name
10984 (marker-buffer org-clock-hd-marker))
10986 (marker-position org-clock-hd-marker)))
10987 (setq goto nil)))
10988 (setq it (or rfloc
10989 (let (heading-text)
10990 (save-excursion
10991 (unless goto
10992 (org-back-to-heading t)
10993 (setq heading-text
10994 (nth 4 (org-heading-components))))
10996 (org-refile-get-location
10997 (cond (goto "Goto")
10998 (regionp (concat actionmsg " region to"))
10999 (t (concat actionmsg " subtree \""
11000 heading-text "\" to")))
11001 default-buffer
11002 (and (not (equal '(4) goto))
11003 org-refile-allow-creating-parent-nodes)
11004 goto))))))
11005 (setq file (nth 1 it)
11006 re (nth 2 it)
11007 pos (nth 3 it))
11008 (if (and (not goto)
11010 (equal (buffer-file-name) file)
11011 (if regionp
11012 (and (>= pos region-start)
11013 (<= pos region-end))
11014 (and (>= pos (point))
11015 (< pos (save-excursion
11016 (org-end-of-subtree t t))))))
11017 (error "Cannot refile to position inside the tree or region"))
11019 (setq nbuf (or (find-buffer-visiting file)
11020 (find-file-noselect file)))
11021 (if goto
11022 (progn
11023 (org-pop-to-buffer-same-window nbuf)
11024 (goto-char pos)
11025 (org-show-context 'org-goto))
11026 (if regionp
11027 (progn
11028 (org-kill-new (buffer-substring region-start region-end))
11029 (org-save-markers-in-region region-start region-end))
11030 (org-copy-subtree 1 nil t))
11031 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11032 (find-file-noselect file)))
11033 (setq reversed (org-notes-order-reversed-p))
11034 (save-excursion
11035 (save-restriction
11036 (widen)
11037 (if pos
11038 (progn
11039 (goto-char pos)
11040 (looking-at org-outline-regexp)
11041 (setq level (org-get-valid-level (funcall outline-level) 1))
11042 (goto-char
11043 (if reversed
11044 (or (outline-next-heading) (point-max))
11045 (or (save-excursion (org-get-next-sibling))
11046 (org-end-of-subtree t t)
11047 (point-max)))))
11048 (setq level 1)
11049 (if (not reversed)
11050 (goto-char (point-max))
11051 (goto-char (point-min))
11052 (or (outline-next-heading) (goto-char (point-max)))))
11053 (if (not (bolp)) (newline))
11054 (org-paste-subtree level)
11055 (when org-log-refile
11056 (org-add-log-setup 'refile nil nil 'findpos
11057 org-log-refile)
11058 (unless (eq org-log-refile 'note)
11059 (save-excursion (org-add-log-note))))
11060 (and org-auto-align-tags
11061 (let ((org-loop-over-headlines-in-active-region nil))
11062 (org-set-tags nil t)))
11063 (bookmark-set "org-refile-last-stored")
11064 ;; If we are refiling for capture, make sure that the
11065 ;; last-capture pointers point here
11066 (when (org-bound-and-true-p org-refile-for-capture)
11067 (bookmark-set "org-capture-last-stored-marker")
11068 (move-marker org-capture-last-stored-marker (point)))
11069 (if (fboundp 'deactivate-mark) (deactivate-mark))
11070 (run-hooks 'org-after-refile-insert-hook))))
11071 (unless org-refile-keep
11072 (if regionp
11073 (delete-region (point) (+ (point) region-length))
11074 (org-cut-subtree)))
11075 (when (featurep 'org-inlinetask)
11076 (org-inlinetask-remove-END-maybe))
11077 (setq org-markers-to-move nil)
11078 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11080 (defun org-refile-goto-last-stored ()
11081 "Go to the location where the last refile was stored."
11082 (interactive)
11083 (bookmark-jump "org-refile-last-stored")
11084 (message "This is the location of the last refile"))
11086 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11087 no-exclude)
11088 "Prompt the user for a refile location, using PROMPT.
11089 PROMPT should not be suffixed with a colon and a space, because
11090 this function appends the default value from
11091 `org-refile-history' automatically, if that is not empty.
11092 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11093 this is used for the GOTO interface."
11094 (let ((org-refile-targets org-refile-targets)
11095 (org-refile-use-outline-path org-refile-use-outline-path)
11096 excluded-entries)
11097 (when (and (derived-mode-p 'org-mode)
11098 (not org-refile-use-cache)
11099 (not no-exclude))
11100 (org-map-tree
11101 (lambda()
11102 (setq excluded-entries
11103 (append excluded-entries (list (org-get-heading t t)))))))
11104 (setq org-refile-target-table
11105 (org-refile-get-targets default-buffer excluded-entries)))
11106 (unless org-refile-target-table
11107 (error "No refile targets"))
11108 (let* ((cbuf (current-buffer))
11109 (partial-completion-mode nil)
11110 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11111 (cfunc (if (and org-refile-use-outline-path
11112 org-outline-path-complete-in-steps)
11113 'org-olpath-completing-read
11114 'org-icompleting-read))
11115 (extra (if org-refile-use-outline-path "/" ""))
11116 (cbnex (concat (buffer-name) extra))
11117 (filename (and cfn (expand-file-name cfn)))
11118 (tbl (mapcar
11119 (lambda (x)
11120 (if (and (not (member org-refile-use-outline-path
11121 '(file full-file-path)))
11122 (not (equal filename (nth 1 x))))
11123 (cons (concat (car x) extra " ("
11124 (file-name-nondirectory (nth 1 x)) ")")
11125 (cdr x))
11126 (cons (concat (car x) extra) (cdr x))))
11127 org-refile-target-table))
11128 (completion-ignore-case t)
11129 cdef
11130 (prompt (concat prompt
11131 (or (and (car org-refile-history)
11132 (concat " (default " (car org-refile-history) ")"))
11133 (and (assoc cbnex tbl) (setq cdef cbnex)
11134 (concat " (default " cbnex ")"))) ": "))
11135 pa answ parent-target child parent old-hist)
11136 (setq old-hist org-refile-history)
11137 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11138 nil 'org-refile-history (or cdef (car org-refile-history))))
11139 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11140 (org-refile-check-position pa)
11141 (if pa
11142 (progn
11143 (when (or (not org-refile-history)
11144 (not (eq old-hist org-refile-history))
11145 (not (equal (car pa) (car org-refile-history))))
11146 (setq org-refile-history
11147 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11148 org-refile-history
11149 (cdr org-refile-history))))
11150 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11151 (pop org-refile-history)))
11153 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11154 (progn
11155 (setq parent (match-string 1 answ)
11156 child (match-string 2 answ))
11157 (setq parent-target (or (assoc parent tbl)
11158 (assoc (concat parent "/") tbl)))
11159 (when (and parent-target
11160 (or (eq new-nodes t)
11161 (and (eq new-nodes 'confirm)
11162 (y-or-n-p (format "Create new node \"%s\"? "
11163 child)))))
11164 (org-refile-new-child parent-target child)))
11165 (error "Invalid target location")))))
11167 (declare-function org-string-nw-p "org-macs.el" (s))
11168 (defun org-refile-check-position (refile-pointer)
11169 "Check if the refile pointer matches the readline to which it points."
11170 (let* ((file (nth 1 refile-pointer))
11171 (re (nth 2 refile-pointer))
11172 (pos (nth 3 refile-pointer))
11173 buffer)
11174 (when (org-string-nw-p re)
11175 (setq buffer (if (markerp pos)
11176 (marker-buffer pos)
11177 (or (find-buffer-visiting file)
11178 (find-file-noselect file))))
11179 (with-current-buffer buffer
11180 (save-excursion
11181 (save-restriction
11182 (widen)
11183 (goto-char pos)
11184 (beginning-of-line 1)
11185 (unless (org-looking-at-p re)
11186 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11188 (defun org-refile-new-child (parent-target child)
11189 "Use refile target PARENT-TARGET to add new CHILD below it."
11190 (unless parent-target
11191 (error "Cannot find parent for new node"))
11192 (let ((file (nth 1 parent-target))
11193 (pos (nth 3 parent-target))
11194 level)
11195 (with-current-buffer (or (find-buffer-visiting file)
11196 (find-file-noselect file))
11197 (save-excursion
11198 (save-restriction
11199 (widen)
11200 (if pos
11201 (goto-char pos)
11202 (goto-char (point-max))
11203 (if (not (bolp)) (newline)))
11204 (when (looking-at org-outline-regexp)
11205 (setq level (funcall outline-level))
11206 (org-end-of-subtree t t))
11207 (org-back-over-empty-lines)
11208 (insert "\n" (make-string
11209 (if pos (org-get-valid-level level 1) 1) ?*)
11210 " " child "\n")
11211 (beginning-of-line 0)
11212 (list (concat (car parent-target) "/" child) file "" (point)))))))
11214 (defun org-olpath-completing-read (prompt collection &rest args)
11215 "Read an outline path like a file name."
11216 (let ((thetable collection)
11217 (org-completion-use-ido nil) ; does not work with ido.
11218 (org-completion-use-iswitchb nil)) ; or iswitchb
11219 (apply
11220 'org-icompleting-read prompt
11221 (lambda (string predicate &optional flag)
11222 (let (rtn r f (l (length string)))
11223 (cond
11224 ((eq flag nil)
11225 ;; try completion
11226 (try-completion string thetable))
11227 ((eq flag t)
11228 ;; all-completions
11229 (setq rtn (all-completions string thetable predicate))
11230 (mapcar
11231 (lambda (x)
11232 (setq r (substring x l))
11233 (if (string-match " ([^)]*)$" x)
11234 (setq f (match-string 0 x))
11235 (setq f ""))
11236 (if (string-match "/" r)
11237 (concat string (substring r 0 (match-end 0)) f)
11239 rtn))
11240 ((eq flag 'lambda)
11241 ;; exact match?
11242 (assoc string thetable)))))
11243 args)))
11245 ;;;; Dynamic blocks
11247 (defun org-find-dblock (name)
11248 "Find the first dynamic block with name NAME in the buffer.
11249 If not found, stay at current position and return nil."
11250 (let ((case-fold-search t) pos)
11251 (save-excursion
11252 (goto-char (point-min))
11253 (setq pos (and (re-search-forward
11254 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11255 (match-beginning 0))))
11256 (if pos (goto-char pos))
11257 pos))
11259 (defconst org-dblock-start-re
11260 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11261 "Matches the start line of a dynamic block, with parameters.")
11263 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11264 "Matches the end of a dynamic block.")
11266 (defun org-create-dblock (plist)
11267 "Create a dynamic block section, with parameters taken from PLIST.
11268 PLIST must contain a :name entry which is used as name of the block."
11269 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11270 (end-of-line 1)
11271 (newline))
11272 (let ((col (current-column))
11273 (name (plist-get plist :name)))
11274 (insert "#+BEGIN: " name)
11275 (while plist
11276 (if (eq (car plist) :name)
11277 (setq plist (cddr plist))
11278 (insert " " (prin1-to-string (pop plist)))))
11279 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11280 (beginning-of-line -2)))
11282 (defun org-prepare-dblock ()
11283 "Prepare dynamic block for refresh.
11284 This empties the block, puts the cursor at the insert position and returns
11285 the property list including an extra property :name with the block name."
11286 (unless (looking-at org-dblock-start-re)
11287 (error "Not at a dynamic block"))
11288 (let* ((begdel (1+ (match-end 0)))
11289 (name (org-no-properties (match-string 1)))
11290 (params (append (list :name name)
11291 (read (concat "(" (match-string 3) ")")))))
11292 (save-excursion
11293 (beginning-of-line 1)
11294 (skip-chars-forward " \t")
11295 (setq params (plist-put params :indentation-column (current-column))))
11296 (unless (re-search-forward org-dblock-end-re nil t)
11297 (error "Dynamic block not terminated"))
11298 (setq params
11299 (append params
11300 (list :content (buffer-substring
11301 begdel (match-beginning 0)))))
11302 (delete-region begdel (match-beginning 0))
11303 (goto-char begdel)
11304 (open-line 1)
11305 params))
11307 (defun org-map-dblocks (&optional command)
11308 "Apply COMMAND to all dynamic blocks in the current buffer.
11309 If COMMAND is not given, use `org-update-dblock'."
11310 (let ((cmd (or command 'org-update-dblock)))
11311 (save-excursion
11312 (goto-char (point-min))
11313 (while (re-search-forward org-dblock-start-re nil t)
11314 (goto-char (match-beginning 0))
11315 (save-excursion
11316 (condition-case nil
11317 (funcall cmd)
11318 (error (message "Error during update of dynamic block"))))
11319 (unless (re-search-forward org-dblock-end-re nil t)
11320 (error "Dynamic block not terminated"))))))
11322 (defun org-dblock-update (&optional arg)
11323 "User command for updating dynamic blocks.
11324 Update the dynamic block at point. With prefix ARG, update all dynamic
11325 blocks in the buffer."
11326 (interactive "P")
11327 (if arg
11328 (org-update-all-dblocks)
11329 (or (looking-at org-dblock-start-re)
11330 (org-beginning-of-dblock))
11331 (org-update-dblock)))
11333 (defun org-update-dblock ()
11334 "Update the dynamic block at point.
11335 This means to empty the block, parse for parameters and then call
11336 the correct writing function."
11337 (interactive)
11338 (save-window-excursion
11339 (let* ((pos (point))
11340 (line (org-current-line))
11341 (params (org-prepare-dblock))
11342 (name (plist-get params :name))
11343 (indent (plist-get params :indentation-column))
11344 (cmd (intern (concat "org-dblock-write:" name))))
11345 (message "Updating dynamic block `%s' at line %d..." name line)
11346 (funcall cmd params)
11347 (message "Updating dynamic block `%s' at line %d...done" name line)
11348 (goto-char pos)
11349 (when (and indent (> indent 0))
11350 (setq indent (make-string indent ?\ ))
11351 (save-excursion
11352 (org-beginning-of-dblock)
11353 (forward-line 1)
11354 (while (not (looking-at org-dblock-end-re))
11355 (insert indent)
11356 (beginning-of-line 2))
11357 (when (looking-at org-dblock-end-re)
11358 (and (looking-at "[ \t]+")
11359 (replace-match ""))
11360 (insert indent)))))))
11362 (defun org-beginning-of-dblock ()
11363 "Find the beginning of the dynamic block at point.
11364 Error if there is no such block at point."
11365 (let ((pos (point))
11366 beg)
11367 (end-of-line 1)
11368 (if (and (re-search-backward org-dblock-start-re nil t)
11369 (setq beg (match-beginning 0))
11370 (re-search-forward org-dblock-end-re nil t)
11371 (> (match-end 0) pos))
11372 (goto-char beg)
11373 (goto-char pos)
11374 (error "Not in a dynamic block"))))
11376 ;;;###autoload
11377 (defun org-update-all-dblocks ()
11378 "Update all dynamic blocks in the buffer.
11379 This function can be used in a hook."
11380 (interactive)
11381 (when (derived-mode-p 'org-mode)
11382 (org-map-dblocks 'org-update-dblock)))
11385 ;;;; Completion
11387 (defconst org-additional-option-like-keywords
11388 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11389 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11390 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11391 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11392 "BEGIN:" "END:"
11393 "ORGTBL" "TBLFM:" "TBLNAME:"
11394 "BEGIN_EXAMPLE" "END_EXAMPLE"
11395 "BEGIN_VERBATIM" "END_VERBATIM"
11396 "BEGIN_QUOTE" "END_QUOTE"
11397 "BEGIN_VERSE" "END_VERSE"
11398 "BEGIN_CENTER" "END_CENTER"
11399 "BEGIN_SRC" "END_SRC"
11400 "BEGIN_RESULT" "END_RESULT"
11401 "BEGIN_lstlisting" "END_lstlisting"
11402 "NAME:" "RESULTS:"
11403 "HEADER:" "HEADERS:"
11404 "COLUMNS:" "PROPERTY:"
11405 "CAPTION:" "LABEL:"
11406 "SETUPFILE:"
11407 "INCLUDE:"
11408 "BIND:"
11409 "MACRO:"))
11411 (defconst org-options-keywords
11412 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11413 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11414 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11415 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11416 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11417 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11418 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11420 (defconst org-additional-option-like-keywords-for-flyspell
11421 (delete-dups
11422 (split-string
11423 (mapconcat (lambda(k)
11424 (replace-regexp-in-string
11425 "_\\|:" " "
11426 (concat k " " (downcase k) " " (upcase k))))
11427 (append org-options-keywords org-additional-option-like-keywords)
11428 " ")
11429 " +" t)))
11431 (defcustom org-structure-template-alist
11433 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11434 "<src lang=\"?\">\n\n</src>")
11435 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11436 "<example>\n?\n</example>")
11437 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11438 "<quote>\n?\n</quote>")
11439 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11440 "<verse>\n?\n</verse>")
11441 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11442 "<center>\n?\n</center>")
11443 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11444 "<literal style=\"latex\">\n?\n</literal>")
11445 ("L" "#+LaTeX: "
11446 "<literal style=\"latex\">?</literal>")
11447 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11448 "<literal style=\"html\">\n?\n</literal>")
11449 ("H" "#+HTML: "
11450 "<literal style=\"html\">?</literal>")
11451 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11452 ("A" "#+ASCII: ")
11453 ("i" "#+INDEX: ?"
11454 "#+INDEX: ?")
11455 ("I" "#+INCLUDE: %file ?"
11456 "<include file=%file markup=\"?\">")
11458 "Structure completion elements.
11459 This is a list of abbreviation keys and values. The value gets inserted
11460 if you type `<' followed by the key and then press the completion key,
11461 usually `M-TAB'. %file will be replaced by a file name after prompting
11462 for the file using completion. The cursor will be placed at the position
11463 of the `?` in the template.
11464 There are two templates for each key, the first uses the original Org syntax,
11465 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11466 the default when the /org-mtags.el/ module has been loaded. See also the
11467 variable `org-mtags-prefer-muse-templates'."
11468 :group 'org-completion
11469 :type '(repeat
11470 (string :tag "Key")
11471 (string :tag "Template")
11472 (string :tag "Muse Template")))
11474 (defun org-try-structure-completion ()
11475 "Try to complete a structure template before point.
11476 This looks for strings like \"<e\" on an otherwise empty line and
11477 expands them."
11478 (let ((l (buffer-substring (point-at-bol) (point)))
11480 (when (and (looking-at "[ \t]*$")
11481 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11482 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11483 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11484 (match-beginning 1)) a)
11485 t)))
11487 (defun org-complete-expand-structure-template (start cell)
11488 "Expand a structure template."
11489 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11490 (rpl (nth (if musep 2 1) cell))
11491 (ind ""))
11492 (delete-region start (point))
11493 (when (string-match "\\`#\\+" rpl)
11494 (cond
11495 ((bolp))
11496 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11497 (setq ind (buffer-substring (point-at-bol) (point))))
11498 (t (newline))))
11499 (setq start (point))
11500 (if (string-match "%file" rpl)
11501 (setq rpl (replace-match
11502 (concat
11503 "\""
11504 (save-match-data
11505 (abbreviate-file-name (read-file-name "Include file: ")))
11506 "\"")
11507 t t rpl)))
11508 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11509 (concat "\n" ind)))
11510 (insert rpl)
11511 (if (re-search-backward "\\?" start t) (delete-char 1))))
11513 ;;;; TODO, DEADLINE, Comments
11515 (defun org-toggle-comment ()
11516 "Change the COMMENT state of an entry."
11517 (interactive)
11518 (save-excursion
11519 (org-back-to-heading)
11520 (let (case-fold-search)
11521 (cond
11522 ((looking-at (format org-heading-keyword-regexp-format
11523 org-comment-string))
11524 (goto-char (match-end 1))
11525 (looking-at (concat " +" org-comment-string))
11526 (replace-match "" t t)
11527 (when (eolp) (insert " ")))
11528 ((looking-at org-outline-regexp)
11529 (goto-char (match-end 0))
11530 (insert org-comment-string " "))))))
11532 (defvar org-last-todo-state-is-todo nil
11533 "This is non-nil when the last TODO state change led to a TODO state.
11534 If the last change removed the TODO tag or switched to DONE, then
11535 this is nil.")
11537 (defvar org-setting-tags nil) ; dynamically skipped
11539 (defvar org-todo-setup-filter-hook nil
11540 "Hook for functions that pre-filter todo specs.
11541 Each function takes a todo spec and returns either nil or the spec
11542 transformed into canonical form." )
11544 (defvar org-todo-get-default-hook nil
11545 "Hook for functions that get a default item for todo.
11546 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11547 nil or a string to be used for the todo mark." )
11549 (defvar org-agenda-headline-snapshot-before-repeat)
11551 (defun org-current-effective-time ()
11552 "Return current time adjusted for `org-extend-today-until' variable."
11553 (let* ((ct (org-current-time))
11554 (dct (decode-time ct))
11555 (ct1
11556 (cond
11557 (org-use-last-clock-out-time-as-effective-time
11558 (or (org-clock-get-last-clock-out-time) ct))
11559 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11560 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11561 (t ct))))
11562 ct1))
11564 (defun org-todo-yesterday (&optional arg)
11565 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11566 (interactive "P")
11567 (if (eq major-mode 'org-agenda-mode)
11568 (apply 'org-agenda-todo-yesterday arg)
11569 (let* ((hour (third (decode-time
11570 (org-current-time))))
11571 (org-extend-today-until (1+ hour)))
11572 (org-todo arg))))
11574 (defun org-todo (&optional arg)
11575 "Change the TODO state of an item.
11576 The state of an item is given by a keyword at the start of the heading,
11577 like
11578 *** TODO Write paper
11579 *** DONE Call mom
11581 The different keywords are specified in the variable `org-todo-keywords'.
11582 By default the available states are \"TODO\" and \"DONE\".
11583 So for this example: when the item starts with TODO, it is changed to DONE.
11584 When it starts with DONE, the DONE is removed. And when neither TODO nor
11585 DONE are present, add TODO at the beginning of the heading.
11587 With \\[universal-argument] prefix arg, use completion to determine the new \
11588 state.
11589 With numeric prefix arg, switch to that state.
11590 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11591 keywords (nextset).
11592 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11593 With a numeric prefix arg of 0, inhibit note taking for the change.
11595 For calling through lisp, arg is also interpreted in the following way:
11596 'none -> empty state
11597 \"\"(empty string) -> switch to empty state
11598 'done -> switch to DONE
11599 'nextset -> switch to the next set of keywords
11600 'previousset -> switch to the previous set of keywords
11601 \"WAITING\" -> switch to the specified keyword, but only if it
11602 really is a member of `org-todo-keywords'."
11603 (interactive "P")
11604 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11605 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11606 'region-start-level 'region))
11607 org-loop-over-headlines-in-active-region)
11608 (org-map-entries
11609 `(org-todo ,arg)
11610 org-loop-over-headlines-in-active-region
11611 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11612 (if (equal arg '(16)) (setq arg 'nextset))
11613 (let ((org-blocker-hook org-blocker-hook)
11614 (case-fold-search nil))
11615 (when (equal arg '(64))
11616 (setq arg nil org-blocker-hook nil))
11617 (when (and org-blocker-hook
11618 (or org-inhibit-blocking
11619 (org-entry-get nil "NOBLOCKING")))
11620 (setq org-blocker-hook nil))
11621 (save-excursion
11622 (catch 'exit
11623 (org-back-to-heading t)
11624 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11625 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11626 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11627 (let* ((match-data (match-data))
11628 (startpos (point-at-bol))
11629 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11630 (org-log-done org-log-done)
11631 (org-log-repeat org-log-repeat)
11632 (org-todo-log-states org-todo-log-states)
11633 (org-inhibit-logging
11634 (if (equal arg 0)
11635 (progn (setq arg nil) 'note) org-inhibit-logging))
11636 (this (match-string 1))
11637 (hl-pos (match-beginning 0))
11638 (head (org-get-todo-sequence-head this))
11639 (ass (assoc head org-todo-kwd-alist))
11640 (interpret (nth 1 ass))
11641 (done-word (nth 3 ass))
11642 (final-done-word (nth 4 ass))
11643 (org-last-state (or this ""))
11644 (completion-ignore-case t)
11645 (member (member this org-todo-keywords-1))
11646 (tail (cdr member))
11647 (org-state (cond
11648 ((and org-todo-key-trigger
11649 (or (and (equal arg '(4))
11650 (eq org-use-fast-todo-selection 'prefix))
11651 (and (not arg) org-use-fast-todo-selection
11652 (not (eq org-use-fast-todo-selection
11653 'prefix)))))
11654 ;; Use fast selection
11655 (org-fast-todo-selection))
11656 ((and (equal arg '(4))
11657 (or (not org-use-fast-todo-selection)
11658 (not org-todo-key-trigger)))
11659 ;; Read a state with completion
11660 (org-icompleting-read
11661 "State: " (mapcar (lambda(x) (list x))
11662 org-todo-keywords-1)
11663 nil t))
11664 ((eq arg 'right)
11665 (if this
11666 (if tail (car tail) nil)
11667 (car org-todo-keywords-1)))
11668 ((eq arg 'left)
11669 (if (equal member org-todo-keywords-1)
11671 (if this
11672 (nth (- (length org-todo-keywords-1)
11673 (length tail) 2)
11674 org-todo-keywords-1)
11675 (org-last org-todo-keywords-1))))
11676 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11677 (setq arg nil))) ; hack to fall back to cycling
11678 (arg
11679 ;; user or caller requests a specific state
11680 (cond
11681 ((equal arg "") nil)
11682 ((eq arg 'none) nil)
11683 ((eq arg 'done) (or done-word (car org-done-keywords)))
11684 ((eq arg 'nextset)
11685 (or (car (cdr (member head org-todo-heads)))
11686 (car org-todo-heads)))
11687 ((eq arg 'previousset)
11688 (let ((org-todo-heads (reverse org-todo-heads)))
11689 (or (car (cdr (member head org-todo-heads)))
11690 (car org-todo-heads))))
11691 ((car (member arg org-todo-keywords-1)))
11692 ((stringp arg)
11693 (error "State `%s' not valid in this file" arg))
11694 ((nth (1- (prefix-numeric-value arg))
11695 org-todo-keywords-1))))
11696 ((null member) (or head (car org-todo-keywords-1)))
11697 ((equal this final-done-word) nil) ;; -> make empty
11698 ((null tail) nil) ;; -> first entry
11699 ((memq interpret '(type priority))
11700 (if (eq this-command last-command)
11701 (car tail)
11702 (if (> (length tail) 0)
11703 (or done-word (car org-done-keywords))
11704 nil)))
11706 (car tail))))
11707 (org-state (or
11708 (run-hook-with-args-until-success
11709 'org-todo-get-default-hook org-state org-last-state)
11710 org-state))
11711 (next (if org-state (concat " " org-state " ") " "))
11712 (change-plist (list :type 'todo-state-change :from this :to org-state
11713 :position startpos))
11714 dolog now-done-p)
11715 (when org-blocker-hook
11716 (setq org-last-todo-state-is-todo
11717 (not (member this org-done-keywords)))
11718 (unless (save-excursion
11719 (save-match-data
11720 (org-with-wide-buffer
11721 (run-hook-with-args-until-failure
11722 'org-blocker-hook change-plist))))
11723 (if (org-called-interactively-p 'interactive)
11724 (error "TODO state change from %s to %s blocked" this org-state)
11725 ;; fail silently
11726 (message "TODO state change from %s to %s blocked" this org-state)
11727 (throw 'exit nil))))
11728 (store-match-data match-data)
11729 (replace-match next t t)
11730 (unless (pos-visible-in-window-p hl-pos)
11731 (message "TODO state changed to %s" (org-trim next)))
11732 (unless head
11733 (setq head (org-get-todo-sequence-head org-state)
11734 ass (assoc head org-todo-kwd-alist)
11735 interpret (nth 1 ass)
11736 done-word (nth 3 ass)
11737 final-done-word (nth 4 ass)))
11738 (when (memq arg '(nextset previousset))
11739 (message "Keyword-Set %d/%d: %s"
11740 (- (length org-todo-sets) -1
11741 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11742 (length org-todo-sets)
11743 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11744 (setq org-last-todo-state-is-todo
11745 (not (member org-state org-done-keywords)))
11746 (setq now-done-p (and (member org-state org-done-keywords)
11747 (not (member this org-done-keywords))))
11748 (and logging (org-local-logging logging))
11749 (when (and (or org-todo-log-states org-log-done)
11750 (not (eq org-inhibit-logging t))
11751 (not (memq arg '(nextset previousset))))
11752 ;; we need to look at recording a time and note
11753 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11754 (nth 2 (assoc this org-todo-log-states))))
11755 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11756 (setq dolog 'time))
11757 (when (and org-state
11758 (member org-state org-not-done-keywords)
11759 (not (member this org-not-done-keywords)))
11760 ;; This is now a todo state and was not one before
11761 ;; If there was a CLOSED time stamp, get rid of it.
11762 (org-add-planning-info nil nil 'closed))
11763 (when (and now-done-p org-log-done)
11764 ;; It is now done, and it was not done before
11765 (org-add-planning-info 'closed (org-current-effective-time))
11766 (if (and (not dolog) (eq 'note org-log-done))
11767 (org-add-log-setup 'done org-state this 'findpos 'note)))
11768 (when (and org-state dolog)
11769 ;; This is a non-nil state, and we need to log it
11770 (org-add-log-setup 'state org-state this 'findpos dolog)))
11771 ;; Fixup tag positioning
11772 (org-todo-trigger-tag-changes org-state)
11773 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11774 (when org-provide-todo-statistics
11775 (org-update-parent-todo-statistics))
11776 (run-hooks 'org-after-todo-state-change-hook)
11777 (if (and arg (not (member org-state org-done-keywords)))
11778 (setq head (org-get-todo-sequence-head org-state)))
11779 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11780 ;; Do we need to trigger a repeat?
11781 (when now-done-p
11782 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11783 ;; This is for the agenda, take a snapshot of the headline.
11784 (save-match-data
11785 (setq org-agenda-headline-snapshot-before-repeat
11786 (org-get-heading))))
11787 (org-auto-repeat-maybe org-state))
11788 ;; Fixup cursor location if close to the keyword
11789 (if (and (outline-on-heading-p)
11790 (not (bolp))
11791 (save-excursion (beginning-of-line 1)
11792 (looking-at org-todo-line-regexp))
11793 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11794 (progn
11795 (goto-char (or (match-end 2) (match-end 1)))
11796 (and (looking-at " ") (just-one-space))))
11797 (when org-trigger-hook
11798 (save-excursion
11799 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11801 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11802 "Block turning an entry into a TODO, using the hierarchy.
11803 This checks whether the current task should be blocked from state
11804 changes. Such blocking occurs when:
11806 1. The task has children which are not all in a completed state.
11808 2. A task has a parent with the property :ORDERED:, and there
11809 are siblings prior to the current task with incomplete
11810 status.
11812 3. The parent of the task is blocked because it has siblings that should
11813 be done first, or is child of a block grandparent TODO entry."
11815 (if (not org-enforce-todo-dependencies)
11816 t ; if locally turned off don't block
11817 (catch 'dont-block
11818 ;; If this is not a todo state change, or if this entry is already DONE,
11819 ;; do not block
11820 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11821 (member (plist-get change-plist :from)
11822 (cons 'done org-done-keywords))
11823 (member (plist-get change-plist :to)
11824 (cons 'todo org-not-done-keywords))
11825 (not (plist-get change-plist :to)))
11826 (throw 'dont-block t))
11827 ;; If this task has children, and any are undone, it's blocked
11828 (save-excursion
11829 (org-back-to-heading t)
11830 (let ((this-level (funcall outline-level)))
11831 (outline-next-heading)
11832 (let ((child-level (funcall outline-level)))
11833 (while (and (not (eobp))
11834 (> child-level this-level))
11835 ;; this todo has children, check whether they are all
11836 ;; completed
11837 (if (and (not (org-entry-is-done-p))
11838 (org-entry-is-todo-p))
11839 (throw 'dont-block nil))
11840 (outline-next-heading)
11841 (setq child-level (funcall outline-level))))))
11842 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11843 ;; any previous siblings are undone, it's blocked
11844 (save-excursion
11845 (org-back-to-heading t)
11846 (let* ((pos (point))
11847 (parent-pos (and (org-up-heading-safe) (point))))
11848 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11849 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11850 (forward-line 1)
11851 (re-search-forward org-not-done-heading-regexp pos t))
11852 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11853 ;; Search further up the hierarchy, to see if an ancestor is blocked
11854 (while t
11855 (goto-char parent-pos)
11856 (if (not (looking-at org-not-done-heading-regexp))
11857 (throw 'dont-block t)) ; do not block, parent is not a TODO
11858 (setq pos (point))
11859 (setq parent-pos (and (org-up-heading-safe) (point)))
11860 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11861 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11862 (forward-line 1)
11863 (re-search-forward org-not-done-heading-regexp pos t))
11864 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11866 (defcustom org-track-ordered-property-with-tag nil
11867 "Should the ORDERED property also be shown as a tag?
11868 The ORDERED property decides if an entry should require subtasks to be
11869 completed in sequence. Since a property is not very visible, setting
11870 this option means that toggling the ORDERED property with the command
11871 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11872 not relevant for the behavior, but it makes things more visible.
11874 Note that toggling the tag with tags commands will not change the property
11875 and therefore not influence behavior!
11877 This can be t, meaning the tag ORDERED should be used, It can also be a
11878 string to select a different tag for this task."
11879 :group 'org-todo
11880 :type '(choice
11881 (const :tag "No tracking" nil)
11882 (const :tag "Track with ORDERED tag" t)
11883 (string :tag "Use other tag")))
11885 (defun org-toggle-ordered-property ()
11886 "Toggle the ORDERED property of the current entry.
11887 For better visibility, you can track the value of this property with a tag.
11888 See variable `org-track-ordered-property-with-tag'."
11889 (interactive)
11890 (let* ((t1 org-track-ordered-property-with-tag)
11891 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11892 (save-excursion
11893 (org-back-to-heading)
11894 (if (org-entry-get nil "ORDERED")
11895 (progn
11896 (org-delete-property "ORDERED")
11897 (and tag (org-toggle-tag tag 'off))
11898 (message "Subtasks can be completed in arbitrary order"))
11899 (org-entry-put nil "ORDERED" "t")
11900 (and tag (org-toggle-tag tag 'on))
11901 (message "Subtasks must be completed in sequence")))))
11903 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11904 (defun org-block-todo-from-checkboxes (change-plist)
11905 "Block turning an entry into a TODO, using checkboxes.
11906 This checks whether the current task should be blocked from state
11907 changes because there are unchecked boxes in this entry."
11908 (if (not org-enforce-todo-checkbox-dependencies)
11909 t ; if locally turned off don't block
11910 (catch 'dont-block
11911 ;; If this is not a todo state change, or if this entry is already DONE,
11912 ;; do not block
11913 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11914 (member (plist-get change-plist :from)
11915 (cons 'done org-done-keywords))
11916 (member (plist-get change-plist :to)
11917 (cons 'todo org-not-done-keywords))
11918 (not (plist-get change-plist :to)))
11919 (throw 'dont-block t))
11920 ;; If this task has checkboxes that are not checked, it's blocked
11921 (save-excursion
11922 (org-back-to-heading t)
11923 (let ((beg (point)) end)
11924 (outline-next-heading)
11925 (setq end (point))
11926 (goto-char beg)
11927 (if (org-list-search-forward
11928 (concat (org-item-beginning-re)
11929 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11930 "\\[[- ]\\]")
11931 end t)
11932 (progn
11933 (if (boundp 'org-blocked-by-checkboxes)
11934 (setq org-blocked-by-checkboxes t))
11935 (throw 'dont-block nil)))))
11936 t))) ; do not block
11938 (defun org-entry-blocked-p ()
11939 "Is the current entry blocked?"
11940 (if (org-entry-get nil "NOBLOCKING")
11941 nil ;; Never block this entry
11942 (not
11943 (run-hook-with-args-until-failure
11944 'org-blocker-hook
11945 (list :type 'todo-state-change
11946 :position (point)
11947 :from 'todo
11948 :to 'done)))))
11950 (defun org-update-statistics-cookies (all)
11951 "Update the statistics cookie, either from TODO or from checkboxes.
11952 This should be called with the cursor in a line with a statistics cookie."
11953 (interactive "P")
11954 (if all
11955 (progn
11956 (org-update-checkbox-count 'all)
11957 (org-map-entries 'org-update-parent-todo-statistics))
11958 (if (not (org-at-heading-p))
11959 (org-update-checkbox-count)
11960 (let ((pos (move-marker (make-marker) (point)))
11961 end l1 l2)
11962 (ignore-errors (org-back-to-heading t))
11963 (if (not (org-at-heading-p))
11964 (org-update-checkbox-count)
11965 (setq l1 (org-outline-level))
11966 (setq end (save-excursion
11967 (outline-next-heading)
11968 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11969 (point)))
11970 (if (and (save-excursion
11971 (re-search-forward
11972 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11973 (not (save-excursion (re-search-forward
11974 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11975 (org-update-checkbox-count)
11976 (if (and l2 (> l2 l1))
11977 (progn
11978 (goto-char end)
11979 (org-update-parent-todo-statistics))
11980 (goto-char pos)
11981 (beginning-of-line 1)
11982 (while (re-search-forward
11983 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11984 (point-at-eol) t)
11985 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11986 (goto-char pos)
11987 (move-marker pos nil)))))
11989 (defvar org-entry-property-inherited-from) ;; defined below
11990 (defun org-update-parent-todo-statistics ()
11991 "Update any statistics cookie in the parent of the current headline.
11992 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11993 the entire subtree and this will travel up the hierarchy and update
11994 statistics everywhere."
11995 (let* ((prop (save-excursion (org-up-heading-safe)
11996 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11997 (recursive (or (not org-hierarchical-todo-statistics)
11998 (and prop (string-match "\\<recursive\\>" prop))))
11999 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12001 (first t)
12002 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12003 level ltoggle l1 new ndel
12004 (cnt-all 0) (cnt-done 0) is-percent kwd
12005 checkbox-beg ov ovs ove cookie-present)
12006 (catch 'exit
12007 (save-excursion
12008 (beginning-of-line 1)
12009 (setq ltoggle (funcall outline-level))
12010 ;; Three situations are to consider:
12012 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12013 ;; to the top-level ancestor on the headline;
12015 ;; 2. If parent has "recursive" property, repeat up to the
12016 ;; headline setting that property, taking inheritance into
12017 ;; account;
12019 ;; 3. Else, move up to direct parent and proceed only once.
12020 (while (and (setq level (org-up-heading-safe))
12021 (or recursive first)
12022 (>= (point) lim))
12023 (setq first nil cookie-present nil)
12024 (unless (and level
12025 (not (string-match
12026 "\\<checkbox\\>"
12027 (downcase (or (org-entry-get nil "COOKIE_DATA")
12028 "")))))
12029 (throw 'exit nil))
12030 (while (re-search-forward box-re (point-at-eol) t)
12031 (setq cnt-all 0 cnt-done 0 cookie-present t)
12032 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12033 (save-match-data
12034 (unless (outline-next-heading) (throw 'exit nil))
12035 (while (and (looking-at org-complex-heading-regexp)
12036 (> (setq l1 (length (match-string 1))) level))
12037 (setq kwd (and (or recursive (= l1 ltoggle))
12038 (match-string 2)))
12039 (if (or (eq org-provide-todo-statistics 'all-headlines)
12040 (and (listp org-provide-todo-statistics)
12041 (or (member kwd org-provide-todo-statistics)
12042 (member kwd org-done-keywords))))
12043 (setq cnt-all (1+ cnt-all))
12044 (if (eq org-provide-todo-statistics t)
12045 (and kwd (setq cnt-all (1+ cnt-all)))))
12046 (and (member kwd org-done-keywords)
12047 (setq cnt-done (1+ cnt-done)))
12048 (outline-next-heading)))
12049 (setq new
12050 (if is-percent
12051 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12052 (format "[%d/%d]" cnt-done cnt-all))
12053 ndel (- (match-end 0) checkbox-beg))
12054 ;; handle overlays when updating cookie from column view
12055 (when (setq ov (car (overlays-at checkbox-beg)))
12056 (setq ovs (overlay-start ov) ove (overlay-end ov))
12057 (delete-overlay ov))
12058 (goto-char checkbox-beg)
12059 (insert new)
12060 (delete-region (point) (+ (point) ndel))
12061 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12062 (when ov (move-overlay ov ovs ove)))
12063 (when cookie-present
12064 (run-hook-with-args 'org-after-todo-statistics-hook
12065 cnt-done (- cnt-all cnt-done))))))
12066 (run-hooks 'org-todo-statistics-hook)))
12068 (defvar org-after-todo-statistics-hook nil
12069 "Hook that is called after a TODO statistics cookie has been updated.
12070 Each function is called with two arguments: the number of not-done entries
12071 and the number of done entries.
12073 For example, the following function, when added to this hook, will switch
12074 an entry to DONE when all children are done, and back to TODO when new
12075 entries are set to a TODO status. Note that this hook is only called
12076 when there is a statistics cookie in the headline!
12078 (defun org-summary-todo (n-done n-not-done)
12079 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12080 (let (org-log-done org-log-states) ; turn off logging
12081 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12084 (defvar org-todo-statistics-hook nil
12085 "Hook that is run whenever Org thinks TODO statistics should be updated.
12086 This hook runs even if there is no statistics cookie present, in which case
12087 `org-after-todo-statistics-hook' would not run.")
12089 (defun org-todo-trigger-tag-changes (state)
12090 "Apply the changes defined in `org-todo-state-tags-triggers'."
12091 (let ((l org-todo-state-tags-triggers)
12092 changes)
12093 (when (or (not state) (equal state ""))
12094 (setq changes (append changes (cdr (assoc "" l)))))
12095 (when (and (stringp state) (> (length state) 0))
12096 (setq changes (append changes (cdr (assoc state l)))))
12097 (when (member state org-not-done-keywords)
12098 (setq changes (append changes (cdr (assoc 'todo l)))))
12099 (when (member state org-done-keywords)
12100 (setq changes (append changes (cdr (assoc 'done l)))))
12101 (dolist (c changes)
12102 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12104 (defun org-local-logging (value)
12105 "Get logging settings from a property VALUE."
12106 (let* (words w a)
12107 ;; directly set the variables, they are already local.
12108 (setq org-log-done nil
12109 org-log-repeat nil
12110 org-todo-log-states nil)
12111 (setq words (org-split-string value))
12112 (while (setq w (pop words))
12113 (cond
12114 ((setq a (assoc w org-startup-options))
12115 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12116 (set (nth 1 a) (nth 2 a))))
12117 ((setq a (org-extract-log-state-settings w))
12118 (and (member (car a) org-todo-keywords-1)
12119 (push a org-todo-log-states)))))))
12121 (defun org-get-todo-sequence-head (kwd)
12122 "Return the head of the TODO sequence to which KWD belongs.
12123 If KWD is not set, check if there is a text property remembering the
12124 right sequence."
12125 (let (p)
12126 (cond
12127 ((not kwd)
12128 (or (get-text-property (point-at-bol) 'org-todo-head)
12129 (progn
12130 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12131 nil (point-at-eol)))
12132 (get-text-property p 'org-todo-head))))
12133 ((not (member kwd org-todo-keywords-1))
12134 (car org-todo-keywords-1))
12135 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12137 (defun org-fast-todo-selection ()
12138 "Fast TODO keyword selection with single keys.
12139 Returns the new TODO keyword, or nil if no state change should occur."
12140 (let* ((fulltable org-todo-key-alist)
12141 (done-keywords org-done-keywords) ;; needed for the faces.
12142 (maxlen (apply 'max (mapcar
12143 (lambda (x)
12144 (if (stringp (car x)) (string-width (car x)) 0))
12145 fulltable)))
12146 (expert nil)
12147 (fwidth (+ maxlen 3 1 3))
12148 (ncol (/ (- (window-width) 4) fwidth))
12149 tg cnt e c tbl
12150 groups ingroup)
12151 (save-excursion
12152 (save-window-excursion
12153 (if expert
12154 (set-buffer (get-buffer-create " *Org todo*"))
12155 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12156 (erase-buffer)
12157 (org-set-local 'org-done-keywords done-keywords)
12158 (setq tbl fulltable cnt 0)
12159 (while (setq e (pop tbl))
12160 (cond
12161 ((equal e '(:startgroup))
12162 (push '() groups) (setq ingroup t)
12163 (when (not (= cnt 0))
12164 (setq cnt 0)
12165 (insert "\n"))
12166 (insert "{ "))
12167 ((equal e '(:endgroup))
12168 (setq ingroup nil cnt 0)
12169 (insert "}\n"))
12170 ((equal e '(:newline))
12171 (when (not (= cnt 0))
12172 (setq cnt 0)
12173 (insert "\n")
12174 (setq e (car tbl))
12175 (while (equal (car tbl) '(:newline))
12176 (insert "\n")
12177 (setq tbl (cdr tbl)))))
12179 (setq tg (car e) c (cdr e))
12180 (if ingroup (push tg (car groups)))
12181 (setq tg (org-add-props tg nil 'face
12182 (org-get-todo-face tg)))
12183 (if (and (= cnt 0) (not ingroup)) (insert " "))
12184 (insert "[" c "] " tg (make-string
12185 (- fwidth 4 (length tg)) ?\ ))
12186 (when (= (setq cnt (1+ cnt)) ncol)
12187 (insert "\n")
12188 (if ingroup (insert " "))
12189 (setq cnt 0)))))
12190 (insert "\n")
12191 (goto-char (point-min))
12192 (if (not expert) (org-fit-window-to-buffer))
12193 (message "[a-z..]:Set [SPC]:clear")
12194 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12195 (cond
12196 ((or (= c ?\C-g)
12197 (and (= c ?q) (not (rassoc c fulltable))))
12198 (setq quit-flag t))
12199 ((= c ?\ ) nil)
12200 ((setq e (rassoc c fulltable) tg (car e))
12202 (t (setq quit-flag t)))))))
12204 (defun org-entry-is-todo-p ()
12205 (member (org-get-todo-state) org-not-done-keywords))
12207 (defun org-entry-is-done-p ()
12208 (member (org-get-todo-state) org-done-keywords))
12210 (defun org-get-todo-state ()
12211 (save-excursion
12212 (org-back-to-heading t)
12213 (and (looking-at org-todo-line-regexp)
12214 (match-end 2)
12215 (match-string 2))))
12217 (defun org-at-date-range-p (&optional inactive-ok)
12218 "Is the cursor inside a date range?"
12219 (interactive)
12220 (save-excursion
12221 (catch 'exit
12222 (let ((pos (point)))
12223 (skip-chars-backward "^[<\r\n")
12224 (skip-chars-backward "<[")
12225 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12226 (>= (match-end 0) pos)
12227 (throw 'exit t))
12228 (skip-chars-backward "^<[\r\n")
12229 (skip-chars-backward "<[")
12230 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12231 (>= (match-end 0) pos)
12232 (throw 'exit t)))
12233 nil)))
12235 (defun org-get-repeat (&optional tagline)
12236 "Check if there is a deadline/schedule with repeater in this entry."
12237 (save-match-data
12238 (save-excursion
12239 (org-back-to-heading t)
12240 (and (re-search-forward (if tagline
12241 (concat tagline "\\s-*" org-repeat-re)
12242 org-repeat-re)
12243 (org-entry-end-position) t)
12244 (match-string-no-properties 1)))))
12246 (defvar org-last-changed-timestamp)
12247 (defvar org-last-inserted-timestamp)
12248 (defvar org-log-post-message)
12249 (defvar org-log-note-purpose)
12250 (defvar org-log-note-how)
12251 (defvar org-log-note-extra)
12252 (defun org-auto-repeat-maybe (done-word)
12253 "Check if the current headline contains a repeated deadline/schedule.
12254 If yes, set TODO state back to what it was and change the base date
12255 of repeating deadline/scheduled time stamps to new date.
12256 This function is run automatically after each state change to a DONE state."
12257 ;; last-state is dynamically scoped into this function
12258 (let* ((repeat (org-get-repeat))
12259 (aa (assoc org-last-state org-todo-kwd-alist))
12260 (interpret (nth 1 aa))
12261 (head (nth 2 aa))
12262 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12263 (msg "Entry repeats: ")
12264 (org-log-done nil)
12265 (org-todo-log-states nil)
12266 re type n what ts time to-state)
12267 (when repeat
12268 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12269 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12270 org-todo-repeat-to-state))
12271 (unless (and to-state (member to-state org-todo-keywords-1))
12272 (setq to-state (if (eq interpret 'type) org-last-state head)))
12273 (org-todo to-state)
12274 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12275 (org-entry-put nil "LAST_REPEAT" (format-time-string
12276 (org-time-stamp-format t t))))
12277 (when org-log-repeat
12278 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12279 (memq 'org-add-log-note post-command-hook))
12280 ;; OK, we are already setup for some record
12281 (if (eq org-log-repeat 'note)
12282 ;; make sure we take a note, not only a time stamp
12283 (setq org-log-note-how 'note))
12284 ;; Set up for taking a record
12285 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12286 org-last-state
12287 'findpos org-log-repeat)))
12288 (org-back-to-heading t)
12289 (org-add-planning-info nil nil 'closed)
12290 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12291 org-deadline-time-regexp "\\)\\|\\("
12292 org-ts-regexp "\\)"))
12293 (while (re-search-forward
12294 re (save-excursion (outline-next-heading) (point)) t)
12295 (setq type (if (match-end 1) org-scheduled-string
12296 (if (match-end 3) org-deadline-string "Plain:"))
12297 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12298 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12299 (setq n (string-to-number (match-string 2 ts))
12300 what (match-string 3 ts))
12301 (if (equal what "w") (setq n (* n 7) what "d"))
12302 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12303 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12304 ;; Preparation, see if we need to modify the start date for the change
12305 (when (match-end 1)
12306 (setq time (save-match-data (org-time-string-to-time ts)))
12307 (cond
12308 ((equal (match-string 1 ts) ".")
12309 ;; Shift starting date to today
12310 (org-timestamp-change
12311 (- (org-today) (time-to-days time))
12312 'day))
12313 ((equal (match-string 1 ts) "+")
12314 (let ((nshiftmax 10) (nshift 0))
12315 (while (or (= nshift 0)
12316 (<= (time-to-days time)
12317 (time-to-days (current-time))))
12318 (when (= (incf nshift) nshiftmax)
12319 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12320 (error "Abort")))
12321 (org-timestamp-change n (cdr (assoc what whata)))
12322 (org-at-timestamp-p t)
12323 (setq ts (match-string 1))
12324 (setq time (save-match-data (org-time-string-to-time ts)))))
12325 (org-timestamp-change (- n) (cdr (assoc what whata)))
12326 ;; rematch, so that we have everything in place for the real shift
12327 (org-at-timestamp-p t)
12328 (setq ts (match-string 1))
12329 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12330 (org-timestamp-change n (cdr (assoc what whata)))
12331 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12332 (setq org-log-post-message msg)
12333 (message "%s" msg))))
12335 (defun org-show-todo-tree (arg)
12336 "Make a compact tree which shows all headlines marked with TODO.
12337 The tree will show the lines where the regexp matches, and all higher
12338 headlines above the match.
12339 With a \\[universal-argument] prefix, prompt for a regexp to match.
12340 With a numeric prefix N, construct a sparse tree for the Nth element
12341 of `org-todo-keywords-1'."
12342 (interactive "P")
12343 (let ((case-fold-search nil)
12344 (kwd-re
12345 (cond ((null arg) org-not-done-regexp)
12346 ((equal arg '(4))
12347 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12348 (mapcar 'list org-todo-keywords-1))))
12349 (concat "\\("
12350 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12351 "\\)\\>")))
12352 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12353 (regexp-quote (nth (1- (prefix-numeric-value arg))
12354 org-todo-keywords-1)))
12355 (t (error "Invalid prefix argument: %s" arg)))))
12356 (message "%d TODO entries found"
12357 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12359 (defun org-deadline (&optional remove time)
12360 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12361 With argument REMOVE, remove any deadline from the item.
12362 With argument TIME, set the deadline at the corresponding date. TIME
12363 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12364 (interactive "P")
12365 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12366 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12367 'region-start-level 'region))
12368 org-loop-over-headlines-in-active-region)
12369 (org-map-entries
12370 `(org-deadline ',remove ,time)
12371 org-loop-over-headlines-in-active-region
12372 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12373 (let* ((old-date (org-entry-get nil "DEADLINE"))
12374 (repeater (and old-date
12375 (string-match
12376 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12377 old-date)
12378 (match-string 1 old-date))))
12379 (if remove
12380 (progn
12381 (when (and old-date org-log-redeadline)
12382 (org-add-log-setup 'deldeadline nil old-date 'findpos
12383 org-log-redeadline))
12384 (org-remove-timestamp-with-keyword org-deadline-string)
12385 (message "Item no longer has a deadline."))
12386 (org-add-planning-info 'deadline time 'closed)
12387 (when (and old-date org-log-redeadline
12388 (not (equal old-date
12389 (substring org-last-inserted-timestamp 1 -1))))
12390 (org-add-log-setup 'redeadline nil old-date 'findpos
12391 org-log-redeadline))
12392 (when repeater
12393 (save-excursion
12394 (org-back-to-heading t)
12395 (when (re-search-forward (concat org-deadline-string " "
12396 org-last-inserted-timestamp)
12397 (save-excursion
12398 (outline-next-heading) (point)) t)
12399 (goto-char (1- (match-end 0)))
12400 (insert " " repeater)
12401 (setq org-last-inserted-timestamp
12402 (concat (substring org-last-inserted-timestamp 0 -1)
12403 " " repeater
12404 (substring org-last-inserted-timestamp -1))))))
12405 (message "Deadline on %s" org-last-inserted-timestamp)))))
12407 (defun org-schedule (&optional remove time)
12408 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12409 With argument REMOVE, remove any scheduling date from the item.
12410 With argument TIME, scheduled at the corresponding date. TIME can
12411 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12412 (interactive "P")
12413 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12414 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12415 'region-start-level 'region))
12416 org-loop-over-headlines-in-active-region)
12417 (org-map-entries
12418 `(org-schedule ',remove ,time)
12419 org-loop-over-headlines-in-active-region
12420 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12421 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12422 (repeater (and old-date
12423 (string-match
12424 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12425 old-date)
12426 (match-string 1 old-date))))
12427 (if remove
12428 (progn
12429 (when (and old-date org-log-reschedule)
12430 (org-add-log-setup 'delschedule nil old-date 'findpos
12431 org-log-reschedule))
12432 (org-remove-timestamp-with-keyword org-scheduled-string)
12433 (message "Item is no longer scheduled."))
12434 (org-add-planning-info 'scheduled time 'closed)
12435 (when (and old-date org-log-reschedule
12436 (not (equal old-date
12437 (substring org-last-inserted-timestamp 1 -1))))
12438 (org-add-log-setup 'reschedule nil old-date 'findpos
12439 org-log-reschedule))
12440 (when repeater
12441 (save-excursion
12442 (org-back-to-heading t)
12443 (when (re-search-forward (concat org-scheduled-string " "
12444 org-last-inserted-timestamp)
12445 (save-excursion
12446 (outline-next-heading) (point)) t)
12447 (goto-char (1- (match-end 0)))
12448 (insert " " repeater)
12449 (setq org-last-inserted-timestamp
12450 (concat (substring org-last-inserted-timestamp 0 -1)
12451 " " repeater
12452 (substring org-last-inserted-timestamp -1))))))
12453 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12455 (defun org-get-scheduled-time (pom &optional inherit)
12456 "Get the scheduled time as a time tuple, of a format suitable
12457 for calling org-schedule with, or if there is no scheduling,
12458 returns nil."
12459 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12460 (when time
12461 (apply 'encode-time (org-parse-time-string time)))))
12463 (defun org-get-deadline-time (pom &optional inherit)
12464 "Get the deadline as a time tuple, of a format suitable for
12465 calling org-deadline with, or if there is no scheduling, returns
12466 nil."
12467 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12468 (when time
12469 (apply 'encode-time (org-parse-time-string time)))))
12471 (defun org-remove-timestamp-with-keyword (keyword)
12472 "Remove all time stamps with KEYWORD in the current entry."
12473 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12474 beg)
12475 (save-excursion
12476 (org-back-to-heading t)
12477 (setq beg (point))
12478 (outline-next-heading)
12479 (while (re-search-backward re beg t)
12480 (replace-match "")
12481 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12482 (equal (char-before) ?\ ))
12483 (backward-delete-char 1)
12484 (if (string-match "^[ \t]*$" (buffer-substring
12485 (point-at-bol) (point-at-eol)))
12486 (delete-region (point-at-bol)
12487 (min (point-max) (1+ (point-at-eol))))))))))
12489 (defun org-add-planning-info (what &optional time &rest remove)
12490 "Insert new timestamp with keyword in the line directly after the headline.
12491 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12492 If non is given, the user is prompted for a date.
12493 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12494 be removed."
12495 (interactive)
12496 (let (org-time-was-given org-end-time-was-given ts
12497 end default-time default-input)
12499 (catch 'exit
12500 (when (and (memq what '(scheduled deadline))
12501 (or (not time)
12502 (and (stringp time)
12503 (string-match "^[-+]+[0-9]" time))))
12504 ;; Try to get a default date/time from existing timestamp
12505 (save-excursion
12506 (org-back-to-heading t)
12507 (setq end (save-excursion (outline-next-heading) (point)))
12508 (when (re-search-forward (if (eq what 'scheduled)
12509 org-scheduled-time-regexp
12510 org-deadline-time-regexp)
12511 end t)
12512 (setq ts (match-string 1)
12513 default-time
12514 (apply 'encode-time (org-parse-time-string ts))
12515 default-input (and ts (org-get-compact-tod ts))))))
12516 (when what
12517 (setq time
12518 (if (stringp time)
12519 ;; This is a string (relative or absolute), set proper date
12520 (apply 'encode-time
12521 (org-read-date-analyze
12522 time default-time (decode-time default-time)))
12523 ;; If necessary, get the time from the user
12524 (or time (org-read-date nil 'to-time nil nil
12525 default-time default-input)))))
12527 (when (and org-insert-labeled-timestamps-at-point
12528 (member what '(scheduled deadline)))
12529 (insert
12530 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12531 (org-insert-time-stamp time org-time-was-given
12532 nil nil nil (list org-end-time-was-given))
12533 (setq what nil))
12534 (save-excursion
12535 (save-restriction
12536 (let (col list elt ts buffer-invisibility-spec)
12537 (org-back-to-heading t)
12538 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12539 (goto-char (match-end 1))
12540 (setq col (current-column))
12541 (goto-char (match-end 0))
12542 (if (eobp) (insert "\n") (forward-char 1))
12543 (when (and (not what)
12544 (not (looking-at
12545 (concat "[ \t]*"
12546 org-keyword-time-not-clock-regexp))))
12547 ;; Nothing to add, nothing to remove...... :-)
12548 (throw 'exit nil))
12549 (if (and (not (looking-at org-outline-regexp))
12550 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12551 "[^\r\n]*"))
12552 (not (equal (match-string 1) org-clock-string)))
12553 (narrow-to-region (match-beginning 0) (match-end 0))
12554 (insert-before-markers "\n")
12555 (backward-char 1)
12556 (narrow-to-region (point) (point))
12557 (and org-adapt-indentation (org-indent-to-column col)))
12558 ;; Check if we have to remove something.
12559 (setq list (cons what remove))
12560 (while list
12561 (setq elt (pop list))
12562 (when (or (and (eq elt 'scheduled)
12563 (re-search-forward org-scheduled-time-regexp nil t))
12564 (and (eq elt 'deadline)
12565 (re-search-forward org-deadline-time-regexp nil t))
12566 (and (eq elt 'closed)
12567 (re-search-forward org-closed-time-regexp nil t)))
12568 (replace-match "")
12569 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12570 (and (looking-at "[ \t]+") (replace-match ""))
12571 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12572 (when what
12573 (insert
12574 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12575 (cond ((eq what 'scheduled) org-scheduled-string)
12576 ((eq what 'deadline) org-deadline-string)
12577 ((eq what 'closed) org-closed-string))
12578 " ")
12579 (setq ts (org-insert-time-stamp
12580 time
12581 (or org-time-was-given
12582 (and (eq what 'closed) org-log-done-with-time))
12583 (eq what 'closed)
12584 nil nil (list org-end-time-was-given)))
12585 (insert
12586 (if (not (or (bolp) (eq (char-before) ?\ )
12587 (memq (char-after) '(32 10))
12588 (eobp))) " " ""))
12589 (end-of-line 1))
12590 (goto-char (point-min))
12591 (widen)
12592 (if (and (looking-at "[ \t]*\n")
12593 (equal (char-before) ?\n))
12594 (delete-region (1- (point)) (point-at-eol)))
12595 ts))))))
12597 (defvar org-log-note-marker (make-marker))
12598 (defvar org-log-note-purpose nil)
12599 (defvar org-log-note-state nil)
12600 (defvar org-log-note-previous-state nil)
12601 (defvar org-log-note-how nil)
12602 (defvar org-log-note-extra nil)
12603 (defvar org-log-note-window-configuration nil)
12604 (defvar org-log-note-return-to (make-marker))
12605 (defvar org-log-note-effective-time nil
12606 "Remembered current time so that dynamically scoped
12607 `org-extend-today-until' affects tha timestamps in state change
12608 log")
12610 (defvar org-log-post-message nil
12611 "Message to be displayed after a log note has been stored.
12612 The auto-repeater uses this.")
12614 (defun org-add-note ()
12615 "Add a note to the current entry.
12616 This is done in the same way as adding a state change note."
12617 (interactive)
12618 (org-add-log-setup 'note nil nil 'findpos nil))
12620 (defvar org-property-end-re)
12621 (defun org-add-log-setup (&optional purpose state prev-state
12622 findpos how extra)
12623 "Set up the post command hook to take a note.
12624 If this is about to TODO state change, the new state is expected in STATE.
12625 When FINDPOS is non-nil, find the correct position for the note in
12626 the current entry. If not, assume that it can be inserted at point.
12627 HOW is an indicator what kind of note should be created.
12628 EXTRA is additional text that will be inserted into the notes buffer."
12629 (let* ((org-log-into-drawer (org-log-into-drawer))
12630 (drawer (cond ((stringp org-log-into-drawer)
12631 org-log-into-drawer)
12632 (org-log-into-drawer "LOGBOOK"))))
12633 (save-restriction
12634 (save-excursion
12635 (when findpos
12636 (org-back-to-heading t)
12637 (narrow-to-region (point) (save-excursion
12638 (outline-next-heading) (point)))
12639 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12640 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12641 "[^\r\n]*\\)?"))
12642 (goto-char (match-end 0))
12643 (cond
12644 (drawer
12645 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12646 nil t)
12647 (progn
12648 (goto-char (match-end 0))
12649 (or org-log-states-order-reversed
12650 (and (re-search-forward org-property-end-re nil t)
12651 (goto-char (1- (match-beginning 0))))))
12652 (insert "\n:" drawer ":\n:END:")
12653 (beginning-of-line 0)
12654 (org-indent-line)
12655 (beginning-of-line 2)
12656 (org-indent-line)
12657 (end-of-line 0)))
12658 ((and org-log-state-notes-insert-after-drawers
12659 (save-excursion
12660 (forward-line) (looking-at org-drawer-regexp)))
12661 (forward-line)
12662 (while (looking-at org-drawer-regexp)
12663 (goto-char (match-end 0))
12664 (re-search-forward org-property-end-re (point-max) t)
12665 (forward-line))
12666 (forward-line -1)))
12667 (unless org-log-states-order-reversed
12668 (and (= (char-after) ?\n) (forward-char 1))
12669 (org-skip-over-state-notes)
12670 (skip-chars-backward " \t\n\r")))
12671 (move-marker org-log-note-marker (point))
12672 (setq org-log-note-purpose purpose
12673 org-log-note-state state
12674 org-log-note-previous-state prev-state
12675 org-log-note-how how
12676 org-log-note-extra extra
12677 org-log-note-effective-time (org-current-effective-time))
12678 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12680 (defun org-skip-over-state-notes ()
12681 "Skip past the list of State notes in an entry."
12682 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12683 (when (ignore-errors (goto-char (org-in-item-p)))
12684 (let* ((struct (org-list-struct))
12685 (prevs (org-list-prevs-alist struct)))
12686 (while (looking-at "[ \t]*- State")
12687 (goto-char (or (org-list-get-next-item (point) struct prevs)
12688 (org-list-get-item-end (point) struct)))))))
12690 (defun org-add-log-note (&optional purpose)
12691 "Pop up a window for taking a note, and add this note later at point."
12692 (remove-hook 'post-command-hook 'org-add-log-note)
12693 (setq org-log-note-window-configuration (current-window-configuration))
12694 (delete-other-windows)
12695 (move-marker org-log-note-return-to (point))
12696 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12697 (goto-char org-log-note-marker)
12698 (org-switch-to-buffer-other-window "*Org Note*")
12699 (erase-buffer)
12700 (if (memq org-log-note-how '(time state))
12701 (let (current-prefix-arg) (org-store-log-note))
12702 (let ((org-inhibit-startup t)) (org-mode))
12703 (insert (format "# Insert note for %s.
12704 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12705 (cond
12706 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12707 ((eq org-log-note-purpose 'done) "closed todo item")
12708 ((eq org-log-note-purpose 'state)
12709 (format "state change from \"%s\" to \"%s\""
12710 (or org-log-note-previous-state "")
12711 (or org-log-note-state "")))
12712 ((eq org-log-note-purpose 'reschedule)
12713 "rescheduling")
12714 ((eq org-log-note-purpose 'delschedule)
12715 "no longer scheduled")
12716 ((eq org-log-note-purpose 'redeadline)
12717 "changing deadline")
12718 ((eq org-log-note-purpose 'deldeadline)
12719 "removing deadline")
12720 ((eq org-log-note-purpose 'refile)
12721 "refiling")
12722 ((eq org-log-note-purpose 'note)
12723 "this entry")
12724 (t (error "This should not happen")))))
12725 (if org-log-note-extra (insert org-log-note-extra))
12726 (org-set-local 'org-finish-function 'org-store-log-note)
12727 (run-hooks 'org-log-buffer-setup-hook)))
12729 (defvar org-note-abort nil) ; dynamically scoped
12730 (defun org-store-log-note ()
12731 "Finish taking a log note, and insert it to where it belongs."
12732 (let ((txt (buffer-string))
12733 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12734 lines ind bul)
12735 (kill-buffer (current-buffer))
12736 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12737 (setq txt (replace-match "" t t txt)))
12738 (if (string-match "\\s-+\\'" txt)
12739 (setq txt (replace-match "" t t txt)))
12740 (setq lines (org-split-string txt "\n"))
12741 (when (and note (string-match "\\S-" note))
12742 (setq note
12743 (org-replace-escapes
12744 note
12745 (list (cons "%u" (user-login-name))
12746 (cons "%U" user-full-name)
12747 (cons "%t" (format-time-string
12748 (org-time-stamp-format 'long 'inactive)
12749 org-log-note-effective-time))
12750 (cons "%T" (format-time-string
12751 (org-time-stamp-format 'long nil)
12752 org-log-note-effective-time))
12753 (cons "%d" (format-time-string
12754 (org-time-stamp-format nil 'inactive)
12755 org-log-note-effective-time))
12756 (cons "%D" (format-time-string
12757 (org-time-stamp-format nil nil)
12758 org-log-note-effective-time))
12759 (cons "%s" (if org-log-note-state
12760 (concat "\"" org-log-note-state "\"")
12761 ""))
12762 (cons "%S" (if org-log-note-previous-state
12763 (concat "\"" org-log-note-previous-state "\"")
12764 "\"\"")))))
12765 (if lines (setq note (concat note " \\\\")))
12766 (push note lines))
12767 (when (or current-prefix-arg org-note-abort)
12768 (when org-log-into-drawer
12769 (org-remove-empty-drawer-at
12770 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12771 org-log-note-marker))
12772 (setq lines nil))
12773 (when lines
12774 (with-current-buffer (marker-buffer org-log-note-marker)
12775 (save-excursion
12776 (goto-char org-log-note-marker)
12777 (move-marker org-log-note-marker nil)
12778 (end-of-line 1)
12779 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12780 (setq ind (save-excursion
12781 (if (ignore-errors (goto-char (org-in-item-p)))
12782 (let ((struct (org-list-struct)))
12783 (org-list-get-ind
12784 (org-list-get-top-point struct) struct))
12785 (skip-chars-backward " \r\t\n")
12786 (cond
12787 ((and (org-at-heading-p)
12788 org-adapt-indentation)
12789 (1+ (org-current-level)))
12790 ((org-at-heading-p) 0)
12791 (t (org-get-indentation))))))
12792 (setq bul (org-list-bullet-string "-"))
12793 (org-indent-line-to ind)
12794 (insert bul (pop lines))
12795 (let ((ind-body (+ (length bul) ind)))
12796 (while lines
12797 (insert "\n")
12798 (org-indent-line-to ind-body)
12799 (insert (pop lines))))
12800 (message "Note stored")
12801 (org-back-to-heading t)
12802 (org-cycle-hide-drawers 'children)))))
12803 (set-window-configuration org-log-note-window-configuration)
12804 (with-current-buffer (marker-buffer org-log-note-return-to)
12805 (goto-char org-log-note-return-to))
12806 (move-marker org-log-note-return-to nil)
12807 (and org-log-post-message (message "%s" org-log-post-message)))
12809 (defun org-remove-empty-drawer-at (drawer pos)
12810 "Remove an empty drawer DRAWER at position POS.
12811 POS may also be a marker."
12812 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12813 (save-excursion
12814 (save-restriction
12815 (widen)
12816 (goto-char pos)
12817 (if (org-in-regexp
12818 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12819 (replace-match ""))))))
12821 (defvar org-ts-type nil)
12822 (defun org-sparse-tree (&optional arg type)
12823 "Create a sparse tree, prompt for the details.
12824 This command can create sparse trees. You first need to select the type
12825 of match used to create the tree:
12827 t Show all TODO entries.
12828 T Show entries with a specific TODO keyword.
12829 m Show entries selected by a tags/property match.
12830 p Enter a property name and its value (both with completion on existing
12831 names/values) and show entries with that property.
12832 r Show entries matching a regular expression (`/' can be used as well).
12833 b Show deadlines and scheduled items before a date.
12834 a Show deadlines and scheduled items after a date.
12835 d Show deadlines due within `org-deadline-warning-days'.
12836 D Show deadlines and scheduled items between a date range."
12837 (interactive "P")
12838 (let (ans kwd value ts-type)
12839 (setq type (or type org-sparse-tree-default-date-type))
12840 (setq org-ts-type type)
12841 (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"
12842 (cond ((eq type 'all) "all timestamps")
12843 ((eq type 'scheduled) "only scheduled")
12844 ((eq type 'deadline) "only deadline")
12845 ((eq type 'active) "only active timestamps")
12846 ((eq type 'inactive) "only inactive timestamps")
12847 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12848 (t "scheduled/deadline")))
12849 (setq ans (read-char-exclusive))
12850 (cond
12851 ((equal ans ?c)
12852 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12853 ((equal ans ?d)
12854 (call-interactively 'org-check-deadlines))
12855 ((equal ans ?b)
12856 (call-interactively 'org-check-before-date))
12857 ((equal ans ?a)
12858 (call-interactively 'org-check-after-date))
12859 ((equal ans ?D)
12860 (call-interactively 'org-check-dates-range))
12861 ((equal ans ?t)
12862 (org-show-todo-tree nil))
12863 ((equal ans ?T)
12864 (org-show-todo-tree '(4)))
12865 ((member ans '(?T ?m))
12866 (call-interactively 'org-match-sparse-tree))
12867 ((member ans '(?p ?P))
12868 (setq kwd (org-icompleting-read "Property: "
12869 (mapcar 'list (org-buffer-property-keys))))
12870 (setq value (org-icompleting-read "Value: "
12871 (mapcar 'list (org-property-values kwd))))
12872 (unless (string-match "\\`{.*}\\'" value)
12873 (setq value (concat "\"" value "\"")))
12874 (org-match-sparse-tree arg (concat kwd "=" value)))
12875 ((member ans '(?r ?R ?/))
12876 (call-interactively 'org-occur))
12877 (t (error "No such sparse tree command \"%c\"" ans)))))
12879 (defvar org-occur-highlights nil
12880 "List of overlays used for occur matches.")
12881 (make-variable-buffer-local 'org-occur-highlights)
12882 (defvar org-occur-parameters nil
12883 "Parameters of the active org-occur calls.
12884 This is a list, each call to org-occur pushes as cons cell,
12885 containing the regular expression and the callback, onto the list.
12886 The list can contain several entries if `org-occur' has been called
12887 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12888 will only contain one set of parameters. When the highlights are
12889 removed (for example with `C-c C-c', or with the next edit (depending
12890 on `org-remove-highlights-with-change'), this variable is emptied
12891 as well.")
12892 (make-variable-buffer-local 'org-occur-parameters)
12894 (defun org-occur (regexp &optional keep-previous callback)
12895 "Make a compact tree which shows all matches of REGEXP.
12896 The tree will show the lines where the regexp matches, and all higher
12897 headlines above the match. It will also show the heading after the match,
12898 to make sure editing the matching entry is easy.
12899 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12900 call to `org-occur' will be kept, to allow stacking of calls to this
12901 command.
12902 If CALLBACK is non-nil, it is a function which is called to confirm
12903 that the match should indeed be shown."
12904 (interactive "sRegexp: \nP")
12905 (when (equal regexp "")
12906 (error "Regexp cannot be empty"))
12907 (unless keep-previous
12908 (org-remove-occur-highlights nil nil t))
12909 (push (cons regexp callback) org-occur-parameters)
12910 (let ((cnt 0))
12911 (save-excursion
12912 (goto-char (point-min))
12913 (if (or (not keep-previous) ; do not want to keep
12914 (not org-occur-highlights)) ; no previous matches
12915 ;; hide everything
12916 (org-overview))
12917 (while (re-search-forward regexp nil t)
12918 (when (or (not callback)
12919 (save-match-data (funcall callback)))
12920 (setq cnt (1+ cnt))
12921 (when org-highlight-sparse-tree-matches
12922 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12923 (org-show-context 'occur-tree))))
12924 (when org-remove-highlights-with-change
12925 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12926 nil 'local))
12927 (unless org-sparse-tree-open-archived-trees
12928 (org-hide-archived-subtrees (point-min) (point-max)))
12929 (run-hooks 'org-occur-hook)
12930 (if (org-called-interactively-p 'interactive)
12931 (message "%d match(es) for regexp %s" cnt regexp))
12932 cnt))
12934 (defun org-occur-next-match (&optional n reset)
12935 "Function for `next-error-function' to find sparse tree matches.
12936 N is the number of matches to move, when negative move backwards.
12937 RESET is entirely ignored - this function always goes back to the
12938 starting point when no match is found."
12939 (let* ((limit (if (< n 0) (point-min) (point-max)))
12940 (search-func (if (< n 0)
12941 'previous-single-char-property-change
12942 'next-single-char-property-change))
12943 (n (abs n))
12944 (pos (point))
12946 (catch 'exit
12947 (while (setq p1 (funcall search-func (point) 'org-type))
12948 (when (equal p1 limit)
12949 (goto-char pos)
12950 (error "No more matches"))
12951 (when (equal (get-char-property p1 'org-type) 'org-occur)
12952 (setq n (1- n))
12953 (when (= n 0)
12954 (goto-char p1)
12955 (throw 'exit (point))))
12956 (goto-char p1))
12957 (goto-char p1)
12958 (error "No more matches"))))
12960 (defun org-show-context (&optional key)
12961 "Make sure point and context are visible.
12962 How much context is shown depends upon the variables
12963 `org-show-hierarchy-above', `org-show-following-heading',
12964 `org-show-entry-below' and `org-show-siblings'."
12965 (let ((heading-p (org-at-heading-p t))
12966 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12967 (following-p (org-get-alist-option org-show-following-heading key))
12968 (entry-p (org-get-alist-option org-show-entry-below key))
12969 (siblings-p (org-get-alist-option org-show-siblings key)))
12970 (catch 'exit
12971 ;; Show heading or entry text
12972 (if (and heading-p (not entry-p))
12973 (org-flag-heading nil) ; only show the heading
12974 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12975 (org-show-hidden-entry))) ; show entire entry
12976 (when following-p
12977 ;; Show next sibling, or heading below text
12978 (save-excursion
12979 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12980 (org-flag-heading nil))))
12981 (when siblings-p (org-show-siblings))
12982 (when hierarchy-p
12983 ;; show all higher headings, possibly with siblings
12984 (save-excursion
12985 (while (and (condition-case nil
12986 (progn (org-up-heading-all 1) t)
12987 (error nil))
12988 (not (bobp)))
12989 (org-flag-heading nil)
12990 (when siblings-p (org-show-siblings))))))))
12992 (defvar org-reveal-start-hook nil
12993 "Hook run before revealing a location.")
12995 (defun org-reveal (&optional siblings)
12996 "Show current entry, hierarchy above it, and the following headline.
12997 This can be used to show a consistent set of context around locations
12998 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12999 not t for the search context.
13001 With optional argument SIBLINGS, on each level of the hierarchy all
13002 siblings are shown. This repairs the tree structure to what it would
13003 look like when opened with hierarchical calls to `org-cycle'.
13004 With double optional argument \\[universal-argument] \\[universal-argument], \
13005 go to the parent and show the
13006 entire tree."
13007 (interactive "P")
13008 (run-hooks 'org-reveal-start-hook)
13009 (let ((org-show-hierarchy-above t)
13010 (org-show-following-heading t)
13011 (org-show-siblings (if siblings t org-show-siblings)))
13012 (org-show-context nil))
13013 (when (equal siblings '(16))
13014 (save-excursion
13015 (when (org-up-heading-safe)
13016 (org-show-subtree)
13017 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13019 (defun org-highlight-new-match (beg end)
13020 "Highlight from BEG to END and mark the highlight is an occur headline."
13021 (let ((ov (make-overlay beg end)))
13022 (overlay-put ov 'face 'secondary-selection)
13023 (overlay-put ov 'org-type 'org-occur)
13024 (push ov org-occur-highlights)))
13026 (defun org-remove-occur-highlights (&optional beg end noremove)
13027 "Remove the occur highlights from the buffer.
13028 BEG and END are ignored. If NOREMOVE is nil, remove this function
13029 from the `before-change-functions' in the current buffer."
13030 (interactive)
13031 (unless org-inhibit-highlight-removal
13032 (mapc 'delete-overlay org-occur-highlights)
13033 (setq org-occur-highlights nil)
13034 (setq org-occur-parameters nil)
13035 (unless noremove
13036 (remove-hook 'before-change-functions
13037 'org-remove-occur-highlights 'local))))
13039 ;;;; Priorities
13041 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13042 "Regular expression matching the priority indicator.")
13044 (defvar org-remove-priority-next-time nil)
13046 (defun org-priority-up ()
13047 "Increase the priority of the current item."
13048 (interactive)
13049 (org-priority 'up))
13051 (defun org-priority-down ()
13052 "Decrease the priority of the current item."
13053 (interactive)
13054 (org-priority 'down))
13056 (defun org-priority (&optional action show)
13057 "Change the priority of an item.
13058 ACTION can be `set', `up', `down', or a character."
13059 (interactive "P")
13060 (if (equal action '(4))
13061 (org-show-priority)
13062 (unless org-enable-priority-commands
13063 (error "Priority commands are disabled"))
13064 (setq action (or action 'set))
13065 (let (current new news have remove)
13066 (save-excursion
13067 (org-back-to-heading t)
13068 (if (looking-at org-priority-regexp)
13069 (setq current (string-to-char (match-string 2))
13070 have t))
13071 (cond
13072 ((eq action 'remove)
13073 (setq remove t new ?\ ))
13074 ((or (eq action 'set)
13075 (if (featurep 'xemacs) (characterp action) (integerp action)))
13076 (if (not (eq action 'set))
13077 (setq new action)
13078 (message "Priority %c-%c, SPC to remove: "
13079 org-highest-priority org-lowest-priority)
13080 (save-match-data
13081 (setq new (read-char-exclusive))))
13082 (if (and (= (upcase org-highest-priority) org-highest-priority)
13083 (= (upcase org-lowest-priority) org-lowest-priority))
13084 (setq new (upcase new)))
13085 (cond ((equal new ?\ ) (setq remove t))
13086 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13087 (error "Priority must be between `%c' and `%c'"
13088 org-highest-priority org-lowest-priority))))
13089 ((eq action 'up)
13090 (setq new (if have
13091 (1- current) ; normal cycling
13092 ;; last priority was empty
13093 (if (eq last-command this-command)
13094 org-lowest-priority ; wrap around empty to lowest
13095 ;; default
13096 (if org-priority-start-cycle-with-default
13097 org-default-priority
13098 (1- org-default-priority))))))
13099 ((eq action 'down)
13100 (setq new (if have
13101 (1+ current) ; normal cycling
13102 ;; last priority was empty
13103 (if (eq last-command this-command)
13104 org-highest-priority ; wrap around empty to highest
13105 ;; default
13106 (if org-priority-start-cycle-with-default
13107 org-default-priority
13108 (1+ org-default-priority))))))
13109 (t (error "Invalid action")))
13110 (if (or (< (upcase new) org-highest-priority)
13111 (> (upcase new) org-lowest-priority))
13112 (if (and (memq action '(up down))
13113 (not have) (not (eq last-command this-command)))
13114 ;; `new' is from default priority
13115 (error
13116 "The default can not be set, see `org-default-priority' why")
13117 ;; normal cycling: `new' is beyond highest/lowest priority
13118 ;; and is wrapped around to the empty priority
13119 (setq remove t)))
13120 (setq news (format "%c" new))
13121 (if have
13122 (if remove
13123 (replace-match "" t t nil 1)
13124 (replace-match news t t nil 2))
13125 (if remove
13126 (error "No priority cookie found in line")
13127 (let ((case-fold-search nil))
13128 (looking-at org-todo-line-regexp))
13129 (if (match-end 2)
13130 (progn
13131 (goto-char (match-end 2))
13132 (insert " [#" news "]"))
13133 (goto-char (match-beginning 3))
13134 (insert "[#" news "] "))))
13135 (org-preserve-lc (org-set-tags nil 'align)))
13136 (if remove
13137 (message "Priority removed")
13138 (message "Priority of current item set to %s" news)))))
13140 (defun org-show-priority ()
13141 "Show the priority of the current item.
13142 This priority is composed of the main priority given with the [#A] cookies,
13143 and by additional input from the age of a schedules or deadline entry."
13144 (interactive)
13145 (let ((pri (if (eq major-mode 'org-agenda-mode)
13146 (org-get-at-bol 'priority)
13147 (save-excursion
13148 (save-match-data
13149 (beginning-of-line)
13150 (and (looking-at org-heading-regexp)
13151 (org-get-priority (match-string 0))))))))
13152 (message "Priority is %d" (if pri pri -1000))))
13154 (defun org-get-priority (s)
13155 "Find priority cookie and return priority."
13156 (if (functionp org-get-priority-function)
13157 (funcall org-get-priority-function)
13158 (save-match-data
13159 (if (not (string-match org-priority-regexp s))
13160 (* 1000 (- org-lowest-priority org-default-priority))
13161 (* 1000 (- org-lowest-priority
13162 (string-to-char (match-string 2 s))))))))
13164 ;;;; Tags
13166 (defvar org-agenda-archives-mode)
13167 (defvar org-map-continue-from nil
13168 "Position from where mapping should continue.
13169 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13171 (defvar org-scanner-tags nil
13172 "The current tag list while the tags scanner is running.")
13173 (defvar org-trust-scanner-tags nil
13174 "Should `org-get-tags-at' use the tags for the scanner.
13175 This is for internal dynamical scoping only.
13176 When this is non-nil, the function `org-get-tags-at' will return the value
13177 of `org-scanner-tags' instead of building the list by itself. This
13178 can lead to large speed-ups when the tags scanner is used in a file with
13179 many entries, and when the list of tags is retrieved, for example to
13180 obtain a list of properties. Building the tags list for each entry in such
13181 a file becomes an N^2 operation - but with this variable set, it scales
13182 as N.")
13184 (defun org-scan-tags (action matcher todo-only &optional start-level)
13185 "Scan headline tags with inheritance and produce output ACTION.
13187 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13188 or `agenda' to produce an entry list for an agenda view. It can also be
13189 a Lisp form or a function that should be called at each matched headline, in
13190 this case the return value is a list of all return values from these calls.
13192 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13193 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13194 only lines with a not-done TODO keyword are included in the output.
13195 This should be the same variable that was scoped into
13196 and set by `org-make-tags-matcher' when it constructed MATCHER.
13198 START-LEVEL can be a string with asterisks, reducing the scope to
13199 headlines matching this string."
13200 (require 'org-agenda)
13201 (let* ((re (concat "^"
13202 (if start-level
13203 ;; Get the correct level to match
13204 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13205 org-outline-regexp)
13206 " *\\(\\<\\("
13207 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13208 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13209 (props (list 'face 'default
13210 'done-face 'org-agenda-done
13211 'undone-face 'default
13212 'mouse-face 'highlight
13213 'org-not-done-regexp org-not-done-regexp
13214 'org-todo-regexp org-todo-regexp
13215 'org-complex-heading-regexp org-complex-heading-regexp
13216 'help-echo
13217 (format "mouse-2 or RET jump to org file %s"
13218 (abbreviate-file-name
13219 (or (buffer-file-name (buffer-base-buffer))
13220 (buffer-name (buffer-base-buffer)))))))
13221 (case-fold-search nil)
13222 (org-map-continue-from nil)
13223 lspos tags tags-list
13224 (tags-alist (list (cons 0 org-file-tags)))
13225 (llast 0) rtn rtn1 level category i txt
13226 todo marker entry priority)
13227 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13228 (setq action (list 'lambda nil action)))
13229 (save-excursion
13230 (goto-char (point-min))
13231 (when (eq action 'sparse-tree)
13232 (org-overview)
13233 (org-remove-occur-highlights))
13234 (while (re-search-forward re nil t)
13235 (setq org-map-continue-from nil)
13236 (catch :skip
13237 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13238 tags (if (match-end 4) (org-match-string-no-properties 4)))
13239 (goto-char (setq lspos (match-beginning 0)))
13240 (setq level (org-reduced-level (org-outline-level))
13241 category (org-get-category))
13242 (setq i llast llast level)
13243 ;; remove tag lists from same and sublevels
13244 (while (>= i level)
13245 (when (setq entry (assoc i tags-alist))
13246 (setq tags-alist (delete entry tags-alist)))
13247 (setq i (1- i)))
13248 ;; add the next tags
13249 (when tags
13250 (setq tags (org-split-string tags ":")
13251 tags-alist
13252 (cons (cons level tags) tags-alist)))
13253 ;; compile tags for current headline
13254 (setq tags-list
13255 (if org-use-tag-inheritance
13256 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13257 tags)
13258 org-scanner-tags tags-list)
13259 (when org-use-tag-inheritance
13260 (setcdr (car tags-alist)
13261 (mapcar (lambda (x)
13262 (setq x (copy-sequence x))
13263 (org-add-prop-inherited x))
13264 (cdar tags-alist))))
13265 (when (and tags org-use-tag-inheritance
13266 (or (not (eq t org-use-tag-inheritance))
13267 org-tags-exclude-from-inheritance))
13268 ;; selective inheritance, remove uninherited ones
13269 (setcdr (car tags-alist)
13270 (org-remove-uninherited-tags (cdar tags-alist))))
13271 (when (and
13273 ;; eval matcher only when the todo condition is OK
13274 (and (or (not todo-only) (member todo org-not-done-keywords))
13275 (let ((case-fold-search t) (org-trust-scanner-tags t))
13276 (eval matcher)))
13278 ;; Call the skipper, but return t if it does not skip,
13279 ;; so that the `and' form continues evaluating
13280 (progn
13281 (unless (eq action 'sparse-tree) (org-agenda-skip))
13284 ;; Check if timestamps are deselecting this entry
13285 (or (not todo-only)
13286 (and (member todo org-not-done-keywords)
13287 (or (not org-agenda-tags-todo-honor-ignore-options)
13288 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13290 ;; Extra check for the archive tag
13291 ;; FIXME: Does the skipper already do this????
13293 (not (member org-archive-tag tags-list))
13294 ;; we have an archive tag, should we use this anyway?
13295 (or (not org-agenda-skip-archived-trees)
13296 (and (eq action 'agenda) org-agenda-archives-mode))))
13298 ;; select this headline
13299 (cond
13300 ((eq action 'sparse-tree)
13301 (and org-highlight-sparse-tree-matches
13302 (org-get-heading) (match-end 0)
13303 (org-highlight-new-match
13304 (match-beginning 1) (match-end 1)))
13305 (org-show-context 'tags-tree))
13306 ((eq action 'agenda)
13307 (setq txt (org-agenda-format-item
13309 (concat
13310 (if (eq org-tags-match-list-sublevels 'indented)
13311 (make-string (1- level) ?.) "")
13312 (org-get-heading))
13313 level category
13314 tags-list)
13315 priority (org-get-priority txt))
13316 (goto-char lspos)
13317 (setq marker (org-agenda-new-marker))
13318 (org-add-props txt props
13319 'org-marker marker 'org-hd-marker marker 'org-category category
13320 'todo-state todo
13321 'priority priority 'type "tagsmatch")
13322 (push txt rtn))
13323 ((functionp action)
13324 (setq org-map-continue-from nil)
13325 (save-excursion
13326 (setq rtn1 (funcall action))
13327 (push rtn1 rtn)))
13328 (t (error "Invalid action")))
13330 ;; if we are to skip sublevels, jump to end of subtree
13331 (unless org-tags-match-list-sublevels
13332 (org-end-of-subtree t)
13333 (backward-char 1))))
13334 ;; Get the correct position from where to continue
13335 (if org-map-continue-from
13336 (goto-char org-map-continue-from)
13337 (and (= (point) lspos) (end-of-line 1)))))
13338 (when (and (eq action 'sparse-tree)
13339 (not org-sparse-tree-open-archived-trees))
13340 (org-hide-archived-subtrees (point-min) (point-max)))
13341 (nreverse rtn)))
13343 (defun org-remove-uninherited-tags (tags)
13344 "Remove all tags that are not inherited from the list TAGS."
13345 (cond
13346 ((eq org-use-tag-inheritance t)
13347 (if org-tags-exclude-from-inheritance
13348 (org-delete-all org-tags-exclude-from-inheritance tags)
13349 tags))
13350 ((not org-use-tag-inheritance) nil)
13351 ((stringp org-use-tag-inheritance)
13352 (delq nil (mapcar
13353 (lambda (x)
13354 (if (and (string-match org-use-tag-inheritance x)
13355 (not (member x org-tags-exclude-from-inheritance)))
13356 x nil))
13357 tags)))
13358 ((listp org-use-tag-inheritance)
13359 (delq nil (mapcar
13360 (lambda (x)
13361 (if (member x org-use-tag-inheritance) x nil))
13362 tags)))))
13364 (defun org-match-sparse-tree (&optional todo-only match)
13365 "Create a sparse tree according to tags string MATCH.
13366 MATCH can contain positive and negative selection of tags, like
13367 \"+WORK+URGENT-WITHBOSS\".
13368 If optional argument TODO-ONLY is non-nil, only select lines that are
13369 also TODO lines."
13370 (interactive "P")
13371 (org-agenda-prepare-buffers (list (current-buffer)))
13372 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13374 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13376 (defvar org-cached-props nil)
13377 (defun org-cached-entry-get (pom property)
13378 (if (or (eq t org-use-property-inheritance)
13379 (and (stringp org-use-property-inheritance)
13380 (string-match org-use-property-inheritance property))
13381 (and (listp org-use-property-inheritance)
13382 (member property org-use-property-inheritance)))
13383 ;; Caching is not possible, check it directly
13384 (org-entry-get pom property 'inherit)
13385 ;; Get all properties, so that we can do complicated checks easily
13386 (cdr (assoc property (or org-cached-props
13387 (setq org-cached-props
13388 (org-entry-properties pom)))))))
13390 (defun org-global-tags-completion-table (&optional files)
13391 "Return the list of all tags in all agenda buffer/files.
13392 Optional FILES argument is a list of files which can be used
13393 instead of the agenda files."
13394 (save-excursion
13395 (org-uniquify
13396 (delq nil
13397 (apply 'append
13398 (mapcar
13399 (lambda (file)
13400 (set-buffer (find-file-noselect file))
13401 (append (org-get-buffer-tags)
13402 (mapcar (lambda (x) (if (stringp (car-safe x))
13403 (list (car-safe x)) nil))
13404 org-tag-alist)))
13405 (if (and files (car files))
13406 files
13407 (org-agenda-files))))))))
13409 (defun org-make-tags-matcher (match)
13410 "Create the TAGS/TODO matcher form for the selection string MATCH.
13412 The variable `todo-only' is scoped dynamically into this function.
13413 It will be set to t if the matcher restricts matching to TODO entries,
13414 otherwise will not be touched.
13416 Returns a cons of the selection string MATCH and the constructed
13417 lisp form implementing the matcher. The matcher is to be evaluated
13418 at an Org entry, with point on the headline, and returns t if the
13419 entry matches the selection string MATCH. The returned lisp form
13420 references two variables with information about the entry, which
13421 must be bound around the form's evaluation: todo, the TODO keyword
13422 at the entry (or nil of none); and tags-list, the list of all tags
13423 at the entry including inherited ones. Additionally, the category
13424 of the entry (if any) must be specified as the text property
13425 'org-category on the headline.
13427 See also `org-scan-tags'.
13429 (declare (special todo-only))
13430 (unless (boundp 'todo-only)
13431 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13432 (unless match
13433 ;; Get a new match request, with completion
13434 (let ((org-last-tags-completion-table
13435 (org-global-tags-completion-table)))
13436 (setq match (org-completing-read-no-i
13437 "Match: " 'org-tags-completion-function nil nil nil
13438 'org-tags-history))))
13440 ;; Parse the string and create a lisp form
13441 (let ((match0 match)
13442 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13443 minus tag mm
13444 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13445 orterms term orlist re-p str-p level-p level-op time-p
13446 prop-p pn pv po gv rest)
13447 (if (string-match "/+" match)
13448 ;; match contains also a todo-matching request
13449 (progn
13450 (setq tagsmatch (substring match 0 (match-beginning 0))
13451 todomatch (substring match (match-end 0)))
13452 (if (string-match "^!" todomatch)
13453 (setq todo-only t todomatch (substring todomatch 1)))
13454 (if (string-match "^\\s-*$" todomatch)
13455 (setq todomatch nil)))
13456 ;; only matching tags
13457 (setq tagsmatch match todomatch nil))
13459 ;; Make the tags matcher
13460 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13461 (setq tagsmatcher t)
13462 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13463 (while (setq term (pop orterms))
13464 (while (and (equal (substring term -1) "\\") orterms)
13465 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13466 (while (string-match re term)
13467 (setq rest (substring term (match-end 0))
13468 minus (and (match-end 1)
13469 (equal (match-string 1 term) "-"))
13470 tag (save-match-data (replace-regexp-in-string
13471 "\\\\-" "-"
13472 (match-string 2 term)))
13473 re-p (equal (string-to-char tag) ?{)
13474 level-p (match-end 4)
13475 prop-p (match-end 5)
13476 mm (cond
13477 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13478 (level-p
13479 (setq level-op (org-op-to-function (match-string 3 term)))
13480 `(,level-op level ,(string-to-number
13481 (match-string 4 term))))
13482 (prop-p
13483 (setq pn (match-string 5 term)
13484 po (match-string 6 term)
13485 pv (match-string 7 term)
13486 re-p (equal (string-to-char pv) ?{)
13487 str-p (equal (string-to-char pv) ?\")
13488 time-p (save-match-data
13489 (string-match "^\"[[<].*[]>]\"$" pv))
13490 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13491 (if time-p (setq pv (org-matcher-time pv)))
13492 (setq po (org-op-to-function po (if time-p 'time str-p)))
13493 (cond
13494 ((equal pn "CATEGORY")
13495 (setq gv '(get-text-property (point) 'org-category)))
13496 ((equal pn "TODO")
13497 (setq gv 'todo))
13499 (setq gv `(org-cached-entry-get nil ,pn))))
13500 (if re-p
13501 (if (eq po 'org<>)
13502 `(not (string-match ,pv (or ,gv "")))
13503 `(string-match ,pv (or ,gv "")))
13504 (if str-p
13505 `(,po (or ,gv "") ,pv)
13506 `(,po (string-to-number (or ,gv ""))
13507 ,(string-to-number pv) ))))
13508 (t `(member ,tag tags-list)))
13509 mm (if minus (list 'not mm) mm)
13510 term rest)
13511 (push mm tagsmatcher))
13512 (push (if (> (length tagsmatcher) 1)
13513 (cons 'and tagsmatcher)
13514 (car tagsmatcher))
13515 orlist)
13516 (setq tagsmatcher nil))
13517 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13518 (setq tagsmatcher
13519 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13520 ;; Make the todo matcher
13521 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13522 (setq todomatcher t)
13523 (setq orterms (org-split-string todomatch "|") orlist nil)
13524 (while (setq term (pop orterms))
13525 (while (string-match re term)
13526 (setq minus (and (match-end 1)
13527 (equal (match-string 1 term) "-"))
13528 kwd (match-string 2 term)
13529 re-p (equal (string-to-char kwd) ?{)
13530 term (substring term (match-end 0))
13531 mm (if re-p
13532 `(string-match ,(substring kwd 1 -1) todo)
13533 (list 'equal 'todo kwd))
13534 mm (if minus (list 'not mm) mm))
13535 (push mm todomatcher))
13536 (push (if (> (length todomatcher) 1)
13537 (cons 'and todomatcher)
13538 (car todomatcher))
13539 orlist)
13540 (setq todomatcher nil))
13541 (setq todomatcher (if (> (length orlist) 1)
13542 (cons 'or orlist) (car orlist))))
13544 ;; Return the string and lisp forms of the matcher
13545 (setq matcher (if todomatcher
13546 (list 'and tagsmatcher todomatcher)
13547 tagsmatcher))
13548 (when todo-only
13549 (setq matcher (list 'and '(member todo org-not-done-keywords)
13550 matcher)))
13551 (cons match0 matcher)))
13553 (defun org-op-to-function (op &optional stringp)
13554 "Turn an operator into the appropriate function."
13555 (setq op
13556 (cond
13557 ((equal op "<" ) '(< string< org-time<))
13558 ((equal op ">" ) '(> org-string> org-time>))
13559 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13560 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13561 ((member op '("=" "==")) '(= string= org-time=))
13562 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13563 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13565 (defun org<> (a b) (not (= a b)))
13566 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13567 (defun org-string>= (a b) (not (string< a b)))
13568 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13569 (defun org-string<> (a b) (not (string= a b)))
13570 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13571 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13572 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13573 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13574 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13575 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13576 (defun org-2ft (s)
13577 "Convert S to a floating point time.
13578 If S is already a number, just return it. If it is a string, parse
13579 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13580 (cond
13581 ((numberp s) s)
13582 ((stringp s)
13583 (condition-case nil
13584 (float-time (apply 'encode-time (org-parse-time-string s)))
13585 (error 0.)))
13586 (t 0.)))
13588 (defun org-time-today ()
13589 "Time in seconds today at 0:00.
13590 Returns the float number of seconds since the beginning of the
13591 epoch to the beginning of today (00:00)."
13592 (float-time (apply 'encode-time
13593 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13595 (defun org-matcher-time (s)
13596 "Interpret a time comparison value."
13597 (save-match-data
13598 (cond
13599 ((string= s "<now>") (float-time))
13600 ((string= s "<today>") (org-time-today))
13601 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13602 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13603 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13604 (+ (org-time-today)
13605 (* (string-to-number (match-string 1 s))
13606 (cdr (assoc (match-string 2 s)
13607 '(("d" . 86400.0) ("w" . 604800.0)
13608 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13609 (t (org-2ft s)))))
13611 (defun org-match-any-p (re list)
13612 "Does re match any element of list?"
13613 (setq list (mapcar (lambda (x) (string-match re x)) list))
13614 (delq nil list))
13616 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13617 (defvar org-tags-overlay (make-overlay 1 1))
13618 (org-detach-overlay org-tags-overlay)
13620 (defun org-get-local-tags-at (&optional pos)
13621 "Get a list of tags defined in the current headline."
13622 (org-get-tags-at pos 'local))
13624 (defun org-get-local-tags ()
13625 "Get a list of tags defined in the current headline."
13626 (org-get-tags-at nil 'local))
13628 (defun org-get-tags-at (&optional pos local)
13629 "Get a list of all headline tags applicable at POS.
13630 POS defaults to point. If tags are inherited, the list contains
13631 the targets in the same sequence as the headlines appear, i.e.
13632 the tags of the current headline come last.
13633 When LOCAL is non-nil, only return tags from the current headline,
13634 ignore inherited ones."
13635 (interactive)
13636 (if (and org-trust-scanner-tags
13637 (or (not pos) (equal pos (point)))
13638 (not local))
13639 org-scanner-tags
13640 (let (tags ltags lastpos parent)
13641 (save-excursion
13642 (save-restriction
13643 (widen)
13644 (goto-char (or pos (point)))
13645 (save-match-data
13646 (catch 'done
13647 (condition-case nil
13648 (progn
13649 (org-back-to-heading t)
13650 (while (not (equal lastpos (point)))
13651 (setq lastpos (point))
13652 (when (looking-at
13653 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13654 (setq ltags (org-split-string
13655 (org-match-string-no-properties 1) ":"))
13656 (when parent
13657 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13658 (setq tags (append
13659 (if parent
13660 (org-remove-uninherited-tags ltags)
13661 ltags)
13662 tags)))
13663 (or org-use-tag-inheritance (throw 'done t))
13664 (if local (throw 'done t))
13665 (or (org-up-heading-safe) (error nil))
13666 (setq parent t)))
13667 (error nil)))))
13668 (if local
13669 tags
13670 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13672 (defun org-add-prop-inherited (s)
13673 (add-text-properties 0 (length s) '(inherited t) s)
13676 (defun org-toggle-tag (tag &optional onoff)
13677 "Toggle the tag TAG for the current line.
13678 If ONOFF is `on' or `off', don't toggle but set to this state."
13679 (let (res current)
13680 (save-excursion
13681 (org-back-to-heading t)
13682 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13683 (point-at-eol) t)
13684 (progn
13685 (setq current (match-string 1))
13686 (replace-match ""))
13687 (setq current ""))
13688 (setq current (nreverse (org-split-string current ":")))
13689 (cond
13690 ((eq onoff 'on)
13691 (setq res t)
13692 (or (member tag current) (push tag current)))
13693 ((eq onoff 'off)
13694 (or (not (member tag current)) (setq current (delete tag current))))
13695 (t (if (member tag current)
13696 (setq current (delete tag current))
13697 (setq res t)
13698 (push tag current))))
13699 (end-of-line 1)
13700 (if current
13701 (progn
13702 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13703 (org-set-tags nil t))
13704 (delete-horizontal-space))
13705 (run-hooks 'org-after-tags-change-hook))
13706 res))
13708 (defun org-align-tags-here (to-col)
13709 ;; Assumes that this is a headline
13710 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13711 (beginning-of-line 1)
13712 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13713 (< pos (match-beginning 2)))
13714 (progn
13715 (setq tags-l (- (match-end 2) (match-beginning 2)))
13716 (goto-char (match-beginning 1))
13717 (insert " ")
13718 (delete-region (point) (1+ (match-beginning 2)))
13719 (setq ncol (max (current-column)
13720 (1+ col)
13721 (if (> to-col 0)
13722 to-col
13723 (- (abs to-col) tags-l))))
13724 (setq p (point))
13725 (insert (make-string (- ncol (current-column)) ?\ ))
13726 (setq ncol (current-column))
13727 (when indent-tabs-mode (tabify p (point-at-eol)))
13728 (org-move-to-column (min ncol col) t))
13729 (goto-char pos))))
13731 (defun org-set-tags-command (&optional arg just-align)
13732 "Call the set-tags command for the current entry."
13733 (interactive "P")
13734 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13735 (org-set-tags arg just-align)
13736 (save-excursion
13737 (org-back-to-heading t)
13738 (org-set-tags arg just-align))))
13740 (defun org-set-tags-to (data)
13741 "Set the tags of the current entry to DATA, replacing the current tags.
13742 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13743 If DATA is nil or the empty string, any tags will be removed."
13744 (interactive "sTags: ")
13745 (setq data
13746 (cond
13747 ((eq data nil) "")
13748 ((equal data "") "")
13749 ((stringp data)
13750 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13751 ":"))
13752 ((listp data)
13753 (concat ":" (mapconcat 'identity data ":") ":"))))
13754 (when data
13755 (save-excursion
13756 (org-back-to-heading t)
13757 (when (looking-at org-complex-heading-regexp)
13758 (if (match-end 5)
13759 (progn
13760 (goto-char (match-beginning 5))
13761 (insert data)
13762 (delete-region (point) (point-at-eol))
13763 (org-set-tags nil 'align))
13764 (goto-char (point-at-eol))
13765 (insert " " data)
13766 (org-set-tags nil 'align)))
13767 (beginning-of-line 1)
13768 (if (looking-at ".*?\\([ \t]+\\)$")
13769 (delete-region (match-beginning 1) (match-end 1))))))
13771 (defun org-align-all-tags ()
13772 "Align the tags i all headings."
13773 (interactive)
13774 (save-excursion
13775 (or (ignore-errors (org-back-to-heading t))
13776 (outline-next-heading))
13777 (if (org-at-heading-p)
13778 (org-set-tags t)
13779 (message "No headings"))))
13781 (defvar org-indent-indentation-per-level)
13782 (defun org-set-tags (&optional arg just-align)
13783 "Set the tags for the current headline.
13784 With prefix ARG, realign all tags in headings in the current buffer."
13785 (interactive "P")
13786 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13787 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13788 'region-start-level 'region))
13789 org-loop-over-headlines-in-active-region)
13790 (org-map-entries
13791 ;; We don't use ARG and JUST-ALIGN here these args are not
13792 ;; useful when looping over headlines
13793 `(org-set-tags)
13794 org-loop-over-headlines-in-active-region
13795 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13796 (let* ((re org-outline-regexp-bol)
13797 (current (unless arg (org-get-tags-string)))
13798 (col (current-column))
13799 (org-setting-tags t)
13800 table current-tags inherited-tags ; computed below when needed
13801 tags p0 c0 c1 rpl di tc level)
13802 (if arg
13803 (save-excursion
13804 (goto-char (point-min))
13805 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13806 (while (re-search-forward re nil t)
13807 (org-set-tags nil t)
13808 (end-of-line 1)))
13809 (message "All tags realigned to column %d" org-tags-column))
13810 (if just-align
13811 (setq tags current)
13812 ;; Get a new set of tags from the user
13813 (save-excursion
13814 (setq table (append org-tag-persistent-alist
13815 (or org-tag-alist (org-get-buffer-tags))
13816 (and
13817 org-complete-tags-always-offer-all-agenda-tags
13818 (org-global-tags-completion-table
13819 (org-agenda-files))))
13820 org-last-tags-completion-table table
13821 current-tags (org-split-string current ":")
13822 inherited-tags (nreverse
13823 (nthcdr (length current-tags)
13824 (nreverse (org-get-tags-at))))
13825 tags
13826 (if (or (eq t org-use-fast-tag-selection)
13827 (and org-use-fast-tag-selection
13828 (delq nil (mapcar 'cdr table))))
13829 (org-fast-tag-selection
13830 current-tags inherited-tags table
13831 (if org-fast-tag-selection-include-todo
13832 org-todo-key-alist))
13833 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13834 (org-trim
13835 (org-icompleting-read "Tags: "
13836 'org-tags-completion-function
13837 nil nil current 'org-tags-history))))))
13838 (while (string-match "[-+&]+" tags)
13839 ;; No boolean logic, just a list
13840 (setq tags (replace-match ":" t t tags))))
13842 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13844 (if org-tags-sort-function
13845 (setq tags (mapconcat 'identity
13846 (sort (org-split-string
13847 tags (org-re "[^[:alnum:]_@#%]+"))
13848 org-tags-sort-function) ":")))
13850 (if (string-match "\\`[\t ]*\\'" tags)
13851 (setq tags "")
13852 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13853 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13855 ;; Insert new tags at the correct column
13856 (beginning-of-line 1)
13857 (setq level (or (and (looking-at org-outline-regexp)
13858 (- (match-end 0) (point) 1))
13860 (cond
13861 ((and (equal current "") (equal tags "")))
13862 ((re-search-forward
13863 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13864 (point-at-eol) t)
13865 (if (equal tags "")
13866 (setq rpl "")
13867 (goto-char (match-beginning 0))
13868 (setq c0 (current-column)
13869 ;; compute offset for the case of org-indent-mode active
13870 di (if org-indent-mode
13871 (* (1- org-indent-indentation-per-level) (1- level))
13873 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13874 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13875 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13876 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13877 (replace-match rpl t t)
13878 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13879 tags)
13880 (t (error "Tags alignment failed")))
13881 (org-move-to-column col)
13882 (unless just-align
13883 (run-hooks 'org-after-tags-change-hook))))))
13885 (defun org-change-tag-in-region (beg end tag off)
13886 "Add or remove TAG for each entry in the region.
13887 This works in the agenda, and also in an org-mode buffer."
13888 (interactive
13889 (list (region-beginning) (region-end)
13890 (let ((org-last-tags-completion-table
13891 (if (derived-mode-p 'org-mode)
13892 (org-get-buffer-tags)
13893 (org-global-tags-completion-table))))
13894 (org-icompleting-read
13895 "Tag: " 'org-tags-completion-function nil nil nil
13896 'org-tags-history))
13897 (progn
13898 (message "[s]et or [r]emove? ")
13899 (equal (read-char-exclusive) ?r))))
13900 (if (fboundp 'deactivate-mark) (deactivate-mark))
13901 (let ((agendap (equal major-mode 'org-agenda-mode))
13902 l1 l2 m buf pos newhead (cnt 0))
13903 (goto-char end)
13904 (setq l2 (1- (org-current-line)))
13905 (goto-char beg)
13906 (setq l1 (org-current-line))
13907 (loop for l from l1 to l2 do
13908 (org-goto-line l)
13909 (setq m (get-text-property (point) 'org-hd-marker))
13910 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13911 (and agendap m))
13912 (setq buf (if agendap (marker-buffer m) (current-buffer))
13913 pos (if agendap m (point)))
13914 (with-current-buffer buf
13915 (save-excursion
13916 (save-restriction
13917 (goto-char pos)
13918 (setq cnt (1+ cnt))
13919 (org-toggle-tag tag (if off 'off 'on))
13920 (setq newhead (org-get-heading)))))
13921 (and agendap (org-agenda-change-all-lines newhead m))))
13922 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13924 (defun org-tags-completion-function (string predicate &optional flag)
13925 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13926 (confirm (lambda (x) (stringp (car x)))))
13927 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13928 (setq s1 (match-string 1 string)
13929 s2 (match-string 2 string))
13930 (setq s1 "" s2 string))
13931 (cond
13932 ((eq flag nil)
13933 ;; try completion
13934 (setq rtn (try-completion s2 ctable confirm))
13935 (if (stringp rtn)
13936 (setq rtn
13937 (concat s1 s2 (substring rtn (length s2))
13938 (if (and org-add-colon-after-tag-completion
13939 (assoc rtn ctable))
13940 ":" ""))))
13941 rtn)
13942 ((eq flag t)
13943 ;; all-completions
13944 (all-completions s2 ctable confirm)
13946 ((eq flag 'lambda)
13947 ;; exact match?
13948 (assoc s2 ctable)))
13951 (defun org-fast-tag-insert (kwd tags face &optional end)
13952 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13953 (insert (format "%-12s" (concat kwd ":"))
13954 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13955 (or end "")))
13957 (defun org-fast-tag-show-exit (flag)
13958 (save-excursion
13959 (org-goto-line 3)
13960 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13961 (replace-match ""))
13962 (when flag
13963 (end-of-line 1)
13964 (org-move-to-column (- (window-width) 19) t)
13965 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13967 (defun org-set-current-tags-overlay (current prefix)
13968 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13969 (if (featurep 'xemacs)
13970 (org-overlay-display org-tags-overlay (concat prefix s)
13971 'secondary-selection)
13972 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13973 (org-overlay-display org-tags-overlay (concat prefix s)))))
13975 (defvar org-last-tag-selection-key nil)
13976 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13977 "Fast tag selection with single keys.
13978 CURRENT is the current list of tags in the headline, INHERITED is the
13979 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13980 possibly with grouping information. TODO-TABLE is a similar table with
13981 TODO keywords, should these have keys assigned to them.
13982 If the keys are nil, a-z are automatically assigned.
13983 Returns the new tags string, or nil to not change the current settings."
13984 (let* ((fulltable (append table todo-table))
13985 (maxlen (apply 'max (mapcar
13986 (lambda (x)
13987 (if (stringp (car x)) (string-width (car x)) 0))
13988 fulltable)))
13989 (buf (current-buffer))
13990 (expert (eq org-fast-tag-selection-single-key 'expert))
13991 (buffer-tags nil)
13992 (fwidth (+ maxlen 3 1 3))
13993 (ncol (/ (- (window-width) 4) fwidth))
13994 (i-face 'org-done)
13995 (c-face 'org-todo)
13996 tg cnt e c char c1 c2 ntable tbl rtn
13997 ov-start ov-end ov-prefix
13998 (exit-after-next org-fast-tag-selection-single-key)
13999 (done-keywords org-done-keywords)
14000 groups ingroup)
14001 (save-excursion
14002 (beginning-of-line 1)
14003 (if (looking-at
14004 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14005 (setq ov-start (match-beginning 1)
14006 ov-end (match-end 1)
14007 ov-prefix "")
14008 (setq ov-start (1- (point-at-eol))
14009 ov-end (1+ ov-start))
14010 (skip-chars-forward "^\n\r")
14011 (setq ov-prefix
14012 (concat
14013 (buffer-substring (1- (point)) (point))
14014 (if (> (current-column) org-tags-column)
14016 (make-string (- org-tags-column (current-column)) ?\ ))))))
14017 (move-overlay org-tags-overlay ov-start ov-end)
14018 (save-window-excursion
14019 (if expert
14020 (set-buffer (get-buffer-create " *Org tags*"))
14021 (delete-other-windows)
14022 (split-window-vertically)
14023 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14024 (erase-buffer)
14025 (org-set-local 'org-done-keywords done-keywords)
14026 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14027 (org-fast-tag-insert "Current" current c-face "\n\n")
14028 (org-fast-tag-show-exit exit-after-next)
14029 (org-set-current-tags-overlay current ov-prefix)
14030 (setq tbl fulltable char ?a cnt 0)
14031 (while (setq e (pop tbl))
14032 (cond
14033 ((equal (car e) :startgroup)
14034 (push '() groups) (setq ingroup t)
14035 (when (not (= cnt 0))
14036 (setq cnt 0)
14037 (insert "\n"))
14038 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14039 ((equal (car e) :endgroup)
14040 (setq ingroup nil cnt 0)
14041 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14042 ((equal e '(:newline))
14043 (when (not (= cnt 0))
14044 (setq cnt 0)
14045 (insert "\n")
14046 (setq e (car tbl))
14047 (while (equal (car tbl) '(:newline))
14048 (insert "\n")
14049 (setq tbl (cdr tbl)))))
14051 (setq tg (copy-sequence (car e)) c2 nil)
14052 (if (cdr e)
14053 (setq c (cdr e))
14054 ;; automatically assign a character.
14055 (setq c1 (string-to-char
14056 (downcase (substring
14057 tg (if (= (string-to-char tg) ?@) 1 0)))))
14058 (if (or (rassoc c1 ntable) (rassoc c1 table))
14059 (while (or (rassoc char ntable) (rassoc char table))
14060 (setq char (1+ char)))
14061 (setq c2 c1))
14062 (setq c (or c2 char)))
14063 (if ingroup (push tg (car groups)))
14064 (setq tg (org-add-props tg nil 'face
14065 (cond
14066 ((not (assoc tg table))
14067 (org-get-todo-face tg))
14068 ((member tg current) c-face)
14069 ((member tg inherited) i-face))))
14070 (if (and (= cnt 0) (not ingroup)) (insert " "))
14071 (insert "[" c "] " tg (make-string
14072 (- fwidth 4 (length tg)) ?\ ))
14073 (push (cons tg c) ntable)
14074 (when (= (setq cnt (1+ cnt)) ncol)
14075 (insert "\n")
14076 (if ingroup (insert " "))
14077 (setq cnt 0)))))
14078 (setq ntable (nreverse ntable))
14079 (insert "\n")
14080 (goto-char (point-min))
14081 (if (not expert) (org-fit-window-to-buffer))
14082 (setq rtn
14083 (catch 'exit
14084 (while t
14085 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14086 (if (not groups) "no " "")
14087 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14088 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14089 (setq org-last-tag-selection-key c)
14090 (cond
14091 ((= c ?\r) (throw 'exit t))
14092 ((= c ?!)
14093 (setq groups (not groups))
14094 (goto-char (point-min))
14095 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14096 ((= c ?\C-c)
14097 (if (not expert)
14098 (org-fast-tag-show-exit
14099 (setq exit-after-next (not exit-after-next)))
14100 (setq expert nil)
14101 (delete-other-windows)
14102 (set-window-buffer (split-window-vertically) " *Org tags*")
14103 (org-switch-to-buffer-other-window " *Org tags*")
14104 (org-fit-window-to-buffer)))
14105 ((or (= c ?\C-g)
14106 (and (= c ?q) (not (rassoc c ntable))))
14107 (org-detach-overlay org-tags-overlay)
14108 (setq quit-flag t))
14109 ((= c ?\ )
14110 (setq current nil)
14111 (if exit-after-next (setq exit-after-next 'now)))
14112 ((= c ?\t)
14113 (condition-case nil
14114 (setq tg (org-icompleting-read
14115 "Tag: "
14116 (or buffer-tags
14117 (with-current-buffer buf
14118 (org-get-buffer-tags)))))
14119 (quit (setq tg "")))
14120 (when (string-match "\\S-" tg)
14121 (add-to-list 'buffer-tags (list tg))
14122 (if (member tg current)
14123 (setq current (delete tg current))
14124 (push tg current)))
14125 (if exit-after-next (setq exit-after-next 'now)))
14126 ((setq e (rassoc c todo-table) tg (car e))
14127 (with-current-buffer buf
14128 (save-excursion (org-todo tg)))
14129 (if exit-after-next (setq exit-after-next 'now)))
14130 ((setq e (rassoc c ntable) tg (car e))
14131 (if (member tg current)
14132 (setq current (delete tg current))
14133 (loop for g in groups do
14134 (if (member tg g)
14135 (mapc (lambda (x)
14136 (setq current (delete x current)))
14137 g)))
14138 (push tg current))
14139 (if exit-after-next (setq exit-after-next 'now))))
14141 ;; Create a sorted list
14142 (setq current
14143 (sort current
14144 (lambda (a b)
14145 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14146 (if (eq exit-after-next 'now) (throw 'exit t))
14147 (goto-char (point-min))
14148 (beginning-of-line 2)
14149 (delete-region (point) (point-at-eol))
14150 (org-fast-tag-insert "Current" current c-face)
14151 (org-set-current-tags-overlay current ov-prefix)
14152 (while (re-search-forward
14153 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14154 (setq tg (match-string 1))
14155 (add-text-properties
14156 (match-beginning 1) (match-end 1)
14157 (list 'face
14158 (cond
14159 ((member tg current) c-face)
14160 ((member tg inherited) i-face)
14161 (t (get-text-property (match-beginning 1) 'face))))))
14162 (goto-char (point-min)))))
14163 (org-detach-overlay org-tags-overlay)
14164 (if rtn
14165 (mapconcat 'identity current ":")
14166 nil))))
14168 (defun org-get-tags-string ()
14169 "Get the TAGS string in the current headline."
14170 (unless (org-at-heading-p t)
14171 (error "Not on a heading"))
14172 (save-excursion
14173 (beginning-of-line 1)
14174 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14175 (org-match-string-no-properties 1)
14176 "")))
14178 (defun org-get-tags ()
14179 "Get the list of tags specified in the current headline."
14180 (org-split-string (org-get-tags-string) ":"))
14182 (defun org-get-buffer-tags ()
14183 "Get a table of all tags used in the buffer, for completion."
14184 (let (tags)
14185 (save-excursion
14186 (goto-char (point-min))
14187 (while (re-search-forward
14188 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14189 (when (equal (char-after (point-at-bol 0)) ?*)
14190 (mapc (lambda (x) (add-to-list 'tags x))
14191 (org-split-string (org-match-string-no-properties 1) ":")))))
14192 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14193 (mapcar 'list tags)))
14195 ;;;; The mapping API
14197 ;;;###autoload
14198 (defun org-map-entries (func &optional match scope &rest skip)
14199 "Call FUNC at each headline selected by MATCH in SCOPE.
14201 FUNC is a function or a lisp form. The function will be called without
14202 arguments, with the cursor positioned at the beginning of the headline.
14203 The return values of all calls to the function will be collected and
14204 returned as a list.
14206 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14207 does not need to preserve point. After evaluation, the cursor will be
14208 moved to the end of the line (presumably of the headline of the
14209 processed entry) and search continues from there. Under some
14210 circumstances, this may not produce the wanted results. For example,
14211 if you have removed (e.g. archived) the current (sub)tree it could
14212 mean that the next entry will be skipped entirely. In such cases, you
14213 can specify the position from where search should continue by making
14214 FUNC set the variable `org-map-continue-from' to the desired buffer
14215 position.
14217 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14218 Only headlines that are matched by this query will be considered during
14219 the iteration. When MATCH is nil or t, all headlines will be
14220 visited by the iteration.
14222 SCOPE determines the scope of this command. It can be any of:
14224 nil The current buffer, respecting the restriction if any
14225 tree The subtree started with the entry at point
14226 region The entries within the active region, if any
14227 region-start-level
14228 The entries within the active region, but only those at
14229 the same level than the first one.
14230 file The current buffer, without restriction
14231 file-with-archives
14232 The current buffer, and any archives associated with it
14233 agenda All agenda files
14234 agenda-with-archives
14235 All agenda files with any archive files associated with them
14236 \(file1 file2 ...)
14237 If this is a list, all files in the list will be scanned
14239 The remaining args are treated as settings for the skipping facilities of
14240 the scanner. The following items can be given here:
14242 archive skip trees with the archive tag.
14243 comment skip trees with the COMMENT keyword
14244 function or Emacs Lisp form:
14245 will be used as value for `org-agenda-skip-function', so whenever
14246 the function returns t, FUNC will not be called for that
14247 entry and search will continue from the point where the
14248 function leaves it.
14250 If your function needs to retrieve the tags including inherited tags
14251 at the *current* entry, you can use the value of the variable
14252 `org-scanner-tags' which will be much faster than getting the value
14253 with `org-get-tags-at'. If your function gets properties with
14254 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14255 to t around the call to `org-entry-properties' to get the same speedup.
14256 Note that if your function moves around to retrieve tags and properties at
14257 a *different* entry, you cannot use these techniques."
14258 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14259 (not (org-region-active-p)))
14260 (let* ((org-agenda-archives-mode nil) ; just to make sure
14261 (org-agenda-skip-archived-trees (memq 'archive skip))
14262 (org-agenda-skip-comment-trees (memq 'comment skip))
14263 (org-agenda-skip-function
14264 (car (org-delete-all '(comment archive) skip)))
14265 (org-tags-match-list-sublevels t)
14266 (start-level (eq scope 'region-start-level))
14267 matcher file res
14268 org-todo-keywords-for-agenda
14269 org-done-keywords-for-agenda
14270 org-todo-keyword-alist-for-agenda
14271 org-drawers-for-agenda
14272 org-tag-alist-for-agenda
14273 todo-only)
14275 (cond
14276 ((eq match t) (setq matcher t))
14277 ((eq match nil) (setq matcher t))
14278 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14280 (save-excursion
14281 (save-restriction
14282 (cond ((eq scope 'tree)
14283 (org-back-to-heading t)
14284 (org-narrow-to-subtree)
14285 (setq scope nil))
14286 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14287 (org-region-active-p))
14288 ;; If needed, set start-level to a string like "2"
14289 (when start-level
14290 (save-excursion
14291 (goto-char (region-beginning))
14292 (unless (org-at-heading-p) (outline-next-heading))
14293 (setq start-level (org-current-level))))
14294 (narrow-to-region (region-beginning)
14295 (save-excursion
14296 (goto-char (region-end))
14297 (unless (and (bolp) (org-at-heading-p))
14298 (outline-next-heading))
14299 (point)))
14300 (setq scope nil)))
14302 (if (not scope)
14303 (progn
14304 (org-agenda-prepare-buffers
14305 (list (buffer-file-name (current-buffer))))
14306 (setq res (org-scan-tags func matcher todo-only start-level)))
14307 ;; Get the right scope
14308 (cond
14309 ((and scope (listp scope) (symbolp (car scope)))
14310 (setq scope (eval scope)))
14311 ((eq scope 'agenda)
14312 (setq scope (org-agenda-files t)))
14313 ((eq scope 'agenda-with-archives)
14314 (setq scope (org-agenda-files t))
14315 (setq scope (org-add-archive-files scope)))
14316 ((eq scope 'file)
14317 (setq scope (list (buffer-file-name))))
14318 ((eq scope 'file-with-archives)
14319 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14320 (org-agenda-prepare-buffers scope)
14321 (while (setq file (pop scope))
14322 (with-current-buffer (org-find-base-buffer-visiting file)
14323 (save-excursion
14324 (save-restriction
14325 (widen)
14326 (goto-char (point-min))
14327 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14328 res)))
14330 ;;;; Properties
14332 ;;; Setting and retrieving properties
14334 (defconst org-special-properties
14335 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14336 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14337 "The special properties valid in Org-mode.
14339 These are properties that are not defined in the property drawer,
14340 but in some other way.")
14342 (defconst org-default-properties
14343 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14344 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14345 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14346 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14347 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14348 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14349 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14350 "Some properties that are used by Org-mode for various purposes.
14351 Being in this list makes sure that they are offered for completion.")
14353 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14354 "Regular expression matching the first line of a property drawer.")
14356 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14357 "Regular expression matching the last line of a property drawer.")
14359 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14360 "Regular expression matching the first line of a property drawer.")
14362 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14363 "Regular expression matching the first line of a property drawer.")
14365 (defconst org-property-drawer-re
14366 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14367 org-property-end-re "\\)\n?")
14368 "Matches an entire property drawer.")
14370 (defconst org-clock-drawer-re
14371 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14372 org-property-end-re "\\)\n?")
14373 "Matches an entire clock drawer.")
14375 (defsubst org-re-property (property)
14376 "Return a regexp matching a PROPERTY line.
14377 Match group 1 will be set to the value."
14378 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14380 (defsubst org-re-property-keyword (property)
14381 "Return a regexp matching a PROPERTY line, possibly with no
14382 value for the property."
14383 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14385 (defun org-property-action ()
14386 "Do an action on properties."
14387 (interactive)
14388 (let (c)
14389 (org-at-property-p)
14390 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14391 (setq c (read-char-exclusive))
14392 (cond
14393 ((equal c ?s)
14394 (call-interactively 'org-set-property))
14395 ((equal c ?d)
14396 (call-interactively 'org-delete-property))
14397 ((equal c ?D)
14398 (call-interactively 'org-delete-property-globally))
14399 ((equal c ?c)
14400 (call-interactively 'org-compute-property-at-point))
14401 (t (error "No such property action %c" c)))))
14403 (defun org-inc-effort ()
14404 "Increment the value of the effort property in the current entry."
14405 (interactive)
14406 (org-set-effort nil t))
14408 (defun org-set-effort (&optional value increment)
14409 "Set the effort property of the current entry.
14410 With numerical prefix arg, use the nth allowed value, 0 stands for the
14411 10th allowed value.
14413 When INCREMENT is non-nil, set the property to the next allowed value."
14414 (interactive "P")
14415 (if (equal value 0) (setq value 10))
14416 (let* ((completion-ignore-case t)
14417 (prop org-effort-property)
14418 (cur (org-entry-get nil prop))
14419 (allowed (org-property-get-allowed-values nil prop 'table))
14420 (existing (mapcar 'list (org-property-values prop)))
14422 (val (cond
14423 ((stringp value) value)
14424 ((and allowed (integerp value))
14425 (or (car (nth (1- value) allowed))
14426 (car (org-last allowed))))
14427 ((and allowed increment)
14428 (or (caadr (member (list cur) allowed))
14429 (error "Allowed effort values are not set")))
14430 (allowed
14431 (message "Select 1-9,0, [RET%s]: %s"
14432 (if cur (concat "=" cur) "")
14433 (mapconcat 'car allowed " "))
14434 (setq rpl (read-char-exclusive))
14435 (if (equal rpl ?\r)
14437 (setq rpl (- rpl ?0))
14438 (if (equal rpl 0) (setq rpl 10))
14439 (if (and (> rpl 0) (<= rpl (length allowed)))
14440 (car (nth (1- rpl) allowed))
14441 (org-completing-read "Effort: " allowed nil))))
14443 (let (org-completion-use-ido org-completion-use-iswitchb)
14444 (org-completing-read
14445 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14446 (concat "[" cur "]") "")
14447 ": ")
14448 existing nil nil "" nil cur))))))
14449 (unless (equal (org-entry-get nil prop) val)
14450 (org-entry-put nil prop val))
14451 (message "%s is now %s" prop val)))
14453 (defun org-at-property-p ()
14454 "Is cursor inside a property drawer?"
14455 (save-excursion
14456 (beginning-of-line 1)
14457 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14458 (save-match-data ;; Used by calling procedures
14459 (let ((p (point))
14460 (range (unless (org-before-first-heading-p)
14461 (org-get-property-block))))
14462 (and range (<= (car range) p) (< p (cdr range))))))))
14464 (defun org-get-property-block (&optional beg end force)
14465 "Return the (beg . end) range of the body of the property drawer.
14466 BEG and END are the beginning and end of the current subtree, or of
14467 the part before the first headline. If they are not given, they will
14468 be found. If the drawer does not exist and FORCE is non-nil, create
14469 the drawer."
14470 (catch 'exit
14471 (save-excursion
14472 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14473 (progn (org-back-to-heading t) (point))))
14474 (end (or end (and (not (outline-next-heading)) (point-max))
14475 (point))))
14476 (goto-char beg)
14477 (if (re-search-forward org-property-start-re end t)
14478 (setq beg (1+ (match-end 0)))
14479 (if force
14480 (save-excursion
14481 (org-insert-property-drawer)
14482 (setq end (progn (outline-next-heading) (point))))
14483 (throw 'exit nil))
14484 (goto-char beg)
14485 (if (re-search-forward org-property-start-re end t)
14486 (setq beg (1+ (match-end 0)))))
14487 (if (re-search-forward org-property-end-re end t)
14488 (setq end (match-beginning 0))
14489 (or force (throw 'exit nil))
14490 (goto-char beg)
14491 (setq end beg)
14492 (org-indent-line)
14493 (insert ":END:\n"))
14494 (cons beg end)))))
14496 (defun org-entry-properties (&optional pom which specific)
14497 "Get all properties of the entry at point-or-marker POM.
14498 This includes the TODO keyword, the tags, time strings for deadline,
14499 scheduled, and clocking, and any additional properties defined in the
14500 entry. The return value is an alist, keys may occur multiple times
14501 if the property key was used several times.
14502 POM may also be nil, in which case the current entry is used.
14503 If WHICH is nil or `all', get all properties. If WHICH is
14504 `special' or `standard', only get that subclass. If WHICH
14505 is a string only get exactly this property. SPECIFIC can be a string, the
14506 specific property we are interested in. Specifying it can speed
14507 things up because then unnecessary parsing is avoided."
14508 (setq which (or which 'all))
14509 (org-with-point-at pom
14510 (let ((clockstr (substring org-clock-string 0 -1))
14511 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14512 (case-fold-search nil)
14513 beg end range props sum-props key key1 value string clocksum clocksumt)
14514 (save-excursion
14515 (when (condition-case nil
14516 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14517 (error nil))
14518 (setq beg (point))
14519 (setq sum-props (get-text-property (point) 'org-summaries))
14520 (setq clocksum (get-text-property (point) :org-clock-minutes)
14521 clocksumt (get-text-property (point) :org-clock-minutes-today))
14522 (outline-next-heading)
14523 (setq end (point))
14524 (when (memq which '(all special))
14525 ;; Get the special properties, like TODO and tags
14526 (goto-char beg)
14527 (when (and (or (not specific) (string= specific "TODO"))
14528 (looking-at org-todo-line-regexp) (match-end 2))
14529 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14530 (when (and (or (not specific) (string= specific "PRIORITY"))
14531 (looking-at org-priority-regexp))
14532 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14533 (when (or (not specific) (string= specific "FILE"))
14534 (push (cons "FILE" buffer-file-name) props))
14535 (when (and (or (not specific) (string= specific "TAGS"))
14536 (setq value (org-get-tags-string))
14537 (string-match "\\S-" value))
14538 (push (cons "TAGS" value) props))
14539 (when (and (or (not specific) (string= specific "ALLTAGS"))
14540 (setq value (org-get-tags-at)))
14541 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14542 ":"))
14543 props))
14544 (when (or (not specific) (string= specific "BLOCKED"))
14545 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14546 (when (or (not specific)
14547 (member specific
14548 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14549 "TIMESTAMP" "TIMESTAMP_IA")))
14550 (catch 'match
14551 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14552 (setq key (if (match-end 1)
14553 (substring (org-match-string-no-properties 1)
14554 0 -1))
14555 string (if (equal key clockstr)
14556 (org-trim
14557 (buffer-substring-no-properties
14558 (match-beginning 3) (goto-char
14559 (point-at-eol))))
14560 (substring (org-match-string-no-properties 3)
14561 1 -1)))
14562 ;; Get the correct property name from the key. This is
14563 ;; necessary if the user has configured time keywords.
14564 (setq key1 (concat key ":"))
14565 (cond
14566 ((not key)
14567 (setq key
14568 (if (= (char-after (match-beginning 3)) ?\[)
14569 "TIMESTAMP_IA" "TIMESTAMP")))
14570 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14571 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14572 ((equal key1 org-closed-string) (setq key "CLOSED"))
14573 ((equal key1 org-clock-string) (setq key "CLOCK")))
14574 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14575 (progn
14576 (push (cons key string) props)
14577 ;; no need to search further if match is found
14578 (throw 'match t))
14579 (when (or (equal key "CLOCK") (not (assoc key props)))
14580 (push (cons key string) props)))))))
14582 (when (memq which '(all standard))
14583 ;; Get the standard properties, like :PROP: ...
14584 (setq range (org-get-property-block beg end))
14585 (when range
14586 (goto-char (car range))
14587 (while (re-search-forward
14588 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14589 (cdr range) t)
14590 (setq key (org-match-string-no-properties 1)
14591 value (org-trim (or (org-match-string-no-properties 2) "")))
14592 (unless (member key excluded)
14593 (push (cons key (or value "")) props)))))
14594 (if clocksum
14595 (push (cons "CLOCKSUM"
14596 (org-columns-number-to-string (/ (float clocksum) 60.)
14597 'add_times))
14598 props))
14599 (if clocksumt
14600 (push (cons "CLOCKSUM_T"
14601 (org-columns-number-to-string (/ (float clocksumt) 60.)
14602 'add_times))
14603 props))
14604 (unless (assoc "CATEGORY" props)
14605 (push (cons "CATEGORY" (org-get-category)) props))
14606 (append sum-props (nreverse props)))))))
14608 (defun org-entry-get (pom property &optional inherit literal-nil)
14609 "Get value of PROPERTY for entry or content at point-or-marker POM.
14610 If INHERIT is non-nil and the entry does not have the property,
14611 then also check higher levels of the hierarchy.
14612 If INHERIT is the symbol `selective', use inheritance only if the setting
14613 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14614 If the property is present but empty, the return value is the empty string.
14615 If the property is not present at all, nil is returned.
14617 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14618 do not interpret it as the list atom nil. This is used for inheritance
14619 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14620 (org-with-point-at pom
14621 (if (and inherit (if (eq inherit 'selective)
14622 (org-property-inherit-p property)
14624 (org-entry-get-with-inheritance property literal-nil)
14625 (if (member property org-special-properties)
14626 ;; We need a special property. Use `org-entry-properties' to
14627 ;; retrieve it, but specify the wanted property
14628 (cdr (assoc property (org-entry-properties nil 'special property)))
14629 (let* ((range (org-get-property-block))
14630 (props (list (or (assoc property org-file-properties)
14631 (assoc property org-global-properties)
14632 (assoc property org-global-properties-fixed))))
14633 (ap (lambda (key)
14634 (when (re-search-forward
14635 (org-re-property key) (cdr range) t)
14636 (setq props
14637 (org-update-property-plist
14639 (if (match-end 1)
14640 (org-match-string-no-properties 1) "")
14641 props)))))
14642 val)
14643 (when (and range (goto-char (car range)))
14644 (funcall ap property)
14645 (goto-char (car range))
14646 (while (funcall ap (concat property "+")))
14647 (setq val (cdr (assoc property props)))
14648 (when val (if literal-nil val (org-not-nil val)))))))))
14650 (defun org-property-or-variable-value (var &optional inherit)
14651 "Check if there is a property fixing the value of VAR.
14652 If yes, return this value. If not, return the current value of the variable."
14653 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14654 (if (and prop (stringp prop) (string-match "\\S-" prop))
14655 (read prop)
14656 (symbol-value var))))
14658 (defun org-entry-delete (pom property)
14659 "Delete the property PROPERTY from entry at point-or-marker POM."
14660 (org-with-point-at pom
14661 (if (member property org-special-properties)
14662 nil ; cannot delete these properties.
14663 (let ((range (org-get-property-block)))
14664 (if (and range
14665 (goto-char (car range))
14666 (re-search-forward
14667 (org-re-property property)
14668 (cdr range) t))
14669 (progn
14670 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14672 nil)))))
14674 ;; Multi-values properties are properties that contain multiple values
14675 ;; These values are assumed to be single words, separated by whitespace.
14676 (defun org-entry-add-to-multivalued-property (pom property value)
14677 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14678 (let* ((old (org-entry-get pom property))
14679 (values (and old (org-split-string old "[ \t]"))))
14680 (setq value (org-entry-protect-space value))
14681 (unless (member value values)
14682 (setq values (cons value values))
14683 (org-entry-put pom property
14684 (mapconcat 'identity values " ")))))
14686 (defun org-entry-remove-from-multivalued-property (pom property value)
14687 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14688 (let* ((old (org-entry-get pom property))
14689 (values (and old (org-split-string old "[ \t]"))))
14690 (setq value (org-entry-protect-space value))
14691 (when (member value values)
14692 (setq values (delete value values))
14693 (org-entry-put pom property
14694 (mapconcat 'identity values " ")))))
14696 (defun org-entry-member-in-multivalued-property (pom property value)
14697 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14698 (let* ((old (org-entry-get pom property))
14699 (values (and old (org-split-string old "[ \t]"))))
14700 (setq value (org-entry-protect-space value))
14701 (member value values)))
14703 (defun org-entry-get-multivalued-property (pom property)
14704 "Return a list of values in a multivalued property."
14705 (let* ((value (org-entry-get pom property))
14706 (values (and value (org-split-string value "[ \t]"))))
14707 (mapcar 'org-entry-restore-space values)))
14709 (defun org-entry-put-multivalued-property (pom property &rest values)
14710 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14711 VALUES should be a list of strings. Spaces will be protected."
14712 (org-entry-put pom property
14713 (mapconcat 'org-entry-protect-space values " "))
14714 (let* ((value (org-entry-get pom property))
14715 (values (and value (org-split-string value "[ \t]"))))
14716 (mapcar 'org-entry-restore-space values)))
14718 (defun org-entry-protect-space (s)
14719 "Protect spaces and newline in string S."
14720 (while (string-match " " s)
14721 (setq s (replace-match "%20" t t s)))
14722 (while (string-match "\n" s)
14723 (setq s (replace-match "%0A" t t s)))
14726 (defun org-entry-restore-space (s)
14727 "Restore spaces and newline in string S."
14728 (while (string-match "%20" s)
14729 (setq s (replace-match " " t t s)))
14730 (while (string-match "%0A" s)
14731 (setq s (replace-match "\n" t t s)))
14734 (defvar org-entry-property-inherited-from (make-marker)
14735 "Marker pointing to the entry from where a property was inherited.
14736 Each call to `org-entry-get-with-inheritance' will set this marker to the
14737 location of the entry where the inheritance search matched. If there was
14738 no match, the marker will point nowhere.
14739 Note that also `org-entry-get' calls this function, if the INHERIT flag
14740 is set.")
14742 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14743 "Get PROPERTY of entry or content at point, search higher levels if needed.
14744 The search will stop at the first ancestor which has the property defined.
14745 If the value found is \"nil\", return nil to show that the property
14746 should be considered as undefined (this is the meaning of nil here).
14747 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14748 (move-marker org-entry-property-inherited-from nil)
14749 (let (tmp)
14750 (save-excursion
14751 (save-restriction
14752 (widen)
14753 (catch 'ex
14754 (while t
14755 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14756 (or (ignore-errors (org-back-to-heading t))
14757 (goto-char (point-min)))
14758 (move-marker org-entry-property-inherited-from (point))
14759 (throw 'ex tmp))
14760 (or (ignore-errors (org-up-heading-safe))
14761 (throw 'ex nil))))))
14762 (setq tmp (or tmp
14763 (cdr (assoc property org-file-properties))
14764 (cdr (assoc property org-global-properties))
14765 (cdr (assoc property org-global-properties-fixed))))
14766 (if literal-nil tmp (org-not-nil tmp))))
14768 (defvar org-property-changed-functions nil
14769 "Hook called when the value of a property has changed.
14770 Each hook function should accept two arguments, the name of the property
14771 and the new value.")
14773 (defun org-entry-put (pom property value)
14774 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14775 (org-with-point-at pom
14776 (org-back-to-heading t)
14777 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14778 range)
14779 (cond
14780 ((equal property "TODO")
14781 (when (and (stringp value) (string-match "\\S-" value)
14782 (not (member value org-todo-keywords-1)))
14783 (error "\"%s\" is not a valid TODO state" value))
14784 (if (or (not value)
14785 (not (string-match "\\S-" value)))
14786 (setq value 'none))
14787 (org-todo value)
14788 (org-set-tags nil 'align))
14789 ((equal property "PRIORITY")
14790 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14791 (string-to-char value) ?\ ))
14792 (org-set-tags nil 'align))
14793 ((equal property "CLOCKSUM")
14794 (if (not (re-search-forward
14795 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14796 (error "Cannot find a clock log")
14797 (goto-char (- (match-end 1) 2))
14798 (cond
14799 ((eq value 'earlier) (org-timestamp-down))
14800 ((eq value 'later) (org-timestamp-up)))
14801 (org-clock-sum-current-item)))
14802 ((equal property "SCHEDULED")
14803 (if (re-search-forward org-scheduled-time-regexp end t)
14804 (cond
14805 ((eq value 'earlier) (org-timestamp-change -1 'day))
14806 ((eq value 'later) (org-timestamp-change 1 'day))
14807 (t (call-interactively 'org-schedule)))
14808 (call-interactively 'org-schedule)))
14809 ((equal property "DEADLINE")
14810 (if (re-search-forward org-deadline-time-regexp end t)
14811 (cond
14812 ((eq value 'earlier) (org-timestamp-change -1 'day))
14813 ((eq value 'later) (org-timestamp-change 1 'day))
14814 (t (call-interactively 'org-deadline)))
14815 (call-interactively 'org-deadline)))
14816 ((member property org-special-properties)
14817 (error "The %s property can not yet be set with `org-entry-put'"
14818 property))
14819 (t ; a non-special property
14820 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14821 (setq range (org-get-property-block beg end 'force))
14822 (goto-char (car range))
14823 (if (re-search-forward
14824 (org-re-property-keyword property) (cdr range) t)
14825 (progn
14826 (delete-region (match-beginning 0) (match-end 0))
14827 (goto-char (match-beginning 0)))
14828 (goto-char (cdr range))
14829 (insert "\n")
14830 (backward-char 1)
14831 (org-indent-line))
14832 (insert ":" property ":")
14833 (and value (insert " " value))
14834 (org-indent-line)))))
14835 (run-hook-with-args 'org-property-changed-functions property value)))
14837 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14838 "Get all property keys in the current buffer.
14839 With INCLUDE-SPECIALS, also list the special properties that reflect things
14840 like tags and TODO state.
14841 With INCLUDE-DEFAULTS, also include properties that has special meaning
14842 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14843 and others.
14844 With INCLUDE-COLUMNS, also include property names given in COLUMN
14845 formats in the current buffer."
14846 (let (rtn range cfmt s p)
14847 (save-excursion
14848 (save-restriction
14849 (widen)
14850 (goto-char (point-min))
14851 (while (re-search-forward org-property-start-re nil t)
14852 (setq range (org-get-property-block))
14853 (goto-char (car range))
14854 (while (re-search-forward
14855 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14856 (cdr range) t)
14857 (add-to-list 'rtn (org-match-string-no-properties 1)))
14858 (outline-next-heading))))
14860 (when include-specials
14861 (setq rtn (append org-special-properties rtn)))
14863 (when include-defaults
14864 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14865 (add-to-list 'rtn org-effort-property))
14867 (when include-columns
14868 (save-excursion
14869 (save-restriction
14870 (widen)
14871 (goto-char (point-min))
14872 (while (re-search-forward
14873 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14874 nil t)
14875 (setq cfmt (match-string 2) s 0)
14876 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14877 cfmt s)
14878 (setq s (match-end 0)
14879 p (match-string 1 cfmt))
14880 (unless (or (equal p "ITEM")
14881 (member p org-special-properties))
14882 (add-to-list 'rtn (match-string 1 cfmt))))))))
14884 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14886 (defun org-property-values (key)
14887 "Return a list of all values of property KEY in the current buffer."
14888 (save-excursion
14889 (save-restriction
14890 (widen)
14891 (goto-char (point-min))
14892 (let ((re (org-re-property key))
14893 values)
14894 (while (re-search-forward re nil t)
14895 (add-to-list 'values (org-trim (match-string 1))))
14896 (delete "" values)))))
14898 (defun org-insert-property-drawer ()
14899 "Insert a property drawer into the current entry."
14900 (org-back-to-heading t)
14901 (looking-at org-outline-regexp)
14902 (let ((indent (if org-adapt-indentation
14903 (- (match-end 0) (match-beginning 0))
14905 (beg (point))
14906 (re (concat "^[ \t]*" org-keyword-time-regexp))
14907 end hiddenp)
14908 (outline-next-heading)
14909 (setq end (point))
14910 (goto-char beg)
14911 (while (re-search-forward re end t))
14912 (setq hiddenp (outline-invisible-p))
14913 (end-of-line 1)
14914 (and (equal (char-after) ?\n) (forward-char 1))
14915 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14916 (if (member (match-string 1) '("CLOCK:" ":END:"))
14917 ;; just skip this line
14918 (beginning-of-line 2)
14919 ;; Drawer start, find the end
14920 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14921 (beginning-of-line 1)))
14922 (org-skip-over-state-notes)
14923 (skip-chars-backward " \t\n\r")
14924 (if (eq (char-before) ?*) (forward-char 1))
14925 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14926 (beginning-of-line 0)
14927 (org-indent-to-column indent)
14928 (beginning-of-line 2)
14929 (org-indent-to-column indent)
14930 (beginning-of-line 0)
14931 (if hiddenp
14932 (save-excursion
14933 (org-back-to-heading t)
14934 (hide-entry))
14935 (org-flag-drawer t))))
14937 (defun org-insert-drawer (&optional arg drawer)
14938 "Insert a drawer at point.
14940 Optional argument DRAWER, when non-nil, is a string representing
14941 drawer's name. Otherwise, the user is prompted for a name.
14943 If a region is active, insert the drawer around that region
14944 instead.
14946 Point is left between drawer's boundaries."
14947 (interactive "P")
14948 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14949 "LOGBOOK"))
14950 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14951 ;; internally by Org. They are meant to be inserted
14952 ;; automatically.
14953 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14954 ;; Remove system drawers from list. Note: For some reason,
14955 ;; `org-completing-read' ignores the predicate while
14956 ;; `completing-read' handles it fine.
14957 (drawer (if arg "PROPERTIES"
14958 (or drawer
14959 (completing-read
14960 "Drawer: " org-drawers
14961 (lambda (d) (not (member d system-drawers))))))))
14962 (cond
14963 ;; With C-u, fall back on `org-insert-property-drawer'
14964 (arg (org-insert-property-drawer))
14965 ;; With an active region, insert a drawer at point.
14966 ((not (org-region-active-p))
14967 (progn
14968 (unless (bolp) (insert "\n"))
14969 (insert (format ":%s:\n\n:END:\n" drawer))
14970 (forward-line -2)))
14971 ;; Otherwise, insert the drawer at point
14973 (let ((rbeg (region-beginning))
14974 (rend (copy-marker (region-end))))
14975 (unwind-protect
14976 (progn
14977 (goto-char rbeg)
14978 (beginning-of-line)
14979 (when (save-excursion
14980 (re-search-forward org-outline-regexp-bol rend t))
14981 (error "Drawers cannot contain headlines"))
14982 ;; Position point at the beginning of the first
14983 ;; non-blank line in region. Insert drawer's opening
14984 ;; there, then indent it.
14985 (org-skip-whitespace)
14986 (beginning-of-line)
14987 (insert ":" drawer ":\n")
14988 (forward-line -1)
14989 (indent-for-tab-command)
14990 ;; Move point to the beginning of the first blank line
14991 ;; after the last non-blank line in region. Insert
14992 ;; drawer's closing, then indent it.
14993 (goto-char rend)
14994 (skip-chars-backward " \r\t\n")
14995 (insert "\n:END:")
14996 (deactivate-mark t)
14997 (indent-for-tab-command)
14998 (unless (eolp) (insert "\n")))
14999 ;; Clear marker, whatever the outcome of insertion is.
15000 (set-marker rend nil)))))))
15002 (defvar org-property-set-functions-alist nil
15003 "Property set function alist.
15004 Each entry should have the following format:
15006 (PROPERTY . READ-FUNCTION)
15008 The read function will be called with the same argument as
15009 `org-completing-read'.")
15011 (defun org-set-property-function (property)
15012 "Get the function that should be used to set PROPERTY.
15013 This is computed according to `org-property-set-functions-alist'."
15014 (or (cdr (assoc property org-property-set-functions-alist))
15015 'org-completing-read))
15017 (defun org-read-property-value (property)
15018 "Read PROPERTY value from user."
15019 (let* ((completion-ignore-case t)
15020 (allowed (org-property-get-allowed-values nil property 'table))
15021 (cur (org-entry-get nil property))
15022 (prompt (concat property " value"
15023 (if (and cur (string-match "\\S-" cur))
15024 (concat " [" cur "]") "") ": "))
15025 (set-function (org-set-property-function property))
15026 (val (if allowed
15027 (funcall set-function prompt allowed nil
15028 (not (get-text-property 0 'org-unrestricted
15029 (caar allowed))))
15030 (let (org-completion-use-ido org-completion-use-iswitchb)
15031 (funcall set-function prompt
15032 (mapcar 'list (org-property-values property))
15033 nil nil "" nil cur)))))
15034 (if (equal val "")
15036 val)))
15038 (defvar org-last-set-property nil)
15039 (defun org-read-property-name ()
15040 "Read a property name."
15041 (let* ((completion-ignore-case t)
15042 (keys (org-buffer-property-keys nil t t))
15043 (default-prop (or (save-excursion
15044 (save-match-data
15045 (beginning-of-line)
15046 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15047 (null (string= (match-string 1) "END"))
15048 (match-string 1))))
15049 org-last-set-property))
15050 (property (org-icompleting-read
15051 (concat "Property"
15052 (if default-prop (concat " [" default-prop "]") "")
15053 ": ")
15054 (mapcar 'list keys)
15055 nil nil nil nil
15056 default-prop
15058 (if (member property keys)
15059 property
15060 (or (cdr (assoc (downcase property)
15061 (mapcar (lambda (x) (cons (downcase x) x))
15062 keys)))
15063 property))))
15065 (defun org-set-property (property value)
15066 "In the current entry, set PROPERTY to VALUE.
15067 When called interactively, this will prompt for a property name, offering
15068 completion on existing and default properties. And then it will prompt
15069 for a value, offering completion either on allowed values (via an inherited
15070 xxx_ALL property) or on existing values in other instances of this property
15071 in the current file."
15072 (interactive (list nil nil))
15073 (let* ((property (or property (org-read-property-name)))
15074 (value (or value (org-read-property-value property)))
15075 (fn (cdr (assoc property org-properties-postprocess-alist))))
15076 (setq org-last-set-property property)
15077 ;; Possibly postprocess the inserted value:
15078 (when fn (setq value (funcall fn value)))
15079 (unless (equal (org-entry-get nil property) value)
15080 (org-entry-put nil property value))))
15082 (defun org-delete-property (property)
15083 "In the current entry, delete PROPERTY."
15084 (interactive
15085 (let* ((completion-ignore-case t)
15086 (prop (org-icompleting-read "Property: "
15087 (org-entry-properties nil 'standard))))
15088 (list prop)))
15089 (message "Property %s %s" property
15090 (if (org-entry-delete nil property)
15091 "deleted"
15092 "was not present in the entry")))
15094 (defun org-delete-property-globally (property)
15095 "Remove PROPERTY globally, from all entries."
15096 (interactive
15097 (let* ((completion-ignore-case t)
15098 (prop (org-icompleting-read
15099 "Globally remove property: "
15100 (mapcar 'list (org-buffer-property-keys)))))
15101 (list prop)))
15102 (save-excursion
15103 (save-restriction
15104 (widen)
15105 (goto-char (point-min))
15106 (let ((cnt 0))
15107 (while (re-search-forward
15108 (org-re-property property)
15109 nil t)
15110 (setq cnt (1+ cnt))
15111 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15112 (message "Property \"%s\" removed from %d entries" property cnt)))))
15114 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15116 (defun org-compute-property-at-point ()
15117 "Compute the property at point.
15118 This looks for an enclosing column format, extracts the operator and
15119 then applies it to the property in the column format's scope."
15120 (interactive)
15121 (unless (org-at-property-p)
15122 (error "Not at a property"))
15123 (let ((prop (org-match-string-no-properties 2)))
15124 (org-columns-get-format-and-top-level)
15125 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15126 (error "No operator defined for property %s" prop))
15127 (org-columns-compute prop)))
15129 (defvar org-property-allowed-value-functions nil
15130 "Hook for functions supplying allowed values for a specific property.
15131 The functions must take a single argument, the name of the property, and
15132 return a flat list of allowed values. If \":ETC\" is one of
15133 the values, this means that these values are intended as defaults for
15134 completion, but that other values should be allowed too.
15135 The functions must return nil if they are not responsible for this
15136 property.")
15138 (defun org-property-get-allowed-values (pom property &optional table)
15139 "Get allowed values for the property PROPERTY.
15140 When TABLE is non-nil, return an alist that can directly be used for
15141 completion."
15142 (let (vals)
15143 (cond
15144 ((equal property "TODO")
15145 (setq vals (org-with-point-at pom
15146 (append org-todo-keywords-1 '("")))))
15147 ((equal property "PRIORITY")
15148 (let ((n org-lowest-priority))
15149 (while (>= n org-highest-priority)
15150 (push (char-to-string n) vals)
15151 (setq n (1- n)))))
15152 ((member property org-special-properties))
15153 ((setq vals (run-hook-with-args-until-success
15154 'org-property-allowed-value-functions property)))
15156 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15157 (when (and vals (string-match "\\S-" vals))
15158 (setq vals (car (read-from-string (concat "(" vals ")"))))
15159 (setq vals (mapcar (lambda (x)
15160 (cond ((stringp x) x)
15161 ((numberp x) (number-to-string x))
15162 ((symbolp x) (symbol-name x))
15163 (t "???")))
15164 vals)))))
15165 (when (member ":ETC" vals)
15166 (setq vals (remove ":ETC" vals))
15167 (org-add-props (car vals) '(org-unrestricted t)))
15168 (if table (mapcar 'list vals) vals)))
15170 (defun org-property-previous-allowed-value (&optional previous)
15171 "Switch to the next allowed value for this property."
15172 (interactive)
15173 (org-property-next-allowed-value t))
15175 (defun org-property-next-allowed-value (&optional previous)
15176 "Switch to the next allowed value for this property."
15177 (interactive)
15178 (unless (org-at-property-p)
15179 (error "Not at a property"))
15180 (let* ((key (match-string 2))
15181 (value (match-string 3))
15182 (allowed (or (org-property-get-allowed-values (point) key)
15183 (and (member value '("[ ]" "[-]" "[X]"))
15184 '("[ ]" "[X]"))))
15185 nval)
15186 (unless allowed
15187 (error "Allowed values for this property have not been defined"))
15188 (if previous (setq allowed (reverse allowed)))
15189 (if (member value allowed)
15190 (setq nval (car (cdr (member value allowed)))))
15191 (setq nval (or nval (car allowed)))
15192 (if (equal nval value)
15193 (error "Only one allowed value for this property"))
15194 (org-at-property-p)
15195 (replace-match (concat " :" key ": " nval) t t)
15196 (org-indent-line)
15197 (beginning-of-line 1)
15198 (skip-chars-forward " \t")
15199 (run-hook-with-args 'org-property-changed-functions key nval)))
15201 (defun org-find-olp (path &optional this-buffer)
15202 "Return a marker pointing to the entry at outline path OLP.
15203 If anything goes wrong, throw an error.
15204 You can wrap this call to catch the error like this:
15206 (condition-case msg
15207 (org-mobile-locate-entry (match-string 4))
15208 (error (nth 1 msg)))
15210 The return value will then be either a string with the error message,
15211 or a marker if everything is OK.
15213 If THIS-BUFFER is set, the outline path does not contain a file,
15214 only headings."
15215 (let* ((file (if this-buffer buffer-file-name (pop path)))
15216 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15217 (level 1)
15218 (lmin 1)
15219 (lmax 1)
15220 limit re end found pos heading cnt flevel)
15221 (unless buffer (error "File not found :%s" file))
15222 (with-current-buffer buffer
15223 (save-excursion
15224 (save-restriction
15225 (widen)
15226 (setq limit (point-max))
15227 (goto-char (point-min))
15228 (while (setq heading (pop path))
15229 (setq re (format org-complex-heading-regexp-format
15230 (regexp-quote heading)))
15231 (setq cnt 0 pos (point))
15232 (while (re-search-forward re end t)
15233 (setq level (- (match-end 1) (match-beginning 1)))
15234 (if (and (>= level lmin) (<= level lmax))
15235 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15236 (when (= cnt 0) (error "Heading not found on level %d: %s"
15237 lmax heading))
15238 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15239 lmax heading))
15240 (goto-char found)
15241 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15242 (setq end (save-excursion (org-end-of-subtree t t))))
15243 (when (org-at-heading-p)
15244 (move-marker (make-marker) (point))))))))
15246 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15247 "Find node HEADING in BUFFER.
15248 Return a marker to the heading if it was found, or nil if not.
15249 If POS-ONLY is set, return just the position instead of a marker.
15251 The heading text must match exact, but it may have a TODO keyword,
15252 a priority cookie and tags in the standard locations."
15253 (with-current-buffer (or buffer (current-buffer))
15254 (save-excursion
15255 (save-restriction
15256 (widen)
15257 (goto-char (point-min))
15258 (let (case-fold-search)
15259 (if (re-search-forward
15260 (format org-complex-heading-regexp-format
15261 (regexp-quote heading)) nil t)
15262 (if pos-only
15263 (match-beginning 0)
15264 (move-marker (make-marker) (match-beginning 0)))))))))
15266 (defun org-find-exact-heading-in-directory (heading &optional dir)
15267 "Find Org node headline HEADING in all .org files in directory DIR.
15268 When the target headline is found, return a marker to this location."
15269 (let ((files (directory-files (or dir default-directory)
15270 nil "\\`[^.#].*\\.org\\'"))
15271 file visiting m buffer)
15272 (catch 'found
15273 (while (setq file (pop files))
15274 (message "trying %s" file)
15275 (setq visiting (org-find-base-buffer-visiting file))
15276 (setq buffer (or visiting (find-file-noselect file)))
15277 (setq m (org-find-exact-headline-in-buffer
15278 heading buffer))
15279 (when (and (not m) (not visiting)) (kill-buffer buffer))
15280 (and m (throw 'found m))))))
15282 (defun org-find-entry-with-id (ident)
15283 "Locate the entry that contains the ID property with exact value IDENT.
15284 IDENT can be a string, a symbol or a number, this function will search for
15285 the string representation of it.
15286 Return the position where this entry starts, or nil if there is no such entry."
15287 (interactive "sID: ")
15288 (let ((id (cond
15289 ((stringp ident) ident)
15290 ((symbol-name ident) (symbol-name ident))
15291 ((numberp ident) (number-to-string ident))
15292 (t (error "IDENT %s must be a string, symbol or number" ident))))
15293 (case-fold-search nil))
15294 (save-excursion
15295 (save-restriction
15296 (widen)
15297 (goto-char (point-min))
15298 (when (re-search-forward
15299 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15300 nil t)
15301 (org-back-to-heading t)
15302 (point))))))
15304 ;;;; Timestamps
15306 (defvar org-last-changed-timestamp nil)
15307 (defvar org-last-inserted-timestamp nil
15308 "The last time stamp inserted with `org-insert-time-stamp'.")
15309 (defvar org-time-was-given) ; dynamically scoped parameter
15310 (defvar org-end-time-was-given) ; dynamically scoped parameter
15311 (defvar org-ts-what) ; dynamically scoped parameter
15313 (defun org-time-stamp (arg &optional inactive)
15314 "Prompt for a date/time and insert a time stamp.
15315 If the user specifies a time like HH:MM or if this command is
15316 called with at least one prefix argument, the time stamp contains
15317 the date and the time. Otherwise, only the date is be included.
15319 All parts of a date not specified by the user is filled in from
15320 the current date/time. So if you just press return without
15321 typing anything, the time stamp will represent the current
15322 date/time.
15324 If there is already a timestamp at the cursor, it will be
15325 modified.
15327 With two universal prefix arguments, insert an active timestamp
15328 with the current time without prompting the user."
15329 (interactive "P")
15330 (let* ((ts nil)
15331 (default-time
15332 ;; Default time is either today, or, when entering a range,
15333 ;; the range start.
15334 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15335 (save-excursion
15336 (re-search-backward
15337 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15338 (- (point) 20) t)))
15339 (apply 'encode-time (org-parse-time-string (match-string 1)))
15340 (current-time)))
15341 (default-input (and ts (org-get-compact-tod ts)))
15342 (repeater (save-excursion
15343 (save-match-data
15344 (beginning-of-line)
15345 (when (re-search-forward
15346 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15347 (save-excursion (progn (end-of-line) (point))) t)
15348 (match-string 0)))))
15349 org-time-was-given org-end-time-was-given time)
15350 (cond
15351 ((and (org-at-timestamp-p t)
15352 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15353 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15354 (insert "--")
15355 (setq time (let ((this-command this-command))
15356 (org-read-date arg 'totime nil nil
15357 default-time default-input inactive)))
15358 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15359 ((org-at-timestamp-p t)
15360 (setq time (let ((this-command this-command))
15361 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15362 (when (org-at-timestamp-p t) ; just to get the match data
15363 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15364 (replace-match "")
15365 (setq org-last-changed-timestamp
15366 (org-insert-time-stamp
15367 time (or org-time-was-given arg)
15368 inactive nil nil (list org-end-time-was-given)))
15369 (when repeater (goto-char (1- (point))) (insert " " repeater)
15370 (setq org-last-changed-timestamp
15371 (concat (substring org-last-inserted-timestamp 0 -1)
15372 " " repeater ">"))))
15373 (message "Timestamp updated"))
15374 ((equal arg '(16))
15375 (org-insert-time-stamp (current-time) t))
15377 (setq time (let ((this-command this-command))
15378 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15379 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15380 nil nil (list org-end-time-was-given))))))
15382 ;; FIXME: can we use this for something else, like computing time differences?
15383 (defun org-get-compact-tod (s)
15384 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15385 (let* ((t1 (match-string 1 s))
15386 (h1 (string-to-number (match-string 2 s)))
15387 (m1 (string-to-number (match-string 3 s)))
15388 (t2 (and (match-end 4) (match-string 5 s)))
15389 (h2 (and t2 (string-to-number (match-string 6 s))))
15390 (m2 (and t2 (string-to-number (match-string 7 s))))
15391 dh dm)
15392 (if (not t2)
15394 (setq dh (- h2 h1) dm (- m2 m1))
15395 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15396 (concat t1 "+" (number-to-string dh)
15397 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15399 (defun org-time-stamp-inactive (&optional arg)
15400 "Insert an inactive time stamp.
15401 An inactive time stamp is enclosed in square brackets instead of angle
15402 brackets. It is inactive in the sense that it does not trigger agenda entries,
15403 does not link to the calendar and cannot be changed with the S-cursor keys.
15404 So these are more for recording a certain time/date."
15405 (interactive "P")
15406 (org-time-stamp arg 'inactive))
15408 (defvar org-date-ovl (make-overlay 1 1))
15409 (overlay-put org-date-ovl 'face 'org-date-selected)
15410 (org-detach-overlay org-date-ovl)
15412 (defvar org-ans1) ; dynamically scoped parameter
15413 (defvar org-ans2) ; dynamically scoped parameter
15415 (defvar org-plain-time-of-day-regexp) ; defined below
15417 (defvar org-overriding-default-time nil) ; dynamically scoped
15418 (defvar org-read-date-overlay nil)
15419 (defvar org-dcst nil) ; dynamically scoped
15420 (defvar org-read-date-history nil)
15421 (defvar org-read-date-final-answer nil)
15422 (defvar org-read-date-analyze-futurep nil)
15423 (defvar org-read-date-analyze-forced-year nil)
15424 (defvar org-read-date-inactive)
15426 (defun org-read-date (&optional org-with-time to-time from-string prompt
15427 default-time default-input inactive)
15428 "Read a date, possibly a time, and make things smooth for the user.
15429 The prompt will suggest to enter an ISO date, but you can also enter anything
15430 which will at least partially be understood by `parse-time-string'.
15431 Unrecognized parts of the date will default to the current day, month, year,
15432 hour and minute. If this command is called to replace a timestamp at point,
15433 or to enter the second timestamp of a range, the default time is taken
15434 from the existing stamp. Furthermore, the command prefers the future,
15435 so if you are giving a date where the year is not given, and the day-month
15436 combination is already past in the current year, it will assume you
15437 mean next year. For details, see the manual. A few examples:
15439 3-2-5 --> 2003-02-05
15440 feb 15 --> currentyear-02-15
15441 2/15 --> currentyear-02-15
15442 sep 12 9 --> 2009-09-12
15443 12:45 --> today 12:45
15444 22 sept 0:34 --> currentyear-09-22 0:34
15445 12 --> currentyear-currentmonth-12
15446 Fri --> nearest Friday (today or later)
15447 etc.
15449 Furthermore you can specify a relative date by giving, as the *first* thing
15450 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15451 change in days weeks, months, years.
15452 With a single plus or minus, the date is relative to today. With a double
15453 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15454 +4d --> four days from today
15455 +4 --> same as above
15456 +2w --> two weeks from today
15457 ++5 --> five days from default date
15459 The function understands only English month and weekday abbreviations.
15461 While prompting, a calendar is popped up - you can also select the
15462 date with the mouse (button 1). The calendar shows a period of three
15463 months. To scroll it to other months, use the keys `>' and `<'.
15464 If you don't like the calendar, turn it off with
15465 \(setq org-read-date-popup-calendar nil)
15467 With optional argument TO-TIME, the date will immediately be converted
15468 to an internal time.
15469 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15470 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15471 still enter a time, and this function will inform the calling routine
15472 about this change. The calling routine may then choose to change the
15473 format used to insert the time stamp into the buffer to include the time.
15474 With optional argument FROM-STRING, read from this string instead from
15475 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15476 the time/date that is used for everything that is not specified by the
15477 user."
15478 (require 'parse-time)
15479 (let* ((org-time-stamp-rounding-minutes
15480 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15481 (org-dcst org-display-custom-times)
15482 (ct (org-current-time))
15483 (org-def (or org-overriding-default-time default-time ct))
15484 (org-defdecode (decode-time org-def))
15485 (dummy (progn
15486 (when (< (nth 2 org-defdecode) org-extend-today-until)
15487 (setcar (nthcdr 2 org-defdecode) -1)
15488 (setcar (nthcdr 1 org-defdecode) 59)
15489 (setq org-def (apply 'encode-time org-defdecode)
15490 org-defdecode (decode-time org-def)))))
15491 (calendar-frame-setup nil)
15492 (calendar-setup nil)
15493 (calendar-move-hook nil)
15494 (calendar-view-diary-initially-flag nil)
15495 (calendar-view-holidays-initially-flag nil)
15496 (timestr (format-time-string
15497 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15498 (prompt (concat (if prompt (concat prompt " ") "")
15499 (format "Date+time [%s]: " timestr)))
15500 ans (org-ans0 "") org-ans1 org-ans2 final)
15502 (cond
15503 (from-string (setq ans from-string))
15504 (org-read-date-popup-calendar
15505 (save-excursion
15506 (save-window-excursion
15507 (calendar)
15508 (org-eval-in-calendar '(setq cursor-type nil) t)
15509 (unwind-protect
15510 (progn
15511 (calendar-forward-day (- (time-to-days org-def)
15512 (calendar-absolute-from-gregorian
15513 (calendar-current-date))))
15514 (org-eval-in-calendar nil t)
15515 (let* ((old-map (current-local-map))
15516 (map (copy-keymap calendar-mode-map))
15517 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15518 (org-defkey map (kbd "RET") 'org-calendar-select)
15519 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15520 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15521 (org-defkey minibuffer-local-map [(meta shift left)]
15522 (lambda () (interactive)
15523 (org-eval-in-calendar '(calendar-backward-month 1))))
15524 (org-defkey minibuffer-local-map [(meta shift right)]
15525 (lambda () (interactive)
15526 (org-eval-in-calendar '(calendar-forward-month 1))))
15527 (org-defkey minibuffer-local-map [(meta shift up)]
15528 (lambda () (interactive)
15529 (org-eval-in-calendar '(calendar-backward-year 1))))
15530 (org-defkey minibuffer-local-map [(meta shift down)]
15531 (lambda () (interactive)
15532 (org-eval-in-calendar '(calendar-forward-year 1))))
15533 (org-defkey minibuffer-local-map [?\e (shift left)]
15534 (lambda () (interactive)
15535 (org-eval-in-calendar '(calendar-backward-month 1))))
15536 (org-defkey minibuffer-local-map [?\e (shift right)]
15537 (lambda () (interactive)
15538 (org-eval-in-calendar '(calendar-forward-month 1))))
15539 (org-defkey minibuffer-local-map [?\e (shift up)]
15540 (lambda () (interactive)
15541 (org-eval-in-calendar '(calendar-backward-year 1))))
15542 (org-defkey minibuffer-local-map [?\e (shift down)]
15543 (lambda () (interactive)
15544 (org-eval-in-calendar '(calendar-forward-year 1))))
15545 (org-defkey minibuffer-local-map [(shift up)]
15546 (lambda () (interactive)
15547 (org-eval-in-calendar '(calendar-backward-week 1))))
15548 (org-defkey minibuffer-local-map [(shift down)]
15549 (lambda () (interactive)
15550 (org-eval-in-calendar '(calendar-forward-week 1))))
15551 (org-defkey minibuffer-local-map [(shift left)]
15552 (lambda () (interactive)
15553 (org-eval-in-calendar '(calendar-backward-day 1))))
15554 (org-defkey minibuffer-local-map [(shift right)]
15555 (lambda () (interactive)
15556 (org-eval-in-calendar '(calendar-forward-day 1))))
15557 (org-defkey minibuffer-local-map ">"
15558 (lambda () (interactive)
15559 (org-eval-in-calendar '(scroll-calendar-left 1))))
15560 (org-defkey minibuffer-local-map "<"
15561 (lambda () (interactive)
15562 (org-eval-in-calendar '(scroll-calendar-right 1))))
15563 (org-defkey minibuffer-local-map "\C-v"
15564 (lambda () (interactive)
15565 (org-eval-in-calendar
15566 '(calendar-scroll-left-three-months 1))))
15567 (org-defkey minibuffer-local-map "\M-v"
15568 (lambda () (interactive)
15569 (org-eval-in-calendar
15570 '(calendar-scroll-right-three-months 1))))
15571 (run-hooks 'org-read-date-minibuffer-setup-hook)
15572 (unwind-protect
15573 (progn
15574 (use-local-map map)
15575 (setq org-read-date-inactive inactive)
15576 (add-hook 'post-command-hook 'org-read-date-display)
15577 (setq org-ans0 (read-string prompt default-input
15578 'org-read-date-history nil))
15579 ;; org-ans0: from prompt
15580 ;; org-ans1: from mouse click
15581 ;; org-ans2: from calendar motion
15582 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15583 (remove-hook 'post-command-hook 'org-read-date-display)
15584 (use-local-map old-map)
15585 (when org-read-date-overlay
15586 (delete-overlay org-read-date-overlay)
15587 (setq org-read-date-overlay nil)))))
15588 (bury-buffer "*Calendar*")))))
15590 (t ; Naked prompt only
15591 (unwind-protect
15592 (setq ans (read-string prompt default-input
15593 'org-read-date-history timestr))
15594 (when org-read-date-overlay
15595 (delete-overlay org-read-date-overlay)
15596 (setq org-read-date-overlay nil)))))
15598 (setq final (org-read-date-analyze ans org-def org-defdecode))
15600 (when org-read-date-analyze-forced-year
15601 (message "Year was forced into %s"
15602 (if org-read-date-force-compatible-dates
15603 "compatible range (1970-2037)"
15604 "range representable on this machine"))
15605 (ding))
15607 ;; One round trip to get rid of 34th of August and stuff like that....
15608 (setq final (decode-time (apply 'encode-time final)))
15610 (setq org-read-date-final-answer ans)
15612 (if to-time
15613 (apply 'encode-time final)
15614 (if (and (boundp 'org-time-was-given) org-time-was-given)
15615 (format "%04d-%02d-%02d %02d:%02d"
15616 (nth 5 final) (nth 4 final) (nth 3 final)
15617 (nth 2 final) (nth 1 final))
15618 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15620 (defvar org-def)
15621 (defvar org-defdecode)
15622 (defvar org-with-time)
15623 (defun org-read-date-display ()
15624 "Display the current date prompt interpretation in the minibuffer."
15625 (when org-read-date-display-live
15626 (when org-read-date-overlay
15627 (delete-overlay org-read-date-overlay))
15628 (when (minibufferp (current-buffer))
15629 (save-excursion
15630 (end-of-line 1)
15631 (while (not (equal (buffer-substring
15632 (max (point-min) (- (point) 4)) (point))
15633 " "))
15634 (insert " ")))
15635 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15636 " " (or org-ans1 org-ans2)))
15637 (org-end-time-was-given nil)
15638 (f (org-read-date-analyze ans org-def org-defdecode))
15639 (fmts (if org-dcst
15640 org-time-stamp-custom-formats
15641 org-time-stamp-formats))
15642 (fmt (if (or org-with-time
15643 (and (boundp 'org-time-was-given) org-time-was-given))
15644 (cdr fmts)
15645 (car fmts)))
15646 (txt (format-time-string fmt (apply 'encode-time f)))
15647 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15648 (txt (concat "=> " txt)))
15649 (when (and org-end-time-was-given
15650 (string-match org-plain-time-of-day-regexp txt))
15651 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15652 org-end-time-was-given
15653 (substring txt (match-end 0)))))
15654 (when org-read-date-analyze-futurep
15655 (setq txt (concat txt " (=>F)")))
15656 (setq org-read-date-overlay
15657 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15658 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15660 (defun org-read-date-analyze (ans org-def org-defdecode)
15661 "Analyze the combined answer of the date prompt."
15662 ;; FIXME: cleanup and comment
15663 (let ((nowdecode (decode-time (current-time)))
15664 delta deltan deltaw deltadef year month day
15665 hour minute second wday pm h2 m2 tl wday1
15666 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15667 (setq org-read-date-analyze-futurep nil
15668 org-read-date-analyze-forced-year nil)
15669 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15670 (setq ans "+0"))
15672 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15673 (setq ans (replace-match "" t t ans)
15674 deltan (car delta)
15675 deltaw (nth 1 delta)
15676 deltadef (nth 2 delta)))
15678 ;; Check if there is an iso week date in there. If yes, store the
15679 ;; info and postpone interpreting it until the rest of the parsing
15680 ;; is done.
15681 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15682 (setq iso-year (if (match-end 1)
15683 (org-small-year-to-year
15684 (string-to-number (match-string 1 ans))))
15685 iso-weekday (if (match-end 3)
15686 (string-to-number (match-string 3 ans)))
15687 iso-week (string-to-number (match-string 2 ans)))
15688 (setq ans (replace-match "" t t ans)))
15690 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15691 (when (string-match
15692 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15693 (setq year (if (match-end 2)
15694 (string-to-number (match-string 2 ans))
15695 (progn (setq kill-year t)
15696 (string-to-number (format-time-string "%Y"))))
15697 month (string-to-number (match-string 3 ans))
15698 day (string-to-number (match-string 4 ans)))
15699 (if (< year 100) (setq year (+ 2000 year)))
15700 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15701 t nil ans)))
15703 ;; Help matching dotted european dates
15704 (when (string-match
15705 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15706 (setq year (if (match-end 3)
15707 (string-to-number (match-string 3 ans))
15708 (progn (setq kill-year t)
15709 (string-to-number (format-time-string "%Y"))))
15710 day (string-to-number (match-string 1 ans))
15711 month (string-to-number (match-string 2 ans))
15712 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15713 t nil ans)))
15715 ;; Help matching american dates, like 5/30 or 5/30/7
15716 (when (string-match
15717 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15718 (setq year (if (match-end 4)
15719 (string-to-number (match-string 4 ans))
15720 (progn (setq kill-year t)
15721 (string-to-number (format-time-string "%Y"))))
15722 month (string-to-number (match-string 1 ans))
15723 day (string-to-number (match-string 2 ans)))
15724 (if (< year 100) (setq year (+ 2000 year)))
15725 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15726 t nil ans)))
15727 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15728 ;; If there is a time with am/pm, and *no* time without it, we convert
15729 ;; so that matching will be successful.
15730 (loop for i from 1 to 2 do ; twice, for end time as well
15731 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15732 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15733 (setq hour (string-to-number (match-string 1 ans))
15734 minute (if (match-end 3)
15735 (string-to-number (match-string 3 ans))
15737 pm (equal ?p
15738 (string-to-char (downcase (match-string 4 ans)))))
15739 (if (and (= hour 12) (not pm))
15740 (setq hour 0)
15741 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15742 (setq ans (replace-match (format "%02d:%02d" hour minute)
15743 t t ans))))
15745 ;; Check if a time range is given as a duration
15746 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15747 (setq hour (string-to-number (match-string 1 ans))
15748 h2 (+ hour (string-to-number (match-string 3 ans)))
15749 minute (string-to-number (match-string 2 ans))
15750 m2 (+ minute (if (match-end 5) (string-to-number
15751 (match-string 5 ans))0)))
15752 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15753 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15754 t t ans)))
15756 ;; Check if there is a time range
15757 (when (boundp 'org-end-time-was-given)
15758 (setq org-time-was-given nil)
15759 (when (and (string-match org-plain-time-of-day-regexp ans)
15760 (match-end 8))
15761 (setq org-end-time-was-given (match-string 8 ans))
15762 (setq ans (concat (substring ans 0 (match-beginning 7))
15763 (substring ans (match-end 7))))))
15765 (setq tl (parse-time-string ans)
15766 day (or (nth 3 tl) (nth 3 org-defdecode))
15767 month (or (nth 4 tl)
15768 (if (and org-read-date-prefer-future
15769 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15770 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15771 (nth 4 org-defdecode)))
15772 year (or (and (not kill-year) (nth 5 tl))
15773 (if (and org-read-date-prefer-future
15774 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15775 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15776 (nth 5 org-defdecode)))
15777 hour (or (nth 2 tl) (nth 2 org-defdecode))
15778 minute (or (nth 1 tl) (nth 1 org-defdecode))
15779 second (or (nth 0 tl) 0)
15780 wday (nth 6 tl))
15782 (when (and (eq org-read-date-prefer-future 'time)
15783 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15784 (equal day (nth 3 nowdecode))
15785 (equal month (nth 4 nowdecode))
15786 (equal year (nth 5 nowdecode))
15787 (nth 2 tl)
15788 (or (< (nth 2 tl) (nth 2 nowdecode))
15789 (and (= (nth 2 tl) (nth 2 nowdecode))
15790 (nth 1 tl)
15791 (< (nth 1 tl) (nth 1 nowdecode)))))
15792 (setq day (1+ day)
15793 futurep t))
15795 ;; Special date definitions below
15796 (cond
15797 (iso-week
15798 ;; There was an iso week
15799 (require 'cal-iso)
15800 (setq futurep nil)
15801 (setq year (or iso-year year)
15802 day (or iso-weekday wday 1)
15803 wday nil ; to make sure that the trigger below does not match
15804 iso-date (calendar-gregorian-from-absolute
15805 (calendar-absolute-from-iso
15806 (list iso-week day year))))
15807 ; FIXME: Should we also push ISO weeks into the future?
15808 ; (when (and org-read-date-prefer-future
15809 ; (not iso-year)
15810 ; (< (calendar-absolute-from-gregorian iso-date)
15811 ; (time-to-days (current-time))))
15812 ; (setq year (1+ year)
15813 ; iso-date (calendar-gregorian-from-absolute
15814 ; (calendar-absolute-from-iso
15815 ; (list iso-week day year)))))
15816 (setq month (car iso-date)
15817 year (nth 2 iso-date)
15818 day (nth 1 iso-date)))
15819 (deltan
15820 (setq futurep nil)
15821 (unless deltadef
15822 (let ((now (decode-time (current-time))))
15823 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15824 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15825 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15826 ((equal deltaw "m") (setq month (+ month deltan)))
15827 ((equal deltaw "y") (setq year (+ year deltan)))))
15828 ((and wday (not (nth 3 tl)))
15829 ;; Weekday was given, but no day, so pick that day in the week
15830 ;; on or after the derived date.
15831 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15832 (unless (equal wday wday1)
15833 (setq day (+ day (% (- wday wday1 -7) 7))))))
15834 (if (and (boundp 'org-time-was-given)
15835 (nth 2 tl))
15836 (setq org-time-was-given t))
15837 (if (< year 100) (setq year (+ 2000 year)))
15838 ;; Check of the date is representable
15839 (if org-read-date-force-compatible-dates
15840 (progn
15841 (if (< year 1970)
15842 (setq year 1970 org-read-date-analyze-forced-year t))
15843 (if (> year 2037)
15844 (setq year 2037 org-read-date-analyze-forced-year t)))
15845 (condition-case nil
15846 (ignore (encode-time second minute hour day month year))
15847 (error
15848 (setq year (nth 5 org-defdecode))
15849 (setq org-read-date-analyze-forced-year t))))
15850 (setq org-read-date-analyze-futurep futurep)
15851 (list second minute hour day month year)))
15853 (defvar parse-time-weekdays)
15854 (defun org-read-date-get-relative (s today default)
15855 "Check string S for special relative date string.
15856 TODAY and DEFAULT are internal times, for today and for a default.
15857 Return shift list (N what def-flag)
15858 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15859 N is the number of WHATs to shift.
15860 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15861 the DEFAULT date rather than TODAY."
15862 (require 'parse-time)
15863 (when (and
15864 (string-match
15865 (concat
15866 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15867 "\\([0-9]+\\)?"
15868 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15869 "\\([ \t]\\|$\\)") s)
15870 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15871 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15872 (string-to-char (substring (match-string 1 s) -1))
15873 ?+))
15874 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15875 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15876 (what (if (match-end 3) (match-string 3 s) "d"))
15877 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15878 (date (if rel default today))
15879 (wday (nth 6 (decode-time date)))
15880 delta)
15881 (if wday1
15882 (progn
15883 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15884 (if (= dir ?-) (setq delta (- delta 7)))
15885 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15886 (list delta "d" rel))
15887 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15889 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15890 "Turn a user-specified date into the internal representation.
15891 The internal representation needed by the calendar is (month day year).
15892 This is a wrapper to handle the brain-dead convention in calendar that
15893 user function argument order change dependent on argument order."
15894 (if (boundp 'calendar-date-style)
15895 (cond
15896 ((eq calendar-date-style 'american)
15897 (list arg1 arg2 arg3))
15898 ((eq calendar-date-style 'european)
15899 (list arg2 arg1 arg3))
15900 ((eq calendar-date-style 'iso)
15901 (list arg2 arg3 arg1)))
15902 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15903 (if (org-bound-and-true-p european-calendar-style)
15904 (list arg2 arg1 arg3)
15905 (list arg1 arg2 arg3)))))
15907 (defun org-eval-in-calendar (form &optional keepdate)
15908 "Eval FORM in the calendar window and return to current window.
15909 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15910 otherwise stick to the current value of `org-ans2'."
15911 (let ((sf (selected-frame))
15912 (sw (selected-window)))
15913 (select-window (get-buffer-window "*Calendar*" t))
15914 (eval form)
15915 (when (and (not keepdate) (calendar-cursor-to-date))
15916 (let* ((date (calendar-cursor-to-date))
15917 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15918 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15919 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15920 (select-window sw)
15921 (org-select-frame-set-input-focus sf)))
15923 (defun org-calendar-select ()
15924 "Return to `org-read-date' with the date currently selected.
15925 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15926 (interactive)
15927 (when (calendar-cursor-to-date)
15928 (let* ((date (calendar-cursor-to-date))
15929 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15930 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15931 (if (active-minibuffer-window) (exit-minibuffer))))
15933 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15934 "Insert a date stamp for the date given by the internal TIME.
15935 WITH-HM means use the stamp format that includes the time of the day.
15936 INACTIVE means use square brackets instead of angular ones, so that the
15937 stamp will not contribute to the agenda.
15938 PRE and POST are optional strings to be inserted before and after the
15939 stamp.
15940 The command returns the inserted time stamp."
15941 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15942 stamp)
15943 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15944 (insert-before-markers (or pre ""))
15945 (when (listp extra)
15946 (setq extra (car extra))
15947 (if (and (stringp extra)
15948 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15949 (setq extra (format "-%02d:%02d"
15950 (string-to-number (match-string 1 extra))
15951 (string-to-number (match-string 2 extra))))
15952 (setq extra nil)))
15953 (when extra
15954 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15955 (insert-before-markers (setq stamp (format-time-string fmt time)))
15956 (insert-before-markers (or post ""))
15957 (setq org-last-inserted-timestamp stamp)))
15959 (defun org-toggle-time-stamp-overlays ()
15960 "Toggle the use of custom time stamp formats."
15961 (interactive)
15962 (setq org-display-custom-times (not org-display-custom-times))
15963 (unless org-display-custom-times
15964 (let ((p (point-min)) (bmp (buffer-modified-p)))
15965 (while (setq p (next-single-property-change p 'display))
15966 (if (and (get-text-property p 'display)
15967 (eq (get-text-property p 'face) 'org-date))
15968 (remove-text-properties
15969 p (setq p (next-single-property-change p 'display))
15970 '(display t))))
15971 (set-buffer-modified-p bmp)))
15972 (if (featurep 'xemacs)
15973 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15974 (org-restart-font-lock)
15975 (setq org-table-may-need-update t)
15976 (if org-display-custom-times
15977 (message "Time stamps are overlaid with custom format")
15978 (message "Time stamp overlays removed")))
15980 (defun org-display-custom-time (beg end)
15981 "Overlay modified time stamp format over timestamp between BEG and END."
15982 (let* ((ts (buffer-substring beg end))
15983 t1 w1 with-hm tf time str w2 (off 0))
15984 (save-match-data
15985 (setq t1 (org-parse-time-string ts t))
15986 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15987 (setq off (- (match-end 0) (match-beginning 0)))))
15988 (setq end (- end off))
15989 (setq w1 (- end beg)
15990 with-hm (and (nth 1 t1) (nth 2 t1))
15991 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15992 time (org-fix-decoded-time t1)
15993 str (org-add-props
15994 (format-time-string
15995 (substring tf 1 -1) (apply 'encode-time time))
15996 nil 'mouse-face 'highlight)
15997 w2 (length str))
15998 (if (not (= w2 w1))
15999 (add-text-properties (1+ beg) (+ 2 beg)
16000 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16001 (if (featurep 'xemacs)
16002 (progn
16003 (put-text-property beg end 'invisible t)
16004 (put-text-property beg end 'end-glyph (make-glyph str)))
16005 (put-text-property beg end 'display str))))
16007 (defun org-translate-time (string)
16008 "Translate all timestamps in STRING to custom format.
16009 But do this only if the variable `org-display-custom-times' is set."
16010 (when org-display-custom-times
16011 (save-match-data
16012 (let* ((start 0)
16013 (re org-ts-regexp-both)
16014 t1 with-hm inactive tf time str beg end)
16015 (while (setq start (string-match re string start))
16016 (setq beg (match-beginning 0)
16017 end (match-end 0)
16018 t1 (save-match-data
16019 (org-parse-time-string (substring string beg end) t))
16020 with-hm (and (nth 1 t1) (nth 2 t1))
16021 inactive (equal (substring string beg (1+ beg)) "[")
16022 tf (funcall (if with-hm 'cdr 'car)
16023 org-time-stamp-custom-formats)
16024 time (org-fix-decoded-time t1)
16025 str (format-time-string
16026 (concat
16027 (if inactive "[" "<") (substring tf 1 -1)
16028 (if inactive "]" ">"))
16029 (apply 'encode-time time))
16030 string (replace-match str t t string)
16031 start (+ start (length str)))))))
16032 string)
16034 (defun org-fix-decoded-time (time)
16035 "Set 0 instead of nil for the first 6 elements of time.
16036 Don't touch the rest."
16037 (let ((n 0))
16038 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16040 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16042 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16043 "Difference between TIMESTAMP-STRING and now in days.
16044 If SECONDS is non-nil, return the difference in seconds."
16045 (let ((fdiff (if seconds 'time-to-seconds 'time-to-days)))
16046 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16047 (funcall fdiff (current-time)))))
16049 (defun org-deadline-close (timestamp-string &optional ndays)
16050 "Is the time in TIMESTAMP-STRING close to the current date?"
16051 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16052 (and (< (org-days-to-time timestamp-string) ndays)
16053 (not (org-entry-is-done-p))))
16055 (defun org-get-wdays (ts)
16056 "Get the deadline lead time appropriate for timestring TS."
16057 (cond
16058 ((<= org-deadline-warning-days 0)
16059 ;; 0 or negative, enforce this value no matter what
16060 (- org-deadline-warning-days))
16061 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16062 ;; lead time is specified.
16063 (floor (* (string-to-number (match-string 1 ts))
16064 (cdr (assoc (match-string 2 ts)
16065 '(("d" . 1) ("w" . 7)
16066 ("m" . 30.4) ("y" . 365.25)))))))
16067 ;; go for the default.
16068 (t org-deadline-warning-days)))
16070 (defun org-calendar-select-mouse (ev)
16071 "Return to `org-read-date' with the date currently selected.
16072 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16073 (interactive "e")
16074 (mouse-set-point ev)
16075 (when (calendar-cursor-to-date)
16076 (let* ((date (calendar-cursor-to-date))
16077 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16078 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16079 (if (active-minibuffer-window) (exit-minibuffer))))
16081 (defun org-check-deadlines (ndays)
16082 "Check if there are any deadlines due or past due.
16083 A deadline is considered due if it happens within `org-deadline-warning-days'
16084 days from today's date. If the deadline appears in an entry marked DONE,
16085 it is not shown. The prefix arg NDAYS can be used to test that many
16086 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16087 (interactive "P")
16088 (let* ((org-warn-days
16089 (cond
16090 ((equal ndays '(4)) 100000)
16091 (ndays (prefix-numeric-value ndays))
16092 (t (abs org-deadline-warning-days))))
16093 (case-fold-search nil)
16094 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16095 (callback
16096 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16098 (message "%d deadlines past-due or due within %d days"
16099 (org-occur regexp nil callback)
16100 org-warn-days)))
16102 (defsubst org-re-timestamp (type)
16103 "Return a regexp for timestamp TYPE.
16104 Allowed values for TYPE are:
16106 all: all timestamps
16107 active: only active timestamps (<...>)
16108 inactive: only inactive timestamps ([...])
16109 scheduled: only scheduled timestamps
16110 deadline: only deadline timestamps
16112 When TYPE is nil, fall back on returning a regexp that matches
16113 both scheduled and deadline timestamps."
16114 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16115 ((eq type 'active) org-ts-regexp)
16116 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16117 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16118 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16119 ((eq type 'scheduled-or-deadline)
16120 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16122 (defun org-check-before-date (date)
16123 "Check if there are deadlines or scheduled entries before DATE."
16124 (interactive (list (org-read-date)))
16125 (let ((case-fold-search nil)
16126 (regexp (org-re-timestamp org-ts-type))
16127 (callback
16128 (lambda () (time-less-p
16129 (org-time-string-to-time (match-string 1))
16130 (org-time-string-to-time date)))))
16131 (message "%d entries before %s"
16132 (org-occur regexp nil callback) date)))
16134 (defun org-check-after-date (date)
16135 "Check if there are deadlines or scheduled entries after DATE."
16136 (interactive (list (org-read-date)))
16137 (let ((case-fold-search nil)
16138 (regexp (org-re-timestamp org-ts-type))
16139 (callback
16140 (lambda () (not
16141 (time-less-p
16142 (org-time-string-to-time (match-string 1))
16143 (org-time-string-to-time date))))))
16144 (message "%d entries after %s"
16145 (org-occur regexp nil callback) date)))
16147 (defun org-check-dates-range (start-date end-date)
16148 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16149 (interactive (list (org-read-date nil nil nil "Range starts")
16150 (org-read-date nil nil nil "Range end")))
16151 (let ((case-fold-search nil)
16152 (regexp (org-re-timestamp org-ts-type))
16153 (callback
16154 (lambda ()
16155 (let ((match (match-string 1)))
16156 (and
16157 (not (time-less-p
16158 (org-time-string-to-time match)
16159 (org-time-string-to-time start-date)))
16160 (time-less-p
16161 (org-time-string-to-time match)
16162 (org-time-string-to-time end-date)))))))
16163 (message "%d entries between %s and %s"
16164 (org-occur regexp nil callback) start-date end-date)))
16166 (defun org-evaluate-time-range (&optional to-buffer)
16167 "Evaluate a time range by computing the difference between start and end.
16168 Normally the result is just printed in the echo area, but with prefix arg
16169 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16170 If the time range is actually in a table, the result is inserted into the
16171 next column.
16172 For time difference computation, a year is assumed to be exactly 365
16173 days in order to avoid rounding problems."
16174 (interactive "P")
16176 (org-clock-update-time-maybe)
16177 (save-excursion
16178 (unless (org-at-date-range-p t)
16179 (goto-char (point-at-bol))
16180 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16181 (if (not (org-at-date-range-p t))
16182 (error "Not at a time-stamp range, and none found in current line")))
16183 (let* ((ts1 (match-string 1))
16184 (ts2 (match-string 2))
16185 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16186 (match-end (match-end 0))
16187 (time1 (org-time-string-to-time ts1))
16188 (time2 (org-time-string-to-time ts2))
16189 (t1 (org-float-time time1))
16190 (t2 (org-float-time time2))
16191 (diff (abs (- t2 t1)))
16192 (negative (< (- t2 t1) 0))
16193 ;; (ys (floor (* 365 24 60 60)))
16194 (ds (* 24 60 60))
16195 (hs (* 60 60))
16196 (fy "%dy %dd %02d:%02d")
16197 (fy1 "%dy %dd")
16198 (fd "%dd %02d:%02d")
16199 (fd1 "%dd")
16200 (fh "%02d:%02d")
16201 y d h m align)
16202 (if havetime
16203 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16205 d (floor (/ diff ds)) diff (mod diff ds)
16206 h (floor (/ diff hs)) diff (mod diff hs)
16207 m (floor (/ diff 60)))
16208 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16210 d (floor (+ (/ diff ds) 0.5))
16211 h 0 m 0))
16212 (if (not to-buffer)
16213 (message "%s" (org-make-tdiff-string y d h m))
16214 (if (org-at-table-p)
16215 (progn
16216 (goto-char match-end)
16217 (setq align t)
16218 (and (looking-at " *|") (goto-char (match-end 0))))
16219 (goto-char match-end))
16220 (if (looking-at
16221 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16222 (replace-match ""))
16223 (if negative (insert " -"))
16224 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16225 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16226 (insert " " (format fh h m))))
16227 (if align (org-table-align))
16228 (message "Time difference inserted")))))
16230 (defun org-make-tdiff-string (y d h m)
16231 (let ((fmt "")
16232 (l nil))
16233 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16234 l (push y l)))
16235 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16236 l (push d l)))
16237 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16238 l (push h l)))
16239 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16240 l (push m l)))
16241 (apply 'format fmt (nreverse l))))
16243 (defun org-time-string-to-time (s &optional buffer pos)
16244 "Convert a timestamp string into internal time."
16245 (condition-case errdata
16246 (apply 'encode-time (org-parse-time-string s))
16247 (error (error "Bad timestamp `%s'%s\nError was: %s"
16248 s (if (not (and buffer pos))
16250 (format " at %d in buffer `%s'" pos buffer))
16251 (cdr errdata)))))
16253 (defun org-time-string-to-seconds (s)
16254 "Convert a timestamp string to a number of seconds."
16255 (org-float-time (org-time-string-to-time s)))
16257 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16258 "Convert a time stamp to an absolute day number.
16259 If there is a specifier for a cyclic time stamp, get the closest date to
16260 DAYNR.
16261 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16262 The variable date is bound by the calendar when this is called."
16263 (cond
16264 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16265 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16266 daynr
16267 (+ daynr 1000)))
16268 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16269 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16270 (time-to-days (current-time))) (match-string 0 s)
16271 prefer show-all))
16272 (t (time-to-days
16273 (condition-case errdata
16274 (apply 'encode-time (org-parse-time-string s))
16275 (error (error "Bad timestamp `%s'%s\nError was: %s"
16276 s (if (not (and buffer pos))
16278 (format " at %d in buffer `%s'" pos buffer))
16279 (cdr errdata))))))))
16281 (defun org-days-to-iso-week (days)
16282 "Return the iso week number."
16283 (require 'cal-iso)
16284 (car (calendar-iso-from-absolute days)))
16286 (defun org-small-year-to-year (year)
16287 "Convert 2-digit years into 4-digit years.
16288 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16289 The year 2000 cannot be abbreviated. Any year larger than 99
16290 is returned unchanged."
16291 (if (< year 38)
16292 (setq year (+ 2000 year))
16293 (if (< year 100)
16294 (setq year (+ 1900 year))))
16295 year)
16297 (defun org-time-from-absolute (d)
16298 "Return the time corresponding to date D.
16299 D may be an absolute day number, or a calendar-type list (month day year)."
16300 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16301 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16303 (defun org-calendar-holiday ()
16304 "List of holidays, for Diary display in Org-mode."
16305 (require 'holidays)
16306 (let ((hl (funcall
16307 (if (fboundp 'calendar-check-holidays)
16308 'calendar-check-holidays 'check-calendar-holidays) date)))
16309 (if hl (mapconcat 'identity hl "; "))))
16311 (defun org-diary-sexp-entry (sexp entry date)
16312 "Process a SEXP diary ENTRY for DATE."
16313 (require 'diary-lib)
16314 (let ((result (if calendar-debug-sexp
16315 (let ((stack-trace-on-error t))
16316 (eval (car (read-from-string sexp))))
16317 (condition-case nil
16318 (eval (car (read-from-string sexp)))
16319 (error
16320 (beep)
16321 (message "Bad sexp at line %d in %s: %s"
16322 (org-current-line)
16323 (buffer-file-name) sexp)
16324 (sleep-for 2))))))
16325 (cond ((stringp result) (split-string result "; "))
16326 ((and (consp result)
16327 (not (consp (cdr result)))
16328 (stringp (cdr result))) (cdr result))
16329 ((and (consp result)
16330 (stringp (car result))) result)
16331 (result entry))))
16333 (defun org-diary-to-ical-string (frombuf)
16334 "Get iCalendar entries from diary entries in buffer FROMBUF.
16335 This uses the icalendar.el library."
16336 (let* ((tmpdir (if (featurep 'xemacs)
16337 (temp-directory)
16338 temporary-file-directory))
16339 (tmpfile (make-temp-name
16340 (expand-file-name "orgics" tmpdir)))
16341 buf rtn b e)
16342 (with-current-buffer frombuf
16343 (icalendar-export-region (point-min) (point-max) tmpfile)
16344 (setq buf (find-buffer-visiting tmpfile))
16345 (set-buffer buf)
16346 (goto-char (point-min))
16347 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16348 (setq b (match-beginning 0)))
16349 (goto-char (point-max))
16350 (if (re-search-backward "^END:VEVENT" nil t)
16351 (setq e (match-end 0)))
16352 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16353 (kill-buffer buf)
16354 (delete-file tmpfile)
16355 rtn))
16357 (defun org-closest-date (start current change prefer show-all)
16358 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16359 When PREFER is `past', return a date that is either CURRENT or past.
16360 When PREFER is `future', return a date that is either CURRENT or future.
16361 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16362 ;; Make the proper lists from the dates
16363 (catch 'exit
16364 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16365 dn dw sday cday n1 n2 n0
16366 d m y y1 y2 date1 date2 nmonths nm ny m2)
16368 (setq start (org-date-to-gregorian start)
16369 current (org-date-to-gregorian
16370 (if show-all
16371 current
16372 (time-to-days (current-time))))
16373 sday (calendar-absolute-from-gregorian start)
16374 cday (calendar-absolute-from-gregorian current))
16376 (if (<= cday sday) (throw 'exit sday))
16378 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16379 (setq dn (string-to-number (match-string 1 change))
16380 dw (cdr (assoc (match-string 2 change) a1)))
16381 (error "Invalid change specifier: %s" change))
16382 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16383 (cond
16384 ((eq dw 'day)
16385 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16386 n2 (+ n1 dn)))
16387 ((eq dw 'year)
16388 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16389 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16390 (setq date1 (list m d y1)
16391 n1 (calendar-absolute-from-gregorian date1)
16392 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16393 n2 (calendar-absolute-from-gregorian date2)))
16394 ((eq dw 'month)
16395 ;; approx number of month between the two dates
16396 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16397 ;; How often does dn fit in there?
16398 (setq d (nth 1 start) m (car start) y (nth 2 start)
16399 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16400 m (+ m nm)
16401 ny (floor (/ m 12))
16402 y (+ y ny)
16403 m (- m (* ny 12)))
16404 (while (> m 12) (setq m (- m 12) y (1+ y)))
16405 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16406 (setq m2 (+ m dn) y2 y)
16407 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16408 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16409 (while (<= n2 cday)
16410 (setq n1 n2 m m2 y y2)
16411 (setq m2 (+ m dn) y2 y)
16412 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16413 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16414 ;; Make sure n1 is the earlier date
16415 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16416 (if show-all
16417 (cond
16418 ((eq prefer 'past) (if (= cday n2) n2 n1))
16419 ((eq prefer 'future) (if (= cday n1) n1 n2))
16420 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16421 (cond
16422 ((eq prefer 'past) (if (= cday n2) n2 n1))
16423 ((eq prefer 'future) (if (= cday n1) n1 n2))
16424 (t (if (= cday n1) n1 n2)))))))
16426 (defun org-date-to-gregorian (date)
16427 "Turn any specification of DATE into a Gregorian date for the calendar."
16428 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16429 ((and (listp date) (= (length date) 3)) date)
16430 ((stringp date)
16431 (setq date (org-parse-time-string date))
16432 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16433 ((listp date)
16434 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16436 (defun org-parse-time-string (s &optional nodefault)
16437 "Parse the standard Org-mode time string.
16438 This should be a lot faster than the normal `parse-time-string'.
16439 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16440 hour and minute fields will be nil if not given."
16441 (if (string-match org-ts-regexp0 s)
16442 (list 0
16443 (if (or (match-beginning 8) (not nodefault))
16444 (string-to-number (or (match-string 8 s) "0")))
16445 (if (or (match-beginning 7) (not nodefault))
16446 (string-to-number (or (match-string 7 s) "0")))
16447 (string-to-number (match-string 4 s))
16448 (string-to-number (match-string 3 s))
16449 (string-to-number (match-string 2 s))
16450 nil nil nil)
16451 (error "Not a standard Org-mode time string: %s" s)))
16453 (defun org-timestamp-up (&optional arg)
16454 "Increase the date item at the cursor by one.
16455 If the cursor is on the year, change the year. If it is on the month,
16456 the day or the time, change that.
16457 With prefix ARG, change by that many units."
16458 (interactive "p")
16459 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16461 (defun org-timestamp-down (&optional arg)
16462 "Decrease the date item at the cursor by one.
16463 If the cursor is on the year, change the year. If it is on the month,
16464 the day or the time, change that.
16465 With prefix ARG, change by that many units."
16466 (interactive "p")
16467 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16469 (defun org-timestamp-up-day (&optional arg)
16470 "Increase the date in the time stamp by one day.
16471 With prefix ARG, change that many days."
16472 (interactive "p")
16473 (if (and (not (org-at-timestamp-p t))
16474 (org-at-heading-p))
16475 (org-todo 'up)
16476 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16478 (defun org-timestamp-down-day (&optional arg)
16479 "Decrease the date in the time stamp by one day.
16480 With prefix ARG, change that many days."
16481 (interactive "p")
16482 (if (and (not (org-at-timestamp-p t))
16483 (org-at-heading-p))
16484 (org-todo 'down)
16485 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16487 (defun org-at-timestamp-p (&optional inactive-ok)
16488 "Determine if the cursor is in or at a timestamp."
16489 (interactive)
16490 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16491 (pos (point))
16492 (ans (or (looking-at tsr)
16493 (save-excursion
16494 (skip-chars-backward "^[<\n\r\t")
16495 (if (> (point) (point-min)) (backward-char 1))
16496 (and (looking-at tsr)
16497 (> (- (match-end 0) pos) -1))))))
16498 (and ans
16499 (boundp 'org-ts-what)
16500 (setq org-ts-what
16501 (cond
16502 ((= pos (match-beginning 0)) 'bracket)
16503 ;; Point is considered to be "on the bracket" whether
16504 ;; it's really on it or right after it.
16505 ((= pos (1- (match-end 0))) 'bracket)
16506 ((= pos (match-end 0)) 'after)
16507 ((org-pos-in-match-range pos 2) 'year)
16508 ((org-pos-in-match-range pos 3) 'month)
16509 ((org-pos-in-match-range pos 7) 'hour)
16510 ((org-pos-in-match-range pos 8) 'minute)
16511 ((or (org-pos-in-match-range pos 4)
16512 (org-pos-in-match-range pos 5)) 'day)
16513 ((and (> pos (or (match-end 8) (match-end 5)))
16514 (< pos (match-end 0)))
16515 (- pos (or (match-end 8) (match-end 5))))
16516 (t 'day))))
16517 ans))
16519 (defun org-toggle-timestamp-type ()
16520 "Toggle the type (<active> or [inactive]) of a time stamp."
16521 (interactive)
16522 (when (org-at-timestamp-p t)
16523 (let ((beg (match-beginning 0)) (end (match-end 0))
16524 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16525 (save-excursion
16526 (goto-char beg)
16527 (while (re-search-forward "[][<>]" end t)
16528 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16529 t t)))
16530 (message "Timestamp is now %sactive"
16531 (if (equal (char-after beg) ?<) "" "in")))))
16533 (defvar org-clock-history) ; defined in org-clock.el
16534 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16535 (defun org-timestamp-change (n &optional what updown)
16536 "Change the date in the time stamp at point.
16537 The date will be changed by N times WHAT. WHAT can be `day', `month',
16538 `year', `minute', `second'. If WHAT is not given, the cursor position
16539 in the timestamp determines what will be changed."
16540 (let ((origin (point)) origin-cat
16541 with-hm inactive
16542 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16543 org-ts-what
16544 extra rem
16545 ts time time0 fixnext clrgx)
16546 (if (not (org-at-timestamp-p t))
16547 (error "Not at a timestamp"))
16548 (if (and (not what) (eq org-ts-what 'bracket))
16549 (org-toggle-timestamp-type)
16550 ;; Point isn't on brackets. Remember the part of the time-stamp
16551 ;; the point was in. Indeed, size of time-stamps may change,
16552 ;; but point must be kept in the same category nonetheless.
16553 (setq origin-cat org-ts-what)
16554 (if (and (not what) (not (eq org-ts-what 'day))
16555 org-display-custom-times
16556 (get-text-property (point) 'display)
16557 (not (get-text-property (1- (point)) 'display)))
16558 (setq org-ts-what 'day))
16559 (setq org-ts-what (or what org-ts-what)
16560 inactive (= (char-after (match-beginning 0)) ?\[)
16561 ts (match-string 0))
16562 (replace-match "")
16563 (if (string-match
16564 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16566 (setq extra (match-string 1 ts)))
16567 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16568 (setq with-hm t))
16569 (setq time0 (org-parse-time-string ts))
16570 (when (and updown
16571 (eq org-ts-what 'minute)
16572 (not current-prefix-arg))
16573 ;; This looks like s-up and s-down. Change by one rounding step.
16574 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16575 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16576 (setcar (cdr time0) (+ (nth 1 time0)
16577 (if (> n 0) (- rem) (- dm rem))))))
16578 (setq time
16579 (encode-time (or (car time0) 0)
16580 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16581 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16582 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16583 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16584 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16585 (nthcdr 6 time0)))
16586 (when (and (member org-ts-what '(hour minute))
16587 extra
16588 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16589 (setq extra (org-modify-ts-extra
16590 extra
16591 (if (eq org-ts-what 'hour) 2 5)
16592 n dm)))
16593 (when (integerp org-ts-what)
16594 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16595 (if (eq what 'calendar)
16596 (let ((cal-date (org-get-date-from-calendar)))
16597 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16598 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16599 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16600 (setcar time0 (or (car time0) 0))
16601 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16602 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16603 (setq time (apply 'encode-time time0))))
16604 ;; Insert the new time-stamp, and ensure point stays in the same
16605 ;; category as before (i.e. not after the last position in that
16606 ;; category).
16607 (let ((pos (point)))
16608 ;; Stay before inserted string. `save-excursion' is of no use.
16609 (setq org-last-changed-timestamp
16610 (org-insert-time-stamp time with-hm inactive nil nil extra))
16611 (goto-char pos))
16612 (save-match-data
16613 (looking-at org-ts-regexp3)
16614 (goto-char (cond
16615 ;; `day' category ends before `hour' if any, or at
16616 ;; the end of the day name.
16617 ((eq origin-cat 'day)
16618 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16619 ((eq origin-cat 'hour) (min (match-end 7) origin))
16620 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16621 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16622 ;; `year' and `month' have both fixed size: point
16623 ;; couldn't have moved into another part.
16624 (t origin))))
16625 ;; Update clock if on a CLOCK line.
16626 (org-clock-update-time-maybe)
16627 ;; Maybe adjust the closest clock in `org-clock-history'
16628 (when org-clock-adjust-closest
16629 (if (not (and (org-at-clock-log-p)
16630 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16631 org-clock-history))))))
16632 (message "No clock to adjust")
16633 (cond ((save-excursion ; fix previous clock?
16634 (re-search-backward org-ts-regexp0 nil t)
16635 (org-looking-back (concat org-clock-string " \\[")))
16636 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16637 ((save-excursion ; fix next clock?
16638 (re-search-backward org-ts-regexp0 nil t)
16639 (looking-at (concat org-ts-regexp0 "\\] =>")))
16640 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16641 (save-window-excursion
16642 ;; Find closest clock to point, adjust the previous/next one in history
16643 (let* ((p (save-excursion (org-back-to-heading t)))
16644 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16645 (clfixnth
16646 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16647 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16648 (if (not clfixpos)
16649 (message "No clock to adjust")
16650 (save-excursion
16651 (org-goto-marker-or-bmk clfixpos)
16652 (org-show-subtree)
16653 (when (re-search-forward clrgx nil t)
16654 (goto-char (match-beginning 1))
16655 (let (org-clock-adjust-closest)
16656 (org-timestamp-change n org-ts-what updown))
16657 (message "Clock adjusted in %s for heading: %s"
16658 (file-name-nondirectory (buffer-file-name))
16659 (org-get-heading t t)))))))))
16660 ;; Try to recenter the calendar window, if any.
16661 (if (and org-calendar-follow-timestamp-change
16662 (get-buffer-window "*Calendar*" t)
16663 (memq org-ts-what '(day month year)))
16664 (org-recenter-calendar (time-to-days time))))))
16666 (defun org-modify-ts-extra (s pos n dm)
16667 "Change the different parts of the lead-time and repeat fields in timestamp."
16668 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16669 ng h m new rem)
16670 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16671 (cond
16672 ((or (org-pos-in-match-range pos 2)
16673 (org-pos-in-match-range pos 3))
16674 (setq m (string-to-number (match-string 3 s))
16675 h (string-to-number (match-string 2 s)))
16676 (if (org-pos-in-match-range pos 2)
16677 (setq h (+ h n))
16678 (setq n (* dm (org-no-warnings (signum n))))
16679 (when (not (= 0 (setq rem (% m dm))))
16680 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16681 (setq m (+ m n)))
16682 (if (< m 0) (setq m (+ m 60) h (1- h)))
16683 (if (> m 59) (setq m (- m 60) h (1+ h)))
16684 (setq h (min 24 (max 0 h)))
16685 (setq ng 1 new (format "-%02d:%02d" h m)))
16686 ((org-pos-in-match-range pos 6)
16687 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16688 ((org-pos-in-match-range pos 5)
16689 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16691 ((org-pos-in-match-range pos 9)
16692 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16693 ((org-pos-in-match-range pos 8)
16694 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16696 (when ng
16697 (setq s (concat
16698 (substring s 0 (match-beginning ng))
16700 (substring s (match-end ng))))))
16703 (defun org-recenter-calendar (date)
16704 "If the calendar is visible, recenter it to DATE."
16705 (let ((cwin (get-buffer-window "*Calendar*" t)))
16706 (when cwin
16707 (let ((calendar-move-hook nil))
16708 (with-selected-window cwin
16709 (calendar-goto-date (if (listp date) date
16710 (calendar-gregorian-from-absolute date))))))))
16712 (defun org-goto-calendar (&optional arg)
16713 "Go to the Emacs calendar at the current date.
16714 If there is a time stamp in the current line, go to that date.
16715 A prefix ARG can be used to force the current date."
16716 (interactive "P")
16717 (let ((tsr org-ts-regexp) diff
16718 (calendar-move-hook nil)
16719 (calendar-view-holidays-initially-flag nil)
16720 (calendar-view-diary-initially-flag nil))
16721 (if (or (org-at-timestamp-p)
16722 (save-excursion
16723 (beginning-of-line 1)
16724 (looking-at (concat ".*" tsr))))
16725 (let ((d1 (time-to-days (current-time)))
16726 (d2 (time-to-days
16727 (org-time-string-to-time (match-string 1)))))
16728 (setq diff (- d2 d1))))
16729 (calendar)
16730 (calendar-goto-today)
16731 (if (and diff (not arg)) (calendar-forward-day diff))))
16733 (defun org-get-date-from-calendar ()
16734 "Return a list (month day year) of date at point in calendar."
16735 (with-current-buffer "*Calendar*"
16736 (save-match-data
16737 (calendar-cursor-to-date))))
16739 (defun org-date-from-calendar ()
16740 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16741 If there is already a time stamp at the cursor position, update it."
16742 (interactive)
16743 (if (org-at-timestamp-p t)
16744 (org-timestamp-change 0 'calendar)
16745 (let ((cal-date (org-get-date-from-calendar)))
16746 (org-insert-time-stamp
16747 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16749 (defun org-minutes-to-hh:mm-string (m)
16750 "Compute H:MM from a number of minutes."
16751 (let ((h (/ m 60)))
16752 (setq m (- m (* 60 h)))
16753 (format org-time-clocksum-format h m)))
16755 (defun org-hh:mm-string-to-minutes (s)
16756 "Convert a string H:MM to a number of minutes.
16757 If the string is just a number, interpret it as minutes.
16758 In fact, the first hh:mm or number in the string will be taken,
16759 there can be extra stuff in the string.
16760 If no number is found, the return value is 0."
16761 (cond
16762 ((integerp s) s)
16763 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16764 (+ (* (string-to-number (match-string 1 s)) 60)
16765 (string-to-number (match-string 2 s))))
16766 ((string-match "\\([0-9]+\\)" s)
16767 (string-to-number (match-string 1 s)))
16768 (t 0)))
16770 (defcustom org-effort-durations
16771 `(("h" . 60)
16772 ("d" . ,(* 60 8))
16773 ("w" . ,(* 60 8 5))
16774 ("m" . ,(* 60 8 5 4))
16775 ("y" . ,(* 60 8 5 40)))
16776 "Conversion factor to minutes for an effort modifier.
16778 Each entry has the form (MODIFIER . MINUTES).
16780 In an effort string, a number followed by MODIFIER is multiplied
16781 by the specified number of MINUTES to obtain an effort in
16782 minutes.
16784 For example, if the value of this variable is ((\"hours\" . 60)), then an
16785 effort string \"2hours\" is equivalent to 120 minutes."
16786 :group 'org-agenda
16787 :version "24.1"
16788 :type '(alist :key-type (string :tag "Modifier")
16789 :value-type (number :tag "Minutes")))
16791 (defcustom org-image-actual-width t
16792 "Should we use the actual width of images when inlining them?
16794 When set to `t', always use the image width.
16796 When set to a number, use imagemagick (when available) to set
16797 the image's width to this value.
16799 When set to a number in a list, try to get the width from the
16800 #+ATTR.* keyword if it matches a width specification like
16801 width=\"[0-9]+\", and fall back on that number if none is found.
16803 When set to nil, try to get the width from an #+ATTR.* keyword
16804 and fall back on the original width if none is found.
16806 This requires Emacs >= 24.1, build with imagemagick support."
16807 :group 'org-appearance
16808 :version "24.3"
16809 :type '(choice
16810 (const :tag "Use the image width" t)
16811 (integer :tag "Use a number of pixels")
16812 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16813 (const :tag "Use #+ATTR* or don't resize" nil)))
16815 (defun org-duration-string-to-minutes (s &optional output-to-string)
16816 "Convert a duration string S to minutes.
16818 A bare number is interpreted as minutes, modifiers can be set by
16819 customizing `org-effort-durations' (which see).
16821 Entries containing a colon are interpreted as H:MM by
16822 `org-hh:mm-string-to-minutes'."
16823 (let ((result 0)
16824 (re (concat "\\([0-9.]+\\) *\\("
16825 (regexp-opt (mapcar 'car org-effort-durations))
16826 "\\)")))
16827 (while (string-match re s)
16828 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16829 (string-to-number (match-string 1 s))))
16830 (setq s (replace-match "" nil t s)))
16831 (setq result (floor result))
16832 (incf result (org-hh:mm-string-to-minutes s))
16833 (if output-to-string (number-to-string result) result)))
16835 ;;;; Files
16837 (defun org-save-all-org-buffers ()
16838 "Save all Org-mode buffers without user confirmation."
16839 (interactive)
16840 (message "Saving all Org-mode buffers...")
16841 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16842 (when (featurep 'org-id) (org-id-locations-save))
16843 (message "Saving all Org-mode buffers... done"))
16845 (defun org-revert-all-org-buffers ()
16846 "Revert all Org-mode buffers.
16847 Prompt for confirmation when there are unsaved changes.
16848 Be sure you know what you are doing before letting this function
16849 overwrite your changes.
16851 This function is useful in a setup where one tracks org files
16852 with a version control system, to revert on one machine after pulling
16853 changes from another. I believe the procedure must be like this:
16855 1. M-x org-save-all-org-buffers
16856 2. Pull changes from the other machine, resolve conflicts
16857 3. M-x org-revert-all-org-buffers"
16858 (interactive)
16859 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16860 (error "Abort"))
16861 (save-excursion
16862 (save-window-excursion
16863 (mapc
16864 (lambda (b)
16865 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16866 (with-current-buffer b buffer-file-name))
16867 (org-pop-to-buffer-same-window b)
16868 (revert-buffer t 'no-confirm)))
16869 (buffer-list))
16870 (when (and (featurep 'org-id) org-id-track-globally)
16871 (org-id-locations-load)))))
16873 ;;;; Agenda files
16875 ;;;###autoload
16876 (defun org-switchb (&optional arg)
16877 "Switch between Org buffers.
16878 With one prefix argument, restrict available buffers to files.
16879 With two prefix arguments, restrict available buffers to agenda files.
16881 Defaults to `iswitchb' for buffer name completion.
16882 Set `org-completion-use-ido' to make it use ido instead."
16883 (interactive "P")
16884 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16885 ((equal arg '(16)) (org-buffer-list 'agenda))
16886 (t (org-buffer-list))))
16887 (org-completion-use-iswitchb org-completion-use-iswitchb)
16888 (org-completion-use-ido org-completion-use-ido))
16889 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16890 (setq org-completion-use-iswitchb t))
16891 (org-pop-to-buffer-same-window
16892 (org-icompleting-read "Org buffer: "
16893 (mapcar 'list (mapcar 'buffer-name blist))
16894 nil t))))
16896 ;;; Define some older names previously used for this functionality
16897 ;;;###autoload
16898 (defalias 'org-ido-switchb 'org-switchb)
16899 ;;;###autoload
16900 (defalias 'org-iswitchb 'org-switchb)
16902 (defun org-buffer-list (&optional predicate exclude-tmp)
16903 "Return a list of Org buffers.
16904 PREDICATE can be `export', `files' or `agenda'.
16906 export restrict the list to Export buffers.
16907 files restrict the list to buffers visiting Org files.
16908 agenda restrict the list to buffers visiting agenda files.
16910 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16911 (let* ((bfn nil)
16912 (agenda-files (and (eq predicate 'agenda)
16913 (mapcar 'file-truename (org-agenda-files t))))
16914 (filter
16915 (cond
16916 ((eq predicate 'files)
16917 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16918 ((eq predicate 'export)
16919 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16920 ((eq predicate 'agenda)
16921 (lambda (b)
16922 (with-current-buffer b
16923 (and (derived-mode-p 'org-mode)
16924 (setq bfn (buffer-file-name b))
16925 (member (file-truename bfn) agenda-files)))))
16926 (t (lambda (b) (with-current-buffer b
16927 (or (derived-mode-p 'org-mode)
16928 (string-match "\*Org .*Export"
16929 (buffer-name b)))))))))
16930 (delq nil
16931 (mapcar
16932 (lambda(b)
16933 (if (and (funcall filter b)
16934 (or (not exclude-tmp)
16935 (not (string-match "tmp" (buffer-name b)))))
16937 nil))
16938 (buffer-list)))))
16940 (defun org-agenda-files (&optional unrestricted archives)
16941 "Get the list of agenda files.
16942 Optional UNRESTRICTED means return the full list even if a restriction
16943 is currently in place.
16944 When ARCHIVES is t, include all archive files that are really being
16945 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16946 `org-agenda-archives-mode' is t."
16947 (let ((files
16948 (cond
16949 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16950 ((stringp org-agenda-files) (org-read-agenda-file-list))
16951 ((listp org-agenda-files) org-agenda-files)
16952 (t (error "Invalid value of `org-agenda-files'")))))
16953 (setq files (apply 'append
16954 (mapcar (lambda (f)
16955 (if (file-directory-p f)
16956 (directory-files
16957 f t org-agenda-file-regexp)
16958 (list f)))
16959 files)))
16960 (when org-agenda-skip-unavailable-files
16961 (setq files (delq nil
16962 (mapcar (function
16963 (lambda (file)
16964 (and (file-readable-p file) file)))
16965 files))))
16966 (when (or (eq archives t)
16967 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16968 (setq files (org-add-archive-files files)))
16969 files))
16971 (defun org-agenda-file-p (&optional file)
16972 "Return non-nil, if FILE is an agenda file.
16973 If FILE is omitted, use the file associated with the current
16974 buffer."
16975 (member (or file (buffer-file-name))
16976 (org-agenda-files t)))
16978 (defun org-edit-agenda-file-list ()
16979 "Edit the list of agenda files.
16980 Depending on setup, this either uses customize to edit the variable
16981 `org-agenda-files', or it visits the file that is holding the list. In the
16982 latter case, the buffer is set up in a way that saving it automatically kills
16983 the buffer and restores the previous window configuration."
16984 (interactive)
16985 (if (stringp org-agenda-files)
16986 (let ((cw (current-window-configuration)))
16987 (find-file org-agenda-files)
16988 (org-set-local 'org-window-configuration cw)
16989 (org-add-hook 'after-save-hook
16990 (lambda ()
16991 (set-window-configuration
16992 (prog1 org-window-configuration
16993 (kill-buffer (current-buffer))))
16994 (org-install-agenda-files-menu)
16995 (message "New agenda file list installed"))
16996 nil 'local)
16997 (message "%s" (substitute-command-keys
16998 "Edit list and finish with \\[save-buffer]")))
16999 (customize-variable 'org-agenda-files)))
17001 (defun org-store-new-agenda-file-list (list)
17002 "Set new value for the agenda file list and save it correctly."
17003 (if (stringp org-agenda-files)
17004 (let ((fe (org-read-agenda-file-list t)) b u)
17005 (while (setq b (find-buffer-visiting org-agenda-files))
17006 (kill-buffer b))
17007 (with-temp-file org-agenda-files
17008 (insert
17009 (mapconcat
17010 (lambda (f) ;; Keep un-expanded entries.
17011 (if (setq u (assoc f fe))
17012 (cdr u)
17014 list "\n")
17015 "\n")))
17016 (let ((org-mode-hook nil) (org-inhibit-startup t)
17017 (org-insert-mode-line-in-empty-file nil))
17018 (setq org-agenda-files list)
17019 (customize-save-variable 'org-agenda-files org-agenda-files))))
17021 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17022 "Read the list of agenda files from a file.
17023 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17024 filenames, used by `org-store-new-agenda-file-list' to write back
17025 un-expanded file names."
17026 (when (file-directory-p org-agenda-files)
17027 (error "`org-agenda-files' cannot be a single directory"))
17028 (when (stringp org-agenda-files)
17029 (with-temp-buffer
17030 (insert-file-contents org-agenda-files)
17031 (mapcar
17032 (lambda (f)
17033 (let ((e (expand-file-name (substitute-in-file-name f)
17034 org-directory)))
17035 (if pair-with-expansion
17036 (cons e f)
17037 e)))
17038 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17040 ;;;###autoload
17041 (defun org-cycle-agenda-files ()
17042 "Cycle through the files in `org-agenda-files'.
17043 If the current buffer visits an agenda file, find the next one in the list.
17044 If the current buffer does not, find the first agenda file."
17045 (interactive)
17046 (let* ((fs (org-agenda-files t))
17047 (files (append fs (list (car fs))))
17048 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17049 file)
17050 (unless files (error "No agenda files"))
17051 (catch 'exit
17052 (while (setq file (pop files))
17053 (if (equal (file-truename file) tcf)
17054 (when (car files)
17055 (find-file (car files))
17056 (throw 'exit t))))
17057 (find-file (car fs)))
17058 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17060 (defun org-agenda-file-to-front (&optional to-end)
17061 "Move/add the current file to the top of the agenda file list.
17062 If the file is not present in the list, it is added to the front. If it is
17063 present, it is moved there. With optional argument TO-END, add/move to the
17064 end of the list."
17065 (interactive "P")
17066 (let ((org-agenda-skip-unavailable-files nil)
17067 (file-alist (mapcar (lambda (x)
17068 (cons (file-truename x) x))
17069 (org-agenda-files t)))
17070 (ctf (file-truename buffer-file-name))
17071 x had)
17072 (setq x (assoc ctf file-alist) had x)
17074 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17075 (if to-end
17076 (setq file-alist (append (delq x file-alist) (list x)))
17077 (setq file-alist (cons x (delq x file-alist))))
17078 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17079 (org-install-agenda-files-menu)
17080 (message "File %s to %s of agenda file list"
17081 (if had "moved" "added") (if to-end "end" "front"))))
17083 (defun org-remove-file (&optional file)
17084 "Remove current file from the list of files in variable `org-agenda-files'.
17085 These are the files which are being checked for agenda entries.
17086 Optional argument FILE means use this file instead of the current."
17087 (interactive)
17088 (let* ((org-agenda-skip-unavailable-files nil)
17089 (file (or file buffer-file-name))
17090 (true-file (file-truename file))
17091 (afile (abbreviate-file-name file))
17092 (files (delq nil (mapcar
17093 (lambda (x)
17094 (if (equal true-file
17095 (file-truename x))
17096 nil x))
17097 (org-agenda-files t)))))
17098 (if (not (= (length files) (length (org-agenda-files t))))
17099 (progn
17100 (org-store-new-agenda-file-list files)
17101 (org-install-agenda-files-menu)
17102 (message "Removed file: %s" afile))
17103 (message "File was not in list: %s (not removed)" afile))))
17105 (defun org-file-menu-entry (file)
17106 (vector file (list 'find-file file) t))
17108 (defun org-check-agenda-file (file)
17109 "Make sure FILE exists. If not, ask user what to do."
17110 (when (not (file-exists-p file))
17111 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17112 (abbreviate-file-name file))
17113 (let ((r (downcase (read-char-exclusive))))
17114 (cond
17115 ((equal r ?r)
17116 (org-remove-file file)
17117 (throw 'nextfile t))
17118 (t (error "Abort"))))))
17120 (defun org-get-agenda-file-buffer (file)
17121 "Get a buffer visiting FILE. If the buffer needs to be created, add
17122 it to the list of buffers which might be released later."
17123 (let ((buf (org-find-base-buffer-visiting file)))
17124 (if buf
17125 buf ; just return it
17126 ;; Make a new buffer and remember it
17127 (setq buf (find-file-noselect file))
17128 (if buf (push buf org-agenda-new-buffers))
17129 buf)))
17131 (defun org-release-buffers (blist)
17132 "Release all buffers in list, asking the user for confirmation when needed.
17133 When a buffer is unmodified, it is just killed. When modified, it is saved
17134 \(if the user agrees) and then killed."
17135 (let (buf file)
17136 (while (setq buf (pop blist))
17137 (setq file (buffer-file-name buf))
17138 (when (and (buffer-modified-p buf)
17139 file
17140 (y-or-n-p (format "Save file %s? " file)))
17141 (with-current-buffer buf (save-buffer)))
17142 (kill-buffer buf))))
17144 (defun org-agenda-prepare-buffers (files)
17145 "Create buffers for all agenda files, protect archived trees and comments."
17146 (interactive)
17147 (let ((pa '(:org-archived t))
17148 (pc '(:org-comment t))
17149 (pall '(:org-archived t :org-comment t))
17150 (inhibit-read-only t)
17151 (rea (concat ":" org-archive-tag ":"))
17152 bmp file re)
17153 (save-excursion
17154 (save-restriction
17155 (while (setq file (pop files))
17156 (catch 'nextfile
17157 (if (bufferp file)
17158 (set-buffer file)
17159 (org-check-agenda-file file)
17160 (set-buffer (org-get-agenda-file-buffer file)))
17161 (widen)
17162 (setq bmp (buffer-modified-p))
17163 (org-refresh-category-properties)
17164 (setq org-todo-keywords-for-agenda
17165 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17166 (setq org-done-keywords-for-agenda
17167 (append org-done-keywords-for-agenda org-done-keywords))
17168 (setq org-todo-keyword-alist-for-agenda
17169 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17170 (setq org-drawers-for-agenda
17171 (append org-drawers-for-agenda org-drawers))
17172 (setq org-tag-alist-for-agenda
17173 (append org-tag-alist-for-agenda org-tag-alist))
17175 (save-excursion
17176 (remove-text-properties (point-min) (point-max) pall)
17177 (when org-agenda-skip-archived-trees
17178 (goto-char (point-min))
17179 (while (re-search-forward rea nil t)
17180 (if (org-at-heading-p t)
17181 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17182 (goto-char (point-min))
17183 (setq re (format org-heading-keyword-regexp-format
17184 org-comment-string))
17185 (while (re-search-forward re nil t)
17186 (add-text-properties
17187 (match-beginning 0) (org-end-of-subtree t) pc)))
17188 (set-buffer-modified-p bmp)))))
17189 (setq org-todo-keywords-for-agenda
17190 (org-uniquify org-todo-keywords-for-agenda))
17191 (setq org-todo-keyword-alist-for-agenda
17192 (org-uniquify org-todo-keyword-alist-for-agenda)
17193 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17195 ;;;; Embedded LaTeX
17197 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17198 "Keymap for the minor `org-cdlatex-mode'.")
17200 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17201 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17202 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17203 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17204 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17206 (defvar org-cdlatex-texmathp-advice-is-done nil
17207 "Flag remembering if we have applied the advice to texmathp already.")
17209 (define-minor-mode org-cdlatex-mode
17210 "Toggle the minor `org-cdlatex-mode'.
17211 This mode supports entering LaTeX environment and math in LaTeX fragments
17212 in Org-mode.
17213 \\{org-cdlatex-mode-map}"
17214 nil " OCDL" nil
17215 (when org-cdlatex-mode
17216 (require 'cdlatex)
17217 (run-hooks 'cdlatex-mode-hook)
17218 (cdlatex-compute-tables))
17219 (unless org-cdlatex-texmathp-advice-is-done
17220 (setq org-cdlatex-texmathp-advice-is-done t)
17221 (defadvice texmathp (around org-math-always-on activate)
17222 "Always return t in org-mode buffers.
17223 This is because we want to insert math symbols without dollars even outside
17224 the LaTeX math segments. If Orgmode thinks that point is actually inside
17225 an embedded LaTeX fragment, let texmathp do its job.
17226 \\[org-cdlatex-mode-map]"
17227 (interactive)
17228 (let (p)
17229 (cond
17230 ((not (derived-mode-p 'org-mode)) ad-do-it)
17231 ((eq this-command 'cdlatex-math-symbol)
17232 (setq ad-return-value t
17233 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17235 (let ((p (org-inside-LaTeX-fragment-p)))
17236 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17237 (setq ad-return-value t
17238 texmathp-why '("Org-mode embedded math" . 0))
17239 (if p ad-do-it)))))))))
17241 (defun turn-on-org-cdlatex ()
17242 "Unconditionally turn on `org-cdlatex-mode'."
17243 (org-cdlatex-mode 1))
17245 (defun org-inside-LaTeX-fragment-p ()
17246 "Test if point is inside a LaTeX fragment.
17247 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17248 sequence appearing also before point.
17249 Even though the matchers for math are configurable, this function assumes
17250 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17251 delimiters are skipped when they have been removed by customization.
17252 The return value is nil, or a cons cell with the delimiter and the
17253 position of this delimiter.
17255 This function does a reasonably good job, but can locally be fooled by
17256 for example currency specifications. For example it will assume being in
17257 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17258 fragments that are properly closed, but during editing, we have to live
17259 with the uncertainty caused by missing closing delimiters. This function
17260 looks only before point, not after."
17261 (catch 'exit
17262 (let ((pos (point))
17263 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17264 (lim (progn
17265 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17266 (point)))
17267 dd-on str (start 0) m re)
17268 (goto-char pos)
17269 (when dodollar
17270 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17271 re (nth 1 (assoc "$" org-latex-regexps)))
17272 (while (string-match re str start)
17273 (cond
17274 ((= (match-end 0) (length str))
17275 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17276 ((= (match-end 0) (- (length str) 5))
17277 (throw 'exit nil))
17278 (t (setq start (match-end 0))))))
17279 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17280 (goto-char pos)
17281 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17282 (and (match-beginning 2) (throw 'exit nil))
17283 ;; count $$
17284 (while (re-search-backward "\\$\\$" lim t)
17285 (setq dd-on (not dd-on)))
17286 (goto-char pos)
17287 (if dd-on (cons "$$" m))))))
17289 (defun org-inside-latex-macro-p ()
17290 "Is point inside a LaTeX macro or its arguments?"
17291 (save-match-data
17292 (org-in-regexp
17293 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17295 (defun org-try-cdlatex-tab ()
17296 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17297 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17298 - inside a LaTeX fragment, or
17299 - after the first word in a line, where an abbreviation expansion could
17300 insert a LaTeX environment."
17301 (when org-cdlatex-mode
17302 (cond
17303 ;; Before any word on the line: No expansion possible.
17304 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17305 ;; Just after first word on the line: Expand it. Make sure it
17306 ;; cannot happen on headlines, though.
17307 ((save-excursion
17308 (skip-chars-backward "a-zA-Z0-9*")
17309 (skip-chars-backward " \t")
17310 (and (bolp) (not (org-at-heading-p))))
17311 (cdlatex-tab) t)
17312 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17314 (defun org-cdlatex-underscore-caret (&optional arg)
17315 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17316 Revert to the normal definition outside of these fragments."
17317 (interactive "P")
17318 (if (org-inside-LaTeX-fragment-p)
17319 (call-interactively 'cdlatex-sub-superscript)
17320 (let (org-cdlatex-mode)
17321 (call-interactively (key-binding (vector last-input-event))))))
17323 (defun org-cdlatex-math-modify (&optional arg)
17324 "Execute `cdlatex-math-modify' in LaTeX fragments.
17325 Revert to the normal definition outside of these fragments."
17326 (interactive "P")
17327 (if (org-inside-LaTeX-fragment-p)
17328 (call-interactively 'cdlatex-math-modify)
17329 (let (org-cdlatex-mode)
17330 (call-interactively (key-binding (vector last-input-event))))))
17332 (defvar org-latex-fragment-image-overlays nil
17333 "List of overlays carrying the images of latex fragments.")
17334 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17336 (defun org-remove-latex-fragment-image-overlays ()
17337 "Remove all overlays with LaTeX fragment images in current buffer."
17338 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17339 (setq org-latex-fragment-image-overlays nil))
17341 (defun org-preview-latex-fragment (&optional subtree)
17342 "Preview the LaTeX fragment at point, or all locally or globally.
17343 If the cursor is in a LaTeX fragment, create the image and overlay
17344 it over the source code. If there is no fragment at point, display
17345 all fragments in the current text, from one headline to the next. With
17346 prefix SUBTREE, display all fragments in the current subtree. With a
17347 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17348 the cursor is before the first headline,
17349 display all fragments in the buffer.
17350 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17351 (interactive "P")
17352 (unless buffer-file-name
17353 (error "Can't preview LaTeX fragment in a non-file buffer"))
17354 (org-remove-latex-fragment-image-overlays)
17355 (save-excursion
17356 (save-restriction
17357 (let (beg end at msg)
17358 (cond
17359 ((or (equal subtree '(16))
17360 (not (save-excursion
17361 (re-search-backward org-outline-regexp-bol nil t))))
17362 (setq beg (point-min) end (point-max)
17363 msg "Creating images for buffer...%s"))
17364 ((equal subtree '(4))
17365 (org-back-to-heading)
17366 (setq beg (point) end (org-end-of-subtree t)
17367 msg "Creating images for subtree...%s"))
17369 (if (setq at (org-inside-LaTeX-fragment-p))
17370 (goto-char (max (point-min) (- (cdr at) 2)))
17371 (org-back-to-heading))
17372 (setq beg (point) end (progn (outline-next-heading) (point))
17373 msg (if at "Creating image...%s"
17374 "Creating images for entry...%s"))))
17375 (message msg "")
17376 (narrow-to-region beg end)
17377 (goto-char beg)
17378 (org-format-latex
17379 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17380 (file-name-nondirectory
17381 buffer-file-name)))
17382 default-directory 'overlays msg at 'forbuffer
17383 org-latex-create-formula-image-program)
17384 (message msg "done. Use `C-c C-c' to remove images.")))))
17386 (defvar org-latex-regexps
17387 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17388 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17389 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17390 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17391 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17392 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17393 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17394 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17395 "Regular expressions for matching embedded LaTeX.")
17397 (defvar org-export-have-math nil) ;; dynamic scoping
17398 (defun org-format-latex (prefix &optional dir overlays msg at
17399 forbuffer processing-type)
17400 "Replace LaTeX fragments with links to an image, and produce images.
17401 Some of the options can be changed using the variable
17402 `org-format-latex-options'."
17403 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17404 (let* ((prefixnodir (file-name-nondirectory prefix))
17405 (absprefix (expand-file-name prefix dir))
17406 (todir (file-name-directory absprefix))
17407 (opt org-format-latex-options)
17408 (optnew org-format-latex-options)
17409 (matchers (plist-get opt :matchers))
17410 (re-list org-latex-regexps)
17411 (org-format-latex-header-extra
17412 (plist-get (org-infile-export-plist) :latex-header-extra))
17413 (cnt 0) txt hash link beg end re e checkdir
17414 string
17415 m n block-type block linkfile movefile ov)
17416 ;; Check the different regular expressions
17417 (while (setq e (pop re-list))
17418 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17419 block (if block-type "\n\n" ""))
17420 (when (member m matchers)
17421 (goto-char (point-min))
17422 (while (re-search-forward re nil t)
17423 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17424 (not (get-text-property (match-beginning n)
17425 'org-protected))
17426 (or (not overlays)
17427 (not (eq (get-char-property (match-beginning n)
17428 'org-overlay-type)
17429 'org-latex-overlay))))
17430 (setq org-export-have-math t)
17431 (cond
17432 ((eq processing-type 'verbatim)
17433 ;; Leave the text verbatim, just protect it
17434 (add-text-properties (match-beginning n) (match-end n)
17435 '(org-protected t)))
17436 ((eq processing-type 'mathjax)
17437 ;; Prepare for MathJax processing
17438 (setq string (match-string n))
17439 (if (member m '("$" "$1"))
17440 (save-excursion
17441 (delete-region (match-beginning n) (match-end n))
17442 (goto-char (match-beginning n))
17443 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17444 "\\)")
17445 '(org-protected t))))
17446 (add-text-properties (match-beginning n) (match-end n)
17447 '(org-protected t))))
17448 ((or (eq processing-type 'dvipng)
17449 (eq processing-type 'imagemagick))
17450 ;; Process to an image
17451 (setq txt (match-string n)
17452 beg (match-beginning n) end (match-end n)
17453 cnt (1+ cnt))
17454 (let ((face (face-at-point))
17455 (fg (plist-get opt :foreground))
17456 (bg (plist-get opt :background))
17457 print-length print-level) ; make sure full list is printed
17458 (when forbuffer
17459 ; Get the colors from the face at point
17460 (goto-char beg)
17461 (when (eq fg 'auto)
17462 (setq fg (face-attribute face :foreground nil 'default)))
17463 (when (eq bg 'auto)
17464 (setq bg (face-attribute face :background nil 'default)))
17465 (setq optnew (copy-sequence opt))
17466 (plist-put optnew :foreground fg)
17467 (plist-put optnew :background bg))
17468 (setq hash (sha1 (prin1-to-string
17469 (list org-format-latex-header
17470 org-format-latex-header-extra
17471 org-export-latex-default-packages-alist
17472 org-export-latex-packages-alist
17473 org-format-latex-options
17474 forbuffer txt fg bg)))
17475 linkfile (format "%s_%s.png" prefix hash)
17476 movefile (format "%s_%s.png" absprefix hash)))
17477 (setq link (concat block "[[file:" linkfile "]]" block))
17478 (if msg (message msg cnt))
17479 (goto-char beg)
17480 (unless checkdir ; make sure the directory exists
17481 (setq checkdir t)
17482 (or (file-directory-p todir) (make-directory todir t)))
17483 (org-create-formula-image
17484 txt movefile optnew forbuffer processing-type)
17485 (if overlays
17486 (progn
17487 (mapc (lambda (o)
17488 (if (eq (overlay-get o 'org-overlay-type)
17489 'org-latex-overlay)
17490 (delete-overlay o)))
17491 (overlays-in beg end))
17492 (setq ov (make-overlay beg end))
17493 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17494 (if (featurep 'xemacs)
17495 (progn
17496 (overlay-put ov 'invisible t)
17497 (overlay-put
17498 ov 'end-glyph
17499 (make-glyph (vector 'png :file movefile))))
17500 (overlay-put
17501 ov 'display
17502 (list 'image :type 'png :file movefile :ascent 'center)))
17503 (push ov org-latex-fragment-image-overlays)
17504 (goto-char end))
17505 (delete-region beg end)
17506 (insert (org-add-props link
17507 (list 'org-latex-src
17508 (replace-regexp-in-string
17509 "\"" "" txt)
17510 'org-latex-src-embed-type
17511 (if block-type 'paragraph 'character))))))
17512 ((eq processing-type 'mathml)
17513 ;; Process to MathML
17514 (unless (save-match-data (org-format-latex-mathml-available-p))
17515 (error "LaTeX to MathML converter not configured"))
17516 (setq txt (match-string n)
17517 beg (match-beginning n) end (match-end n)
17518 cnt (1+ cnt))
17519 (if msg (message msg cnt))
17520 (goto-char beg)
17521 (delete-region beg end)
17522 (insert (org-format-latex-as-mathml
17523 txt block-type prefix dir)))
17525 (error "Unknown conversion type %s for latex fragments"
17526 processing-type)))))))))
17528 (defun org-create-math-formula (latex-frag &optional mathml-file)
17529 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17530 Use `org-latex-to-mathml-convert-command'. If the conversion is
17531 sucessful, return the portion between \"<math...> </math>\"
17532 elements otherwise return nil. When MATHML-FILE is specified,
17533 write the results in to that file. When invoked as an
17534 interactive command, prompt for LATEX-FRAG, with initial value
17535 set to the current active region and echo the results for user
17536 inspection."
17537 (interactive (list (let ((frag (when (org-region-active-p)
17538 (buffer-substring-no-properties
17539 (region-beginning) (region-end)))))
17540 (read-string "LaTeX Fragment: " frag nil frag))))
17541 (unless latex-frag (error "Invalid latex-frag"))
17542 (let* ((tmp-in-file (file-relative-name
17543 (make-temp-name (expand-file-name "ltxmathml-in"))))
17544 (ignore (write-region latex-frag nil tmp-in-file))
17545 (tmp-out-file (file-relative-name
17546 (make-temp-name (expand-file-name "ltxmathml-out"))))
17547 (cmd (format-spec
17548 org-latex-to-mathml-convert-command
17549 `((?j . ,(shell-quote-argument
17550 (expand-file-name org-latex-to-mathml-jar-file)))
17551 (?I . ,(shell-quote-argument tmp-in-file))
17552 (?o . ,(shell-quote-argument tmp-out-file)))))
17553 mathml shell-command-output)
17554 (when (org-called-interactively-p 'any)
17555 (unless (org-format-latex-mathml-available-p)
17556 (error "LaTeX to MathML converter not configured")))
17557 (message "Running %s" cmd)
17558 (setq shell-command-output (shell-command-to-string cmd))
17559 (setq mathml
17560 (when (file-readable-p tmp-out-file)
17561 (with-current-buffer (find-file-noselect tmp-out-file t)
17562 (goto-char (point-min))
17563 (when (re-search-forward
17564 (concat
17565 (regexp-quote
17566 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17567 "\\(.\\|\n\\)*"
17568 (regexp-quote "</math>")) nil t)
17569 (prog1 (match-string 0) (kill-buffer))))))
17570 (cond
17571 (mathml
17572 (setq mathml
17573 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17574 (when mathml-file
17575 (write-region mathml nil mathml-file))
17576 (when (org-called-interactively-p 'any)
17577 (message mathml)))
17578 ((message "LaTeX to MathML conversion failed")
17579 (message shell-command-output)))
17580 (delete-file tmp-in-file)
17581 (when (file-exists-p tmp-out-file)
17582 (delete-file tmp-out-file))
17583 mathml))
17585 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17586 prefix &optional dir)
17587 "Use `org-create-math-formula' but check local cache first."
17588 (let* ((absprefix (expand-file-name prefix dir))
17589 (print-length nil) (print-level nil)
17590 (formula-id (concat
17591 "formula-"
17592 (sha1
17593 (prin1-to-string
17594 (list latex-frag
17595 org-latex-to-mathml-convert-command)))))
17596 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17597 (formula-cache-dir (file-name-directory formula-cache)))
17599 (unless (file-directory-p formula-cache-dir)
17600 (make-directory formula-cache-dir t))
17602 (unless (file-exists-p formula-cache)
17603 (org-create-math-formula latex-frag formula-cache))
17605 (if (file-exists-p formula-cache)
17606 ;; Successful conversion. Return the link to MathML file.
17607 (org-add-props
17608 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17609 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17610 'org-latex-src-embed-type (if latex-frag-type
17611 'paragraph 'character)))
17612 ;; Failed conversion. Return the LaTeX fragment verbatim
17613 (add-text-properties
17614 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17615 latex-frag)))
17617 (defun org-create-formula-image (string tofile options buffer &optional type)
17618 "Create an image from LaTeX source using dvipng or convert.
17619 This function calls either `org-create-formula-image-with-dvipng'
17620 or `org-create-formula-image-with-imagemagick' depending on the
17621 value of `org-latex-create-formula-image-program' or on the value
17622 of the optional TYPE variable.
17624 Note: ultimately these two function should be combined as they
17625 share a good deal of logic."
17626 (org-check-external-command
17627 "latex" "needed to convert LaTeX fragments to images")
17628 (funcall
17629 (case (or type org-latex-create-formula-image-program)
17630 ('dvipng
17631 (org-check-external-command
17632 "dvipng" "needed to convert LaTeX fragments to images")
17633 #'org-create-formula-image-with-dvipng)
17634 ('imagemagick
17635 (org-check-external-command
17636 "convert" "you need to install imagemagick")
17637 #'org-create-formula-image-with-imagemagick)
17638 (t (error
17639 "invalid value of `org-latex-create-formula-image-program'")))
17640 string tofile options buffer))
17642 ;; This function borrows from Ganesh Swami's latex2png.el
17643 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17644 "This calls dvipng."
17645 (require 'org-latex)
17646 (let* ((tmpdir (if (featurep 'xemacs)
17647 (temp-directory)
17648 temporary-file-directory))
17649 (texfilebase (make-temp-name
17650 (expand-file-name "orgtex" tmpdir)))
17651 (texfile (concat texfilebase ".tex"))
17652 (dvifile (concat texfilebase ".dvi"))
17653 (pngfile (concat texfilebase ".png"))
17654 (fnh (if (featurep 'xemacs)
17655 (font-height (face-font 'default))
17656 (face-attribute 'default :height nil)))
17657 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17658 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17659 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17660 "Black"))
17661 (bg (or (plist-get options (if buffer :background :html-background))
17662 "Transparent")))
17663 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17664 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17665 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17666 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17667 (with-temp-file texfile
17668 (insert (org-splice-latex-header
17669 org-format-latex-header
17670 org-export-latex-default-packages-alist
17671 org-export-latex-packages-alist t
17672 org-format-latex-header-extra))
17673 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17674 (require 'org-latex)
17675 (org-export-latex-fix-inputenc))
17676 (let ((dir default-directory))
17677 (condition-case nil
17678 (progn
17679 (cd tmpdir)
17680 (call-process "latex" nil nil nil texfile))
17681 (error nil))
17682 (cd dir))
17683 (if (not (file-exists-p dvifile))
17684 (progn (message "Failed to create dvi file from %s" texfile) nil)
17685 (condition-case nil
17686 (if (featurep 'xemacs)
17687 (call-process "dvipng" nil nil nil
17688 "-fg" fg "-bg" bg
17689 "-T" "tight"
17690 "-o" pngfile
17691 dvifile)
17692 (call-process "dvipng" nil nil nil
17693 "-fg" fg "-bg" bg
17694 "-D" dpi
17695 ;;"-x" scale "-y" scale
17696 "-T" "tight"
17697 "-o" pngfile
17698 dvifile))
17699 (error nil))
17700 (if (not (file-exists-p pngfile))
17701 (if org-format-latex-signal-error
17702 (error "Failed to create png file from %s" texfile)
17703 (message "Failed to create png file from %s" texfile)
17704 nil)
17705 ;; Use the requested file name and clean up
17706 (copy-file pngfile tofile 'replace)
17707 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17708 (if (file-exists-p (concat texfilebase e))
17709 (delete-file (concat texfilebase e))))
17710 pngfile))))
17712 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17713 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17714 "This calls convert, which is included into imagemagick."
17715 (require 'org-latex)
17716 (let* ((tmpdir (if (featurep 'xemacs)
17717 (temp-directory)
17718 temporary-file-directory))
17719 (texfilebase (make-temp-name
17720 (expand-file-name "orgtex" tmpdir)))
17721 (texfile (concat texfilebase ".tex"))
17722 (pdffile (concat texfilebase ".pdf"))
17723 (pngfile (concat texfilebase ".png"))
17724 (fnh (if (featurep 'xemacs)
17725 (font-height (face-font 'default))
17726 (face-attribute 'default :height nil)))
17727 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17728 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17729 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17730 "black"))
17731 (bg (or (plist-get options (if buffer :background :html-background))
17732 "white")))
17733 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17734 (setq fg (org-latex-color-format fg)))
17735 (if (eq bg 'default) (setq bg (org-latex-color :background))
17736 (setq bg (org-latex-color-format
17737 (if (string= bg "Transparent") "white" bg))))
17738 (with-temp-file texfile
17739 (insert (org-splice-latex-header
17740 org-format-latex-header
17741 org-export-latex-default-packages-alist
17742 org-export-latex-packages-alist t
17743 org-format-latex-header-extra))
17744 (insert "\n\\begin{document}\n"
17745 "\\definecolor{fg}{rgb}{" fg "}\n"
17746 "\\definecolor{bg}{rgb}{" bg "}\n"
17747 "\n\\pagecolor{bg}\n"
17748 "\n{\\color{fg}\n"
17749 string
17750 "\n}\n"
17751 "\n\\end{document}\n" )
17752 (require 'org-latex)
17753 (org-export-latex-fix-inputenc))
17754 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17755 (condition-case nil
17756 (progn
17757 (cd tmpdir)
17758 (setq cmds org-latex-to-pdf-process)
17759 (while cmds
17760 (setq latex-frags-cmds (pop cmds))
17761 (if (listp latex-frags-cmds)
17762 (setq cmds nil)
17763 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17764 (while latex-frags-cmds
17765 (setq cmd (pop latex-frags-cmds))
17766 (while (string-match "%b" cmd)
17767 (setq cmd (replace-match
17768 (save-match-data
17769 (shell-quote-argument texfile))
17770 t t cmd)))
17771 (while (string-match "%f" cmd)
17772 (setq cmd (replace-match
17773 (save-match-data
17774 (shell-quote-argument (file-name-nondirectory texfile)))
17775 t t cmd)))
17776 (while (string-match "%o" cmd)
17777 (setq cmd (replace-match
17778 (save-match-data
17779 (shell-quote-argument (file-name-directory texfile)))
17780 t t cmd)))
17781 (setq cmd (split-string cmd))
17782 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17783 (error nil))
17784 (cd dir))
17785 (if (not (file-exists-p pdffile))
17786 (progn (message "Failed to create pdf file from %s" texfile) nil)
17787 (condition-case nil
17788 (if (featurep 'xemacs)
17789 (call-process "convert" nil nil nil
17790 "-density" "96"
17791 "-trim"
17792 "-antialias"
17793 pdffile
17794 "-quality" "100"
17795 ;; "-sharpen" "0x1.0"
17796 pngfile)
17797 (call-process "convert" nil nil nil
17798 "-density" dpi
17799 "-trim"
17800 "-antialias"
17801 pdffile
17802 "-quality" "100"
17803 ; "-sharpen" "0x1.0"
17804 pngfile))
17805 (error nil))
17806 (if (not (file-exists-p pngfile))
17807 (if org-format-latex-signal-error
17808 (error "Failed to create png file from %s" texfile)
17809 (message "Failed to create png file from %s" texfile)
17810 nil)
17811 ;; Use the requested file name and clean up
17812 (copy-file pngfile tofile 'replace)
17813 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17814 (if (file-exists-p (concat texfilebase e))
17815 (delete-file (concat texfilebase e))))
17816 pngfile))))
17818 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17819 "Fill a LaTeX header template TPL.
17820 In the template, the following place holders will be recognized:
17822 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17823 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17824 [PACKAGES] \\usepackage statements for PKG
17825 [NO-PACKAGES] do not include PKG
17826 [EXTRA] the string EXTRA
17827 [NO-EXTRA] do not include EXTRA
17829 For backward compatibility, if both the positive and the negative place
17830 holder is missing, the positive one (without the \"NO-\") will be
17831 assumed to be present at the end of the template.
17832 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17833 EXTRA is a string.
17834 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17835 (let (rpl (end ""))
17836 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17837 (setq rpl (if (or (match-end 1) (not def-pkg))
17838 "" (org-latex-packages-to-string def-pkg snippets-p t))
17839 tpl (replace-match rpl t t tpl))
17840 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17842 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17843 (setq rpl (if (or (match-end 1) (not pkg))
17844 "" (org-latex-packages-to-string pkg snippets-p t))
17845 tpl (replace-match rpl t t tpl))
17846 (if pkg (setq end
17847 (concat end "\n"
17848 (org-latex-packages-to-string pkg snippets-p)))))
17850 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17851 (setq rpl (if (or (match-end 1) (not extra))
17852 "" (concat extra "\n"))
17853 tpl (replace-match rpl t t tpl))
17854 (if (and extra (string-match "\\S-" extra))
17855 (setq end (concat end "\n" extra))))
17857 (if (string-match "\\S-" end)
17858 (concat tpl "\n" end)
17859 tpl)))
17861 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17862 "Turn an alist of packages into a string with the \\usepackage macros."
17863 (setq pkg (mapconcat (lambda(p)
17864 (cond
17865 ((stringp p) p)
17866 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17867 (format "%% Package %s omitted" (cadr p)))
17868 ((equal "" (car p))
17869 (format "\\usepackage{%s}" (cadr p)))
17871 (format "\\usepackage[%s]{%s}"
17872 (car p) (cadr p)))))
17874 "\n"))
17875 (if newline (concat pkg "\n") pkg))
17877 (defun org-dvipng-color (attr)
17878 "Return a RGB color specification for dvipng."
17879 (apply 'format "rgb %s %s %s"
17880 (mapcar 'org-normalize-color
17881 (if (featurep 'xemacs)
17882 (color-rgb-components
17883 (face-property 'default
17884 (cond ((eq attr :foreground) 'foreground)
17885 ((eq attr :background) 'background))))
17886 (color-values (face-attribute 'default attr nil))))))
17888 (defun org-dvipng-color-format (color-name)
17889 "Convert COLOR-NAME to a RGB color value for dvipng."
17890 (apply 'format "rgb %s %s %s"
17891 (mapcar 'org-normalize-color
17892 (color-values color-name))))
17894 (defun org-latex-color (attr)
17895 "Return a RGB color for the LaTeX color package."
17896 (apply 'format "%s,%s,%s"
17897 (mapcar 'org-normalize-color
17898 (if (featurep 'xemacs)
17899 (color-rgb-components
17900 (face-property 'default
17901 (cond ((eq attr :foreground) 'foreground)
17902 ((eq attr :background) 'background))))
17903 (color-values (face-attribute 'default attr nil))))))
17905 (defun org-latex-color-format (color-name)
17906 "Convert COLOR-NAME to a RGB color value."
17907 (apply 'format "%s,%s,%s"
17908 (mapcar 'org-normalize-color
17909 (color-values color-name))))
17911 (defun org-normalize-color (value)
17912 "Return string to be used as color value for an RGB component."
17913 (format "%g" (/ value 65535.0)))
17915 ;; Image display
17918 (defvar org-inline-image-overlays nil)
17919 (make-variable-buffer-local 'org-inline-image-overlays)
17921 (defun org-toggle-inline-images (&optional include-linked)
17922 "Toggle the display of inline images.
17923 INCLUDE-LINKED is passed to `org-display-inline-images'."
17924 (interactive "P")
17925 (if org-inline-image-overlays
17926 (progn
17927 (org-remove-inline-images)
17928 (message "Inline image display turned off"))
17929 (org-display-inline-images include-linked)
17930 (if (and (org-called-interactively-p)
17931 org-inline-image-overlays)
17932 (message "%d images displayed inline"
17933 (length org-inline-image-overlays))
17934 (message "No images to display inline"))))
17936 (defun org-redisplay-inline-images ()
17937 "Refresh the display of inline images."
17938 (interactive)
17939 (if (not org-inline-image-overlays)
17940 (org-toggle-inline-images)
17941 (org-toggle-inline-images)
17942 (org-toggle-inline-images)))
17944 (defun org-display-inline-images (&optional include-linked refresh beg end)
17945 "Display inline images.
17946 Normally only links without a description part are inlined, because this
17947 is how it will work for export. When INCLUDE-LINKED is set, also links
17948 with a description part will be inlined. This can be nice for a quick
17949 look at those images, but it does not reflect what exported files will look
17950 like.
17951 When REFRESH is set, refresh existing images between BEG and END.
17952 This will create new image displays only if necessary.
17953 BEG and END default to the buffer boundaries."
17954 (interactive "P")
17955 (unless refresh
17956 (org-remove-inline-images)
17957 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17958 (save-excursion
17959 (save-restriction
17960 (widen)
17961 (setq beg (or beg (point-min)) end (or end (point-max)))
17962 (goto-char beg)
17963 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17964 (substring (org-image-file-name-regexp) 0 -2)
17965 "\\)\\]" (if include-linked "" "\\]")))
17966 old file ov img type attrwidth width)
17967 (while (re-search-forward re end t)
17968 (setq old (get-char-property-and-overlay (match-beginning 1)
17969 'org-image-overlay)
17970 file (expand-file-name
17971 (concat (or (match-string 3) "") (match-string 4))))
17972 (when (image-type-available-p 'imagemagick)
17973 (setq attrwidth (if (or (listp org-image-actual-width)
17974 (null org-image-actual-width))
17975 (save-excursion
17976 (save-match-data
17977 (when (re-search-backward
17978 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
17979 (save-excursion
17980 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
17981 (string-to-number (match-string 1))))))
17982 width (cond ((eq org-image-actual-width t) nil)
17983 ((null org-image-actual-width) attrwidth)
17984 ((numberp org-image-actual-width)
17985 org-image-actual-width)
17986 ((listp org-image-actual-width)
17987 (or attrwidth (car org-image-actual-width))))
17988 type (if width 'imagemagick)))
17989 (when (file-exists-p file)
17990 (if (and (car-safe old) refresh)
17991 (image-refresh (overlay-get (cdr old) 'display))
17992 (setq img (save-match-data (create-image file type nil :width width)))
17993 (when img
17994 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17995 (overlay-put ov 'display img)
17996 (overlay-put ov 'face 'default)
17997 (overlay-put ov 'org-image-overlay t)
17998 (overlay-put ov 'modification-hooks
17999 (list 'org-display-inline-remove-overlay))
18000 (push ov org-inline-image-overlays)))))))))
18002 (define-obsolete-function-alias
18003 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18005 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18006 "Remove inline-display overlay if a corresponding region is modified."
18007 (let ((inhibit-modification-hooks t))
18008 (when (and ov after)
18009 (delete ov org-inline-image-overlays)
18010 (delete-overlay ov))))
18012 (defun org-remove-inline-images ()
18013 "Remove inline display of images."
18014 (interactive)
18015 (mapc 'delete-overlay org-inline-image-overlays)
18016 (setq org-inline-image-overlays nil))
18018 ;;;; Key bindings
18020 ;; Outline functions from `outline-mode-prefix-map'
18021 ;; that can be remapped in Org:
18022 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18023 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18024 (define-key org-mode-map [remap outline-forward-same-level]
18025 'org-forward-heading-same-level)
18026 (define-key org-mode-map [remap outline-backward-same-level]
18027 'org-backward-heading-same-level)
18028 (define-key org-mode-map [remap show-branches]
18029 'org-kill-note-or-show-branches)
18030 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18031 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18032 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18034 ;; Outline functions from `outline-mode-prefix-map' that can not
18035 ;; be remapped in Org:
18037 ;; - the column "key binding" shows whether the Outline function is still
18038 ;; available in Org mode on the same key that it has been bound to in
18039 ;; Outline mode:
18040 ;; - "overridden": key used for a different functionality in Org mode
18041 ;; - else: key still bound to the same Outline function in Org mode
18043 ;; | Outline function | key binding | Org replacement |
18044 ;; |------------------------------------+-------------+-----------------------|
18045 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18046 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18047 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18048 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18049 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18050 ;; | `show-entry' | overridden | no replacement |
18051 ;; | `show-children' | `C-c C-i' | visibility cycling |
18052 ;; | `show-branches' | `C-c C-k' | still same function |
18053 ;; | `show-subtree' | overridden | visibility cycling |
18054 ;; | `show-all' | overridden | no replacement |
18055 ;; | `hide-subtree' | overridden | visibility cycling |
18056 ;; | `hide-body' | overridden | no replacement |
18057 ;; | `hide-entry' | overridden | visibility cycling |
18058 ;; | `hide-leaves' | overridden | no replacement |
18059 ;; | `hide-sublevels' | overridden | no replacement |
18060 ;; | `hide-other' | overridden | no replacement |
18062 ;; Make `C-c C-x' a prefix key
18063 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18065 ;; TAB key with modifiers
18066 (org-defkey org-mode-map "\C-i" 'org-cycle)
18067 (org-defkey org-mode-map [(tab)] 'org-cycle)
18068 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18069 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18070 ;; The following line is necessary under Suse GNU/Linux
18071 (unless (featurep 'xemacs)
18072 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18073 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18074 (define-key org-mode-map [backtab] 'org-shifttab)
18076 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18077 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18078 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18080 ;; Cursor keys with modifiers
18081 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18082 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18083 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18084 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18086 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18087 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18088 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18089 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18091 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18092 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18093 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18094 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18096 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18097 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18098 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18099 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18101 ;; Babel keys
18102 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18103 (mapc (lambda (pair)
18104 (define-key org-babel-map (car pair) (cdr pair)))
18105 org-babel-key-bindings)
18107 ;;; Extra keys for tty access.
18108 ;; We only set them when really needed because otherwise the
18109 ;; menus don't show the simple keys
18111 (when (or org-use-extra-keys
18112 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18113 (not window-system))
18114 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18115 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18116 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18117 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18118 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18119 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18120 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18121 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18122 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18123 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18124 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18125 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18126 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18127 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18128 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18129 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18130 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18131 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18132 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18133 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18134 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18135 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18136 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18137 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18138 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18139 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18140 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18141 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18143 ;; All the other keys
18145 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18146 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18147 (if (boundp 'narrow-map)
18148 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18149 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18150 (if (boundp 'narrow-map)
18151 (org-defkey narrow-map "b" 'org-narrow-to-block)
18152 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18153 (if (boundp 'narrow-map)
18154 (org-defkey narrow-map "e" 'org-narrow-to-element)
18155 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18156 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18157 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18158 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18159 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18160 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18161 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18162 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18163 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18164 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18165 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18166 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18167 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18168 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18169 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18170 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18171 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18172 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18173 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18174 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18175 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18176 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18177 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18178 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18179 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18180 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18181 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18182 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18183 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18184 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18185 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18186 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18187 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18188 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18189 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18190 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18191 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18192 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18193 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18194 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18195 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18196 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18197 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18198 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18199 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18200 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18201 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18202 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18203 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18204 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18205 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18206 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18207 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18208 (org-defkey org-mode-map "\C-c^" 'org-sort)
18209 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18210 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18211 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18212 (org-defkey org-mode-map "\C-m" 'org-return)
18213 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18214 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18215 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18216 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18217 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18218 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18219 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18220 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18221 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18222 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18223 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18224 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18225 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18226 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18227 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18228 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18229 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18230 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18231 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18232 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18233 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18234 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18235 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18237 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18238 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18239 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18241 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18242 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18243 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18244 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18245 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18246 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18247 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18248 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18249 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18250 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18251 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18252 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18253 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18254 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18255 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18256 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18257 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18258 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18259 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18260 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18261 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18262 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18264 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18265 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18266 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18267 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18268 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18270 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18272 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18274 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18275 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18277 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18280 (when (featurep 'xemacs)
18281 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18284 (defconst org-speed-commands-default
18286 ("Outline Navigation")
18287 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18288 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18289 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18290 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18291 ("u" . (org-speed-move-safe 'outline-up-heading))
18292 ("j" . org-goto)
18293 ("g" . (org-refile t))
18294 ("Outline Visibility")
18295 ("c" . org-cycle)
18296 ("C" . org-shifttab)
18297 (" " . org-display-outline-path)
18298 (":" . org-columns)
18299 ("Outline Structure Editing")
18300 ("U" . org-shiftmetaup)
18301 ("D" . org-shiftmetadown)
18302 ("r" . org-metaright)
18303 ("l" . org-metaleft)
18304 ("R" . org-shiftmetaright)
18305 ("L" . org-shiftmetaleft)
18306 ("i" . (progn (forward-char 1) (call-interactively
18307 'org-insert-heading-respect-content)))
18308 ("^" . org-sort)
18309 ("w" . org-refile)
18310 ("a" . org-archive-subtree-default-with-confirmation)
18311 ("." . org-mark-subtree)
18312 ("#" . org-toggle-comment)
18313 ("Clock Commands")
18314 ("I" . org-clock-in)
18315 ("O" . org-clock-out)
18316 ("Meta Data Editing")
18317 ("t" . org-todo)
18318 ("," . (org-priority))
18319 ("0" . (org-priority ?\ ))
18320 ("1" . (org-priority ?A))
18321 ("2" . (org-priority ?B))
18322 ("3" . (org-priority ?C))
18323 (";" . org-set-tags-command)
18324 ("e" . org-set-effort)
18325 ("E" . org-inc-effort)
18326 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18327 (org-entry-put (point) "APPT_WARNTIME" m)))
18328 ("Agenda Views etc")
18329 ("v" . org-agenda)
18330 ("/" . org-sparse-tree)
18331 ("Misc")
18332 ("o" . org-open-at-point)
18333 ("?" . org-speed-command-help)
18334 ("<" . (org-agenda-set-restriction-lock 'subtree))
18335 (">" . (org-agenda-remove-restriction-lock))
18337 "The default speed commands.")
18339 (defun org-print-speed-command (e)
18340 (if (> (length (car e)) 1)
18341 (progn
18342 (princ "\n")
18343 (princ (car e))
18344 (princ "\n")
18345 (princ (make-string (length (car e)) ?-))
18346 (princ "\n"))
18347 (princ (car e))
18348 (princ " ")
18349 (if (symbolp (cdr e))
18350 (princ (symbol-name (cdr e)))
18351 (prin1 (cdr e)))
18352 (princ "\n")))
18354 (defun org-speed-command-help ()
18355 "Show the available speed commands."
18356 (interactive)
18357 (if (not org-use-speed-commands)
18358 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18359 (with-output-to-temp-buffer "*Help*"
18360 (princ "User-defined Speed commands\n===========================\n")
18361 (mapc 'org-print-speed-command org-speed-commands-user)
18362 (princ "\n")
18363 (princ "Built-in Speed commands\n=======================\n")
18364 (mapc 'org-print-speed-command org-speed-commands-default))
18365 (with-current-buffer "*Help*"
18366 (setq truncate-lines t))))
18368 (defun org-speed-move-safe (cmd)
18369 "Execute CMD, but make sure that the cursor always ends up in a headline.
18370 If not, return to the original position and throw an error."
18371 (interactive)
18372 (let ((pos (point)))
18373 (call-interactively cmd)
18374 (unless (and (bolp) (org-at-heading-p))
18375 (goto-char pos)
18376 (error "Boundary reached while executing %s" cmd))))
18378 (defvar org-self-insert-command-undo-counter 0)
18380 (defvar org-table-auto-blank-field) ; defined in org-table.el
18381 (defvar org-speed-command nil)
18383 (define-obsolete-function-alias
18384 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18386 (defun org-speed-command-activate (keys)
18387 "Hook for activating single-letter speed commands.
18388 `org-speed-commands-default' specifies a minimal command set.
18389 Use `org-speed-commands-user' for further customization."
18390 (when (or (and (bolp) (looking-at org-outline-regexp))
18391 (and (functionp org-use-speed-commands)
18392 (funcall org-use-speed-commands)))
18393 (cdr (assoc keys (append org-speed-commands-user
18394 org-speed-commands-default)))))
18396 (define-obsolete-function-alias
18397 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18399 (defun org-babel-speed-command-activate (keys)
18400 "Hook for activating single-letter code block commands."
18401 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18402 (cdr (assoc keys org-babel-key-bindings))))
18404 (defcustom org-speed-command-hook
18405 '(org-speed-command-default-hook org-babel-speed-command-hook)
18406 "Hook for activating speed commands at strategic locations.
18407 Hook functions are called in sequence until a valid handler is
18408 found.
18410 Each hook takes a single argument, a user-pressed command key
18411 which is also a `self-insert-command' from the global map.
18413 Within the hook, examine the cursor position and the command key
18414 and return nil or a valid handler as appropriate. Handler could
18415 be one of an interactive command, a function, or a form.
18417 Set `org-use-speed-commands' to non-nil value to enable this
18418 hook. The default setting is `org-speed-command-activate'."
18419 :group 'org-structure
18420 :version "24.1"
18421 :type 'hook)
18423 (defun org-self-insert-command (N)
18424 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18425 If the cursor is in a table looking at whitespace, the whitespace is
18426 overwritten, and the table is not marked as requiring realignment."
18427 (interactive "p")
18428 (org-check-before-invisible-edit 'insert)
18429 (cond
18430 ((and org-use-speed-commands
18431 (setq org-speed-command
18432 (run-hook-with-args-until-success
18433 'org-speed-command-hook (this-command-keys))))
18434 (cond
18435 ((commandp org-speed-command)
18436 (setq this-command org-speed-command)
18437 (call-interactively org-speed-command))
18438 ((functionp org-speed-command)
18439 (funcall org-speed-command))
18440 ((and org-speed-command (listp org-speed-command))
18441 (eval org-speed-command))
18442 (t (let (org-use-speed-commands)
18443 (call-interactively 'org-self-insert-command)))))
18444 ((and
18445 (org-table-p)
18446 (progn
18447 ;; check if we blank the field, and if that triggers align
18448 (and (featurep 'org-table) org-table-auto-blank-field
18449 (member last-command
18450 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18451 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18452 ;; got extra space, this field does not determine column width
18453 (let (org-table-may-need-update) (org-table-blank-field))
18454 ;; no extra space, this field may determine column width
18455 (org-table-blank-field)))
18457 (eq N 1)
18458 (looking-at "[^|\n]* |"))
18459 (let (org-table-may-need-update)
18460 (goto-char (1- (match-end 0)))
18461 (backward-delete-char 1)
18462 (goto-char (match-beginning 0))
18463 (self-insert-command N)))
18465 (setq org-table-may-need-update t)
18466 (self-insert-command N)
18467 (org-fix-tags-on-the-fly)
18468 (if org-self-insert-cluster-for-undo
18469 (if (not (eq last-command 'org-self-insert-command))
18470 (setq org-self-insert-command-undo-counter 1)
18471 (if (>= org-self-insert-command-undo-counter 20)
18472 (setq org-self-insert-command-undo-counter 1)
18473 (and (> org-self-insert-command-undo-counter 0)
18474 buffer-undo-list (listp buffer-undo-list)
18475 (not (cadr buffer-undo-list)) ; remove nil entry
18476 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18477 (setq org-self-insert-command-undo-counter
18478 (1+ org-self-insert-command-undo-counter))))))))
18480 (defun org-check-before-invisible-edit (kind)
18481 "Check is editing if kind KIND would be dangerous with invisible text around.
18482 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18483 ;; First, try to get out of here as quickly as possible, to reduce overhead
18484 (if (and org-catch-invisible-edits
18485 (or (not (boundp 'visible-mode)) (not visible-mode))
18486 (or (get-char-property (point) 'invisible)
18487 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18488 ;; OK, we need to take a closer look
18489 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18490 (invisible-before-point (if (bobp) nil (get-char-property
18491 (1- (point)) 'invisible)))
18492 (border-and-ok-direction
18494 ;; Check if we are acting predictably before invisible text
18495 (and invisible-at-point (not invisible-before-point)
18496 (memq kind '(insert delete-backward)))
18497 ;; Check if we are acting predictably after invisible text
18498 ;; This works not well, and I have turned it off. It seems
18499 ;; better to always show and stop after invisible text.
18500 ;; (and (not invisible-at-point) invisible-before-point
18501 ;; (memq kind '(insert delete)))
18503 (when (or (memq invisible-at-point '(outline org-hide-block t))
18504 (memq invisible-before-point '(outline org-hide-block t)))
18505 (if (eq org-catch-invisible-edits 'error)
18506 (error "Editing in invisible areas is prohibited - make visible first"))
18507 (if (and org-custom-properties-overlays
18508 (y-or-n-p "Display invisible properties in this buffer? "))
18509 (org-toggle-custom-properties-visibility)
18510 ;; Make the area visible
18511 (save-excursion
18512 (if invisible-before-point
18513 (goto-char (previous-single-char-property-change
18514 (point) 'invisible)))
18515 (org-cycle))
18516 (cond
18517 ((eq org-catch-invisible-edits 'show)
18518 ;; That's it, we do the edit after showing
18519 (message
18520 "Unfolding invisible region around point before editing")
18521 (sit-for 1))
18522 ((and (eq org-catch-invisible-edits 'smart)
18523 border-and-ok-direction)
18524 (message "Unfolding invisible region around point before editing"))
18526 ;; Don't do the edit, make the user repeat it in full visibility
18527 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18529 (defun org-fix-tags-on-the-fly ()
18530 (when (and (equal (char-after (point-at-bol)) ?*)
18531 (org-at-heading-p))
18532 (org-align-tags-here org-tags-column)))
18534 (defun org-delete-backward-char (N)
18535 "Like `delete-backward-char', insert whitespace at field end in tables.
18536 When deleting backwards, in tables this function will insert whitespace in
18537 front of the next \"|\" separator, to keep the table aligned. The table will
18538 still be marked for re-alignment if the field did fill the entire column,
18539 because, in this case the deletion might narrow the column."
18540 (interactive "p")
18541 (org-check-before-invisible-edit 'delete-backward)
18542 (if (and (org-table-p)
18543 (eq N 1)
18544 (string-match "|" (buffer-substring (point-at-bol) (point)))
18545 (looking-at ".*?|"))
18546 (let ((pos (point))
18547 (noalign (looking-at "[^|\n\r]* |"))
18548 (c org-table-may-need-update))
18549 (backward-delete-char N)
18550 (if (not overwrite-mode)
18551 (progn
18552 (skip-chars-forward "^|")
18553 (insert " ")
18554 (goto-char (1- pos))))
18555 ;; noalign: if there were two spaces at the end, this field
18556 ;; does not determine the width of the column.
18557 (if noalign (setq org-table-may-need-update c)))
18558 (backward-delete-char N)
18559 (org-fix-tags-on-the-fly)))
18561 (defun org-delete-char (N)
18562 "Like `delete-char', but insert whitespace at field end in tables.
18563 When deleting characters, 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)
18569 (if (and (org-table-p)
18570 (not (bolp))
18571 (not (= (char-after) ?|))
18572 (eq N 1))
18573 (if (looking-at ".*?|")
18574 (let ((pos (point))
18575 (noalign (looking-at "[^|\n\r]* |"))
18576 (c org-table-may-need-update))
18577 (replace-match (concat
18578 (substring (match-string 0) 1 -1)
18579 " |"))
18580 (goto-char pos)
18581 ;; noalign: if there were two spaces at the end, this field
18582 ;; does not determine the width of the column.
18583 (if noalign (setq org-table-may-need-update c)))
18584 (delete-char N))
18585 (delete-char N)
18586 (org-fix-tags-on-the-fly)))
18588 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18589 (put 'org-self-insert-command 'delete-selection t)
18590 (put 'orgtbl-self-insert-command 'delete-selection t)
18591 (put 'org-delete-char 'delete-selection 'supersede)
18592 (put 'org-delete-backward-char 'delete-selection 'supersede)
18593 (put 'org-yank 'delete-selection 'yank)
18595 ;; Make `flyspell-mode' delay after some commands
18596 (put 'org-self-insert-command 'flyspell-delayed t)
18597 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18598 (put 'org-delete-char 'flyspell-delayed t)
18599 (put 'org-delete-backward-char 'flyspell-delayed t)
18601 ;; Make pabbrev-mode expand after org-mode commands
18602 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18603 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18605 ;; How to do this: Measure non-white length of current string
18606 ;; If equal to column width, we should realign.
18608 (defun org-remap (map &rest commands)
18609 "In MAP, remap the functions given in COMMANDS.
18610 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18611 (let (new old)
18612 (while commands
18613 (setq old (pop commands) new (pop commands))
18614 (if (fboundp 'command-remapping)
18615 (org-defkey map (vector 'remap old) new)
18616 (substitute-key-definition old new map global-map)))))
18618 (when (eq org-enable-table-editor 'optimized)
18619 ;; If the user wants maximum table support, we need to hijack
18620 ;; some standard editing functions
18621 (org-remap org-mode-map
18622 'self-insert-command 'org-self-insert-command
18623 'delete-char 'org-delete-char
18624 'delete-backward-char 'org-delete-backward-char)
18625 (org-defkey org-mode-map "|" 'org-force-self-insert))
18627 (defvar org-ctrl-c-ctrl-c-hook nil
18628 "Hook for functions attaching themselves to `C-c C-c'.
18630 This can be used to add additional functionality to the C-c C-c
18631 key which executes context-dependent commands. This hook is run
18632 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18633 run after the last test.
18635 Each function will be called with no arguments. The function
18636 must check if the context is appropriate for it to act. If yes,
18637 it should do its thing and then return a non-nil value. If the
18638 context is wrong, just do nothing and return nil.")
18640 (defvar org-ctrl-c-ctrl-c-final-hook nil
18641 "Hook for functions attaching themselves to `C-c C-c'.
18643 This can be used to add additional functionality to the C-c C-c
18644 key which executes context-dependent commands. This hook is run
18645 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18646 before the first test.
18648 Each function will be called with no arguments. The function
18649 must check if the context is appropriate for it to act. If yes,
18650 it should do its thing and then return a non-nil value. If the
18651 context is wrong, just do nothing and return nil.")
18653 (defvar org-tab-first-hook nil
18654 "Hook for functions to attach themselves to TAB.
18655 See `org-ctrl-c-ctrl-c-hook' for more information.
18656 This hook runs as the first action when TAB is pressed, even before
18657 `org-cycle' messes around with the `outline-regexp' to cater for
18658 inline tasks and plain list item folding.
18659 If any function in this hook returns t, any other actions that
18660 would have been caused by TAB (such as table field motion or visibility
18661 cycling) will not occur.")
18663 (defvar org-tab-after-check-for-table-hook nil
18664 "Hook for functions to attach themselves to TAB.
18665 See `org-ctrl-c-ctrl-c-hook' for more information.
18666 This hook runs after it has been established that the cursor is not in a
18667 table, but before checking if the cursor is in a headline or if global cycling
18668 should be done.
18669 If any function in this hook returns t, not other actions like visibility
18670 cycling will be done.")
18672 (defvar org-tab-after-check-for-cycling-hook nil
18673 "Hook for functions to attach themselves to TAB.
18674 See `org-ctrl-c-ctrl-c-hook' for more information.
18675 This hook runs after it has been established that not table field motion and
18676 not visibility should be done because of current context. This is probably
18677 the place where a package like yasnippets can hook in.")
18679 (defvar org-tab-before-tab-emulation-hook nil
18680 "Hook for functions to attach themselves to TAB.
18681 See `org-ctrl-c-ctrl-c-hook' for more information.
18682 This hook runs after every other options for TAB have been exhausted, but
18683 before indentation and \t insertion takes place.")
18685 (defvar org-metaleft-hook nil
18686 "Hook for functions attaching themselves to `M-left'.
18687 See `org-ctrl-c-ctrl-c-hook' for more information.")
18688 (defvar org-metaright-hook nil
18689 "Hook for functions attaching themselves to `M-right'.
18690 See `org-ctrl-c-ctrl-c-hook' for more information.")
18691 (defvar org-metaup-hook nil
18692 "Hook for functions attaching themselves to `M-up'.
18693 See `org-ctrl-c-ctrl-c-hook' for more information.")
18694 (defvar org-metadown-hook nil
18695 "Hook for functions attaching themselves to `M-down'.
18696 See `org-ctrl-c-ctrl-c-hook' for more information.")
18697 (defvar org-shiftmetaleft-hook nil
18698 "Hook for functions attaching themselves to `M-S-left'.
18699 See `org-ctrl-c-ctrl-c-hook' for more information.")
18700 (defvar org-shiftmetaright-hook nil
18701 "Hook for functions attaching themselves to `M-S-right'.
18702 See `org-ctrl-c-ctrl-c-hook' for more information.")
18703 (defvar org-shiftmetaup-hook nil
18704 "Hook for functions attaching themselves to `M-S-up'.
18705 See `org-ctrl-c-ctrl-c-hook' for more information.")
18706 (defvar org-shiftmetadown-hook nil
18707 "Hook for functions attaching themselves to `M-S-down'.
18708 See `org-ctrl-c-ctrl-c-hook' for more information.")
18709 (defvar org-metareturn-hook nil
18710 "Hook for functions attaching themselves to `M-RET'.
18711 See `org-ctrl-c-ctrl-c-hook' for more information.")
18712 (defvar org-shiftup-hook nil
18713 "Hook for functions attaching themselves to `S-up'.
18714 See `org-ctrl-c-ctrl-c-hook' for more information.")
18715 (defvar org-shiftup-final-hook nil
18716 "Hook for functions attaching themselves to `S-up'.
18717 This one runs after all other options except shift-select have been excluded.
18718 See `org-ctrl-c-ctrl-c-hook' for more information.")
18719 (defvar org-shiftdown-hook nil
18720 "Hook for functions attaching themselves to `S-down'.
18721 See `org-ctrl-c-ctrl-c-hook' for more information.")
18722 (defvar org-shiftdown-final-hook nil
18723 "Hook for functions attaching themselves to `S-down'.
18724 This one runs after all other options except shift-select have been excluded.
18725 See `org-ctrl-c-ctrl-c-hook' for more information.")
18726 (defvar org-shiftleft-hook nil
18727 "Hook for functions attaching themselves to `S-left'.
18728 See `org-ctrl-c-ctrl-c-hook' for more information.")
18729 (defvar org-shiftleft-final-hook nil
18730 "Hook for functions attaching themselves to `S-left'.
18731 This one runs after all other options except shift-select have been excluded.
18732 See `org-ctrl-c-ctrl-c-hook' for more information.")
18733 (defvar org-shiftright-hook nil
18734 "Hook for functions attaching themselves to `S-right'.
18735 See `org-ctrl-c-ctrl-c-hook' for more information.")
18736 (defvar org-shiftright-final-hook nil
18737 "Hook for functions attaching themselves to `S-right'.
18738 This one runs after all other options except shift-select have been excluded.
18739 See `org-ctrl-c-ctrl-c-hook' for more information.")
18741 (defun org-modifier-cursor-error ()
18742 "Throw an error, a modified cursor command was applied in wrong context."
18743 (error "This command is active in special context like tables, headlines or items"))
18745 (defun org-shiftselect-error ()
18746 "Throw an error because Shift-Cursor command was applied in wrong context."
18747 (if (and (boundp 'shift-select-mode) shift-select-mode)
18748 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18749 (error "This command works only in special context like headlines or timestamps")))
18751 (defun org-call-for-shift-select (cmd)
18752 (let ((this-command-keys-shift-translated t))
18753 (call-interactively cmd)))
18755 (defun org-shifttab (&optional arg)
18756 "Global visibility cycling or move to previous table field.
18757 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18758 on context.
18759 See the individual commands for more information."
18760 (interactive "P")
18761 (cond
18762 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18763 ((integerp arg)
18764 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18765 (message "Content view to level: %d" arg)
18766 (org-content (prefix-numeric-value arg2))
18767 (setq org-cycle-global-status 'overview)))
18768 (t (call-interactively 'org-global-cycle))))
18770 (defun org-shiftmetaleft ()
18771 "Promote subtree or delete table column.
18772 Calls `org-promote-subtree', `org-outdent-item-tree', or
18773 `org-table-delete-column', depending on context. See the
18774 individual commands for more information."
18775 (interactive)
18776 (cond
18777 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18778 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18779 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18780 ((if (not (org-region-active-p)) (org-at-item-p)
18781 (save-excursion (goto-char (region-beginning))
18782 (org-at-item-p)))
18783 (call-interactively 'org-outdent-item-tree))
18784 (t (org-modifier-cursor-error))))
18786 (defun org-shiftmetaright ()
18787 "Demote subtree or insert table column.
18788 Calls `org-demote-subtree', `org-indent-item-tree', or
18789 `org-table-insert-column', depending on context. See the
18790 individual commands for more information."
18791 (interactive)
18792 (cond
18793 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18794 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18795 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18796 ((if (not (org-region-active-p)) (org-at-item-p)
18797 (save-excursion (goto-char (region-beginning))
18798 (org-at-item-p)))
18799 (call-interactively 'org-indent-item-tree))
18800 (t (org-modifier-cursor-error))))
18802 (defun org-shiftmetaup (&optional arg)
18803 "Move subtree up or kill table row.
18804 Calls `org-move-subtree-up' or `org-table-kill-row' or
18805 `org-move-item-up' or `org-timestamp-up', depending on context.
18806 See the individual commands for more information."
18807 (interactive "P")
18808 (cond
18809 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18810 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18811 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18812 ((org-at-item-p) (call-interactively 'org-move-item-up))
18813 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18814 (call-interactively 'org-timestamp-up)))
18815 (t (org-modifier-cursor-error))))
18817 (defun org-shiftmetadown (&optional arg)
18818 "Move subtree down or insert table row.
18819 Calls `org-move-subtree-down' or `org-table-insert-row' or
18820 `org-move-item-down' or `org-timestamp-up', depending on context.
18821 See the individual commands for more information."
18822 (interactive "P")
18823 (cond
18824 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18825 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18826 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18827 ((org-at-item-p) (call-interactively 'org-move-item-down))
18828 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18829 (call-interactively 'org-timestamp-down)))
18830 (t (org-modifier-cursor-error))))
18832 (defsubst org-hidden-tree-error ()
18833 (error
18834 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18836 (defun org-metaleft (&optional arg)
18837 "Promote heading or move table column to left.
18838 Calls `org-do-promote' or `org-table-move-column', depending on context.
18839 With no specific context, calls the Emacs default `backward-word'.
18840 See the individual commands for more information."
18841 (interactive "P")
18842 (cond
18843 ((run-hook-with-args-until-success 'org-metaleft-hook))
18844 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18845 ((org-with-limited-levels
18846 (or (org-at-heading-p)
18847 (and (org-region-active-p)
18848 (save-excursion
18849 (goto-char (region-beginning))
18850 (org-at-heading-p)))))
18851 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18852 (call-interactively 'org-do-promote))
18853 ;; At an inline task.
18854 ((org-at-heading-p)
18855 (call-interactively 'org-inlinetask-promote))
18856 ((or (org-at-item-p)
18857 (and (org-region-active-p)
18858 (save-excursion
18859 (goto-char (region-beginning))
18860 (org-at-item-p))))
18861 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18862 (call-interactively 'org-outdent-item))
18863 (t (call-interactively 'backward-word))))
18865 (defun org-metaright (&optional arg)
18866 "Demote a subtree, a list item or move table column to right.
18867 In front of a drawer or a block keyword, indent it correctly.
18868 With no specific context, calls the Emacs default `forward-word'.
18869 See the individual commands for more information."
18870 (interactive "P")
18871 (cond
18872 ((run-hook-with-args-until-success 'org-metaright-hook))
18873 ((org-at-table-p) (call-interactively 'org-table-move-column))
18874 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18875 ((org-at-block-p) (call-interactively 'org-indent-block))
18876 ((org-with-limited-levels
18877 (or (org-at-heading-p)
18878 (and (org-region-active-p)
18879 (save-excursion
18880 (goto-char (region-beginning))
18881 (org-at-heading-p)))))
18882 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18883 (call-interactively 'org-do-demote))
18884 ;; At an inline task.
18885 ((org-at-heading-p)
18886 (call-interactively 'org-inlinetask-demote))
18887 ((or (org-at-item-p)
18888 (and (org-region-active-p)
18889 (save-excursion
18890 (goto-char (region-beginning))
18891 (org-at-item-p))))
18892 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18893 (call-interactively 'org-indent-item))
18894 (t (call-interactively 'forward-word))))
18896 (defun org-check-for-hidden (what)
18897 "Check if there are hidden headlines/items in the current visual line.
18898 WHAT can be either `headlines' or `items'. If the current line is
18899 an outline or item heading and it has a folded subtree below it,
18900 this function returns t, nil otherwise."
18901 (let ((re (cond
18902 ((eq what 'headlines) org-outline-regexp-bol)
18903 ((eq what 'items) (org-item-beginning-re))
18904 (t (error "This should not happen"))))
18905 beg end)
18906 (save-excursion
18907 (catch 'exit
18908 (unless (org-region-active-p)
18909 (setq beg (point-at-bol))
18910 (beginning-of-line 2)
18911 (while (and (not (eobp)) ;; this is like `next-line'
18912 (get-char-property (1- (point)) 'invisible))
18913 (beginning-of-line 2))
18914 (setq end (point))
18915 (goto-char beg)
18916 (goto-char (point-at-eol))
18917 (setq end (max end (point)))
18918 (while (re-search-forward re end t)
18919 (if (get-char-property (match-beginning 0) 'invisible)
18920 (throw 'exit t))))
18921 nil))))
18923 (autoload 'org-element-at-point "org-element")
18925 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18926 (declare-function org-element-type "org-element" (element))
18927 (declare-function org-element-context "org-element" ())
18928 (declare-function org-element-contents "org-element" (element))
18929 (declare-function org-element-property "org-element" (property element))
18930 (declare-function org-element-paragraph-parser "org-element" (limit))
18931 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18932 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18933 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18934 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18935 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18937 (defun org-metaup (&optional arg)
18938 "Move subtree up or move table row up.
18939 Calls `org-move-subtree-up' or `org-table-move-row' or
18940 `org-move-item-up', depending on context. See the individual commands
18941 for more information."
18942 (interactive "P")
18943 (cond
18944 ((run-hook-with-args-until-success 'org-metaup-hook))
18945 ((org-region-active-p)
18946 (let* ((a (min (region-beginning) (region-end)))
18947 (b (1- (max (region-beginning) (region-end))))
18948 (c (save-excursion (goto-char a)
18949 (move-beginning-of-line 0)))
18950 (d (save-excursion (goto-char a)
18951 (move-end-of-line 0) (point))))
18952 (transpose-regions a b c d)
18953 (goto-char c)))
18954 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18955 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18956 ((org-at-item-p) (call-interactively 'org-move-item-up))
18957 (t (org-drag-element-backward))))
18959 (defun org-metadown (&optional arg)
18960 "Move subtree down or move table row down.
18961 Calls `org-move-subtree-down' or `org-table-move-row' or
18962 `org-move-item-down', depending on context. See the individual
18963 commands for more information."
18964 (interactive "P")
18965 (cond
18966 ((run-hook-with-args-until-success 'org-metadown-hook))
18967 ((org-region-active-p)
18968 (let* ((a (min (region-beginning) (region-end)))
18969 (b (max (region-beginning) (region-end)))
18970 (c (save-excursion (goto-char b)
18971 (move-beginning-of-line 1)))
18972 (d (save-excursion (goto-char b)
18973 (move-end-of-line 1) (1+ (point)))))
18974 (transpose-regions a b c d)
18975 (goto-char d)))
18976 ((org-at-table-p) (call-interactively 'org-table-move-row))
18977 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18978 ((org-at-item-p) (call-interactively 'org-move-item-down))
18979 (t (org-drag-element-forward))))
18981 (defun org-shiftup (&optional arg)
18982 "Increase item in timestamp or increase priority of current headline.
18983 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18984 depending on context. See the individual commands for more information."
18985 (interactive "P")
18986 (cond
18987 ((run-hook-with-args-until-success 'org-shiftup-hook))
18988 ((and org-support-shift-select (org-region-active-p))
18989 (org-call-for-shift-select 'previous-line))
18990 ((org-at-timestamp-p t)
18991 (call-interactively (if org-edit-timestamp-down-means-later
18992 'org-timestamp-down 'org-timestamp-up)))
18993 ((and (not (eq org-support-shift-select 'always))
18994 org-enable-priority-commands
18995 (org-at-heading-p))
18996 (call-interactively 'org-priority-up))
18997 ((and (not org-support-shift-select) (org-at-item-p))
18998 (call-interactively 'org-previous-item))
18999 ((org-clocktable-try-shift 'up arg))
19000 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19001 (org-support-shift-select
19002 (org-call-for-shift-select 'previous-line))
19003 (t (org-shiftselect-error))))
19005 (defun org-shiftdown (&optional arg)
19006 "Decrease item in timestamp or decrease priority of current headline.
19007 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19008 depending on context. See the individual commands for more information."
19009 (interactive "P")
19010 (cond
19011 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19012 ((and org-support-shift-select (org-region-active-p))
19013 (org-call-for-shift-select 'next-line))
19014 ((org-at-timestamp-p t)
19015 (call-interactively (if org-edit-timestamp-down-means-later
19016 'org-timestamp-up 'org-timestamp-down)))
19017 ((and (not (eq org-support-shift-select 'always))
19018 org-enable-priority-commands
19019 (org-at-heading-p))
19020 (call-interactively 'org-priority-down))
19021 ((and (not org-support-shift-select) (org-at-item-p))
19022 (call-interactively 'org-next-item))
19023 ((org-clocktable-try-shift 'down arg))
19024 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19025 (org-support-shift-select
19026 (org-call-for-shift-select 'next-line))
19027 (t (org-shiftselect-error))))
19029 (defun org-shiftright (&optional arg)
19030 "Cycle the thing at point or in the current line, depending on context.
19031 Depending on context, this does one of the following:
19033 - switch a timestamp at point one day into the future
19034 - on a headline, switch to the next TODO keyword.
19035 - on an item, switch entire list to the next bullet type
19036 - on a property line, switch to the next allowed value
19037 - on a clocktable definition line, move time block into the future"
19038 (interactive "P")
19039 (cond
19040 ((run-hook-with-args-until-success 'org-shiftright-hook))
19041 ((and org-support-shift-select (org-region-active-p))
19042 (org-call-for-shift-select 'forward-char))
19043 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19044 ((and (not (eq org-support-shift-select 'always))
19045 (org-at-heading-p))
19046 (let ((org-inhibit-logging
19047 (not org-treat-S-cursor-todo-selection-as-state-change))
19048 (org-inhibit-blocking
19049 (not org-treat-S-cursor-todo-selection-as-state-change)))
19050 (org-call-with-arg 'org-todo 'right)))
19051 ((or (and org-support-shift-select
19052 (not (eq org-support-shift-select 'always))
19053 (org-at-item-bullet-p))
19054 (and (not org-support-shift-select) (org-at-item-p)))
19055 (org-call-with-arg 'org-cycle-list-bullet nil))
19056 ((and (not (eq org-support-shift-select 'always))
19057 (org-at-property-p))
19058 (call-interactively 'org-property-next-allowed-value))
19059 ((org-clocktable-try-shift 'right arg))
19060 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19061 (org-support-shift-select
19062 (org-call-for-shift-select 'forward-char))
19063 (t (org-shiftselect-error))))
19065 (defun org-shiftleft (&optional arg)
19066 "Cycle the thing at point or in the current line, depending on context.
19067 Depending on context, this does one of the following:
19069 - switch a timestamp at point one day into the past
19070 - on a headline, switch to the previous TODO keyword.
19071 - on an item, switch entire list to the previous bullet type
19072 - on a property line, switch to the previous allowed value
19073 - on a clocktable definition line, move time block into the past"
19074 (interactive "P")
19075 (cond
19076 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19077 ((and org-support-shift-select (org-region-active-p))
19078 (org-call-for-shift-select 'backward-char))
19079 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19080 ((and (not (eq org-support-shift-select 'always))
19081 (org-at-heading-p))
19082 (let ((org-inhibit-logging
19083 (not org-treat-S-cursor-todo-selection-as-state-change))
19084 (org-inhibit-blocking
19085 (not org-treat-S-cursor-todo-selection-as-state-change)))
19086 (org-call-with-arg 'org-todo 'left)))
19087 ((or (and org-support-shift-select
19088 (not (eq org-support-shift-select 'always))
19089 (org-at-item-bullet-p))
19090 (and (not org-support-shift-select) (org-at-item-p)))
19091 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19092 ((and (not (eq org-support-shift-select 'always))
19093 (org-at-property-p))
19094 (call-interactively 'org-property-previous-allowed-value))
19095 ((org-clocktable-try-shift 'left arg))
19096 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19097 (org-support-shift-select
19098 (org-call-for-shift-select 'backward-char))
19099 (t (org-shiftselect-error))))
19101 (defun org-shiftcontrolright ()
19102 "Switch to next TODO set."
19103 (interactive)
19104 (cond
19105 ((and org-support-shift-select (org-region-active-p))
19106 (org-call-for-shift-select 'forward-word))
19107 ((and (not (eq org-support-shift-select 'always))
19108 (org-at-heading-p))
19109 (org-call-with-arg 'org-todo 'nextset))
19110 (org-support-shift-select
19111 (org-call-for-shift-select 'forward-word))
19112 (t (org-shiftselect-error))))
19114 (defun org-shiftcontrolleft ()
19115 "Switch to previous TODO set."
19116 (interactive)
19117 (cond
19118 ((and org-support-shift-select (org-region-active-p))
19119 (org-call-for-shift-select 'backward-word))
19120 ((and (not (eq org-support-shift-select 'always))
19121 (org-at-heading-p))
19122 (org-call-with-arg 'org-todo 'previousset))
19123 (org-support-shift-select
19124 (org-call-for-shift-select 'backward-word))
19125 (t (org-shiftselect-error))))
19127 (defun org-shiftcontrolup ()
19128 "Change timestamps synchronously up in CLOCK log lines."
19129 (interactive)
19130 (cond ((and (not org-support-shift-select)
19131 (org-at-clock-log-p)
19132 (org-at-timestamp-p t))
19133 (org-clock-timestamps-up))
19134 (t (org-shiftselect-error))))
19136 (defun org-shiftcontroldown ()
19137 "Change timestamps synchronously down in CLOCK log lines."
19138 (interactive)
19139 (cond ((and (not org-support-shift-select)
19140 (org-at-clock-log-p)
19141 (org-at-timestamp-p t))
19142 (org-clock-timestamps-down))
19143 (t (org-shiftselect-error))))
19145 (defun org-ctrl-c-ret ()
19146 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19147 (interactive)
19148 (cond
19149 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19150 (t (call-interactively 'org-insert-heading))))
19152 (defun org-find-visible ()
19153 (let ((s (point)))
19154 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19155 (get-char-property s 'invisible)))
19157 (defun org-find-invisible ()
19158 (let ((s (point)))
19159 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19160 (not (get-char-property s 'invisible))))
19163 (defun org-copy-visible (beg end)
19164 "Copy the visible parts of the region."
19165 (interactive "r")
19166 (let (snippets s)
19167 (save-excursion
19168 (save-restriction
19169 (narrow-to-region beg end)
19170 (setq s (goto-char (point-min)))
19171 (while (not (= (point) (point-max)))
19172 (goto-char (org-find-invisible))
19173 (push (buffer-substring s (point)) snippets)
19174 (setq s (goto-char (org-find-visible))))))
19175 (kill-new (apply 'concat (nreverse snippets)))))
19177 (defun org-copy-special ()
19178 "Copy region in table or copy current subtree.
19179 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19180 See the individual commands for more information."
19181 (interactive)
19182 (call-interactively
19183 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19185 (defun org-cut-special ()
19186 "Cut region in table or cut current subtree.
19187 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19188 See the individual commands for more information."
19189 (interactive)
19190 (call-interactively
19191 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19193 (defun org-paste-special (arg)
19194 "Paste rectangular region into table, or past subtree relative to level.
19195 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19196 See the individual commands for more information."
19197 (interactive "P")
19198 (if (org-at-table-p)
19199 (org-table-paste-rectangle)
19200 (org-paste-subtree arg)))
19202 (defun org-edit-special (&optional arg)
19203 "Call a special editor for the stuff at point.
19204 When at a table, call the formula editor with `org-table-edit-formulas'.
19205 When at the first line of an src example, call `org-edit-src-code'.
19206 When in an #+include line, visit the include file. Otherwise call
19207 `ffap' to visit the file at point."
19208 (interactive)
19209 ;; possibly prep session before editing source
19210 (when arg
19211 (let* ((info (org-babel-get-src-block-info))
19212 (lang (nth 0 info))
19213 (params (nth 2 info))
19214 (session (cdr (assoc :session params))))
19215 (when (and info session) ;; we are in a source-code block with a session
19216 (funcall
19217 (intern (concat "org-babel-prep-session:" lang)) session params))))
19218 (cond ;; proceed with `org-edit-special'
19219 ((save-excursion
19220 (beginning-of-line 1)
19221 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19222 (find-file (org-trim (match-string 1))))
19223 ((org-edit-src-code))
19224 ((org-edit-fixed-width-region))
19225 ((org-at-table.el-p)
19226 (org-edit-src-code))
19227 ((or (org-at-table-p)
19228 (save-excursion
19229 (beginning-of-line 1)
19230 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19231 (call-interactively 'org-table-edit-formulas))
19232 (t (call-interactively 'ffap))))
19234 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19235 (defun org-ctrl-c-ctrl-c (&optional arg)
19236 "Set tags in headline, or update according to changed information at point.
19238 This command does many different things, depending on context:
19240 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19241 this is what we do.
19243 - If the cursor is on a statistics cookie, update it.
19245 - If the cursor is in a headline, prompt for tags and insert them
19246 into the current line, aligned to `org-tags-column'. When called
19247 with prefix arg, realign all tags in the current buffer.
19249 - If the cursor is in one of the special #+KEYWORD lines, this
19250 triggers scanning the buffer for these lines and updating the
19251 information.
19253 - If the cursor is inside a table, realign the table. This command
19254 works even if the automatic table editor has been turned off.
19256 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19257 the entire table.
19259 - If the cursor is at a footnote reference or definition, jump to
19260 the corresponding definition or references, respectively.
19262 - If the cursor is a the beginning of a dynamic block, update it.
19264 - If the current buffer is a capture buffer, close note and file it.
19266 - If the cursor is on a <<<target>>>, update radio targets and
19267 corresponding links in this buffer.
19269 - If the cursor is on a numbered item in a plain list, renumber the
19270 ordered list.
19272 - If the cursor is on a checkbox, toggle it.
19274 - If the cursor is on a code block, evaluate it. The variable
19275 `org-confirm-babel-evaluate' can be used to control prompting
19276 before code block evaluation, by default every code block
19277 evaluation requires confirmation. Code block evaluation can be
19278 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19279 (interactive "P")
19280 (let ((org-enable-table-editor t))
19281 (cond
19282 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19283 org-occur-highlights
19284 org-latex-fragment-image-overlays)
19285 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19286 (org-remove-occur-highlights)
19287 (org-remove-latex-fragment-image-overlays)
19288 (message "Temporary highlights/overlays removed from current buffer"))
19289 ((and (local-variable-p 'org-finish-function (current-buffer))
19290 (fboundp org-finish-function))
19291 (funcall org-finish-function))
19292 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19293 ((org-in-regexp org-ts-regexp-both)
19294 (org-timestamp-change 0 'day))
19295 ((or (looking-at org-property-start-re)
19296 (org-at-property-p))
19297 (call-interactively 'org-property-action))
19298 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19299 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19300 (or (org-at-heading-p) (org-at-item-p)))
19301 (call-interactively 'org-update-statistics-cookies))
19302 ((org-at-heading-p) (call-interactively 'org-set-tags))
19303 ((org-at-table.el-p)
19304 (message "Use C-c ' to edit table.el tables"))
19305 ((org-at-table-p)
19306 (org-table-maybe-eval-formula)
19307 (if arg
19308 (call-interactively 'org-table-recalculate)
19309 (org-table-maybe-recalculate-line))
19310 (call-interactively 'org-table-align)
19311 (orgtbl-send-table 'maybe))
19312 ((or (org-footnote-at-reference-p)
19313 (org-footnote-at-definition-p))
19314 (call-interactively 'org-footnote-action))
19315 ((org-at-item-checkbox-p)
19316 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19317 ;; list only if at top item.
19318 (let* ((cbox (match-string 1))
19319 (struct (org-list-struct))
19320 (old-struct (copy-tree struct))
19321 (parents (org-list-parents-alist struct))
19322 (orderedp (org-entry-get nil "ORDERED"))
19323 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19324 block-item)
19325 ;; Use a light version of `org-toggle-checkbox' to avoid
19326 ;; computing list structure twice.
19327 (let ((new-box (cond
19328 ((equal arg '(16)) "[-]")
19329 ((equal arg '(4)) nil)
19330 ((equal "[X]" cbox) "[ ]")
19331 (t "[X]"))))
19332 (if (and firstp arg)
19333 ;; If at first item of sub-list, remove check-box from
19334 ;; every item at the same level.
19335 (mapc
19336 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19337 (org-list-get-all-items
19338 (point-at-bol) struct (org-list-prevs-alist struct)))
19339 (org-list-set-checkbox (point-at-bol) struct new-box)))
19340 ;; Replicate `org-list-write-struct', while grabbing a return
19341 ;; value from `org-list-struct-fix-box'.
19342 (org-list-struct-fix-ind struct parents 2)
19343 (org-list-struct-fix-item-end struct)
19344 (let ((prevs (org-list-prevs-alist struct)))
19345 (org-list-struct-fix-bul struct prevs)
19346 (org-list-struct-fix-ind struct parents)
19347 (setq block-item
19348 (org-list-struct-fix-box struct parents prevs orderedp)))
19349 (org-list-struct-apply-struct struct old-struct)
19350 (org-update-checkbox-count-maybe)
19351 (when block-item
19352 (message
19353 "Checkboxes were removed due to unchecked box at line %d"
19354 (org-current-line block-item)))
19355 (when firstp (org-list-send-list 'maybe))))
19356 ((org-at-item-p)
19357 ;; Cursor at an item: repair list. Do checkbox related actions
19358 ;; only if function was called with an argument. Send list only
19359 ;; if at top item.
19360 (let* ((struct (org-list-struct))
19361 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19362 old-struct)
19363 (when arg
19364 (setq old-struct (copy-tree struct))
19365 (if firstp
19366 ;; If at first item of sub-list, add check-box to every
19367 ;; item at the same level.
19368 (mapc
19369 (lambda (pos)
19370 (unless (org-list-get-checkbox pos struct)
19371 (org-list-set-checkbox pos struct "[ ]")))
19372 (org-list-get-all-items
19373 (point-at-bol) struct (org-list-prevs-alist struct)))
19374 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19375 (org-list-write-struct
19376 struct (org-list-parents-alist struct) old-struct)
19377 (when arg (org-update-checkbox-count-maybe))
19378 (when firstp (org-list-send-list 'maybe))))
19379 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19380 ;; Dynamic block
19381 (beginning-of-line 1)
19382 (save-excursion (org-update-dblock)))
19383 ((save-excursion
19384 (let ((case-fold-search t))
19385 (beginning-of-line 1)
19386 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19387 (cond
19388 ((or (equal (match-string 1) "TBLFM")
19389 (equal (match-string 1) "tblfm"))
19390 ;; Recalculate the table before this line
19391 (save-excursion
19392 (beginning-of-line 1)
19393 (skip-chars-backward " \r\n\t")
19394 (if (org-at-table-p)
19395 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19397 (let ((org-inhibit-startup-visibility-stuff t)
19398 (org-startup-align-all-tables nil))
19399 (when (boundp 'org-table-coordinate-overlays)
19400 (mapc 'delete-overlay org-table-coordinate-overlays)
19401 (setq org-table-coordinate-overlays nil))
19402 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19403 (message "Local setup has been refreshed"))))
19404 ((org-clock-update-time-maybe))
19406 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19407 (error "C-c C-c can do nothing useful at this location"))))))
19409 (defun org-mode-restart ()
19410 "Restart Org-mode, to scan again for special lines.
19411 Also updates the keyword regular expressions."
19412 (interactive)
19413 (org-mode)
19414 (message "Org-mode restarted"))
19416 (defun org-kill-note-or-show-branches ()
19417 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19418 (interactive)
19419 (if (not org-finish-function)
19420 (progn
19421 (hide-subtree)
19422 (call-interactively 'show-branches))
19423 (let ((org-note-abort t))
19424 (funcall org-finish-function))))
19426 (defun org-return (&optional indent)
19427 "Goto next table row or insert a newline.
19428 Calls `org-table-next-row' or `newline', depending on context.
19429 See the individual commands for more information."
19430 (interactive)
19431 (let (org-ts-what)
19432 (cond
19433 ((or (bobp) (org-in-src-block-p))
19434 (if indent (newline-and-indent) (newline)))
19435 ((org-at-table-p)
19436 (org-table-justify-field-maybe)
19437 (call-interactively 'org-table-next-row))
19438 ;; when `newline-and-indent' is called within a list, make sure
19439 ;; text moved stays inside the item.
19440 ((and (org-in-item-p) indent)
19441 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19442 (progn
19443 (save-match-data (newline))
19444 (org-indent-line-to (length (match-string 0))))
19445 (let ((ind (org-get-indentation)))
19446 (newline)
19447 (if (org-looking-back org-list-end-re)
19448 (org-indent-line)
19449 (org-indent-line-to ind)))))
19450 ((and org-return-follows-link
19451 (org-at-timestamp-p t)
19452 (not (eq org-ts-what 'after)))
19453 (org-follow-timestamp-link))
19454 ((and org-return-follows-link
19455 (let ((tprop (get-text-property (point) 'face)))
19456 (or (eq tprop 'org-link)
19457 (and (listp tprop) (memq 'org-link tprop)))))
19458 (call-interactively 'org-open-at-point))
19459 ((and (org-at-heading-p)
19460 (looking-at
19461 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19462 (org-show-entry)
19463 (end-of-line 1)
19464 (newline))
19465 (t (if indent (newline-and-indent) (newline))))))
19467 (defun org-return-indent ()
19468 "Goto next table row or insert a newline and indent.
19469 Calls `org-table-next-row' or `newline-and-indent', depending on
19470 context. See the individual commands for more information."
19471 (interactive)
19472 (org-return t))
19474 (defun org-ctrl-c-star ()
19475 "Compute table, or change heading status of lines.
19476 Calls `org-table-recalculate' or `org-toggle-heading',
19477 depending on context."
19478 (interactive)
19479 (cond
19480 ((org-at-table-p)
19481 (call-interactively 'org-table-recalculate))
19483 ;; Convert all lines in region to list items
19484 (call-interactively 'org-toggle-heading))))
19486 (defun org-ctrl-c-minus ()
19487 "Insert separator line in table or modify bullet status of line.
19488 Also turns a plain line or a region of lines into list items.
19489 Calls `org-table-insert-hline', `org-toggle-item', or
19490 `org-cycle-list-bullet', depending on context."
19491 (interactive)
19492 (cond
19493 ((org-at-table-p)
19494 (call-interactively 'org-table-insert-hline))
19495 ((org-region-active-p)
19496 (call-interactively 'org-toggle-item))
19497 ((org-in-item-p)
19498 (call-interactively 'org-cycle-list-bullet))
19500 (call-interactively 'org-toggle-item))))
19502 (defun org-toggle-item (arg)
19503 "Convert headings or normal lines to items, items to normal lines.
19504 If there is no active region, only the current line is considered.
19506 If the first non blank line in the region is an headline, convert
19507 all headlines to items, shifting text accordingly.
19509 If it is an item, convert all items to normal lines.
19511 If it is normal text, change region into an item. With a prefix
19512 argument ARG, change each line in region into an item."
19513 (interactive "P")
19514 (let ((shift-text
19515 (function
19516 ;; Shift text in current section to IND, from point to END.
19517 ;; The function leaves point to END line.
19518 (lambda (ind end)
19519 (let ((min-i 1000) (end (copy-marker end)))
19520 ;; First determine the minimum indentation (MIN-I) of
19521 ;; the text.
19522 (save-excursion
19523 (catch 'exit
19524 (while (< (point) end)
19525 (let ((i (org-get-indentation)))
19526 (cond
19527 ;; Skip blank lines and inline tasks.
19528 ((looking-at "^[ \t]*$"))
19529 ((looking-at org-outline-regexp-bol))
19530 ;; We can't find less than 0 indentation.
19531 ((zerop i) (throw 'exit (setq min-i 0)))
19532 ((< i min-i) (setq min-i i))))
19533 (forward-line))))
19534 ;; Then indent each line so that a line indented to
19535 ;; MIN-I becomes indented to IND. Ignore blank lines
19536 ;; and inline tasks in the process.
19537 (let ((delta (- ind min-i)))
19538 (while (< (point) end)
19539 (unless (or (looking-at "^[ \t]*$")
19540 (looking-at org-outline-regexp-bol))
19541 (org-indent-line-to (+ (org-get-indentation) delta)))
19542 (forward-line)))))))
19543 (skip-blanks
19544 (function
19545 ;; Return beginning of first non-blank line, starting from
19546 ;; line at POS.
19547 (lambda (pos)
19548 (save-excursion
19549 (goto-char pos)
19550 (skip-chars-forward " \r\t\n")
19551 (point-at-bol)))))
19552 beg end)
19553 ;; Determine boundaries of changes.
19554 (if (org-region-active-p)
19555 (setq beg (funcall skip-blanks (region-beginning))
19556 end (copy-marker (region-end)))
19557 (setq beg (funcall skip-blanks (point-at-bol))
19558 end (copy-marker (point-at-eol))))
19559 ;; Depending on the starting line, choose an action on the text
19560 ;; between BEG and END.
19561 (org-with-limited-levels
19562 (save-excursion
19563 (goto-char beg)
19564 (cond
19565 ;; Case 1. Start at an item: de-itemize. Note that it only
19566 ;; happens when a region is active: `org-ctrl-c-minus'
19567 ;; would call `org-cycle-list-bullet' otherwise.
19568 ((org-at-item-p)
19569 (while (< (point) end)
19570 (when (org-at-item-p)
19571 (skip-chars-forward " \t")
19572 (delete-region (point) (match-end 0)))
19573 (forward-line)))
19574 ;; Case 2. Start at an heading: convert to items.
19575 ((org-at-heading-p)
19576 (let* ((bul (org-list-bullet-string "-"))
19577 (bul-len (length bul))
19578 ;; Indentation of the first heading. It should be
19579 ;; relative to the indentation of its parent, if any.
19580 (start-ind (save-excursion
19581 (cond
19582 ((not org-adapt-indentation) 0)
19583 ((not (outline-previous-heading)) 0)
19584 (t (length (match-string 0))))))
19585 ;; Level of first heading. Further headings will be
19586 ;; compared to it to determine hierarchy in the list.
19587 (ref-level (org-reduced-level (org-outline-level))))
19588 (while (< (point) end)
19589 (let* ((level (org-reduced-level (org-outline-level)))
19590 (delta (max 0 (- level ref-level))))
19591 ;; If current headline is less indented than the first
19592 ;; one, set it as reference, in order to preserve
19593 ;; subtrees.
19594 (when (< level ref-level) (setq ref-level level))
19595 (replace-match bul t t)
19596 (org-indent-line-to (+ start-ind (* delta bul-len)))
19597 ;; Ensure all text down to END (or SECTION-END) belongs
19598 ;; to the newly created item.
19599 (let ((section-end (save-excursion
19600 (or (outline-next-heading) (point)))))
19601 (forward-line)
19602 (funcall shift-text
19603 (+ start-ind (* (1+ delta) bul-len))
19604 (min end section-end)))))))
19605 ;; Case 3. Normal line with ARG: turn each non-item line into
19606 ;; an item.
19607 (arg
19608 (while (< (point) end)
19609 (unless (or (org-at-heading-p) (org-at-item-p))
19610 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19611 (replace-match
19612 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19613 (forward-line)))
19614 ;; Case 4. Normal line without ARG: make the first line of
19615 ;; region an item, and shift indentation of others
19616 ;; lines to set them as item's body.
19617 (t (let* ((bul (org-list-bullet-string "-"))
19618 (bul-len (length bul))
19619 (ref-ind (org-get-indentation)))
19620 (skip-chars-forward " \t")
19621 (insert bul)
19622 (forward-line)
19623 (while (< (point) end)
19624 ;; Ensure that lines less indented than first one
19625 ;; still get included in item body.
19626 (funcall shift-text
19627 (+ ref-ind bul-len)
19628 (min end (save-excursion (or (outline-next-heading)
19629 (point)))))
19630 (forward-line)))))))))
19632 (defun org-toggle-heading (&optional nstars)
19633 "Convert headings to normal text, or items or text to headings.
19634 If there is no active region, only the current line is considered.
19636 With a \\[universal-argument] prefix, convert the whole list at
19637 point into heading.
19639 In a region:
19641 - If the first non blank line is an headline, remove the stars
19642 from all headlines in the region.
19644 - If it is a normal line turn each and every normal line (i.e. not an
19645 heading or an item) in the region into a heading.
19647 - If it is a plain list item, turn all plain list items into headings.
19649 When converting a line into a heading, the number of stars is chosen
19650 such that the lines become children of the current entry. However,
19651 when a prefix argument is given, its value determines the number of
19652 stars to add."
19653 (interactive "P")
19654 (let ((skip-blanks
19655 (function
19656 ;; Return beginning of first non-blank line, starting from
19657 ;; line at POS.
19658 (lambda (pos)
19659 (save-excursion
19660 (goto-char pos)
19661 (while (org-at-comment-p) (forward-line))
19662 (skip-chars-forward " \r\t\n")
19663 (point-at-bol)))))
19664 beg end toggled)
19665 ;; Determine boundaries of changes. If a universal prefix has
19666 ;; been given, put the list in a region. If region ends at a bol,
19667 ;; do not consider the last line to be in the region.
19669 (when (and current-prefix-arg (org-at-item-p))
19670 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19671 (org-mark-element))
19673 (if (org-region-active-p)
19674 (setq beg (funcall skip-blanks (region-beginning))
19675 end (copy-marker (save-excursion
19676 (goto-char (region-end))
19677 (if (bolp) (point) (point-at-eol)))))
19678 (setq beg (funcall skip-blanks (point-at-bol))
19679 end (copy-marker (point-at-eol))))
19680 ;; Ensure inline tasks don't count as headings.
19681 (org-with-limited-levels
19682 (save-excursion
19683 (goto-char beg)
19684 (cond
19685 ;; Case 1. Started at an heading: de-star headings.
19686 ((org-at-heading-p)
19687 (while (< (point) end)
19688 (when (org-at-heading-p t)
19689 (looking-at org-outline-regexp) (replace-match "")
19690 (setq toggled t))
19691 (forward-line)))
19692 ;; Case 2. Started at an item: change items into headlines.
19693 ;; One star will be added by `org-list-to-subtree'.
19694 ((org-at-item-p)
19695 (let* ((stars (make-string
19696 (if nstars
19697 ;; subtract the star that will be added again by
19698 ;; `org-list-to-subtree'
19699 (1- (prefix-numeric-value current-prefix-arg))
19700 (or (org-current-level) 0))
19701 ?*))
19702 (add-stars
19703 (cond (nstars "") ; stars from prefix only
19704 ((equal stars "") "") ; before first heading
19705 (org-odd-levels-only "*") ; inside heading, odd
19706 (t "")))) ; inside heading, oddeven
19707 (while (< (point) end)
19708 (when (org-at-item-p)
19709 ;; Pay attention to cases when region ends before list.
19710 (let* ((struct (org-list-struct))
19711 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19712 (save-restriction
19713 (narrow-to-region (point) list-end)
19714 (insert
19715 (org-list-to-subtree
19716 (org-list-parse-list t)
19717 '(:istart (concat stars add-stars (funcall get-stars depth))
19718 :icount (concat stars add-stars (funcall get-stars depth)))))))
19719 (setq toggled t))
19720 (forward-line))))
19721 ;; Case 3. Started at normal text: make every line an heading,
19722 ;; skipping headlines and items.
19723 (t (let* ((stars (make-string
19724 (if nstars
19725 (prefix-numeric-value current-prefix-arg)
19726 (or (org-current-level) 0))
19727 ?*))
19728 (add-stars
19729 (cond (nstars "") ; stars from prefix only
19730 ((equal stars "") "*") ; before first heading
19731 (org-odd-levels-only "**") ; inside heading, odd
19732 (t "*"))) ; inside heading, oddeven
19733 (rpl (concat stars add-stars " ")))
19734 (while (< (point) end)
19735 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19736 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19737 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19738 (forward-line)))))))
19739 (unless toggled (message "Cannot toggle heading from here"))))
19741 (defun org-meta-return (&optional arg)
19742 "Insert a new heading or wrap a region in a table.
19743 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19744 See the individual commands for more information."
19745 (interactive "P")
19746 (cond
19747 ((run-hook-with-args-until-success 'org-metareturn-hook))
19748 ((or (org-at-drawer-p) (org-at-property-p))
19749 (newline-and-indent))
19750 ((org-at-table-p)
19751 (call-interactively 'org-table-wrap-region))
19752 (t (call-interactively 'org-insert-heading))))
19754 ;;; Menu entries
19756 (defsubst org-in-subtree-not-table-p ()
19757 "Are we in a subtree and not in a table?"
19758 (and (not (org-before-first-heading-p))
19759 (not (org-at-table-p))))
19761 ;; Define the Org-mode menus
19762 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19763 '("Tbl"
19764 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19765 ["Next Field" org-cycle (org-at-table-p)]
19766 ["Previous Field" org-shifttab (org-at-table-p)]
19767 ["Next Row" org-return (org-at-table-p)]
19768 "--"
19769 ["Blank Field" org-table-blank-field (org-at-table-p)]
19770 ["Edit Field" org-table-edit-field (org-at-table-p)]
19771 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19772 "--"
19773 ("Column"
19774 ["Move Column Left" org-metaleft (org-at-table-p)]
19775 ["Move Column Right" org-metaright (org-at-table-p)]
19776 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19777 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19778 ("Row"
19779 ["Move Row Up" org-metaup (org-at-table-p)]
19780 ["Move Row Down" org-metadown (org-at-table-p)]
19781 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19782 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19783 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19784 "--"
19785 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19786 ("Rectangle"
19787 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19788 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19789 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19790 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19791 "--"
19792 ("Calculate"
19793 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19794 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19795 ["Edit Formulas" org-edit-special (org-at-table-p)]
19796 "--"
19797 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19798 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19799 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19800 "--"
19801 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19802 "--"
19803 ["Sum Column/Rectangle" org-table-sum
19804 (or (org-at-table-p) (org-region-active-p))]
19805 ["Which Column?" org-table-current-column (org-at-table-p)])
19806 ["Debug Formulas"
19807 org-table-toggle-formula-debugger
19808 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19809 ["Show Col/Row Numbers"
19810 org-table-toggle-coordinate-overlays
19811 :style toggle
19812 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19813 "--"
19814 ["Create" org-table-create (and (not (org-at-table-p))
19815 org-enable-table-editor)]
19816 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19817 ["Import from File" org-table-import (not (org-at-table-p))]
19818 ["Export to File" org-table-export (org-at-table-p)]
19819 "--"
19820 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19822 (easy-menu-define org-org-menu org-mode-map "Org menu"
19823 '("Org"
19824 ("Show/Hide"
19825 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19826 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19827 ["Sparse Tree..." org-sparse-tree t]
19828 ["Reveal Context" org-reveal t]
19829 ["Show All" show-all t]
19830 "--"
19831 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19832 "--"
19833 ["New Heading" org-insert-heading t]
19834 ("Navigate Headings"
19835 ["Up" outline-up-heading t]
19836 ["Next" outline-next-visible-heading t]
19837 ["Previous" outline-previous-visible-heading t]
19838 ["Next Same Level" outline-forward-same-level t]
19839 ["Previous Same Level" outline-backward-same-level t]
19840 "--"
19841 ["Jump" org-goto t])
19842 ("Edit Structure"
19843 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19844 "--"
19845 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19846 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19847 "--"
19848 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19849 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19850 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19851 "--"
19852 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19853 "--"
19854 ["Copy visible text" org-copy-visible t]
19855 "--"
19856 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19857 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19858 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19859 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19860 "--"
19861 ["Sort Region/Children" org-sort t]
19862 "--"
19863 ["Convert to odd levels" org-convert-to-odd-levels t]
19864 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19865 ("Editing"
19866 ["Emphasis..." org-emphasize t]
19867 ["Edit Source Example" org-edit-special t]
19868 "--"
19869 ["Footnote new/jump" org-footnote-action t]
19870 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19871 ("Archive"
19872 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19873 "--"
19874 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19875 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19876 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19878 "--"
19879 ("Hyperlinks"
19880 ["Store Link (Global)" org-store-link t]
19881 ["Find existing link to here" org-occur-link-in-agenda-files t]
19882 ["Insert Link" org-insert-link t]
19883 ["Follow Link" org-open-at-point t]
19884 "--"
19885 ["Next link" org-next-link t]
19886 ["Previous link" org-previous-link t]
19887 "--"
19888 ["Descriptive Links"
19889 org-toggle-link-display
19890 :style radio
19891 :selected org-descriptive-links
19893 ["Literal Links"
19894 org-toggle-link-display
19895 :style radio
19896 :selected (not org-descriptive-links)])
19897 "--"
19898 ("TODO Lists"
19899 ["TODO/DONE/-" org-todo t]
19900 ("Select keyword"
19901 ["Next keyword" org-shiftright (org-at-heading-p)]
19902 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19903 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19904 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19905 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19906 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19907 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19908 "--"
19909 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19910 :selected org-enforce-todo-dependencies :style toggle :active t]
19911 "Settings for tree at point"
19912 ["Do Children sequentially" org-toggle-ordered-property :style radio
19913 :selected (org-entry-get nil "ORDERED")
19914 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19915 ["Do Children parallel" org-toggle-ordered-property :style radio
19916 :selected (not (org-entry-get nil "ORDERED"))
19917 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19918 "--"
19919 ["Set Priority" org-priority t]
19920 ["Priority Up" org-shiftup t]
19921 ["Priority Down" org-shiftdown t]
19922 "--"
19923 ["Get news from all feeds" org-feed-update-all t]
19924 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19925 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19926 ("TAGS and Properties"
19927 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19928 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19929 "--"
19930 ["Set property" org-set-property (not (org-before-first-heading-p))]
19931 ["Column view of properties" org-columns t]
19932 ["Insert Column View DBlock" org-insert-columns-dblock t])
19933 ("Dates and Scheduling"
19934 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19935 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19936 ("Change Date"
19937 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19938 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19939 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19940 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19941 ["Compute Time Range" org-evaluate-time-range t]
19942 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19943 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19944 "--"
19945 ["Custom time format" org-toggle-time-stamp-overlays
19946 :style radio :selected org-display-custom-times]
19947 "--"
19948 ["Goto Calendar" org-goto-calendar t]
19949 ["Date from Calendar" org-date-from-calendar t]
19950 "--"
19951 ["Start/Restart Timer" org-timer-start t]
19952 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19953 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19954 ["Insert Timer String" org-timer t]
19955 ["Insert Timer Item" org-timer-item t])
19956 ("Logging work"
19957 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19958 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19959 ["Clock out" org-clock-out t]
19960 ["Clock cancel" org-clock-cancel t]
19961 "--"
19962 ["Mark as default task" org-clock-mark-default-task t]
19963 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19964 ["Goto running clock" org-clock-goto t]
19965 "--"
19966 ["Display times" org-clock-display t]
19967 ["Create clock table" org-clock-report t]
19968 "--"
19969 ["Record DONE time"
19970 (progn (setq org-log-done (not org-log-done))
19971 (message "Switching to %s will %s record a timestamp"
19972 (car org-done-keywords)
19973 (if org-log-done "automatically" "not")))
19974 :style toggle :selected org-log-done])
19975 "--"
19976 ["Agenda Command..." org-agenda t]
19977 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19978 ("File List for Agenda")
19979 ("Special views current file"
19980 ["TODO Tree" org-show-todo-tree t]
19981 ["Check Deadlines" org-check-deadlines t]
19982 ["Timeline" org-timeline t]
19983 ["Tags/Property tree" org-match-sparse-tree t])
19984 "--"
19985 ["Export/Publish..." org-export t]
19986 ("LaTeX"
19987 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19988 :selected org-cdlatex-mode]
19989 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19990 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19991 ["Modify math symbol" org-cdlatex-math-modify
19992 (org-inside-LaTeX-fragment-p)]
19993 ["Insert citation" org-reftex-citation t]
19994 "--"
19995 ["Template for BEAMER" (progn (require 'org-beamer)
19996 (org-insert-beamer-options-template)) t])
19997 "--"
19998 ("MobileOrg"
19999 ["Push Files and Views" org-mobile-push t]
20000 ["Get Captured and Flagged" org-mobile-pull t]
20001 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20002 "--"
20003 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20004 "--"
20005 ("Documentation"
20006 ["Show Version" org-version t]
20007 ["Info Documentation" org-info t])
20008 ("Customize"
20009 ["Browse Org Group" org-customize t]
20010 "--"
20011 ["Expand This Menu" org-create-customize-menu
20012 (fboundp 'customize-menu-create)])
20013 ["Send bug report" org-submit-bug-report t]
20014 "--"
20015 ("Refresh/Reload"
20016 ["Refresh setup current buffer" org-mode-restart t]
20017 ["Reload Org (after update)" org-reload t]
20018 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20021 (defun org-info (&optional node)
20022 "Read documentation for Org-mode in the info system.
20023 With optional NODE, go directly to that node."
20024 (interactive)
20025 (info (format "(org)%s" (or node ""))))
20027 ;;;###autoload
20028 (defun org-submit-bug-report ()
20029 "Submit a bug report on Org-mode via mail.
20031 Don't hesitate to report any problems or inaccurate documentation.
20033 If you don't have setup sending mail from (X)Emacs, please copy the
20034 output buffer into your mail program, as it gives us important
20035 information about your Org-mode version and configuration."
20036 (interactive)
20037 (require 'reporter)
20038 (org-load-modules-maybe)
20039 (org-require-autoloaded-modules)
20040 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20041 (reporter-submit-bug-report
20042 "emacs-orgmode@gnu.org"
20043 (org-version nil 'full)
20044 (let (list)
20045 (save-window-excursion
20046 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20047 (delete-other-windows)
20048 (erase-buffer)
20049 (insert "You are about to submit a bug report to the Org-mode mailing list.
20051 We would like to add your full Org-mode and Outline configuration to the
20052 bug report. This greatly simplifies the work of the maintainer and
20053 other experts on the mailing list.
20055 HOWEVER, some variables you have customized may contain private
20056 information. The names of customers, colleagues, or friends, might
20057 appear in the form of file names, tags, todo states, or search strings.
20058 If you answer yes to the prompt, you might want to check and remove
20059 such private information before sending the email.")
20060 (add-text-properties (point-min) (point-max) '(face org-warning))
20061 (when (yes-or-no-p "Include your Org-mode configuration ")
20062 (mapatoms
20063 (lambda (v)
20064 (and (boundp v)
20065 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20066 (or (and (symbol-value v)
20067 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20068 (and
20069 (get v 'custom-type) (get v 'standard-value)
20070 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20071 (push v list)))))
20072 (kill-buffer (get-buffer "*Warn about privacy*"))
20073 list))
20074 nil nil
20075 "Remember to cover the basics, that is, what you expected to happen and
20076 what in fact did happen. You don't know how to make a good report? See
20078 http://orgmode.org/manual/Feedback.html#Feedback
20080 Your bug report will be posted to the Org-mode mailing list.
20081 ------------------------------------------------------------------------")
20082 (save-excursion
20083 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20084 (replace-match "\\1Bug: \\3 [\\2]")))))
20087 (defun org-install-agenda-files-menu ()
20088 (let ((bl (buffer-list)))
20089 (save-excursion
20090 (while bl
20091 (set-buffer (pop bl))
20092 (if (derived-mode-p 'org-mode) (setq bl nil)))
20093 (when (derived-mode-p 'org-mode)
20094 (easy-menu-change
20095 '("Org") "File List for Agenda"
20096 (append
20097 (list
20098 ["Edit File List" (org-edit-agenda-file-list) t]
20099 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20100 ["Remove Current File from List" org-remove-file t]
20101 ["Cycle through agenda files" org-cycle-agenda-files t]
20102 ["Occur in all agenda files" org-occur-in-agenda-files t]
20103 "--")
20104 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20106 ;;;; Documentation
20108 ;;;###autoload
20109 (defun org-require-autoloaded-modules ()
20110 (interactive)
20111 (mapc 'require
20112 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20113 org-docbook org-exp org-html org-icalendar
20114 org-id org-latex
20115 org-publish org-remember org-table
20116 org-timer org-xoxo)))
20118 ;;;###autoload
20119 (defun org-reload (&optional uncompiled)
20120 "Reload all org lisp files.
20121 With prefix arg UNCOMPILED, load the uncompiled versions."
20122 (interactive "P")
20123 (require 'find-func)
20124 (let* ((file-re "^org\\(-.*\\)?\\.el")
20125 (dir-org (file-name-directory (org-find-library-dir "org")))
20126 (dir-org-contrib (ignore-errors
20127 (file-name-directory
20128 (org-find-library-dir "org-contribdir"))))
20129 (babel-files
20130 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20131 (append (list nil "comint" "eval" "exp" "keys"
20132 "lob" "ref" "table" "tangle")
20133 (delq nil
20134 (mapcar
20135 (lambda (lang)
20136 (when (cdr lang) (symbol-name (car lang))))
20137 org-babel-load-languages)))))
20138 (files
20139 (append babel-files
20140 (and dir-org-contrib
20141 (directory-files dir-org-contrib t file-re))
20142 (directory-files dir-org t file-re)))
20143 (remove-re (concat (if (featurep 'xemacs)
20144 "org-colview" "org-colview-xemacs")
20145 "\\'")))
20146 (setq files (mapcar 'file-name-sans-extension files))
20147 (setq files (mapcar
20148 (lambda (x) (if (string-match remove-re x) nil x))
20149 files))
20150 (setq files (delq nil files))
20151 (mapc
20152 (lambda (f)
20153 (when (featurep (intern (file-name-nondirectory f)))
20154 (if (and (not uncompiled)
20155 (file-exists-p (concat f ".elc")))
20156 (load (concat f ".elc") nil nil 'nosuffix)
20157 (load (concat f ".el") nil nil 'nosuffix))))
20158 files)
20159 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20160 (org-version nil 'full 'message))
20162 ;;;###autoload
20163 (defun org-customize ()
20164 "Call the customize function with org as argument."
20165 (interactive)
20166 (org-load-modules-maybe)
20167 (org-require-autoloaded-modules)
20168 (customize-browse 'org))
20170 (defun org-create-customize-menu ()
20171 "Create a full customization menu for Org-mode, insert it into the menu."
20172 (interactive)
20173 (org-load-modules-maybe)
20174 (org-require-autoloaded-modules)
20175 (if (fboundp 'customize-menu-create)
20176 (progn
20177 (easy-menu-change
20178 '("Org") "Customize"
20179 `(["Browse Org group" org-customize t]
20180 "--"
20181 ,(customize-menu-create 'org)
20182 ["Set" Custom-set t]
20183 ["Save" Custom-save t]
20184 ["Reset to Current" Custom-reset-current t]
20185 ["Reset to Saved" Custom-reset-saved t]
20186 ["Reset to Standard Settings" Custom-reset-standard t]))
20187 (message "\"Org\"-menu now contains full customization menu"))
20188 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20190 ;;;; Miscellaneous stuff
20192 ;;; Generally useful functions
20194 (defun org-get-at-bol (property)
20195 "Get text property PROPERTY at beginning of line."
20196 (get-text-property (point-at-bol) property))
20198 (defun org-find-text-property-in-string (prop s)
20199 "Return the first non-nil value of property PROP in string S."
20200 (or (get-text-property 0 prop s)
20201 (get-text-property (or (next-single-property-change 0 prop s) 0)
20202 prop s)))
20204 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20205 "Display the given MESSAGE as a warning."
20206 (if (fboundp 'display-warning)
20207 (display-warning 'org message
20208 (if (featurep 'xemacs) 'warning :warning))
20209 (let ((buf (get-buffer-create "*Org warnings*")))
20210 (with-current-buffer buf
20211 (goto-char (point-max))
20212 (insert "Warning (Org): " message)
20213 (unless (bolp)
20214 (newline)))
20215 (display-buffer buf)
20216 (sit-for 0))))
20218 (defun org-eval (form)
20219 "Eval FORM and return result."
20220 (condition-case error
20221 (eval form)
20222 (error (format "%%![Error: %s]" error))))
20224 (defun org-in-clocktable-p ()
20225 "Check if the cursor is in a clocktable."
20226 (let ((pos (point)) start)
20227 (save-excursion
20228 (end-of-line 1)
20229 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20230 (setq start (match-beginning 0))
20231 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20232 (>= (match-end 0) pos)
20233 start))))
20235 (defun org-in-commented-line ()
20236 "Is point in a line starting with `#'?"
20237 (equal (char-after (point-at-bol)) ?#))
20239 (defun org-in-indented-comment-line ()
20240 "Is point in a line starting with `#' after some white space?"
20241 (save-excursion
20242 (save-match-data
20243 (goto-char (point-at-bol))
20244 (looking-at "[ \t]*#"))))
20246 (defun org-in-verbatim-emphasis ()
20247 (save-match-data
20248 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20250 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20251 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20252 (if (and marker (marker-buffer marker)
20253 (buffer-live-p (marker-buffer marker)))
20254 (progn
20255 (org-pop-to-buffer-same-window (marker-buffer marker))
20256 (if (or (> marker (point-max)) (< marker (point-min)))
20257 (widen))
20258 (goto-char marker)
20259 (org-show-context 'org-goto))
20260 (if bookmark
20261 (bookmark-jump bookmark)
20262 (error "Cannot find location"))))
20264 (defun org-quote-csv-field (s)
20265 "Quote field for inclusion in CSV material."
20266 (if (string-match "[\",]" s)
20267 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20270 (defun org-force-self-insert (N)
20271 "Needed to enforce self-insert under remapping."
20272 (interactive "p")
20273 (self-insert-command N))
20275 (defun org-string-width (s)
20276 "Compute width of string, ignoring invisible characters.
20277 This ignores character with invisibility property `org-link', and also
20278 characters with property `org-cwidth', because these will become invisible
20279 upon the next fontification round."
20280 (let (b l)
20281 (when (or (eq t buffer-invisibility-spec)
20282 (assq 'org-link buffer-invisibility-spec))
20283 (while (setq b (text-property-any 0 (length s)
20284 'invisible 'org-link s))
20285 (setq s (concat (substring s 0 b)
20286 (substring s (or (next-single-property-change
20287 b 'invisible s) (length s)))))))
20288 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20289 (setq s (concat (substring s 0 b)
20290 (substring s (or (next-single-property-change
20291 b 'org-cwidth s) (length s))))))
20292 (setq l (string-width s) b -1)
20293 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20294 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20297 (defun org-shorten-string (s maxlength)
20298 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20299 If the string is shorter or has length MAXLENGTH, just return the
20300 original string. If it is longer, the functions finds a space in the
20301 string, breaks this string off at that locations and adds three dots
20302 as ellipsis. Including the ellipsis, the string will not be longer
20303 than MAXLENGTH. If finding a good breaking point in the string does
20304 not work, the string is just chopped off in the middle of a word
20305 if necessary."
20306 (if (<= (length s) maxlength)
20308 (let* ((n (max (- maxlength 4) 1))
20309 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20310 (if (string-match re s)
20311 (concat (match-string 1 s) "...")
20312 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20314 (defun org-get-indentation (&optional line)
20315 "Get the indentation of the current line, interpreting tabs.
20316 When LINE is given, assume it represents a line and compute its indentation."
20317 (if line
20318 (if (string-match "^ *" (org-remove-tabs line))
20319 (match-end 0))
20320 (save-excursion
20321 (beginning-of-line 1)
20322 (skip-chars-forward " \t")
20323 (current-column))))
20325 (defun org-get-string-indentation (s)
20326 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20327 (let ((n -1) (i 0) (w tab-width) c)
20328 (catch 'exit
20329 (while (< (setq n (1+ n)) (length s))
20330 (setq c (aref s n))
20331 (cond ((= c ?\ ) (setq i (1+ i)))
20332 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20333 (t (throw 'exit t)))))
20336 (defun org-remove-tabs (s &optional width)
20337 "Replace tabulators in S with spaces.
20338 Assumes that s is a single line, starting in column 0."
20339 (setq width (or width tab-width))
20340 (while (string-match "\t" s)
20341 (setq s (replace-match
20342 (make-string
20343 (- (* width (/ (+ (match-beginning 0) width) width))
20344 (match-beginning 0)) ?\ )
20345 t t s)))
20348 (defun org-fix-indentation (line ind)
20349 "Fix indentation in LINE.
20350 IND is a cons cell with target and minimum indentation.
20351 If the current indentation in LINE is smaller than the minimum,
20352 leave it alone. If it is larger than ind, set it to the target."
20353 (let* ((l (org-remove-tabs line))
20354 (i (org-get-indentation l))
20355 (i1 (car ind)) (i2 (cdr ind)))
20356 (if (>= i i2) (setq l (substring line i2)))
20357 (if (> i1 0)
20358 (concat (make-string i1 ?\ ) l)
20359 l)))
20361 (defun org-remove-indentation (code &optional n)
20362 "Remove the maximum common indentation from the lines in CODE.
20363 N may optionally be the number of spaces to remove."
20364 (with-temp-buffer
20365 (insert code)
20366 (org-do-remove-indentation n)
20367 (buffer-string)))
20369 (defun org-do-remove-indentation (&optional n)
20370 "Remove the maximum common indentation from the buffer."
20371 (untabify (point-min) (point-max))
20372 (let ((min 10000) re)
20373 (if n
20374 (setq min n)
20375 (goto-char (point-min))
20376 (while (re-search-forward "^ *[^ \n]" nil t)
20377 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20378 (unless (or (= min 0) (= min 10000))
20379 (setq re (format "^ \\{%d\\}" min))
20380 (goto-char (point-min))
20381 (while (re-search-forward re nil t)
20382 (replace-match "")
20383 (end-of-line 1))
20384 min)))
20386 (defun org-fill-template (template alist)
20387 "Find each %key of ALIST in TEMPLATE and replace it."
20388 (let ((case-fold-search nil)
20389 entry key value)
20390 (setq alist (sort (copy-sequence alist)
20391 (lambda (a b) (< (length (car a)) (length (car b))))))
20392 (while (setq entry (pop alist))
20393 (setq template
20394 (replace-regexp-in-string
20395 (concat "%" (regexp-quote (car entry)))
20396 (or (cdr entry) "") template t t)))
20397 template))
20399 (defun org-base-buffer (buffer)
20400 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20401 (if (not buffer)
20402 buffer
20403 (or (buffer-base-buffer buffer)
20404 buffer)))
20406 (defun org-trim (s)
20407 "Remove whitespace at beginning and end of string."
20408 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20409 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20412 (defun org-wrap (string &optional width lines)
20413 "Wrap string to either a number of lines, or a width in characters.
20414 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20415 that costs. If there is a word longer than WIDTH, the text is actually
20416 wrapped to the length of that word.
20417 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20418 many lines, whatever width that takes.
20419 The return value is a list of lines, without newlines at the end."
20420 (let* ((words (org-split-string string "[ \t\n]+"))
20421 (maxword (apply 'max (mapcar 'org-string-width words)))
20422 w ll)
20423 (cond (width
20424 (org-do-wrap words (max maxword width)))
20425 (lines
20426 (setq w maxword)
20427 (setq ll (org-do-wrap words maxword))
20428 (if (<= (length ll) lines)
20430 (setq ll words)
20431 (while (> (length ll) lines)
20432 (setq w (1+ w))
20433 (setq ll (org-do-wrap words w)))
20434 ll))
20435 (t (error "Cannot wrap this")))))
20437 (defun org-do-wrap (words width)
20438 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20439 (let (lines line)
20440 (while words
20441 (setq line (pop words))
20442 (while (and words (< (+ (length line) (length (car words))) width))
20443 (setq line (concat line " " (pop words))))
20444 (setq lines (push line lines)))
20445 (nreverse lines)))
20447 (defun org-split-string (string &optional separators)
20448 "Splits STRING into substrings at SEPARATORS.
20449 No empty strings are returned if there are matches at the beginning
20450 and end of string."
20451 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20452 (start 0)
20453 notfirst
20454 (list nil))
20455 (while (and (string-match rexp string
20456 (if (and notfirst
20457 (= start (match-beginning 0))
20458 (< start (length string)))
20459 (1+ start) start))
20460 (< (match-beginning 0) (length string)))
20461 (setq notfirst t)
20462 (or (eq (match-beginning 0) 0)
20463 (and (eq (match-beginning 0) (match-end 0))
20464 (eq (match-beginning 0) start))
20465 (setq list
20466 (cons (substring string start (match-beginning 0))
20467 list)))
20468 (setq start (match-end 0)))
20469 (or (eq start (length string))
20470 (setq list
20471 (cons (substring string start)
20472 list)))
20473 (nreverse list)))
20475 (defun org-quote-vert (s)
20476 "Replace \"|\" with \"\\vert\"."
20477 (while (string-match "|" s)
20478 (setq s (replace-match "\\vert" t t s)))
20481 (defun org-uuidgen-p (s)
20482 "Is S an ID created by UUIDGEN?"
20483 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20485 (defun org-in-src-block-p nil
20486 "Whether point is in a code source block."
20487 (let (ov)
20488 (when (setq ov (overlays-at (point)))
20489 (memq 'org-block-background
20490 (overlay-properties
20491 (car ov))))))
20493 (defun org-context ()
20494 "Return a list of contexts of the current cursor position.
20495 If several contexts apply, all are returned.
20496 Each context entry is a list with a symbol naming the context, and
20497 two positions indicating start and end of the context. Possible
20498 contexts are:
20500 :headline anywhere in a headline
20501 :headline-stars on the leading stars in a headline
20502 :todo-keyword on a TODO keyword (including DONE) in a headline
20503 :tags on the TAGS in a headline
20504 :priority on the priority cookie in a headline
20505 :item on the first line of a plain list item
20506 :item-bullet on the bullet/number of a plain list item
20507 :checkbox on the checkbox in a plain list item
20508 :table in an org-mode table
20509 :table-special on a special filed in a table
20510 :table-table in a table.el table
20511 :clocktable in a clocktable
20512 :src-block in a source block
20513 :link on a hyperlink
20514 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20515 :target on a <<target>>
20516 :radio-target on a <<<radio-target>>>
20517 :latex-fragment on a LaTeX fragment
20518 :latex-preview on a LaTeX fragment with overlaid preview image
20520 This function expects the position to be visible because it uses font-lock
20521 faces as a help to recognize the following contexts: :table-special, :link,
20522 and :keyword."
20523 (let* ((f (get-text-property (point) 'face))
20524 (faces (if (listp f) f (list f)))
20525 (case-fold-search t)
20526 (p (point)) clist o)
20527 ;; First the large context
20528 (cond
20529 ((org-at-heading-p t)
20530 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20531 (when (progn
20532 (beginning-of-line 1)
20533 (looking-at org-todo-line-tags-regexp))
20534 (push (org-point-in-group p 1 :headline-stars) clist)
20535 (push (org-point-in-group p 2 :todo-keyword) clist)
20536 (push (org-point-in-group p 4 :tags) clist))
20537 (goto-char p)
20538 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20539 (if (looking-at "\\[#[A-Z0-9]\\]")
20540 (push (org-point-in-group p 0 :priority) clist)))
20542 ((org-at-item-p)
20543 (push (org-point-in-group p 2 :item-bullet) clist)
20544 (push (list :item (point-at-bol)
20545 (save-excursion (org-end-of-item) (point)))
20546 clist)
20547 (and (org-at-item-checkbox-p)
20548 (push (org-point-in-group p 0 :checkbox) clist)))
20550 ((org-at-table-p)
20551 (push (list :table (org-table-begin) (org-table-end)) clist)
20552 (if (memq 'org-formula faces)
20553 (push (list :table-special
20554 (previous-single-property-change p 'face)
20555 (next-single-property-change p 'face)) clist)))
20556 ((org-at-table-p 'any)
20557 (push (list :table-table) clist)))
20558 (goto-char p)
20560 (let ((case-fold-search t))
20561 ;; New the "medium" contexts: clocktables, source blocks
20562 (cond ((org-in-clocktable-p)
20563 (push (list :clocktable
20564 (and (or (looking-at "#\\+BEGIN: clocktable")
20565 (search-backward "#+BEGIN: clocktable" nil t))
20566 (match-beginning 0))
20567 (and (re-search-forward "#\\+END:?" nil t)
20568 (match-end 0))) clist))
20569 ((org-in-src-block-p)
20570 (push (list :src-block
20571 (and (or (looking-at "#\\+BEGIN_SRC")
20572 (search-backward "#+BEGIN_SRC" nil t))
20573 (match-beginning 0))
20574 (and (search-forward "#+END_SRC" nil t)
20575 (match-beginning 0))) clist))))
20576 (goto-char p)
20578 ;; Now the small context
20579 (cond
20580 ((org-at-timestamp-p)
20581 (push (org-point-in-group p 0 :timestamp) clist))
20582 ((memq 'org-link faces)
20583 (push (list :link
20584 (previous-single-property-change p 'face)
20585 (next-single-property-change p 'face)) clist))
20586 ((memq 'org-special-keyword faces)
20587 (push (list :keyword
20588 (previous-single-property-change p 'face)
20589 (next-single-property-change p 'face)) clist))
20590 ((org-at-target-p)
20591 (push (org-point-in-group p 0 :target) clist)
20592 (goto-char (1- (match-beginning 0)))
20593 (if (looking-at org-radio-target-regexp)
20594 (push (org-point-in-group p 0 :radio-target) clist))
20595 (goto-char p))
20596 ((setq o (car (delq nil
20597 (mapcar
20598 (lambda (x)
20599 (if (memq x org-latex-fragment-image-overlays) x))
20600 (overlays-at (point))))))
20601 (push (list :latex-fragment
20602 (overlay-start o) (overlay-end o)) clist)
20603 (push (list :latex-preview
20604 (overlay-start o) (overlay-end o)) clist))
20605 ((org-inside-LaTeX-fragment-p)
20606 ;; FIXME: positions wrong.
20607 (push (list :latex-fragment (point) (point)) clist)))
20609 (setq clist (nreverse (delq nil clist)))
20610 clist))
20612 ;; FIXME: Compare with at-regexp-p Do we need both?
20613 (defun org-in-regexp (re &optional nlines visually)
20614 "Check if point is inside a match of regexp.
20615 Normally only the current line is checked, but you can include NLINES extra
20616 lines both before and after point into the search.
20617 If VISUALLY is set, require that the cursor is not after the match but
20618 really on, so that the block visually is on the match."
20619 (catch 'exit
20620 (let ((pos (point))
20621 (eol (point-at-eol (+ 1 (or nlines 0))))
20622 (inc (if visually 1 0)))
20623 (save-excursion
20624 (beginning-of-line (- 1 (or nlines 0)))
20625 (while (re-search-forward re eol t)
20626 (if (and (<= (match-beginning 0) pos)
20627 (>= (+ inc (match-end 0)) pos))
20628 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20630 (defun org-at-regexp-p (regexp)
20631 "Is point inside a match of REGEXP in the current line?"
20632 (catch 'exit
20633 (save-excursion
20634 (let ((pos (point)) (end (point-at-eol)))
20635 (beginning-of-line 1)
20636 (while (re-search-forward regexp end t)
20637 (if (and (<= (match-beginning 0) pos)
20638 (>= (match-end 0) pos))
20639 (throw 'exit t)))
20640 nil))))
20642 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20643 "Non-nil when point is between matches of START-RE and END-RE.
20645 Also return a non-nil value when point is on one of the matches.
20647 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20648 buffer positions. Default values are the positions of headlines
20649 surrounding the point.
20651 The functions returns a cons cell whose car (resp. cdr) is the
20652 position before START-RE (resp. after END-RE)."
20653 (save-match-data
20654 (let ((pos (point))
20655 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20656 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20657 beg end)
20658 (save-excursion
20659 ;; Point is on a block when on START-RE or if START-RE can be
20660 ;; found before it...
20661 (and (or (org-at-regexp-p start-re)
20662 (re-search-backward start-re limit-up t))
20663 (setq beg (match-beginning 0))
20664 ;; ... and END-RE after it...
20665 (goto-char (match-end 0))
20666 (re-search-forward end-re limit-down t)
20667 (> (setq end (match-end 0)) pos)
20668 ;; ... without another START-RE in-between.
20669 (goto-char (match-beginning 0))
20670 (not (re-search-backward start-re (1+ beg) t))
20671 ;; Return value.
20672 (cons beg end))))))
20674 (defun org-in-block-p (names)
20675 "Non-nil when point belongs to a block whose name belongs to NAMES.
20677 NAMES is a list of strings containing names of blocks.
20679 Return first block name matched, or nil. Beware that in case of
20680 nested blocks, the returned name may not belong to the closest
20681 block from point."
20682 (save-match-data
20683 (catch 'exit
20684 (let ((case-fold-search t)
20685 (lim-up (save-excursion (outline-previous-heading)))
20686 (lim-down (save-excursion (outline-next-heading))))
20687 (mapc (lambda (name)
20688 (let ((n (regexp-quote name)))
20689 (when (org-between-regexps-p
20690 (concat "^[ \t]*#\\+begin_" n)
20691 (concat "^[ \t]*#\\+end_" n)
20692 lim-up lim-down)
20693 (throw 'exit n))))
20694 names))
20695 nil)))
20697 (defun org-occur-in-agenda-files (regexp &optional nlines)
20698 "Call `multi-occur' with buffers for all agenda files."
20699 (interactive "sOrg-files matching: \np")
20700 (let* ((files (org-agenda-files))
20701 (tnames (mapcar 'file-truename files))
20702 (extra org-agenda-text-search-extra-files)
20704 (when (eq (car extra) 'agenda-archives)
20705 (setq extra (cdr extra))
20706 (setq files (org-add-archive-files files)))
20707 (while (setq f (pop extra))
20708 (unless (member (file-truename f) tnames)
20709 (add-to-list 'files f 'append)
20710 (add-to-list 'tnames (file-truename f) 'append)))
20711 (multi-occur
20712 (mapcar (lambda (x)
20713 (with-current-buffer
20714 (or (get-file-buffer x) (find-file-noselect x))
20715 (widen)
20716 (current-buffer)))
20717 files)
20718 regexp)))
20720 (if (boundp 'occur-mode-find-occurrence-hook)
20721 ;; Emacs 23
20722 (add-hook 'occur-mode-find-occurrence-hook
20723 (lambda ()
20724 (when (derived-mode-p 'org-mode)
20725 (org-reveal))))
20726 ;; Emacs 22
20727 (defadvice occur-mode-goto-occurrence
20728 (after org-occur-reveal activate)
20729 (and (derived-mode-p 'org-mode) (org-reveal)))
20730 (defadvice occur-mode-goto-occurrence-other-window
20731 (after org-occur-reveal activate)
20732 (and (derived-mode-p 'org-mode) (org-reveal)))
20733 (defadvice occur-mode-display-occurrence
20734 (after org-occur-reveal activate)
20735 (when (derived-mode-p 'org-mode)
20736 (let ((pos (occur-mode-find-occurrence)))
20737 (with-current-buffer (marker-buffer pos)
20738 (save-excursion
20739 (goto-char pos)
20740 (org-reveal)))))))
20742 (defun org-occur-link-in-agenda-files ()
20743 "Create a link and search for it in the agendas.
20744 The link is not stored in `org-stored-links', it is just created
20745 for the search purpose."
20746 (interactive)
20747 (let ((link (condition-case nil
20748 (org-store-link nil)
20749 (error "Unable to create a link to here"))))
20750 (org-occur-in-agenda-files (regexp-quote link))))
20752 (defun org-uniquify (list)
20753 "Remove duplicate elements from LIST."
20754 (let (res)
20755 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20756 res))
20758 (defun org-delete-all (elts list)
20759 "Remove all elements in ELTS from LIST."
20760 (while elts
20761 (setq list (delete (pop elts) list)))
20762 list)
20764 (defun org-count (cl-item cl-seq)
20765 "Count the number of occurrences of ITEM in SEQ.
20766 Taken from `count' in cl-seq.el with all keyword arguments removed."
20767 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20768 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20769 (while (< cl-start cl-end)
20770 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20771 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20772 (setq cl-start (1+ cl-start)))
20773 cl-count))
20775 (defun org-remove-if (predicate seq)
20776 "Remove everything from SEQ that fulfills PREDICATE."
20777 (let (res e)
20778 (while seq
20779 (setq e (pop seq))
20780 (if (not (funcall predicate e)) (push e res)))
20781 (nreverse res)))
20783 (defun org-remove-if-not (predicate seq)
20784 "Remove everything from SEQ that does not fulfill PREDICATE."
20785 (let (res e)
20786 (while seq
20787 (setq e (pop seq))
20788 (if (funcall predicate e) (push e res)))
20789 (nreverse res)))
20791 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20792 "Reduce two-argument FUNCTION across SEQ.
20793 Taken from `reduce' in cl-seq.el with all keyword arguments but
20794 \":initial-value\" removed."
20795 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20796 (cadr (memq :initial-value cl-keys)))
20797 (cl-seq (pop cl-seq))
20798 (t (funcall cl-func)))))
20799 (while cl-seq
20800 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20801 cl-accum))
20803 (defun org-back-over-empty-lines ()
20804 "Move backwards over whitespace, to the beginning of the first empty line.
20805 Returns the number of empty lines passed."
20806 (let ((pos (point)))
20807 (if (cdr (assoc 'heading org-blank-before-new-entry))
20808 (skip-chars-backward " \t\n\r")
20809 (unless (eobp)
20810 (forward-line -1)))
20811 (beginning-of-line 2)
20812 (goto-char (min (point) pos))
20813 (count-lines (point) pos)))
20815 (defun org-skip-whitespace ()
20816 (skip-chars-forward " \t\n\r"))
20818 (defun org-point-in-group (point group &optional context)
20819 "Check if POINT is in match-group GROUP.
20820 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20821 match. If the match group does not exist or point is not inside it,
20822 return nil."
20823 (and (match-beginning group)
20824 (>= point (match-beginning group))
20825 (<= point (match-end group))
20826 (if context
20827 (list context (match-beginning group) (match-end group))
20828 t)))
20830 (defun org-switch-to-buffer-other-window (&rest args)
20831 "Switch to buffer in a second window on the current frame.
20832 In particular, do not allow pop-up frames.
20833 Returns the newly created buffer."
20834 (let (pop-up-frames special-display-buffer-names special-display-regexps
20835 special-display-function)
20836 (apply 'switch-to-buffer-other-window args)))
20838 (defun org-combine-plists (&rest plists)
20839 "Create a single property list from all plists in PLISTS.
20840 The process starts by copying the first list, and then setting properties
20841 from the other lists. Settings in the last list are the most significant
20842 ones and overrule settings in the other lists."
20843 (let ((rtn (copy-sequence (pop plists)))
20844 p v ls)
20845 (while plists
20846 (setq ls (pop plists))
20847 (while ls
20848 (setq p (pop ls) v (pop ls))
20849 (setq rtn (plist-put rtn p v))))
20850 rtn))
20852 (defun org-replace-escapes (string table)
20853 "Replace %-escapes in STRING with values in TABLE.
20854 TABLE is an association list with keys like \"%a\" and string values.
20855 The sequences in STRING may contain normal field width and padding information,
20856 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20857 so values can contain further %-escapes if they are define later in TABLE."
20858 (let ((tbl (copy-alist table))
20859 (case-fold-search nil)
20860 (pchg 0)
20861 e re rpl)
20862 (while (setq e (pop tbl))
20863 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20864 (when (and (cdr e) (string-match re (cdr e)))
20865 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20866 (safe "SREF"))
20867 (add-text-properties 0 3 (list 'sref sref) safe)
20868 (setcdr e (replace-match safe t t (cdr e)))))
20869 (while (string-match re string)
20870 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20871 (cdr e)))
20872 (setq string (replace-match rpl t t string))))
20873 (while (setq pchg (next-property-change pchg string))
20874 (let ((sref (get-text-property pchg 'sref string)))
20875 (when (and sref (string-match "SREF" string pchg))
20876 (setq string (replace-match sref t t string)))))
20877 string))
20879 (defun org-sublist (list start end)
20880 "Return a section of LIST, from START to END.
20881 Counting starts at 1."
20882 (let (rtn (c start))
20883 (setq list (nthcdr (1- start) list))
20884 (while (and list (<= c end))
20885 (push (pop list) rtn)
20886 (setq c (1+ c)))
20887 (nreverse rtn)))
20889 (defun org-find-base-buffer-visiting (file)
20890 "Like `find-buffer-visiting' but always return the base buffer and
20891 not an indirect buffer."
20892 (let ((buf (or (get-file-buffer file)
20893 (find-buffer-visiting file))))
20894 (if buf
20895 (or (buffer-base-buffer buf) buf)
20896 nil)))
20898 (defun org-image-file-name-regexp (&optional extensions)
20899 "Return regexp matching the file names of images.
20900 If EXTENSIONS is given, only match these."
20901 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20902 (image-file-name-regexp)
20903 (let ((image-file-name-extensions
20904 (or extensions
20905 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20906 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20907 (concat "\\."
20908 (regexp-opt (nconc (mapcar 'upcase
20909 image-file-name-extensions)
20910 image-file-name-extensions)
20912 "\\'"))))
20914 (defun org-file-image-p (file &optional extensions)
20915 "Return non-nil if FILE is an image."
20916 (save-match-data
20917 (string-match (org-image-file-name-regexp extensions) file)))
20919 (defun org-get-cursor-date ()
20920 "Return the date at cursor in as a time.
20921 This works in the calendar and in the agenda, anywhere else it just
20922 returns the current time."
20923 (let (date day defd)
20924 (cond
20925 ((eq major-mode 'calendar-mode)
20926 (setq date (calendar-cursor-to-date)
20927 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20928 ((eq major-mode 'org-agenda-mode)
20929 (setq day (get-text-property (point) 'day))
20930 (if day
20931 (setq date (calendar-gregorian-from-absolute day)
20932 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20933 (nth 2 date))))))
20934 (or defd (current-time))))
20936 (defun org-mark-subtree (&optional up)
20937 "Mark the current subtree.
20938 This puts point at the start of the current subtree, and mark at
20939 the end. If a numeric prefix UP is given, move up into the
20940 hierarchy of headlines by UP levels before marking the subtree."
20941 (interactive "P")
20942 (org-with-limited-levels
20943 (cond ((org-at-heading-p) (beginning-of-line))
20944 ((org-before-first-heading-p) (error "Not in a subtree"))
20945 (t (outline-previous-visible-heading 1))))
20946 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20947 (if (org-called-interactively-p 'any)
20948 (call-interactively 'org-mark-element)
20949 (org-mark-element)))
20952 ;;; Macros
20954 ;; Macros are expanded with `org-macro-replace-all', which relies
20955 ;; internally on `org-macro-expand'.
20957 ;; Templates for expansion are stored in the buffer-local variable
20958 ;; `org-macro-templates'. This variable is updated by
20959 ;; `org-macro-initialize-templates'.
20962 (defvar org-macro-templates nil
20963 "Alist containing all macro templates in current buffer.
20964 Associations are in the shape of (NAME . TEMPLATE) where NAME
20965 stands for macro's name and template for its replacement value,
20966 both as strings. This is an internal variable. Do not set it
20967 directly, use instead:
20969 #+MACRO: name template")
20970 (make-variable-buffer-local 'org-macro-templates)
20972 (defun org-macro-expand (macro)
20973 "Return expanded MACRO, as a string.
20974 MACRO is an object, obtained, for example, with
20975 `org-element-context'. Return nil if no template was found."
20976 (let ((template
20977 (cdr (assoc-string (org-element-property :key macro)
20978 org-macro-templates
20979 ;; Macro names are case-insensitive.
20980 t))))
20981 (when template
20982 (let ((value (replace-regexp-in-string
20983 "\\$[0-9]+"
20984 (lambda (arg)
20985 (or (nth (1- (string-to-number (substring arg 1)))
20986 (org-element-property :args macro))
20987 ;; No argument provided: remove
20988 ;; place-holder.
20989 ""))
20990 template)))
20991 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20992 (when (string-match "\\`(eval\\>" value)
20993 (setq value (eval (read value))))
20994 ;; Return string.
20995 (format "%s" (or value ""))))))
20997 (defun org-macro-replace-all ()
20998 "Replace all macros in current buffer by their expansion."
20999 (save-excursion
21000 (goto-char (point-min))
21001 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21002 (let ((object (org-element-context)))
21003 (when (eq (org-element-type object) 'macro)
21004 (let ((value (org-macro-expand object)))
21005 (when value
21006 (delete-region
21007 (org-element-property :begin object)
21008 ;; Preserve white spaces after the macro.
21009 (progn (goto-char (org-element-property :end object))
21010 (skip-chars-backward " \t")
21011 (point)))
21012 ;; Leave point before replacement in case of recursive
21013 ;; expansions.
21014 (save-excursion (insert value)))))))))
21016 (defun org-macro-initialize-templates ()
21017 "Collect macro templates defined in current buffer.
21018 Templates are stored in buffer-local variable
21019 `org-macro-templates'. In addition to buffer-defined macros, the
21020 function installs the following ones: \"property\", \"date\",
21021 \"time\". and, if appropriate, \"input-file\" and
21022 \"modification-time\"."
21023 (let ((case-fold-search t)
21024 (set-template
21025 (lambda (cell)
21026 ;; Add CELL to `org-macro-templates' if there's no
21027 ;; association matching its name already. Otherwise,
21028 ;; replace old association with the new one in that
21029 ;; variable.
21030 (let ((old-template (assoc (car cell) org-macro-templates)))
21031 (if old-template (setcdr old-template (cdr cell))
21032 (push cell org-macro-templates))))))
21033 ;; Install buffer-local macros.
21034 (org-with-wide-buffer
21035 (goto-char (point-min))
21036 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21037 (let ((element (org-element-at-point)))
21038 (when (eq (org-element-type element) 'keyword)
21039 (let ((value (org-element-property :value element)))
21040 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21041 (funcall set-template
21042 (cons (match-string 1 value)
21043 (or (match-string 2 value) "")))))))))
21044 ;; Install hard-coded macros.
21045 (mapc (lambda (cell) (funcall set-template cell))
21046 (list
21047 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21048 (cons "date" "(eval (format-time-string \"$1\"))")
21049 (cons "time" "(eval (format-time-string \"$1\"))")))
21050 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21051 (when (and visited-file (file-exists-p visited-file))
21052 (mapc (lambda (cell) (funcall set-template cell))
21053 (list
21054 (cons "input-file" (file-name-nondirectory visited-file))
21055 (cons "modification-time"
21056 (format "(eval (format-time-string \"$1\" '%s))"
21057 (prin1-to-string
21058 (nth 5 (file-attributes visited-file)))))))))))
21061 ;;; Indentation
21063 (defun org-indent-line ()
21064 "Indent line depending on context."
21065 (interactive)
21066 (let* ((pos (point))
21067 (itemp (org-at-item-p))
21068 (case-fold-search t)
21069 (org-drawer-regexp (or org-drawer-regexp "\000"))
21070 (inline-task-p (and (featurep 'org-inlinetask)
21071 (org-inlinetask-in-task-p)))
21072 (inline-re (and inline-task-p
21073 (org-inlinetask-outline-regexp)))
21074 column)
21075 (if (and orgstruct-is-++ (eq pos (point)))
21076 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21077 (indent-according-to-mode))
21078 (beginning-of-line 1)
21079 (cond
21080 ;; Headings
21081 ((looking-at org-outline-regexp) (setq column 0))
21082 ;; Included files
21083 ((looking-at "#\\+include:") (setq column 0))
21084 ;; Footnote definition
21085 ((looking-at org-footnote-definition-re) (setq column 0))
21086 ;; Literal examples
21087 ((looking-at "[ \t]*:\\( \\|$\\)")
21088 (setq column (org-get-indentation))) ; do nothing
21089 ;; Lists
21090 ((ignore-errors (goto-char (org-in-item-p)))
21091 (setq column (if itemp
21092 (org-get-indentation)
21093 (org-list-item-body-column (point))))
21094 (goto-char pos))
21095 ;; Drawers
21096 ((and (looking-at "[ \t]*:END:")
21097 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21098 (save-excursion
21099 (goto-char (1- (match-beginning 1)))
21100 (setq column (current-column))))
21101 ;; Special blocks
21102 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21103 (save-excursion
21104 (re-search-backward
21105 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21106 (setq column (org-get-indentation (match-string 0))))
21107 ((and (not (looking-at "[ \t]*#\\+begin_"))
21108 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21109 (save-excursion
21110 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21111 (setq column
21112 (cond ((equal (downcase (match-string 1)) "src")
21113 ;; src blocks: let `org-edit-src-exit' handle them
21114 (org-get-indentation))
21115 ((equal (downcase (match-string 1)) "example")
21116 (max (org-get-indentation)
21117 (org-get-indentation (match-string 0))))
21119 (org-get-indentation (match-string 0))))))
21120 ;; This line has nothing special, look at the previous relevant
21121 ;; line to compute indentation
21123 (beginning-of-line 0)
21124 (while (and (not (bobp))
21125 (not (looking-at org-drawer-regexp))
21126 ;; When point started in an inline task, do not move
21127 ;; above task starting line.
21128 (not (and inline-task-p (looking-at inline-re)))
21129 ;; Skip drawers, blocks, empty lines, verbatim,
21130 ;; comments, tables, footnotes definitions, lists,
21131 ;; inline tasks.
21132 (or (and (looking-at "[ \t]*:END:")
21133 (re-search-backward org-drawer-regexp nil t))
21134 (and (looking-at "[ \t]*#\\+end_")
21135 (re-search-backward "[ \t]*#\\+begin_"nil t))
21136 (looking-at "[ \t]*[\n:#|]")
21137 (looking-at org-footnote-definition-re)
21138 (and (ignore-errors (goto-char (org-in-item-p)))
21139 (goto-char
21140 (org-list-get-top-point (org-list-struct))))
21141 (and (not inline-task-p)
21142 (featurep 'org-inlinetask)
21143 (org-inlinetask-in-task-p)
21144 (or (org-inlinetask-goto-beginning) t))))
21145 (beginning-of-line 0))
21146 (cond
21147 ;; There was an heading above.
21148 ((looking-at "\\*+[ \t]+")
21149 (if (not org-adapt-indentation)
21150 (setq column 0)
21151 (goto-char (match-end 0))
21152 (setq column (current-column))))
21153 ;; A drawer had started and is unfinished
21154 ((looking-at org-drawer-regexp)
21155 (goto-char (1- (match-beginning 1)))
21156 (setq column (current-column)))
21157 ;; Else, nothing noticeable found: get indentation and go on.
21158 (t (setq column (org-get-indentation))))))
21159 ;; Now apply indentation and move cursor accordingly
21160 (goto-char pos)
21161 (if (<= (current-column) (current-indentation))
21162 (org-indent-line-to column)
21163 (save-excursion (org-indent-line-to column)))
21164 ;; Special polishing for properties, see `org-property-format'
21165 (setq column (current-column))
21166 (beginning-of-line 1)
21167 (if (looking-at
21168 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21169 (replace-match (concat (match-string 1)
21170 (format org-property-format
21171 (match-string 2) (match-string 3)))
21172 t t))
21173 (org-move-to-column column))))
21175 (defun org-indent-drawer ()
21176 "Indent the drawer at point."
21177 (interactive)
21178 (let ((p (point))
21179 (e (and (save-excursion (re-search-forward ":END:" nil t))
21180 (match-end 0)))
21181 (folded
21182 (save-excursion
21183 (end-of-line)
21184 (when (overlays-at (point))
21185 (member 'invisible (overlay-properties
21186 (car (overlays-at (point)))))))))
21187 (when folded (org-cycle))
21188 (indent-for-tab-command)
21189 (while (and (move-beginning-of-line 2) (< (point) e))
21190 (indent-for-tab-command))
21191 (goto-char p)
21192 (when folded (org-cycle)))
21193 (message "Drawer at point indented"))
21195 (defun org-indent-block ()
21196 "Indent the block at point."
21197 (interactive)
21198 (let ((p (point))
21199 (case-fold-search t)
21200 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21201 (match-end 0)))
21202 (folded
21203 (save-excursion
21204 (end-of-line)
21205 (when (overlays-at (point))
21206 (member 'invisible (overlay-properties
21207 (car (overlays-at (point)))))))))
21208 (when folded (org-cycle))
21209 (indent-for-tab-command)
21210 (while (and (move-beginning-of-line 2) (< (point) e))
21211 (indent-for-tab-command))
21212 (goto-char p)
21213 (when folded (org-cycle)))
21214 (message "Block at point indented"))
21216 (defun org-indent-region (start end)
21217 "Indent region."
21218 (interactive "r")
21219 (save-excursion
21220 (let ((line-end (org-current-line end)))
21221 (goto-char start)
21222 (while (< (org-current-line) line-end)
21223 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21224 (t (call-interactively 'org-indent-line)))
21225 (move-beginning-of-line 2)))))
21228 ;;; Filling
21230 ;; We use our own fill-paragraph and auto-fill functions.
21232 ;; `org-fill-paragraph' relies on adaptive filling and context
21233 ;; checking. Appropriate `fill-prefix' is computed with
21234 ;; `org-adaptive-fill-function'.
21236 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21237 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21238 ;; `org-adaptive-fill-function' value. Internally,
21239 ;; `org-comment-line-break-function' breaks the line.
21241 ;; `org-setup-filling' installs filling and auto-filling related
21242 ;; variables during `org-mode' initialization.
21244 (defun org-setup-filling ()
21245 (interactive)
21246 ;; Prevent auto-fill from inserting unwanted new items.
21247 (when (boundp 'fill-nobreak-predicate)
21248 (org-set-local
21249 'fill-nobreak-predicate
21250 (org-uniquify
21251 (append fill-nobreak-predicate
21252 '(org-fill-paragraph-separate-nobreak-p
21253 org-fill-line-break-nobreak-p)))))
21254 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21255 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21256 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21257 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21259 (defvar org-element-paragraph-separate) ; org-element.el
21260 (defun org-fill-paragraph-separate-nobreak-p ()
21261 "Non-nil when a line break at point would insert a new item."
21262 (looking-at (substring org-element-paragraph-separate 1)))
21264 (defun org-fill-line-break-nobreak-p ()
21265 "Non-nil when a line break at point would create an Org line break."
21266 (save-excursion
21267 (skip-chars-backward "[ \t]")
21268 (skip-chars-backward "\\\\")
21269 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21271 (declare-function message-in-body-p "message" ())
21272 (defvar org-element--affiliated-re) ; From org-element.el
21273 (defun org-adaptive-fill-function ()
21274 "Compute a fill prefix for the current line.
21275 Return fill prefix, as a string, or nil if current line isn't
21276 meant to be filled."
21277 (org-with-wide-buffer
21278 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21279 ;; FIXME: This is really the job of orgstruct++-mode
21280 (let* ((p (line-beginning-position))
21281 (element (save-excursion (beginning-of-line)
21282 (org-element-at-point)))
21283 (type (org-element-type element))
21284 (post-affiliated
21285 (save-excursion
21286 (goto-char (org-element-property :begin element))
21287 (while (looking-at org-element--affiliated-re) (forward-line))
21288 (point))))
21289 (unless (< p post-affiliated)
21290 (case type
21291 (comment (looking-at "[ \t]*# ?") (match-string 0))
21292 (footnote-definition "")
21293 ((item plain-list)
21294 (make-string (org-list-item-body-column post-affiliated) ? ))
21295 (paragraph
21296 ;; Fill prefix is usually the same as the current line,
21297 ;; except if the paragraph is at the beginning of an item.
21298 (let ((parent (org-element-property :parent element)))
21299 (cond ((eq (org-element-type parent) 'item)
21300 (make-string (org-list-item-body-column
21301 (org-element-property :begin parent))
21302 ? ))
21303 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21304 (match-string 0))
21305 (t ""))))
21306 (comment-block
21307 ;; Only fill contents if P is within block boundaries.
21308 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21309 (forward-line)
21310 (point)))
21311 (cend (save-excursion
21312 (goto-char (org-element-property :end element))
21313 (skip-chars-backward " \r\t\n")
21314 (line-beginning-position))))
21315 (when (and (>= p cbeg) (< p cend))
21316 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21317 (match-string 0)
21318 ""))))))))))
21320 (declare-function message-goto-body "message" ())
21321 (defvar message-cite-prefix-regexp) ; From message.el
21322 (defvar org-element-all-objects) ; From org-element.el
21323 (defun org-fill-paragraph (&optional justify)
21324 "Fill element at point, when applicable.
21326 This function only applies to comment blocks, comments, example
21327 blocks and paragraphs. Also, as a special case, re-align table
21328 when point is at one.
21330 If JUSTIFY is non-nil (interactively, with prefix argument),
21331 justify as well. If `sentence-end-double-space' is non-nil, then
21332 period followed by one space does not end a sentence, so don't
21333 break a line there. The variable `fill-column' controls the
21334 width for filling.
21336 For convenience, when point is at a plain list, an item or
21337 a footnote definition, try to fill the first paragraph within."
21338 ;; Falls back on message-fill-paragraph when necessary
21339 (interactive)
21340 (if (and (derived-mode-p 'message-mode)
21341 (or (not (message-in-body-p))
21342 (save-excursion (move-beginning-of-line 1)
21343 (looking-at message-cite-prefix-regexp))))
21344 (let ((fill-paragraph-function
21345 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21346 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21347 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21348 (paragraph-separate
21349 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21350 (fill-paragraph nil))
21351 (save-excursion
21352 ;; Move to end of line in order to get the first paragraph
21353 ;; within a plain list or a footnote definition.
21354 (end-of-line)
21355 (let ((element (org-element-at-point)))
21356 ;; First check if point is in a blank line at the beginning of
21357 ;; the buffer. In that case, ignore filling.
21358 (if (< (point) (org-element-property :begin element)) t
21359 (case (org-element-type element)
21360 ;; Align Org tables, leave table.el tables as-is.
21361 (table-row (org-table-align) t)
21362 (table
21363 (when (eq (org-element-property :type element) 'org)
21364 (org-table-align))
21366 (paragraph
21367 ;; Paragraphs may contain `line-break' type objects.
21368 (let ((beg (max (point-min)
21369 (org-element-property :contents-begin element)))
21370 (end (min (point-max)
21371 (org-element-property :contents-end element))))
21372 ;; Do nothing if point is at an affiliated keyword.
21373 (if (< (point) beg) t
21374 (when (derived-mode-p 'message-mode)
21375 ;; In `message-mode', do not fill following
21376 ;; citation in current paragraph nor text before
21377 ;; message body.
21378 (let ((body-start (save-excursion (message-goto-body))))
21379 (when body-start (setq beg (max body-start beg))))
21380 (when (save-excursion
21381 (re-search-forward
21382 (concat "^" message-cite-prefix-regexp) end t))
21383 (setq end (match-beginning 0))))
21384 ;; Fill paragraph, taking line breaks into
21385 ;; consideration. For that, slice the paragraph
21386 ;; using line breaks as separators, and fill the
21387 ;; parts in reverse order to avoid messing with
21388 ;; markers.
21389 (save-excursion
21390 (goto-char end)
21391 (mapc
21392 (lambda (pos)
21393 (fill-region-as-paragraph pos (point) justify)
21394 (goto-char pos))
21395 ;; Find the list of ending positions for line
21396 ;; breaks in the current paragraph. Add paragraph
21397 ;; beginning to include first slice.
21398 (nreverse
21399 (cons
21401 (org-element-map
21402 (org-element--parse-objects
21403 beg end nil org-element-all-objects)
21404 'line-break
21405 (lambda (lb) (org-element-property :end lb)))))))
21406 t)))
21407 ;; Contents of `comment-block' type elements should be
21408 ;; filled as plain text, but only if point is within block
21409 ;; markers.
21410 (comment-block
21411 (let* ((case-fold-search t)
21412 (beg (save-excursion
21413 (goto-char (org-element-property :begin element))
21414 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21415 (forward-line)
21416 (point)))
21417 (end (save-excursion
21418 (goto-char (org-element-property :end element))
21419 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21420 (line-beginning-position))))
21421 (when (and (>= (point) beg) (< (point) end))
21422 (fill-region-as-paragraph
21423 (save-excursion
21424 (end-of-line)
21425 (re-search-backward "^[ \t]*$" beg 'move)
21426 (line-beginning-position))
21427 (save-excursion
21428 (beginning-of-line)
21429 (re-search-forward "^[ \t]*$" end 'move)
21430 (line-beginning-position))
21431 justify)))
21433 ;; Fill comments.
21434 (comment (fill-comment-paragraph justify))
21435 ;; Ignore every other element.
21436 (otherwise t)))))))
21438 (defun org-auto-fill-function ()
21439 "Auto-fill function."
21440 ;; Check if auto-filling is meaningful.
21441 (let ((fc (current-fill-column)))
21442 (when (and fc (> (current-column) fc))
21443 (let ((fill-prefix (org-adaptive-fill-function)))
21444 (when fill-prefix (do-auto-fill))))))
21446 (defun org-comment-line-break-function (&optional soft)
21447 "Break line at point and indent, continuing comment if within one.
21448 The inserted newline is marked hard if variable
21449 `use-hard-newlines' is true, unless optional argument SOFT is
21450 non-nil."
21451 (if soft (insert-and-inherit ?\n) (newline 1))
21452 (save-excursion (forward-char -1) (delete-horizontal-space))
21453 (delete-horizontal-space)
21454 (indent-to-left-margin)
21455 (insert-before-markers-and-inherit fill-prefix))
21458 ;;; Comments
21460 ;; Org comments syntax is quite complex. It requires the entire line
21461 ;; to be just a comment. Also, even with the right syntax at the
21462 ;; beginning of line, some some elements (i.e. verse-block or
21463 ;; example-block) don't accept comments. Usual Emacs comment commands
21464 ;; cannot cope with those requirements. Therefore, Org replaces them.
21466 ;; Org still relies on `comment-dwim', but cannot trust
21467 ;; `comment-only-p'. So, `comment-region-function' and
21468 ;; `uncomment-region-function' both point
21469 ;; to`org-comment-or-uncomment-region'. Eventually,
21470 ;; `org-insert-comment' takes care of insertion of comments at the
21471 ;; beginning of line.
21473 ;; `org-setup-comments-handling' install comments related variables
21474 ;; during `org-mode' initialization.
21476 (defun org-setup-comments-handling ()
21477 (interactive)
21478 (org-set-local 'comment-use-syntax nil)
21479 (org-set-local 'comment-start "# ")
21480 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21481 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21482 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21483 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21485 (defun org-insert-comment ()
21486 "Insert an empty comment above current line.
21487 If the line is empty, insert comment at its beginning."
21488 (beginning-of-line)
21489 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21490 (org-indent-line)
21491 (insert "# "))
21493 (defvar comment-empty-lines) ; From newcomment.el.
21494 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21495 "Comment or uncomment each non-blank line in the region.
21496 Uncomment each non-blank line between BEG and END if it only
21497 contains commented lines. Otherwise, comment them."
21498 (save-restriction
21499 ;; Restrict region
21500 (narrow-to-region (save-excursion (goto-char beg)
21501 (skip-chars-forward " \r\t\n" end)
21502 (line-beginning-position))
21503 (save-excursion (goto-char end)
21504 (skip-chars-backward " \r\t\n" beg)
21505 (line-end-position)))
21506 (let ((uncommentp
21507 ;; UNCOMMENTP is non-nil when every non blank line between
21508 ;; BEG and END is a comment.
21509 (save-excursion
21510 (goto-char (point-min))
21511 (while (and (not (eobp))
21512 (let ((element (org-element-at-point)))
21513 (and (eq (org-element-type element) 'comment)
21514 (goto-char (min (point-max)
21515 (org-element-property
21516 :end element)))))))
21517 (eobp))))
21518 (if uncommentp
21519 ;; Only blank lines and comments in region: uncomment it.
21520 (save-excursion
21521 (goto-char (point-min))
21522 (while (not (eobp))
21523 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21524 (replace-match "" nil nil nil 1))
21525 (forward-line)))
21526 ;; Comment each line in region.
21527 (let ((min-indent (point-max)))
21528 ;; First find the minimum indentation across all lines.
21529 (save-excursion
21530 (goto-char (point-min))
21531 (while (and (not (eobp)) (not (zerop min-indent)))
21532 (unless (looking-at "[ \t]*$")
21533 (setq min-indent (min min-indent (current-indentation))))
21534 (forward-line)))
21535 ;; Then loop over all lines.
21536 (save-excursion
21537 (goto-char (point-min))
21538 (while (not (eobp))
21539 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21540 (org-move-to-column min-indent t)
21541 (insert comment-start))
21542 (forward-line))))))))
21545 ;;; Other stuff.
21547 (defun org-toggle-fixed-width-section (arg)
21548 "Toggle the fixed-width export.
21549 If there is no active region, the QUOTE keyword at the current headline is
21550 inserted or removed. When present, it causes the text between this headline
21551 and the next to be exported as fixed-width text, and unmodified.
21552 If there is an active region, this command adds or removes a colon as the
21553 first character of this line. If the first character of a line is a colon,
21554 this line is also exported in fixed-width font."
21555 (interactive "P")
21556 (let* ((cc 0)
21557 (regionp (org-region-active-p))
21558 (beg (if regionp (region-beginning) (point)))
21559 (end (if regionp (region-end)))
21560 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21561 (case-fold-search nil)
21562 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21563 off)
21564 (if regionp
21565 (save-excursion
21566 (goto-char beg)
21567 (setq cc (current-column))
21568 (beginning-of-line 1)
21569 (setq off (looking-at re))
21570 (while (> nlines 0)
21571 (setq nlines (1- nlines))
21572 (beginning-of-line 1)
21573 (cond
21574 (arg
21575 (org-move-to-column cc t)
21576 (insert ": \n")
21577 (forward-line -1))
21578 ((and off (looking-at re))
21579 (replace-match "" t t nil 1))
21580 ((not off) (org-move-to-column cc t) (insert ": ")))
21581 (forward-line 1)))
21582 (save-excursion
21583 (org-back-to-heading)
21584 (cond
21585 ((looking-at (format org-heading-keyword-regexp-format
21586 org-quote-string))
21587 (goto-char (match-end 1))
21588 (looking-at (concat " +" org-quote-string))
21589 (replace-match "" t t)
21590 (when (eolp) (insert " ")))
21591 ((looking-at org-outline-regexp)
21592 (goto-char (match-end 0))
21593 (insert org-quote-string " ")))))))
21595 (defun org-reftex-citation ()
21596 "Use reftex-citation to insert a citation into the buffer.
21597 This looks for a line like
21599 #+BIBLIOGRAPHY: foo plain option:-d
21601 and derives from it that foo.bib is the bibliography file relevant
21602 for this document. It then installs the necessary environment for RefTeX
21603 to work in this buffer and calls `reftex-citation' to insert a citation
21604 into the buffer.
21606 Export of such citations to both LaTeX and HTML is handled by the contributed
21607 package org-exp-bibtex by Taru Karttunen."
21608 (interactive)
21609 (let ((reftex-docstruct-symbol 'rds)
21610 (reftex-cite-format "\\cite{%l}")
21611 rds bib)
21612 (save-excursion
21613 (save-restriction
21614 (widen)
21615 (let ((case-fold-search t)
21616 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21617 (if (not (save-excursion
21618 (or (re-search-forward re nil t)
21619 (re-search-backward re nil t))))
21620 (error "No bibliography defined in file")
21621 (setq bib (concat (match-string 1) ".bib")
21622 rds (list (list 'bib bib)))))))
21623 (call-interactively 'reftex-citation)))
21625 ;;;; Functions extending outline functionality
21627 (defun org-beginning-of-line (&optional arg)
21628 "Go to the beginning of the current line. If that is invisible, continue
21629 to a visible line beginning. This makes the function of C-a more intuitive.
21630 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21631 first attempt, and only move to after the tags when the cursor is already
21632 beyond the end of the headline."
21633 (interactive "P")
21634 (let ((pos (point))
21635 (special (if (consp org-special-ctrl-a/e)
21636 (car org-special-ctrl-a/e)
21637 org-special-ctrl-a/e))
21638 refpos)
21639 (if (org-bound-and-true-p line-move-visual)
21640 (beginning-of-visual-line 1)
21641 (beginning-of-line 1))
21642 (if (and arg (fboundp 'move-beginning-of-line))
21643 (call-interactively 'move-beginning-of-line)
21644 (if (bobp)
21646 (backward-char 1)
21647 (if (org-truely-invisible-p)
21648 (while (and (not (bobp)) (org-truely-invisible-p))
21649 (backward-char 1)
21650 (beginning-of-line 1))
21651 (forward-char 1))))
21652 (when special
21653 (cond
21654 ((and (looking-at org-complex-heading-regexp)
21655 (= (char-after (match-end 1)) ?\ ))
21656 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21657 (point-at-eol)))
21658 (goto-char
21659 (if (eq special t)
21660 (cond ((> pos refpos) refpos)
21661 ((= pos (point)) refpos)
21662 (t (point)))
21663 (cond ((> pos (point)) (point))
21664 ((not (eq last-command this-command)) (point))
21665 (t refpos)))))
21666 ((org-at-item-p)
21667 ;; Being at an item and not looking at an the item means point
21668 ;; was previously moved to beginning of a visual line, which
21669 ;; doesn't contain the item. Therefore, do nothing special,
21670 ;; just stay here.
21671 (when (looking-at org-list-full-item-re)
21672 ;; Set special position at first white space character after
21673 ;; bullet, and check-box, if any.
21674 (let ((after-bullet
21675 (let ((box (match-end 3)))
21676 (if (not box) (match-end 1)
21677 (let ((after (char-after box)))
21678 (if (and after (= after ? )) (1+ box) box))))))
21679 ;; Special case: Move point to special position when
21680 ;; currently after it or at beginning of line.
21681 (if (eq special t)
21682 (when (or (> pos after-bullet) (= (point) pos))
21683 (goto-char after-bullet))
21684 ;; Reversed case: Move point to special position when
21685 ;; point was already at beginning of line and command is
21686 ;; repeated.
21687 (when (and (= (point) pos) (eq last-command this-command))
21688 (goto-char after-bullet))))))))
21689 (org-no-warnings
21690 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21692 (defun org-end-of-line (&optional arg)
21693 "Go to the end of the line.
21694 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21695 first attempt, and only move to after the tags when the cursor is already
21696 beyond the end of the headline."
21697 (interactive "P")
21698 (let ((special (if (consp org-special-ctrl-a/e)
21699 (cdr org-special-ctrl-a/e)
21700 org-special-ctrl-a/e)))
21701 (cond
21702 ((or (not special) arg
21703 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21704 (call-interactively
21705 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21706 ((fboundp 'move-end-of-line) 'move-end-of-line)
21707 (t 'end-of-line))))
21708 ((org-at-heading-p)
21709 (let ((pos (point)))
21710 (beginning-of-line 1)
21711 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21712 (if (eq special t)
21713 (if (or (< pos (match-beginning 1))
21714 (= pos (match-end 0)))
21715 (goto-char (match-beginning 1))
21716 (goto-char (match-end 0)))
21717 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21718 (goto-char (match-end 0))
21719 (goto-char (match-beginning 1))))
21720 (call-interactively (if (fboundp 'move-end-of-line)
21721 'move-end-of-line
21722 'end-of-line)))))
21723 ((org-at-drawer-p)
21724 (move-end-of-line 1)
21725 (when (overlays-at (1- (point))) (backward-char 1)))
21726 ;; At an item: Move before any hidden text.
21727 (t (call-interactively
21728 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21729 ((fboundp 'move-end-of-line) 'move-end-of-line)
21730 (t 'end-of-line)))))
21731 (org-no-warnings
21732 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21734 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21735 (define-key org-mode-map "\C-e" 'org-end-of-line)
21737 (defun org-backward-sentence (&optional arg)
21738 "Go to beginning of sentence, or beginning of table field.
21739 This will call `backward-sentence' or `org-table-beginning-of-field',
21740 depending on context."
21741 (interactive "P")
21742 (cond
21743 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21744 (t (call-interactively 'backward-sentence))))
21746 (defun org-forward-sentence (&optional arg)
21747 "Go to end of sentence, or end of table field.
21748 This will call `forward-sentence' or `org-table-end-of-field',
21749 depending on context."
21750 (interactive "P")
21751 (cond
21752 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21753 (t (call-interactively 'forward-sentence))))
21755 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21756 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21758 (defun org-kill-line (&optional arg)
21759 "Kill line, to tags or end of line."
21760 (interactive "P")
21761 (cond
21762 ((or (not org-special-ctrl-k)
21763 (bolp)
21764 (not (org-at-heading-p)))
21765 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21766 org-ctrl-k-protect-subtree)
21767 (if (or (eq org-ctrl-k-protect-subtree 'error)
21768 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21769 (error "C-k aborted - would kill hidden subtree")))
21770 (call-interactively
21771 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21772 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21773 (kill-region (point) (match-beginning 1))
21774 (org-set-tags nil t))
21775 (t (kill-region (point) (point-at-eol)))))
21777 (define-key org-mode-map "\C-k" 'org-kill-line)
21779 (defun org-yank (&optional arg)
21780 "Yank. If the kill is a subtree, treat it specially.
21781 This command will look at the current kill and check if is a single
21782 subtree, or a series of subtrees[1]. If it passes the test, and if the
21783 cursor is at the beginning of a line or after the stars of a currently
21784 empty headline, then the yank is handled specially. How exactly depends
21785 on the value of the following variables, both set by default.
21787 org-yank-folded-subtrees
21788 When set, the subtree(s) will be folded after insertion, but only
21789 if doing so would now swallow text after the yanked text.
21791 org-yank-adjusted-subtrees
21792 When set, the subtree will be promoted or demoted in order to
21793 fit into the local outline tree structure, which means that the level
21794 will be adjusted so that it becomes the smaller one of the two
21795 *visible* surrounding headings.
21797 Any prefix to this command will cause `yank' to be called directly with
21798 no special treatment. In particular, a simple \\[universal-argument] prefix \
21799 will just
21800 plainly yank the text as it is.
21802 \[1] The test checks if the first non-white line is a heading
21803 and if there are no other headings with fewer stars."
21804 (interactive "P")
21805 (org-yank-generic 'yank arg))
21807 (defun org-yank-generic (command arg)
21808 "Perform some yank-like command.
21810 This function implements the behavior described in the `org-yank'
21811 documentation. However, it has been generalized to work for any
21812 interactive command with similar behavior."
21814 ;; pretend to be command COMMAND
21815 (setq this-command command)
21817 (if arg
21818 (call-interactively command)
21820 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21821 (and (org-kill-is-subtree-p)
21822 (or (bolp)
21823 (and (looking-at "[ \t]*$")
21824 (string-match
21825 "\\`\\*+\\'"
21826 (buffer-substring (point-at-bol) (point)))))))
21827 swallowp)
21828 (cond
21829 ((and subtreep org-yank-folded-subtrees)
21830 (let ((beg (point))
21831 end)
21832 (if (and subtreep org-yank-adjusted-subtrees)
21833 (org-paste-subtree nil nil 'for-yank)
21834 (call-interactively command))
21836 (setq end (point))
21837 (goto-char beg)
21838 (when (and (bolp) subtreep
21839 (not (setq swallowp
21840 (org-yank-folding-would-swallow-text beg end))))
21841 (org-with-limited-levels
21842 (or (looking-at org-outline-regexp)
21843 (re-search-forward org-outline-regexp-bol end t))
21844 (while (and (< (point) end) (looking-at org-outline-regexp))
21845 (hide-subtree)
21846 (org-cycle-show-empty-lines 'folded)
21847 (condition-case nil
21848 (outline-forward-same-level 1)
21849 (error (goto-char end))))))
21850 (when swallowp
21851 (message
21852 "Inserted text not folded because that would swallow text"))
21854 (goto-char end)
21855 (skip-chars-forward " \t\n\r")
21856 (beginning-of-line 1)
21857 (push-mark beg 'nomsg)))
21858 ((and subtreep org-yank-adjusted-subtrees)
21859 (let ((beg (point-at-bol)))
21860 (org-paste-subtree nil nil 'for-yank)
21861 (push-mark beg 'nomsg)))
21863 (call-interactively command))))))
21865 (defun org-yank-folding-would-swallow-text (beg end)
21866 "Would hide-subtree at BEG swallow any text after END?"
21867 (let (level)
21868 (org-with-limited-levels
21869 (save-excursion
21870 (goto-char beg)
21871 (when (or (looking-at org-outline-regexp)
21872 (re-search-forward org-outline-regexp-bol end t))
21873 (setq level (org-outline-level)))
21874 (goto-char end)
21875 (skip-chars-forward " \t\r\n\v\f")
21876 (if (or (eobp)
21877 (and (bolp) (looking-at org-outline-regexp)
21878 (<= (org-outline-level) level)))
21879 nil ; Nothing would be swallowed
21880 t))))) ; something would swallow
21882 (define-key org-mode-map "\C-y" 'org-yank)
21884 (defun org-truely-invisible-p ()
21885 "Check if point is at a character currently not visible.
21886 This version does not only check the character property, but also
21887 `visible-mode'."
21888 ;; Early versions of noutline don't have `outline-invisible-p'.
21889 (if (org-bound-and-true-p visible-mode)
21891 (outline-invisible-p)))
21893 (defun org-invisible-p2 ()
21894 "Check if point is at a character currently not visible."
21895 (save-excursion
21896 (if (and (eolp) (not (bobp))) (backward-char 1))
21897 ;; Early versions of noutline don't have `outline-invisible-p'.
21898 (outline-invisible-p)))
21900 (defun org-back-to-heading (&optional invisible-ok)
21901 "Call `outline-back-to-heading', but provide a better error message."
21902 (condition-case nil
21903 (outline-back-to-heading invisible-ok)
21904 (error (error "Before first headline at position %d in buffer %s"
21905 (point) (current-buffer)))))
21907 (defun org-before-first-heading-p ()
21908 "Before first heading?"
21909 (save-excursion
21910 (end-of-line)
21911 (null (re-search-backward org-outline-regexp-bol nil t))))
21913 (defun org-at-heading-p (&optional ignored)
21914 (outline-on-heading-p t))
21915 ;; Compatibility alias with Org versions < 7.8.03
21916 (defalias 'org-on-heading-p 'org-at-heading-p)
21918 (defun org-at-comment-p nil
21919 "Is cursor in a line starting with a # character?"
21920 (save-excursion
21921 (beginning-of-line)
21922 (looking-at "^#")))
21924 (defun org-at-drawer-p nil
21925 "Is cursor at a drawer keyword?"
21926 (save-excursion
21927 (move-beginning-of-line 1)
21928 (looking-at org-drawer-regexp)))
21930 (defun org-at-block-p nil
21931 "Is cursor at a block keyword?"
21932 (save-excursion
21933 (move-beginning-of-line 1)
21934 (looking-at org-block-regexp)))
21936 (defun org-point-at-end-of-empty-headline ()
21937 "If point is at the end of an empty headline, return t, else nil.
21938 If the heading only contains a TODO keyword, it is still still considered
21939 empty."
21940 (and (looking-at "[ \t]*$")
21941 (when org-todo-line-regexp
21942 (save-excursion
21943 (beginning-of-line 1)
21944 (let ((case-fold-search nil))
21945 (looking-at org-todo-line-regexp)
21946 (string= (match-string 3) ""))))))
21948 (defun org-at-heading-or-item-p ()
21949 (or (org-at-heading-p) (org-at-item-p)))
21951 (defun org-at-target-p ()
21952 (or (org-in-regexp org-radio-target-regexp)
21953 (org-in-regexp org-target-regexp)))
21954 ;; Compatibility alias with Org versions < 7.8.03
21955 (defalias 'org-on-target-p 'org-at-target-p)
21957 (defun org-up-heading-all (arg)
21958 "Move to the heading line of which the present line is a subheading.
21959 This function considers both visible and invisible heading lines.
21960 With argument, move up ARG levels."
21961 (if (fboundp 'outline-up-heading-all)
21962 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21963 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21965 (defun org-up-heading-safe ()
21966 "Move to the heading line of which the present line is a subheading.
21967 This version will not throw an error. It will return the level of the
21968 headline found, or nil if no higher level is found.
21970 Also, this function will be a lot faster than `outline-up-heading',
21971 because it relies on stars being the outline starters. This can really
21972 make a significant difference in outlines with very many siblings."
21973 (let (start-level re)
21974 (org-back-to-heading t)
21975 (setq start-level (funcall outline-level))
21976 (if (equal start-level 1)
21978 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21979 (if (re-search-backward re nil t)
21980 (funcall outline-level)))))
21982 (defun org-first-sibling-p ()
21983 "Is this heading the first child of its parents?"
21984 (interactive)
21985 (let ((re org-outline-regexp-bol)
21986 level l)
21987 (unless (org-at-heading-p t)
21988 (error "Not at a heading"))
21989 (setq level (funcall outline-level))
21990 (save-excursion
21991 (if (not (re-search-backward re nil t))
21993 (setq l (funcall outline-level))
21994 (< l level)))))
21996 (defun org-goto-sibling (&optional previous)
21997 "Goto the next sibling, even if it is invisible.
21998 When PREVIOUS is set, go to the previous sibling instead. Returns t
21999 when a sibling was found. When none is found, return nil and don't
22000 move point."
22001 (let ((fun (if previous 're-search-backward 're-search-forward))
22002 (pos (point))
22003 (re org-outline-regexp-bol)
22004 level l)
22005 (when (condition-case nil (org-back-to-heading t) (error nil))
22006 (setq level (funcall outline-level))
22007 (catch 'exit
22008 (or previous (forward-char 1))
22009 (while (funcall fun re nil t)
22010 (setq l (funcall outline-level))
22011 (when (< l level) (goto-char pos) (throw 'exit nil))
22012 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22013 (goto-char pos)
22014 nil))))
22016 (defun org-show-siblings ()
22017 "Show all siblings of the current headline."
22018 (save-excursion
22019 (while (org-goto-sibling) (org-flag-heading nil)))
22020 (save-excursion
22021 (while (org-goto-sibling 'previous)
22022 (org-flag-heading nil))))
22024 (defun org-goto-first-child ()
22025 "Goto the first child, even if it is invisible.
22026 Return t when a child was found. Otherwise don't move point and
22027 return nil."
22028 (let (level (pos (point)) (re org-outline-regexp-bol))
22029 (when (condition-case nil (org-back-to-heading t) (error nil))
22030 (setq level (outline-level))
22031 (forward-char 1)
22032 (if (and (re-search-forward re nil t) (> (outline-level) level))
22033 (progn (goto-char (match-beginning 0)) t)
22034 (goto-char pos) nil))))
22036 (defun org-show-hidden-entry ()
22037 "Show an entry where even the heading is hidden."
22038 (save-excursion
22039 (org-show-entry)))
22041 (defun org-flag-heading (flag &optional entry)
22042 "Flag the current heading. FLAG non-nil means make invisible.
22043 When ENTRY is non-nil, show the entire entry."
22044 (save-excursion
22045 (org-back-to-heading t)
22046 ;; Check if we should show the entire entry
22047 (if entry
22048 (progn
22049 (org-show-entry)
22050 (save-excursion
22051 (and (outline-next-heading)
22052 (org-flag-heading nil))))
22053 (outline-flag-region (max (point-min) (1- (point)))
22054 (save-excursion (outline-end-of-heading) (point))
22055 flag))))
22057 (defun org-get-next-sibling ()
22058 "Move to next heading of the same level, and return point.
22059 If there is no such heading, return nil.
22060 This is like outline-next-sibling, but invisible headings are ok."
22061 (let ((level (funcall outline-level)))
22062 (outline-next-heading)
22063 (while (and (not (eobp)) (> (funcall outline-level) level))
22064 (outline-next-heading))
22065 (if (or (eobp) (< (funcall outline-level) level))
22067 (point))))
22069 (defun org-get-last-sibling ()
22070 "Move to previous heading of the same level, and return point.
22071 If there is no such heading, return nil."
22072 (let ((opoint (point))
22073 (level (funcall outline-level)))
22074 (outline-previous-heading)
22075 (when (and (/= (point) opoint) (outline-on-heading-p t))
22076 (while (and (> (funcall outline-level) level)
22077 (not (bobp)))
22078 (outline-previous-heading))
22079 (if (< (funcall outline-level) level)
22081 (point)))))
22083 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22084 "Goto to the end of a subtree."
22085 ;; This contains an exact copy of the original function, but it uses
22086 ;; `org-back-to-heading', to make it work also in invisible
22087 ;; trees. And is uses an invisible-ok argument.
22088 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22089 ;; Furthermore, when used inside Org, finding the end of a large subtree
22090 ;; with many children and grandchildren etc, this can be much faster
22091 ;; than the outline version.
22092 (org-back-to-heading invisible-ok)
22093 (let ((first t)
22094 (level (funcall outline-level)))
22095 (if (and (derived-mode-p 'org-mode) (< level 1000))
22096 ;; A true heading (not a plain list item), in Org-mode
22097 ;; This means we can easily find the end by looking
22098 ;; only for the right number of stars. Using a regexp to do
22099 ;; this is so much faster than using a Lisp loop.
22100 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22101 (forward-char 1)
22102 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22103 ;; something else, do it the slow way
22104 (while (and (not (eobp))
22105 (or first (> (funcall outline-level) level)))
22106 (setq first nil)
22107 (outline-next-heading)))
22108 (unless to-heading
22109 (if (memq (preceding-char) '(?\n ?\^M))
22110 (progn
22111 ;; Go to end of line before heading
22112 (forward-char -1)
22113 (if (memq (preceding-char) '(?\n ?\^M))
22114 ;; leave blank line before heading
22115 (forward-char -1))))))
22116 (point))
22118 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22119 "Use Org version in org-mode, for dramatic speed-up."
22120 (if (derived-mode-p 'org-mode)
22121 (progn
22122 (org-end-of-subtree nil t)
22123 (unless (eobp) (backward-char 1)))
22124 ad-do-it))
22126 (defun org-end-of-meta-data-and-drawers ()
22127 "Jump to the first text after meta data and drawers in the current entry.
22128 This will move over empty lines, lines with planning time stamps,
22129 clocking lines, and drawers."
22130 (org-back-to-heading t)
22131 (let ((end (save-excursion (outline-next-heading) (point)))
22132 (re (concat "\\(" org-drawer-regexp "\\)"
22133 "\\|" "[ \t]*" org-keyword-time-regexp)))
22134 (forward-line 1)
22135 (while (re-search-forward re end t)
22136 (if (not (match-end 1))
22137 ;; empty or planning line
22138 (forward-line 1)
22139 ;; a drawer, find the end
22140 (re-search-forward "^[ \t]*:END:" end 'move)
22141 (forward-line 1)))
22142 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22143 (point)))
22145 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22146 "Move forward to the arg'th subheading at same level as this one.
22147 Stop at the first and last subheadings of a superior heading.
22148 Normally this only looks at visible headings, but when INVISIBLE-OK is
22149 non-nil it will also look at invisible ones."
22150 (interactive "p")
22151 (org-back-to-heading invisible-ok)
22152 (org-at-heading-p)
22153 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22154 (re (format "^\\*\\{1,%d\\} " level))
22156 (forward-char 1)
22157 (while (> arg 0)
22158 (while (and (re-search-forward re nil 'move)
22159 (setq l (- (match-end 0) (match-beginning 0) 1))
22160 (= l level)
22161 (not invisible-ok)
22162 (progn (backward-char 1) (outline-invisible-p)))
22163 (if (< l level) (setq arg 1)))
22164 (setq arg (1- arg)))
22165 (beginning-of-line 1)))
22167 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22168 "Move backward to the arg'th subheading at same level as this one.
22169 Stop at the first and last subheadings of a superior heading."
22170 (interactive "p")
22171 (org-back-to-heading)
22172 (org-at-heading-p)
22173 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22174 (re (format "^\\*\\{1,%d\\} " level))
22176 (while (> arg 0)
22177 (while (and (re-search-backward re nil 'move)
22178 (setq l (- (match-end 0) (match-beginning 0) 1))
22179 (= l level)
22180 (not invisible-ok)
22181 (outline-invisible-p))
22182 (if (< l level) (setq arg 1)))
22183 (setq arg (1- arg)))))
22185 ;;;###autoload
22186 (defun org-forward-element ()
22187 "Move forward by one element.
22188 Move to the next element at the same level, when possible."
22189 (interactive)
22190 (cond ((eobp) (error "Cannot move further down"))
22191 ((org-with-limited-levels (org-at-heading-p))
22192 (let ((origin (point)))
22193 (org-forward-heading-same-level 1)
22194 (unless (org-with-limited-levels (org-at-heading-p))
22195 (goto-char origin)
22196 (error "Cannot move further down"))))
22198 (let* ((elem (org-element-at-point))
22199 (end (org-element-property :end elem))
22200 (parent (org-element-property :parent elem)))
22201 (if (and parent (= (org-element-property :contents-end parent) end))
22202 (goto-char (org-element-property :end parent))
22203 (goto-char end))))))
22205 ;;;###autoload
22206 (defun org-backward-element ()
22207 "Move backward by one element.
22208 Move to the previous element at the same level, when possible."
22209 (interactive)
22210 (cond ((bobp) (error "Cannot move further up"))
22211 ((org-with-limited-levels (org-at-heading-p))
22212 ;; At an headline, move to the previous one, if any, or stay
22213 ;; here.
22214 (let ((origin (point)))
22215 (org-backward-heading-same-level 1)
22216 (unless (org-with-limited-levels (org-at-heading-p))
22217 (goto-char origin)
22218 (error "Cannot move further up"))))
22220 (let* ((trail (org-element-at-point 'keep-trail))
22221 (elem (car trail))
22222 (prev-elem (nth 1 trail))
22223 (beg (org-element-property :begin elem)))
22224 (cond
22225 ;; Move to beginning of current element if point isn't
22226 ;; there already.
22227 ((/= (point) beg) (goto-char beg))
22228 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22229 ((org-before-first-heading-p) (goto-char (point-min)))
22230 (t (org-back-to-heading)))))))
22232 ;;;###autoload
22233 (defun org-up-element ()
22234 "Move to upper element."
22235 (interactive)
22236 (if (org-with-limited-levels (org-at-heading-p))
22237 (unless (org-up-heading-safe) (error "No surrounding element"))
22238 (let* ((elem (org-element-at-point))
22239 (parent (org-element-property :parent elem)))
22240 (if parent (goto-char (org-element-property :begin parent))
22241 (if (org-with-limited-levels (org-before-first-heading-p))
22242 (error "No surrounding element")
22243 (org-with-limited-levels (org-back-to-heading)))))))
22245 ;;;###autoload
22246 (defvar org-element-greater-elements)
22247 (defun org-down-element ()
22248 "Move to inner element."
22249 (interactive)
22250 (let ((element (org-element-at-point)))
22251 (cond
22252 ((memq (org-element-type element) '(plain-list table))
22253 (goto-char (org-element-property :contents-begin element))
22254 (forward-char))
22255 ((memq (org-element-type element) org-element-greater-elements)
22256 ;; If contents are hidden, first disclose them.
22257 (when (org-element-property :hiddenp element) (org-cycle))
22258 (goto-char (or (org-element-property :contents-begin element)
22259 (error "No content for this element"))))
22260 (t (error "No inner element")))))
22262 ;;;###autoload
22263 (defun org-drag-element-backward ()
22264 "Move backward element at point."
22265 (interactive)
22266 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22267 (let* ((trail (org-element-at-point 'keep-trail))
22268 (elem (car trail))
22269 (prev-elem (nth 1 trail)))
22270 ;; Error out if no previous element or previous element is
22271 ;; a parent of the current one.
22272 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22273 (error "Cannot drag element backward")
22274 (let ((pos (point)))
22275 (org-element-swap-A-B prev-elem elem)
22276 (goto-char (+ (org-element-property :begin prev-elem)
22277 (- pos (org-element-property :begin elem)))))))))
22279 ;;;###autoload
22280 (defun org-drag-element-forward ()
22281 "Move forward element at point."
22282 (interactive)
22283 (let* ((pos (point))
22284 (elem (org-element-at-point)))
22285 (when (= (point-max) (org-element-property :end elem))
22286 (error "Cannot drag element forward"))
22287 (goto-char (org-element-property :end elem))
22288 (let ((next-elem (org-element-at-point)))
22289 (when (or (org-element-nested-p elem next-elem)
22290 (and (eq (org-element-type next-elem) 'headline)
22291 (not (eq (org-element-type elem) 'headline))))
22292 (goto-char pos)
22293 (error "Cannot drag element forward"))
22294 ;; Compute new position of point: it's shifted by NEXT-ELEM
22295 ;; body's length (without final blanks) and by the length of
22296 ;; blanks between ELEM and NEXT-ELEM.
22297 (let ((size-next (- (save-excursion
22298 (goto-char (org-element-property :end next-elem))
22299 (skip-chars-backward " \r\t\n")
22300 (forward-line)
22301 ;; Small correction if buffer doesn't end
22302 ;; with a newline character.
22303 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22304 (org-element-property :begin next-elem)))
22305 (size-blank (- (org-element-property :end elem)
22306 (save-excursion
22307 (goto-char (org-element-property :end elem))
22308 (skip-chars-backward " \r\t\n")
22309 (forward-line)
22310 (point)))))
22311 (org-element-swap-A-B elem next-elem)
22312 (goto-char (+ pos size-next size-blank))))))
22314 ;;;###autoload
22315 (defun org-mark-element ()
22316 "Put point at beginning of this element, mark at end.
22318 Interactively, if this command is repeated or (in Transient Mark
22319 mode) if the mark is active, it marks the next element after the
22320 ones already marked."
22321 (interactive)
22322 (let (deactivate-mark)
22323 (if (and (org-called-interactively-p 'any)
22324 (or (and (eq last-command this-command) (mark t))
22325 (and transient-mark-mode mark-active)))
22326 (set-mark
22327 (save-excursion
22328 (goto-char (mark))
22329 (goto-char (org-element-property :end (org-element-at-point)))))
22330 (let ((element (org-element-at-point)))
22331 (end-of-line)
22332 (push-mark (org-element-property :end element) t t)
22333 (goto-char (org-element-property :begin element))))))
22335 ;;;###autoload
22336 (defun org-narrow-to-element ()
22337 "Narrow buffer to current element."
22338 (interactive)
22339 (let ((elem (org-element-at-point)))
22340 (cond
22341 ((eq (car elem) 'headline)
22342 (narrow-to-region
22343 (org-element-property :begin elem)
22344 (org-element-property :end elem)))
22345 ((memq (car elem) org-element-greater-elements)
22346 (narrow-to-region
22347 (org-element-property :contents-begin elem)
22348 (org-element-property :contents-end elem)))
22350 (narrow-to-region
22351 (org-element-property :begin elem)
22352 (org-element-property :end elem))))))
22354 ;;;###autoload
22355 (defun org-transpose-element ()
22356 "Transpose current and previous elements, keeping blank lines between.
22357 Point is moved after both elements."
22358 (interactive)
22359 (org-skip-whitespace)
22360 (let ((end (org-element-property :end (org-element-at-point))))
22361 (org-drag-element-backward)
22362 (goto-char end)))
22364 ;;;###autoload
22365 (defun org-unindent-buffer ()
22366 "Un-indent the visible part of the buffer.
22367 Relative indentation (between items, inside blocks, etc.) isn't
22368 modified."
22369 (interactive)
22370 (unless (eq major-mode 'org-mode)
22371 (error "Cannot un-indent a buffer not in Org mode"))
22372 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22373 unindent-tree ; For byte-compiler.
22374 (unindent-tree
22375 (function
22376 (lambda (contents)
22377 (mapc
22378 (lambda (element)
22379 (if (memq (org-element-type element) '(headline section))
22380 (funcall unindent-tree (org-element-contents element))
22381 (save-excursion
22382 (save-restriction
22383 (narrow-to-region
22384 (org-element-property :begin element)
22385 (org-element-property :end element))
22386 (org-do-remove-indentation)))))
22387 (reverse contents))))))
22388 (funcall unindent-tree (org-element-contents parse-tree))))
22390 (defun org-show-subtree ()
22391 "Show everything after this heading at deeper levels."
22392 (interactive)
22393 (outline-flag-region
22394 (point)
22395 (save-excursion
22396 (org-end-of-subtree t t))
22397 nil))
22399 (defun org-show-entry ()
22400 "Show the body directly following this heading.
22401 Show the heading too, if it is currently invisible."
22402 (interactive)
22403 (save-excursion
22404 (condition-case nil
22405 (progn
22406 (org-back-to-heading t)
22407 (outline-flag-region
22408 (max (point-min) (1- (point)))
22409 (save-excursion
22410 (if (re-search-forward
22411 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22412 (match-beginning 1)
22413 (point-max)))
22414 nil)
22415 (org-cycle-hide-drawers 'children))
22416 (error nil))))
22418 (defun org-make-options-regexp (kwds &optional extra)
22419 "Make a regular expression for keyword lines."
22420 (concat
22421 "^#\\+\\("
22422 (mapconcat 'regexp-quote kwds "\\|")
22423 (if extra (concat "\\|" extra))
22424 "\\):[ \t]*\\(.*\\)"))
22426 ;; Make isearch reveal the necessary context
22427 (defun org-isearch-end ()
22428 "Reveal context after isearch exits."
22429 (when isearch-success ; only if search was successful
22430 (if (featurep 'xemacs)
22431 ;; Under XEmacs, the hook is run in the correct place,
22432 ;; we directly show the context.
22433 (org-show-context 'isearch)
22434 ;; In Emacs the hook runs *before* restoring the overlays.
22435 ;; So we have to use a one-time post-command-hook to do this.
22436 ;; (Emacs 22 has a special variable, see function `org-mode')
22437 (unless (and (boundp 'isearch-mode-end-hook-quit)
22438 isearch-mode-end-hook-quit)
22439 ;; Only when the isearch was not quitted.
22440 (org-add-hook 'post-command-hook 'org-isearch-post-command
22441 'append 'local)))))
22443 (defun org-isearch-post-command ()
22444 "Remove self from hook, and show context."
22445 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22446 (org-show-context 'isearch))
22449 ;;;; Integration with and fixes for other packages
22451 ;;; Imenu support
22453 (defvar org-imenu-markers nil
22454 "All markers currently used by Imenu.")
22455 (make-variable-buffer-local 'org-imenu-markers)
22457 (defun org-imenu-new-marker (&optional pos)
22458 "Return a new marker for use by Imenu, and remember the marker."
22459 (let ((m (make-marker)))
22460 (move-marker m (or pos (point)))
22461 (push m org-imenu-markers)
22464 (defun org-imenu-get-tree ()
22465 "Produce the index for Imenu."
22466 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22467 (setq org-imenu-markers nil)
22468 (let* ((n org-imenu-depth)
22469 (re (concat "^" (org-get-limited-outline-regexp)))
22470 (subs (make-vector (1+ n) nil))
22471 (last-level 0)
22472 m level head)
22473 (save-excursion
22474 (save-restriction
22475 (widen)
22476 (goto-char (point-max))
22477 (while (re-search-backward re nil t)
22478 (setq level (org-reduced-level (funcall outline-level)))
22479 (when (and (<= level n)
22480 (looking-at org-complex-heading-regexp))
22481 (setq head (org-link-display-format
22482 (org-match-string-no-properties 4))
22483 m (org-imenu-new-marker))
22484 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22485 (if (>= level last-level)
22486 (push (cons head m) (aref subs level))
22487 (push (cons head (aref subs (1+ level))) (aref subs level))
22488 (loop for i from (1+ level) to n do (aset subs i nil)))
22489 (setq last-level level)))))
22490 (aref subs 1)))
22492 (eval-after-load "imenu"
22493 '(progn
22494 (add-hook 'imenu-after-jump-hook
22495 (lambda ()
22496 (if (derived-mode-p 'org-mode)
22497 (org-show-context 'org-goto))))))
22499 (defun org-link-display-format (link)
22500 "Replace a link with either the description, or the link target
22501 if no description is present"
22502 (save-match-data
22503 (if (string-match org-bracket-link-analytic-regexp link)
22504 (replace-match (if (match-end 5)
22505 (match-string 5 link)
22506 (concat (match-string 1 link)
22507 (match-string 3 link)))
22508 nil t link)
22509 link)))
22511 (defun org-toggle-link-display ()
22512 "Toggle the literal or descriptive display of links."
22513 (interactive)
22514 (if org-descriptive-links
22515 (progn (org-remove-from-invisibility-spec '(org-link))
22516 (org-restart-font-lock)
22517 (setq org-descriptive-links nil))
22518 (progn (add-to-invisibility-spec '(org-link))
22519 (org-restart-font-lock)
22520 (setq org-descriptive-links t))))
22522 ;; Speedbar support
22524 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22525 "Overlay marking the agenda restriction line in speedbar.")
22526 (overlay-put org-speedbar-restriction-lock-overlay
22527 'face 'org-agenda-restriction-lock)
22528 (overlay-put org-speedbar-restriction-lock-overlay
22529 'help-echo "Agendas are currently limited to this item.")
22530 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22532 (defun org-speedbar-set-agenda-restriction ()
22533 "Restrict future agenda commands to the location at point in speedbar.
22534 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22535 (interactive)
22536 (require 'org-agenda)
22537 (let (p m tp np dir txt)
22538 (cond
22539 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22540 'org-imenu t))
22541 (setq m (get-text-property p 'org-imenu-marker))
22542 (with-current-buffer (marker-buffer m)
22543 (goto-char m)
22544 (org-agenda-set-restriction-lock 'subtree)))
22545 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22546 'speedbar-function 'speedbar-find-file))
22547 (setq tp (previous-single-property-change
22548 (1+ p) 'speedbar-function)
22549 np (next-single-property-change
22550 tp 'speedbar-function)
22551 dir (speedbar-line-directory)
22552 txt (buffer-substring-no-properties (or tp (point-min))
22553 (or np (point-max))))
22554 (with-current-buffer (find-file-noselect
22555 (let ((default-directory dir))
22556 (expand-file-name txt)))
22557 (unless (derived-mode-p 'org-mode)
22558 (error "Cannot restrict to non-Org-mode file"))
22559 (org-agenda-set-restriction-lock 'file)))
22560 (t (error "Don't know how to restrict Org-mode's agenda")))
22561 (move-overlay org-speedbar-restriction-lock-overlay
22562 (point-at-bol) (point-at-eol))
22563 (setq current-prefix-arg nil)
22564 (org-agenda-maybe-redo)))
22566 (eval-after-load "speedbar"
22567 '(progn
22568 (speedbar-add-supported-extension ".org")
22569 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22570 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22571 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22572 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22573 (add-hook 'speedbar-visiting-tag-hook
22574 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22576 ;;; Fixes and Hacks for problems with other packages
22578 ;; Make flyspell not check words in links, to not mess up our keymap
22579 (defun org-mode-flyspell-verify ()
22580 "Don't let flyspell put overlays at active buttons, or on
22581 {todo,all-time,additional-option-like}-keywords."
22582 (let ((pos (max (1- (point)) (point-min)))
22583 (word (thing-at-point 'word)))
22584 (and (not (get-text-property pos 'keymap))
22585 (not (get-text-property pos 'org-no-flyspell))
22586 (not (member word org-todo-keywords-1))
22587 (not (member word org-all-time-keywords))
22588 (not (member word org-options-keywords))
22589 (not (member word (mapcar 'car org-startup-options)))
22590 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22592 (defun org-remove-flyspell-overlays-in (beg end)
22593 "Remove flyspell overlays in region."
22594 (and (org-bound-and-true-p flyspell-mode)
22595 (fboundp 'flyspell-delete-region-overlays)
22596 (flyspell-delete-region-overlays beg end))
22597 (add-text-properties beg end '(org-no-flyspell t)))
22599 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22600 (eval-after-load "bookmark"
22601 '(if (boundp 'bookmark-after-jump-hook)
22602 ;; We can use the hook
22603 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22604 ;; Hook not available, use advice
22605 (defadvice bookmark-jump (after org-make-visible activate)
22606 "Make the position visible."
22607 (org-bookmark-jump-unhide))))
22609 ;; Make sure saveplace shows the location if it was hidden
22610 (eval-after-load "saveplace"
22611 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22612 "Make the position visible."
22613 (org-bookmark-jump-unhide)))
22615 ;; Make sure ecb shows the location if it was hidden
22616 (eval-after-load "ecb"
22617 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22618 "Make hierarchy visible when jumping into location from ECB tree buffer."
22619 (if (derived-mode-p 'org-mode)
22620 (org-show-context))))
22622 (defun org-bookmark-jump-unhide ()
22623 "Unhide the current position, to show the bookmark location."
22624 (and (derived-mode-p 'org-mode)
22625 (or (outline-invisible-p)
22626 (save-excursion (goto-char (max (point-min) (1- (point))))
22627 (outline-invisible-p)))
22628 (org-show-context 'bookmark-jump)))
22630 ;; Make session.el ignore our circular variable
22631 (eval-after-load "session"
22632 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22634 ;;;; Experimental code
22636 (defun org-closed-in-range ()
22637 "Sparse tree of items closed in a certain time range.
22638 Still experimental, may disappear in the future."
22639 (interactive)
22640 ;; Get the time interval from the user.
22641 (let* ((time1 (org-float-time
22642 (org-read-date nil 'to-time nil "Starting date: ")))
22643 (time2 (org-float-time
22644 (org-read-date nil 'to-time nil "End date:")))
22645 ;; callback function
22646 (callback (lambda ()
22647 (let ((time
22648 (org-float-time
22649 (apply 'encode-time
22650 (org-parse-time-string
22651 (match-string 1))))))
22652 ;; check if time in interval
22653 (and (>= time time1) (<= time time2))))))
22654 ;; make tree, check each match with the callback
22655 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22657 ;;;; Finish up
22659 (provide 'org)
22661 (run-hooks 'org-load-hook)
22663 ;;; org.el ends here