org-element: Define a new element: node-property
[org-mode.git] / lisp / org.el
blob5eb352c1df40a5bf0f2fb4b902cf0481c0f46317
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 to generate link descriptions from links.
1401 If nil the link location will be used. This function must take
1402 two parameters; the first is the link and the second the
1403 description `org-insert-link' has generated, and should return the
1404 description to use."
1405 :group 'org-link
1406 :type 'function)
1408 (defgroup org-link-store nil
1409 "Options concerning storing links in Org-mode."
1410 :tag "Org Store Link"
1411 :group 'org-link)
1413 (defcustom org-url-hexify-p t
1414 "When non-nil, hexify URL when creating a link."
1415 :type 'boolean
1416 ;; :version "24.3"
1417 :group 'org-link-store)
1419 (defcustom org-email-link-description-format "Email %c: %.30s"
1420 "Format of the description part of a link to an email or usenet message.
1421 The following %-escapes will be replaced by corresponding information:
1423 %F full \"From\" field
1424 %f name, taken from \"From\" field, address if no name
1425 %T full \"To\" field
1426 %t first name in \"To\" field, address if no name
1427 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1428 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1429 %s subject
1430 %d date
1431 %m message-id.
1433 You may use normal field width specification between the % and the letter.
1434 This is for example useful to limit the length of the subject.
1436 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1437 :group 'org-link-store
1438 :type 'string)
1440 (defcustom org-from-is-user-regexp
1441 (let (r1 r2)
1442 (when (and user-mail-address (not (string= user-mail-address "")))
1443 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1444 (when (and user-full-name (not (string= user-full-name "")))
1445 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1446 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1447 "Regexp matched against the \"From:\" header of an email or usenet message.
1448 It should match if the message is from the user him/herself."
1449 :group 'org-link-store
1450 :type 'regexp)
1452 (defcustom org-context-in-file-links t
1453 "Non-nil means file links from `org-store-link' contain context.
1454 A search string will be added to the file name with :: as separator and
1455 used to find the context when the link is activated by the command
1456 `org-open-at-point'. When this option is t, the entire active region
1457 will be placed in the search string of the file link. If set to a
1458 positive integer, only the first n lines of context will be stored.
1460 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1461 negates this setting for the duration of the command."
1462 :group 'org-link-store
1463 :type '(choice boolean integer))
1465 (defcustom org-keep-stored-link-after-insertion nil
1466 "Non-nil means keep link in list for entire session.
1468 The command `org-store-link' adds a link pointing to the current
1469 location to an internal list. These links accumulate during a session.
1470 The command `org-insert-link' can be used to insert links into any
1471 Org-mode file (offering completion for all stored links). When this
1472 option is nil, every link which has been inserted once using \\[org-insert-link]
1473 will be removed from the list, to make completing the unused links
1474 more efficient."
1475 :group 'org-link-store
1476 :type 'boolean)
1478 (defgroup org-link-follow nil
1479 "Options concerning following links in Org-mode."
1480 :tag "Org Follow Link"
1481 :group 'org-link)
1483 (defcustom org-link-translation-function nil
1484 "Function to translate links with different syntax to Org syntax.
1485 This can be used to translate links created for example by the Planner
1486 or emacs-wiki packages to Org syntax.
1487 The function must accept two parameters, a TYPE containing the link
1488 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1489 which is everything after the link protocol. It should return a cons
1490 with possibly modified values of type and path.
1491 Org contains a function for this, so if you set this variable to
1492 `org-translate-link-from-planner', you should be able follow many
1493 links created by planner."
1494 :group 'org-link-follow
1495 :type 'function)
1497 (defcustom org-follow-link-hook nil
1498 "Hook that is run after a link has been followed."
1499 :group 'org-link-follow
1500 :type 'hook)
1502 (defcustom org-tab-follows-link nil
1503 "Non-nil means on links TAB will follow the link.
1504 Needs to be set before org.el is loaded.
1505 This really should not be used, it does not make sense, and the
1506 implementation is bad."
1507 :group 'org-link-follow
1508 :type 'boolean)
1510 (defcustom org-return-follows-link nil
1511 "Non-nil means on links RET will follow the link."
1512 :group 'org-link-follow
1513 :type 'boolean)
1515 (defcustom org-mouse-1-follows-link
1516 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1517 "Non-nil means mouse-1 on a link will follow the link.
1518 A longer mouse click will still set point. Does not work on XEmacs.
1519 Needs to be set before org.el is loaded."
1520 :group 'org-link-follow
1521 :type 'boolean)
1523 (defcustom org-mark-ring-length 4
1524 "Number of different positions to be recorded in the ring.
1525 Changing this requires a restart of Emacs to work correctly."
1526 :group 'org-link-follow
1527 :type 'integer)
1529 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1530 "Non-nil means internal links in Org files must exactly match a headline.
1531 When nil, the link search tries to match a phrase with all words
1532 in the search text."
1533 :group 'org-link-follow
1534 :version "24.1"
1535 :type '(choice
1536 (const :tag "Use fuzzy text search" nil)
1537 (const :tag "Match only exact headline" t)
1538 (const :tag "Match exact headline or query to create it"
1539 query-to-create)))
1541 (defcustom org-link-frame-setup
1542 '((vm . vm-visit-folder-other-frame)
1543 (vm-imap . vm-visit-imap-folder-other-frame)
1544 (gnus . org-gnus-no-new-news)
1545 (file . find-file-other-window)
1546 (wl . wl-other-frame))
1547 "Setup the frame configuration for following links.
1548 When following a link with Emacs, it may often be useful to display
1549 this link in another window or frame. This variable can be used to
1550 set this up for the different types of links.
1551 For VM, use any of
1552 `vm-visit-folder'
1553 `vm-visit-folder-other-window'
1554 `vm-visit-folder-other-frame'
1555 For Gnus, use any of
1556 `gnus'
1557 `gnus-other-frame'
1558 `org-gnus-no-new-news'
1559 For FILE, use any of
1560 `find-file'
1561 `find-file-other-window'
1562 `find-file-other-frame'
1563 For Wanderlust use any of
1564 `wl'
1565 `wl-other-frame'
1566 For the calendar, use the variable `calendar-setup'.
1567 For BBDB, it is currently only possible to display the matches in
1568 another window."
1569 :group 'org-link-follow
1570 :type '(list
1571 (cons (const vm)
1572 (choice
1573 (const vm-visit-folder)
1574 (const vm-visit-folder-other-window)
1575 (const vm-visit-folder-other-frame)))
1576 (cons (const gnus)
1577 (choice
1578 (const gnus)
1579 (const gnus-other-frame)
1580 (const org-gnus-no-new-news)))
1581 (cons (const file)
1582 (choice
1583 (const find-file)
1584 (const find-file-other-window)
1585 (const find-file-other-frame)))
1586 (cons (const wl)
1587 (choice
1588 (const wl)
1589 (const wl-other-frame)))))
1591 (defcustom org-display-internal-link-with-indirect-buffer nil
1592 "Non-nil means use indirect buffer to display infile links.
1593 Activating internal links (from one location in a file to another location
1594 in the same file) normally just jumps to the location. When the link is
1595 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1596 is displayed in
1597 another window. When this option is set, the other window actually displays
1598 an indirect buffer clone of the current buffer, to avoid any visibility
1599 changes to the current buffer."
1600 :group 'org-link-follow
1601 :type 'boolean)
1603 (defcustom org-open-non-existing-files nil
1604 "Non-nil means `org-open-file' will open non-existing files.
1605 When nil, an error will be generated.
1606 This variable applies only to external applications because they
1607 might choke on non-existing files. If the link is to a file that
1608 will be opened in Emacs, the variable is ignored."
1609 :group 'org-link-follow
1610 :type 'boolean)
1612 (defcustom org-open-directory-means-index-dot-org nil
1613 "Non-nil means a link to a directory really means to index.org.
1614 When nil, following a directory link will run dired or open a finder/explorer
1615 window on that directory."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1620 "Function and arguments to call for following mailto links.
1621 This is a list with the first element being a Lisp function, and the
1622 remaining elements being arguments to the function. In string arguments,
1623 %a will be replaced by the address, and %s will be replaced by the subject
1624 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1625 :group 'org-link-follow
1626 :type '(choice
1627 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1628 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1629 (const :tag "message-mail" (message-mail "%a" "%s"))
1630 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1632 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1633 "Non-nil means ask for confirmation before executing shell links.
1634 Shell links can be dangerous: just think about a link
1636 [[shell:rm -rf ~/*][Google Search]]
1638 This link would show up in your Org-mode document as \"Google Search\",
1639 but really it would remove your entire home directory.
1640 Therefore we advise against setting this variable to nil.
1641 Just change it to `y-or-n-p' if you want to confirm with a
1642 single keystroke rather than having to type \"yes\"."
1643 :group 'org-link-follow
1644 :type '(choice
1645 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1646 (const :tag "with y-or-n (faster)" y-or-n-p)
1647 (const :tag "no confirmation (dangerous)" nil)))
1648 (put 'org-confirm-shell-link-function
1649 'safe-local-variable
1650 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1652 (defcustom org-confirm-shell-link-not-regexp ""
1653 "A regexp to skip confirmation for shell links."
1654 :group 'org-link-follow
1655 :version "24.1"
1656 :type 'regexp)
1658 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1660 Elisp links can be dangerous: just think about a link
1662 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-elisp-link-not-regexp ""
1679 "A regexp to skip confirmation for Elisp links."
1680 :group 'org-link-follow
1681 :version "24.1"
1682 :type 'regexp)
1684 (defconst org-file-apps-defaults-gnu
1685 '((remote . emacs)
1686 (system . mailcap)
1687 (t . mailcap))
1688 "Default file applications on a UNIX or GNU/Linux system.
1689 See `org-file-apps'.")
1691 (defconst org-file-apps-defaults-macosx
1692 '((remote . emacs)
1693 (t . "open %s")
1694 (system . "open %s")
1695 ("ps.gz" . "gv %s")
1696 ("eps.gz" . "gv %s")
1697 ("dvi" . "xdvi %s")
1698 ("fig" . "xfig %s"))
1699 "Default file applications on a MacOS X system.
1700 The system \"open\" is known as a default, but we use X11 applications
1701 for some files for which the OS does not have a good default.
1702 See `org-file-apps'.")
1704 (defconst org-file-apps-defaults-windowsnt
1705 (list
1706 '(remote . emacs)
1707 (cons t
1708 (list (if (featurep 'xemacs)
1709 'mswindows-shell-execute
1710 'w32-shell-execute)
1711 "open" 'file))
1712 (cons 'system
1713 (list (if (featurep 'xemacs)
1714 'mswindows-shell-execute
1715 'w32-shell-execute)
1716 "open" 'file)))
1717 "Default file applications on a Windows NT system.
1718 The system \"open\" is used for most files.
1719 See `org-file-apps'.")
1721 (defcustom org-file-apps
1723 (auto-mode . emacs)
1724 ("\\.mm\\'" . default)
1725 ("\\.x?html?\\'" . default)
1726 ("\\.pdf\\'" . default)
1728 "External applications for opening `file:path' items in a document.
1729 Org-mode uses system defaults for different file types, but
1730 you can use this variable to set the application for a given file
1731 extension. The entries in this list are cons cells where the car identifies
1732 files and the cdr the corresponding command. Possible values for the
1733 file identifier are
1734 \"string\" A string as a file identifier can be interpreted in different
1735 ways, depending on its contents:
1737 - Alphanumeric characters only:
1738 Match links with this file extension.
1739 Example: (\"pdf\" . \"evince %s\")
1740 to open PDFs with evince.
1742 - Regular expression: Match links where the
1743 filename matches the regexp. If you want to
1744 use groups here, use shy groups.
1746 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1747 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1748 to open *.html and *.xhtml with firefox.
1750 - Regular expression which contains (non-shy) groups:
1751 Match links where the whole link, including \"::\", and
1752 anything after that, matches the regexp.
1753 In a custom command string, %1, %2, etc. are replaced with
1754 the parts of the link that were matched by the groups.
1755 For backwards compatibility, if a command string is given
1756 that does not use any of the group matches, this case is
1757 handled identically to the second one (i.e. match against
1758 file name only).
1759 In a custom lisp form, you can access the group matches with
1760 (match-string n link).
1762 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1763 to open [[file:document.pdf::5]] with evince at page 5.
1765 `directory' Matches a directory
1766 `remote' Matches a remote file, accessible through tramp or efs.
1767 Remote files most likely should be visited through Emacs
1768 because external applications cannot handle such paths.
1769 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1770 so all files Emacs knows how to handle. Using this with
1771 command `emacs' will open most files in Emacs. Beware that this
1772 will also open html files inside Emacs, unless you add
1773 (\"html\" . default) to the list as well.
1774 t Default for files not matched by any of the other options.
1775 `system' The system command to open files, like `open' on Windows
1776 and Mac OS X, and mailcap under GNU/Linux. This is the command
1777 that will be selected if you call `C-c C-o' with a double
1778 \\[universal-argument] \\[universal-argument] prefix.
1780 Possible values for the command are:
1781 `emacs' The file will be visited by the current Emacs process.
1782 `default' Use the default application for this file type, which is the
1783 association for t in the list, most likely in the system-specific
1784 part.
1785 This can be used to overrule an unwanted setting in the
1786 system-specific variable.
1787 `system' Use the system command for opening files, like \"open\".
1788 This command is specified by the entry whose car is `system'.
1789 Most likely, the system-specific version of this variable
1790 does define this command, but you can overrule/replace it
1791 here.
1792 string A command to be executed by a shell; %s will be replaced
1793 by the path to the file.
1794 sexp A Lisp form which will be evaluated. The file path will
1795 be available in the Lisp variable `file'.
1796 For more examples, see the system specific constants
1797 `org-file-apps-defaults-macosx'
1798 `org-file-apps-defaults-windowsnt'
1799 `org-file-apps-defaults-gnu'."
1800 :group 'org-link-follow
1801 :type '(repeat
1802 (cons (choice :value ""
1803 (string :tag "Extension")
1804 (const :tag "System command to open files" system)
1805 (const :tag "Default for unrecognized files" t)
1806 (const :tag "Remote file" remote)
1807 (const :tag "Links to a directory" directory)
1808 (const :tag "Any files that have Emacs modes"
1809 auto-mode))
1810 (choice :value ""
1811 (const :tag "Visit with Emacs" emacs)
1812 (const :tag "Use default" default)
1813 (const :tag "Use the system command" system)
1814 (string :tag "Command")
1815 (sexp :tag "Lisp form")))))
1817 (defcustom org-doi-server-url "http://dx.doi.org/"
1818 "The URL of the DOI server."
1819 :type 'string
1820 ;; :version "24.3"
1821 :group 'org-link-follow)
1823 (defgroup org-refile nil
1824 "Options concerning refiling entries in Org-mode."
1825 :tag "Org Refile"
1826 :group 'org)
1828 (defcustom org-directory "~/org"
1829 "Directory with org files.
1830 This is just a default location to look for Org files. There is no need
1831 at all to put your files into this directory. It is only used in the
1832 following situations:
1834 1. When a capture template specifies a target file that is not an
1835 absolute path. The path will then be interpreted relative to
1836 `org-directory'
1837 2. When a capture note is filed away in an interactive way (when exiting the
1838 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1839 with `org-directory' as the default path."
1840 :group 'org-refile
1841 :group 'org-remember
1842 :group 'org-capture
1843 :type 'directory)
1845 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1846 "Default target for storing notes.
1847 Used as a fall back file for org-remember.el and org-capture.el, for
1848 templates that do not specify a target file."
1849 :group 'org-refile
1850 :group 'org-remember
1851 :group 'org-capture
1852 :type '(choice
1853 (const :tag "Default from remember-data-file" nil)
1854 file))
1856 (defcustom org-goto-interface 'outline
1857 "The default interface to be used for `org-goto'.
1858 Allowed values are:
1859 outline The interface shows an outline of the relevant file
1860 and the correct heading is found by moving through
1861 the outline or by searching with incremental search.
1862 outline-path-completion Headlines in the current buffer are offered via
1863 completion. This is the interface also used by
1864 the refile command."
1865 :group 'org-refile
1866 :type '(choice
1867 (const :tag "Outline" outline)
1868 (const :tag "Outline-path-completion" outline-path-completion)))
1870 (defcustom org-goto-max-level 5
1871 "Maximum target level when running `org-goto' with refile interface."
1872 :group 'org-refile
1873 :type 'integer)
1875 (defcustom org-reverse-note-order nil
1876 "Non-nil means store new notes at the beginning of a file or entry.
1877 When nil, new notes will be filed to the end of a file or entry.
1878 This can also be a list with cons cells of regular expressions that
1879 are matched against file names, and values."
1880 :group 'org-remember
1881 :group 'org-capture
1882 :group 'org-refile
1883 :type '(choice
1884 (const :tag "Reverse always" t)
1885 (const :tag "Reverse never" nil)
1886 (repeat :tag "By file name regexp"
1887 (cons regexp boolean))))
1889 (defcustom org-log-refile nil
1890 "Information to record when a task is refiled.
1892 Possible values are:
1894 nil Don't add anything
1895 time Add a time stamp to the task
1896 note Prompt for a note and add it with template `org-log-note-headings'
1898 This option can also be set with on a per-file-basis with
1900 #+STARTUP: nologrefile
1901 #+STARTUP: logrefile
1902 #+STARTUP: lognoterefile
1904 You can have local logging settings for a subtree by setting the LOGGING
1905 property to one or more of these keywords.
1907 When bulk-refiling from the agenda, the value `note' is forbidden and
1908 will temporarily be changed to `time'."
1909 :group 'org-refile
1910 :group 'org-progress
1911 :version "24.1"
1912 :type '(choice
1913 (const :tag "No logging" nil)
1914 (const :tag "Record timestamp" time)
1915 (const :tag "Record timestamp with note." note)))
1917 (defcustom org-refile-targets nil
1918 "Targets for refiling entries with \\[org-refile].
1919 This is a list of cons cells. Each cell contains:
1920 - a specification of the files to be considered, either a list of files,
1921 or a symbol whose function or variable value will be used to retrieve
1922 a file name or a list of file names. If you use `org-agenda-files' for
1923 that, all agenda files will be scanned for targets. Nil means consider
1924 headings in the current buffer.
1925 - A specification of how to find candidate refile targets. This may be
1926 any of:
1927 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1928 This tag has to be present in all target headlines, inheritance will
1929 not be considered.
1930 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1931 todo keyword.
1932 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1933 headlines that are refiling targets.
1934 - a cons cell (:level . N). Any headline of level N is considered a target.
1935 Note that, when `org-odd-levels-only' is set, level corresponds to
1936 order in hierarchy, not to the number of stars.
1937 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1938 Note that, when `org-odd-levels-only' is set, level corresponds to
1939 order in hierarchy, not to the number of stars.
1941 Each element of this list generates a set of possible targets.
1942 The union of these sets is presented (with completion) to
1943 the user by `org-refile'.
1945 You can set the variable `org-refile-target-verify-function' to a function
1946 to verify each headline found by the simple criteria above.
1948 When this variable is nil, all top-level headlines in the current buffer
1949 are used, equivalent to the value `((nil . (:level . 1))'."
1950 :group 'org-refile
1951 :type '(repeat
1952 (cons
1953 (choice :value org-agenda-files
1954 (const :tag "All agenda files" org-agenda-files)
1955 (const :tag "Current buffer" nil)
1956 (function) (variable) (file))
1957 (choice :tag "Identify target headline by"
1958 (cons :tag "Specific tag" (const :value :tag) (string))
1959 (cons :tag "TODO keyword" (const :value :todo) (string))
1960 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1961 (cons :tag "Level number" (const :value :level) (integer))
1962 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1964 (defcustom org-refile-target-verify-function nil
1965 "Function to verify if the headline at point should be a refile target.
1966 The function will be called without arguments, with point at the
1967 beginning of the headline. It should return t and leave point
1968 where it is if the headline is a valid target for refiling.
1970 If the target should not be selected, the function must return nil.
1971 In addition to this, it may move point to a place from where the search
1972 should be continued. For example, the function may decide that the entire
1973 subtree of the current entry should be excluded and move point to the end
1974 of the subtree."
1975 :group 'org-refile
1976 :type 'function)
1978 (defcustom org-refile-use-cache nil
1979 "Non-nil means cache refile targets to speed up the process.
1980 The cache for a particular file will be updated automatically when
1981 the buffer has been killed, or when any of the marker used for flagging
1982 refile targets no longer points at a live buffer.
1983 If you have added new entries to a buffer that might themselves be targets,
1984 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1985 find that easier, `C-u C-u C-u C-c C-w'."
1986 :group 'org-refile
1987 :version "24.1"
1988 :type 'boolean)
1990 (defcustom org-refile-use-outline-path nil
1991 "Non-nil means provide refile targets as paths.
1992 So a level 3 headline will be available as level1/level2/level3.
1994 When the value is `file', also include the file name (without directory)
1995 into the path. In this case, you can also stop the completion after
1996 the file name, to get entries inserted as top level in the file.
1998 When `full-file-path', include the full file path."
1999 :group 'org-refile
2000 :type '(choice
2001 (const :tag "Not" nil)
2002 (const :tag "Yes" t)
2003 (const :tag "Start with file name" file)
2004 (const :tag "Start with full file path" full-file-path)))
2006 (defcustom org-outline-path-complete-in-steps t
2007 "Non-nil means complete the outline path in hierarchical steps.
2008 When Org-mode uses the refile interface to select an outline path
2009 \(see variable `org-refile-use-outline-path'), the completion of
2010 the path can be done is a single go, or if can be done in steps down
2011 the headline hierarchy. Going in steps is probably the best if you
2012 do not use a special completion package like `ido' or `icicles'.
2013 However, when using these packages, going in one step can be very
2014 fast, while still showing the whole path to the entry."
2015 :group 'org-refile
2016 :type 'boolean)
2018 (defcustom org-refile-allow-creating-parent-nodes nil
2019 "Non-nil means allow to create new nodes as refile targets.
2020 New nodes are then created by adding \"/new node name\" to the completion
2021 of an existing node. When the value of this variable is `confirm',
2022 new node creation must be confirmed by the user (recommended)
2023 When nil, the completion must match an existing entry.
2025 Note that, if the new heading is not seen by the criteria
2026 listed in `org-refile-targets', multiple instances of the same
2027 heading would be created by trying again to file under the new
2028 heading."
2029 :group 'org-refile
2030 :type '(choice
2031 (const :tag "Never" nil)
2032 (const :tag "Always" t)
2033 (const :tag "Prompt for confirmation" confirm)))
2035 (defcustom org-refile-active-region-within-subtree nil
2036 "Non-nil means also refile active region within a subtree.
2038 By default `org-refile' doesn't allow refiling regions if they
2039 don't contain a set of subtrees, but it might be convenient to
2040 do so sometimes: in that case, the first line of the region is
2041 converted to a headline before refiling."
2042 :group 'org-refile
2043 :version "24.1"
2044 :type 'boolean)
2046 (defgroup org-todo nil
2047 "Options concerning TODO items in Org-mode."
2048 :tag "Org TODO"
2049 :group 'org)
2051 (defgroup org-progress nil
2052 "Options concerning Progress logging in Org-mode."
2053 :tag "Org Progress"
2054 :group 'org-time)
2056 (defvar org-todo-interpretation-widgets
2057 '((:tag "Sequence (cycling hits every state)" sequence)
2058 (:tag "Type (cycling directly to DONE)" type))
2059 "The available interpretation symbols for customizing `org-todo-keywords'.
2060 Interested libraries should add to this list.")
2062 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2063 "List of TODO entry keyword sequences and their interpretation.
2064 \\<org-mode-map>This is a list of sequences.
2066 Each sequence starts with a symbol, either `sequence' or `type',
2067 indicating if the keywords should be interpreted as a sequence of
2068 action steps, or as different types of TODO items. The first
2069 keywords are states requiring action - these states will select a headline
2070 for inclusion into the global TODO list Org-mode produces. If one of
2071 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2072 signify that no further action is necessary. If \"|\" is not found,
2073 the last keyword is treated as the only DONE state of the sequence.
2075 The command \\[org-todo] cycles an entry through these states, and one
2076 additional state where no keyword is present. For details about this
2077 cycling, see the manual.
2079 TODO keywords and interpretation can also be set on a per-file basis with
2080 the special #+SEQ_TODO and #+TYP_TODO lines.
2082 Each keyword can optionally specify a character for fast state selection
2083 \(in combination with the variable `org-use-fast-todo-selection')
2084 and specifiers for state change logging, using the same syntax that
2085 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2086 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2087 indicates to record a time stamp each time this state is selected.
2089 Each keyword may also specify if a timestamp or a note should be
2090 recorded when entering or leaving the state, by adding additional
2091 characters in the parenthesis after the keyword. This looks like this:
2092 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2093 record only the time of the state change. With X and Y being either
2094 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2095 Y when leaving the state if and only if the *target* state does not
2096 define X. You may omit any of the fast-selection key or X or /Y,
2097 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2099 For backward compatibility, this variable may also be just a list
2100 of keywords. In this case the interpretation (sequence or type) will be
2101 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2102 :group 'org-todo
2103 :group 'org-keywords
2104 :type '(choice
2105 (repeat :tag "Old syntax, just keywords"
2106 (string :tag "Keyword"))
2107 (repeat :tag "New syntax"
2108 (cons
2109 (choice
2110 :tag "Interpretation"
2111 ;;Quick and dirty way to see
2112 ;;`org-todo-interpretations'. This takes the
2113 ;;place of item arguments
2114 :convert-widget
2115 (lambda (widget)
2116 (widget-put widget
2117 :args (mapcar
2118 #'(lambda (x)
2119 (widget-convert
2120 (cons 'const x)))
2121 org-todo-interpretation-widgets))
2122 widget))
2123 (repeat
2124 (string :tag "Keyword"))))))
2126 (defvar org-todo-keywords-1 nil
2127 "All TODO and DONE keywords active in a buffer.")
2128 (make-variable-buffer-local 'org-todo-keywords-1)
2129 (defvar org-todo-keywords-for-agenda nil)
2130 (defvar org-done-keywords-for-agenda nil)
2131 (defvar org-drawers-for-agenda nil)
2132 (defvar org-todo-keyword-alist-for-agenda nil)
2133 (defvar org-tag-alist-for-agenda nil)
2134 (defvar org-agenda-contributing-files nil)
2135 (defvar org-not-done-keywords nil)
2136 (make-variable-buffer-local 'org-not-done-keywords)
2137 (defvar org-done-keywords nil)
2138 (make-variable-buffer-local 'org-done-keywords)
2139 (defvar org-todo-heads nil)
2140 (make-variable-buffer-local 'org-todo-heads)
2141 (defvar org-todo-sets nil)
2142 (make-variable-buffer-local 'org-todo-sets)
2143 (defvar org-todo-log-states nil)
2144 (make-variable-buffer-local 'org-todo-log-states)
2145 (defvar org-todo-kwd-alist nil)
2146 (make-variable-buffer-local 'org-todo-kwd-alist)
2147 (defvar org-todo-key-alist nil)
2148 (make-variable-buffer-local 'org-todo-key-alist)
2149 (defvar org-todo-key-trigger nil)
2150 (make-variable-buffer-local 'org-todo-key-trigger)
2152 (defcustom org-todo-interpretation 'sequence
2153 "Controls how TODO keywords are interpreted.
2154 This variable is in principle obsolete and is only used for
2155 backward compatibility, if the interpretation of todo keywords is
2156 not given already in `org-todo-keywords'. See that variable for
2157 more information."
2158 :group 'org-todo
2159 :group 'org-keywords
2160 :type '(choice (const sequence)
2161 (const type)))
2163 (defcustom org-use-fast-todo-selection t
2164 "Non-nil means use the fast todo selection scheme with C-c C-t.
2165 This variable describes if and under what circumstances the cycling
2166 mechanism for TODO keywords will be replaced by a single-key, direct
2167 selection scheme.
2169 When nil, fast selection is never used.
2171 When the symbol `prefix', it will be used when `org-todo' is called
2172 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2173 `C-u t' in an agenda buffer.
2175 When t, fast selection is used by default. In this case, the prefix
2176 argument forces cycling instead.
2178 In all cases, the special interface is only used if access keys have
2179 actually been assigned by the user, i.e. if keywords in the configuration
2180 are followed by a letter in parenthesis, like TODO(t)."
2181 :group 'org-todo
2182 :type '(choice
2183 (const :tag "Never" nil)
2184 (const :tag "By default" t)
2185 (const :tag "Only with C-u C-c C-t" prefix)))
2187 (defcustom org-provide-todo-statistics t
2188 "Non-nil means update todo statistics after insert and toggle.
2189 ALL-HEADLINES means update todo statistics by including headlines
2190 with no TODO keyword as well, counting them as not done.
2191 A list of TODO keywords means the same, but skip keywords that are
2192 not in this list.
2194 When this is set, todo statistics is updated in the parent of the
2195 current entry each time a todo state is changed."
2196 :group 'org-todo
2197 :type '(choice
2198 (const :tag "Yes, only for TODO entries" t)
2199 (const :tag "Yes, including all entries" 'all-headlines)
2200 (repeat :tag "Yes, for TODOs in this list"
2201 (string :tag "TODO keyword"))
2202 (other :tag "No TODO statistics" nil)))
2204 (defcustom org-hierarchical-todo-statistics t
2205 "Non-nil means TODO statistics covers just direct children.
2206 When nil, all entries in the subtree are considered.
2207 This has only an effect if `org-provide-todo-statistics' is set.
2208 To set this to nil for only a single subtree, use a COOKIE_DATA
2209 property and include the word \"recursive\" into the value."
2210 :group 'org-todo
2211 :type 'boolean)
2213 (defcustom org-after-todo-state-change-hook nil
2214 "Hook which is run after the state of a TODO item was changed.
2215 The new state (a string with a TODO keyword, or nil) is available in the
2216 Lisp variable `org-state'."
2217 :group 'org-todo
2218 :type 'hook)
2220 (defvar org-blocker-hook nil
2221 "Hook for functions that are allowed to block a state change.
2223 Each function gets as its single argument a property list, see
2224 `org-trigger-hook' for more information about this list.
2226 If any of the functions in this hook returns nil, the state change
2227 is blocked.")
2229 (defvar org-trigger-hook nil
2230 "Hook for functions that are triggered by a state change.
2232 Each function gets as its single argument a property list with at least
2233 the following elements:
2235 (:type type-of-change :position pos-at-entry-start
2236 :from old-state :to new-state)
2238 Depending on the type, more properties may be present.
2240 This mechanism is currently implemented for:
2242 TODO state changes
2243 ------------------
2244 :type todo-state-change
2245 :from previous state (keyword as a string), or nil, or a symbol
2246 'todo' or 'done', to indicate the general type of state.
2247 :to new state, like in :from")
2249 (defcustom org-enforce-todo-dependencies nil
2250 "Non-nil means undone TODO entries will block switching the parent to DONE.
2251 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2252 be blocked if any prior sibling is not yet done.
2253 Finally, if the parent is blocked because of ordered siblings of its own,
2254 the child will also be blocked."
2255 :set (lambda (var val)
2256 (set var val)
2257 (if val
2258 (add-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent)
2260 (remove-hook 'org-blocker-hook
2261 'org-block-todo-from-children-or-siblings-or-parent)))
2262 :group 'org-todo
2263 :type 'boolean)
2265 (defcustom org-enforce-todo-checkbox-dependencies nil
2266 "Non-nil means unchecked boxes will block switching the parent to DONE.
2267 When this is nil, checkboxes have no influence on switching TODO states.
2268 When non-nil, you first need to check off all check boxes before the TODO
2269 entry can be switched to DONE.
2270 This variable needs to be set before org.el is loaded, and you need to
2271 restart Emacs after a change to make the change effective. The only way
2272 to change is while Emacs is running is through the customize interface."
2273 :set (lambda (var val)
2274 (set var val)
2275 (if val
2276 (add-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes)
2278 (remove-hook 'org-blocker-hook
2279 'org-block-todo-from-checkboxes)))
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-treat-insert-todo-heading-as-state-change nil
2284 "Non-nil means inserting a TODO heading is treated as state change.
2285 So when the command \\[org-insert-todo-heading] is used, state change
2286 logging will apply if appropriate. When nil, the new TODO item will
2287 be inserted directly, and no logging will take place."
2288 :group 'org-todo
2289 :type 'boolean)
2291 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2292 "Non-nil means switching TODO states with S-cursor counts as state change.
2293 This is the default behavior. However, setting this to nil allows a
2294 convenient way to select a TODO state and bypass any logging associated
2295 with that."
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-todo-state-tags-triggers nil
2300 "Tag changes that should be triggered by TODO state changes.
2301 This is a list. Each entry is
2303 (state-change (tag . flag) .......)
2305 State-change can be a string with a state, and empty string to indicate the
2306 state that has no TODO keyword, or it can be one of the symbols `todo'
2307 or `done', meaning any not-done or done state, respectively."
2308 :group 'org-todo
2309 :group 'org-tags
2310 :type '(repeat
2311 (cons (choice :tag "When changing to"
2312 (const :tag "Not-done state" todo)
2313 (const :tag "Done state" done)
2314 (string :tag "State"))
2315 (repeat
2316 (cons :tag "Tag action"
2317 (string :tag "Tag")
2318 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2320 (defcustom org-log-done nil
2321 "Information to record when a task moves to the DONE state.
2323 Possible values are:
2325 nil Don't add anything, just change the keyword
2326 time Add a time stamp to the task
2327 note Prompt for a note and add it with template `org-log-note-headings'
2329 This option can also be set with on a per-file-basis with
2331 #+STARTUP: nologdone
2332 #+STARTUP: logdone
2333 #+STARTUP: lognotedone
2335 You can have local logging settings for a subtree by setting the LOGGING
2336 property to one or more of these keywords."
2337 :group 'org-todo
2338 :group 'org-progress
2339 :type '(choice
2340 (const :tag "No logging" nil)
2341 (const :tag "Record CLOSED timestamp" time)
2342 (const :tag "Record CLOSED timestamp with note." note)))
2344 ;; Normalize old uses of org-log-done.
2345 (cond
2346 ((eq org-log-done t) (setq org-log-done 'time))
2347 ((and (listp org-log-done) (memq 'done org-log-done))
2348 (setq org-log-done 'note)))
2350 (defcustom org-log-reschedule nil
2351 "Information to record when the scheduling date of a tasks is modified.
2353 Possible values are:
2355 nil Don't add anything, just change the date
2356 time Add a time stamp to the task
2357 note Prompt for a note and add it with template `org-log-note-headings'
2359 This option can also be set with on a per-file-basis with
2361 #+STARTUP: nologreschedule
2362 #+STARTUP: logreschedule
2363 #+STARTUP: lognotereschedule"
2364 :group 'org-todo
2365 :group 'org-progress
2366 :type '(choice
2367 (const :tag "No logging" nil)
2368 (const :tag "Record timestamp" time)
2369 (const :tag "Record timestamp with note." note)))
2371 (defcustom org-log-redeadline nil
2372 "Information to record when the deadline date of a tasks is modified.
2374 Possible values are:
2376 nil Don't add anything, just change the date
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologredeadline
2383 #+STARTUP: logredeadline
2384 #+STARTUP: lognoteredeadline
2386 You can have local logging settings for a subtree by setting the LOGGING
2387 property to one or more of these keywords."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "No logging" nil)
2392 (const :tag "Record timestamp" time)
2393 (const :tag "Record timestamp with note." note)))
2395 (defcustom org-log-note-clock-out nil
2396 "Non-nil means record a note when clocking out of an item.
2397 This can also be configured on a per-file basis by adding one of
2398 the following lines anywhere in the buffer:
2400 #+STARTUP: lognoteclock-out
2401 #+STARTUP: nolognoteclock-out"
2402 :group 'org-todo
2403 :group 'org-progress
2404 :type 'boolean)
2406 (defcustom org-log-done-with-time t
2407 "Non-nil means the CLOSED time stamp will contain date and time.
2408 When nil, only the date will be recorded."
2409 :group 'org-progress
2410 :type 'boolean)
2412 (defcustom org-log-note-headings
2413 '((done . "CLOSING NOTE %t")
2414 (state . "State %-12s from %-12S %t")
2415 (note . "Note taken on %t")
2416 (reschedule . "Rescheduled from %S on %t")
2417 (delschedule . "Not scheduled, was %S on %t")
2418 (redeadline . "New deadline from %S on %t")
2419 (deldeadline . "Removed deadline, was %S on %t")
2420 (refile . "Refiled on %t")
2421 (clock-out . ""))
2422 "Headings for notes added to entries.
2423 The value is an alist, with the car being a symbol indicating the note
2424 context, and the cdr is the heading to be used. The heading may also be the
2425 empty string.
2426 %t in the heading will be replaced by a time stamp.
2427 %T will be an active time stamp instead the default inactive one
2428 %d will be replaced by a short-format time stamp.
2429 %D will be replaced by an active short-format time stamp.
2430 %s will be replaced by the new TODO state, in double quotes.
2431 %S will be replaced by the old TODO state, in double quotes.
2432 %u will be replaced by the user name.
2433 %U will be replaced by the full user name.
2435 In fact, it is not a good idea to change the `state' entry, because
2436 agenda log mode depends on the format of these entries."
2437 :group 'org-todo
2438 :group 'org-progress
2439 :type '(list :greedy t
2440 (cons (const :tag "Heading when closing an item" done) string)
2441 (cons (const :tag
2442 "Heading when changing todo state (todo sequence only)"
2443 state) string)
2444 (cons (const :tag "Heading when just taking a note" note) string)
2445 (cons (const :tag "Heading when clocking out" clock-out) string)
2446 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2447 (cons (const :tag "Heading when rescheduling" reschedule) string)
2448 (cons (const :tag "Heading when changing deadline" redeadline) string)
2449 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2450 (cons (const :tag "Heading when refiling" refile) string)))
2452 (unless (assq 'note org-log-note-headings)
2453 (push '(note . "%t") org-log-note-headings))
2455 (defcustom org-log-into-drawer nil
2456 "Non-nil means insert state change notes and time stamps into a drawer.
2457 When nil, state changes notes will be inserted after the headline and
2458 any scheduling and clock lines, but not inside a drawer.
2460 The value of this variable should be the name of the drawer to use.
2461 LOGBOOK is proposed as the default drawer for this purpose, you can
2462 also set this to a string to define the drawer of your choice.
2464 A value of t is also allowed, representing \"LOGBOOK\".
2466 If this variable is set, `org-log-state-notes-insert-after-drawers'
2467 will be ignored.
2469 You can set the property LOG_INTO_DRAWER to overrule this setting for
2470 a subtree."
2471 :group 'org-todo
2472 :group 'org-progress
2473 :type '(choice
2474 (const :tag "Not into a drawer" nil)
2475 (const :tag "LOGBOOK" t)
2476 (string :tag "Other")))
2478 (if (fboundp 'defvaralias)
2479 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2481 (defun org-log-into-drawer ()
2482 "Return the value of `org-log-into-drawer', but let properties overrule.
2483 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2484 used instead of the default value."
2485 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2486 (cond
2487 ((or (not p) (equal p "nil")) org-log-into-drawer)
2488 ((equal p "t") "LOGBOOK")
2489 (t p))))
2491 (defcustom org-log-state-notes-insert-after-drawers nil
2492 "Non-nil means insert state change notes after any drawers in entry.
2493 Only the drawers that *immediately* follow the headline and the
2494 deadline/scheduled line are skipped.
2495 When nil, insert notes right after the heading and perhaps the line
2496 with deadline/scheduling if present.
2498 This variable will have no effect if `org-log-into-drawer' is
2499 set."
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type 'boolean)
2504 (defcustom org-log-states-order-reversed t
2505 "Non-nil means the latest state note will be directly after heading.
2506 When nil, the state change notes will be ordered according to time."
2507 :group 'org-todo
2508 :group 'org-progress
2509 :type 'boolean)
2511 (defcustom org-todo-repeat-to-state nil
2512 "The TODO state to which a repeater should return the repeating task.
2513 By default this is the first task in a TODO sequence, or the previous state
2514 in a TODO_TYP set. But you can specify another task here.
2515 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2516 :group 'org-todo
2517 :version "24.1"
2518 :type '(choice (const :tag "Head of sequence" nil)
2519 (string :tag "Specific state")))
2521 (defcustom org-log-repeat 'time
2522 "Non-nil means record moving through the DONE state when triggering repeat.
2523 An auto-repeating task is immediately switched back to TODO when
2524 marked DONE. If you are not logging state changes (by adding \"@\"
2525 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2526 record a closing note, there will be no record of the task moving
2527 through DONE. This variable forces taking a note anyway.
2529 nil Don't force a record
2530 time Record a time stamp
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologrepeat
2536 #+STARTUP: logrepeat
2537 #+STARTUP: lognoterepeat
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "Don't force a record" nil)
2545 (const :tag "Force recording the DONE state" time)
2546 (const :tag "Force recording a note with the DONE state" note)))
2549 (defgroup org-priorities nil
2550 "Priorities in Org-mode."
2551 :tag "Org Priorities"
2552 :group 'org-todo)
2554 (defcustom org-enable-priority-commands t
2555 "Non-nil means priority commands are active.
2556 When nil, these commands will be disabled, so that you never accidentally
2557 set a priority."
2558 :group 'org-priorities
2559 :type 'boolean)
2561 (defcustom org-highest-priority ?A
2562 "The highest priority of TODO items. A character like ?A, ?B etc.
2563 Must have a smaller ASCII number than `org-lowest-priority'."
2564 :group 'org-priorities
2565 :type 'character)
2567 (defcustom org-lowest-priority ?C
2568 "The lowest priority of TODO items. A character like ?A, ?B etc.
2569 Must have a larger ASCII number than `org-highest-priority'."
2570 :group 'org-priorities
2571 :type 'character)
2573 (defcustom org-default-priority ?B
2574 "The default priority of TODO items.
2575 This is the priority an item gets if no explicit priority is given.
2576 When starting to cycle on an empty priority the first step in the cycle
2577 depends on `org-priority-start-cycle-with-default'. The resulting first
2578 step priority must not exceed the range from `org-highest-priority' to
2579 `org-lowest-priority' which means that `org-default-priority' has to be
2580 in this range exclusive or inclusive the range boundaries. Else the
2581 first step refuses to set the default and the second will fall back
2582 to (depending on the command used) the highest or lowest priority."
2583 :group 'org-priorities
2584 :type 'character)
2586 (defcustom org-priority-start-cycle-with-default t
2587 "Non-nil means start with default priority when starting to cycle.
2588 When this is nil, the first step in the cycle will be (depending on the
2589 command used) one higher or lower than the default priority.
2590 See also `org-default-priority'."
2591 :group 'org-priorities
2592 :type 'boolean)
2594 (defcustom org-get-priority-function nil
2595 "Function to extract the priority from a string.
2596 The string is normally the headline. If this is nil Org computes the
2597 priority from the priority cookie like [#A] in the headline. It returns
2598 an integer, increasing by 1000 for each priority level.
2599 The user can set a different function here, which should take a string
2600 as an argument and return the numeric priority."
2601 :group 'org-priorities
2602 :version "24.1"
2603 :type 'function)
2605 (defgroup org-time nil
2606 "Options concerning time stamps and deadlines in Org-mode."
2607 :tag "Org Time"
2608 :group 'org)
2610 (defcustom org-insert-labeled-timestamps-at-point nil
2611 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2612 When nil, these labeled time stamps are forces into the second line of an
2613 entry, just after the headline. When scheduling from the global TODO list,
2614 the time stamp will always be forced into the second line."
2615 :group 'org-time
2616 :type 'boolean)
2618 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2619 "Formats for `format-time-string' which are used for time stamps.
2620 It is not recommended to change this constant.")
2622 (defcustom org-time-stamp-rounding-minutes '(0 5)
2623 "Number of minutes to round time stamps to.
2624 These are two values, the first applies when first creating a time stamp.
2625 The second applies when changing it with the commands `S-up' and `S-down'.
2626 When changing the time stamp, this means that it will change in steps
2627 of N minutes, as given by the second value.
2629 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2630 numbers should be factors of 60, so for example 5, 10, 15.
2632 When this is larger than 1, you can still force an exact time stamp by using
2633 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2634 and by using a prefix arg to `S-up/down' to specify the exact number
2635 of minutes to shift."
2636 :group 'org-time
2637 :get #'(lambda (var) ; Make sure both elements are there
2638 (if (integerp (default-value var))
2639 (list (default-value var) 5)
2640 (default-value var)))
2641 :type '(list
2642 (integer :tag "when inserting times")
2643 (integer :tag "when modifying times")))
2645 ;; Normalize old customizations of this variable.
2646 (when (integerp org-time-stamp-rounding-minutes)
2647 (setq org-time-stamp-rounding-minutes
2648 (list org-time-stamp-rounding-minutes
2649 org-time-stamp-rounding-minutes)))
2651 (defcustom org-display-custom-times nil
2652 "Non-nil means overlay custom formats over all time stamps.
2653 The formats are defined through the variable `org-time-stamp-custom-formats'.
2654 To turn this on on a per-file basis, insert anywhere in the file:
2655 #+STARTUP: customtime"
2656 :group 'org-time
2657 :set 'set-default
2658 :type 'sexp)
2659 (make-variable-buffer-local 'org-display-custom-times)
2661 (defcustom org-time-stamp-custom-formats
2662 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2663 "Custom formats for time stamps. See `format-time-string' for the syntax.
2664 These are overlaid over the default ISO format if the variable
2665 `org-display-custom-times' is set. Time like %H:%M should be at the
2666 end of the second format. The custom formats are also honored by export
2667 commands, if custom time display is turned on at the time of export."
2668 :group 'org-time
2669 :type 'sexp)
2671 (defun org-time-stamp-format (&optional long inactive)
2672 "Get the right format for a time string."
2673 (let ((f (if long (cdr org-time-stamp-formats)
2674 (car org-time-stamp-formats))))
2675 (if inactive
2676 (concat "[" (substring f 1 -1) "]")
2677 f)))
2679 (defcustom org-time-clocksum-format "%d:%02d"
2680 "The format string used when creating CLOCKSUM lines.
2681 This is also used when org-mode generates a time duration."
2682 :group 'org-time
2683 :type 'string)
2685 (defcustom org-time-clocksum-use-fractional nil
2686 "If non-nil, \\[org-clock-display] uses fractional times.
2687 org-mode generates a time duration."
2688 :group 'org-time
2689 :type 'boolean)
2691 (defcustom org-time-clocksum-fractional-format "%.2f"
2692 "The format string used when creating CLOCKSUM lines, or when
2693 org-mode generates a time duration."
2694 :group 'org-time
2695 :type 'string)
2697 (defcustom org-deadline-warning-days 14
2698 "No. of days before expiration during which a deadline becomes active.
2699 This variable governs the display in sparse trees and in the agenda.
2700 When 0 or negative, it means use this number (the absolute value of it)
2701 even if a deadline has a different individual lead time specified.
2703 Custom commands can set this variable in the options section."
2704 :group 'org-time
2705 :group 'org-agenda-daily/weekly
2706 :type 'integer)
2708 (defcustom org-read-date-prefer-future t
2709 "Non-nil means assume future for incomplete date input from user.
2710 This affects the following situations:
2711 1. The user gives a month but not a year.
2712 For example, if it is April and you enter \"feb 2\", this will be read
2713 as Feb 2, *next* year. \"May 5\", however, will be this year.
2714 2. The user gives a day, but no month.
2715 For example, if today is the 15th, and you enter \"3\", Org-mode will
2716 read this as the third of *next* month. However, if you enter \"17\",
2717 it will be considered as *this* month.
2719 If you set this variable to the symbol `time', then also the following
2720 will work:
2722 3. If the user gives a time.
2723 If the time is before now, it will be interpreted as tomorrow.
2725 Currently none of this works for ISO week specifications.
2727 When this option is nil, the current day, month and year will always be
2728 used as defaults.
2730 See also `org-agenda-jump-prefer-future'."
2731 :group 'org-time
2732 :type '(choice
2733 (const :tag "Never" nil)
2734 (const :tag "Check month and day" t)
2735 (const :tag "Check month, day, and time" time)))
2737 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2738 "Should the agenda jump command prefer the future for incomplete dates?
2739 The default is to do the same as configured in `org-read-date-prefer-future'.
2740 But you can also set a deviating value here.
2741 This may t or nil, or the symbol `org-read-date-prefer-future'."
2742 :group 'org-agenda
2743 :group 'org-time
2744 :version "24.1"
2745 :type '(choice
2746 (const :tag "Use org-read-date-prefer-future"
2747 org-read-date-prefer-future)
2748 (const :tag "Never" nil)
2749 (const :tag "Always" t)))
2751 (defcustom org-read-date-force-compatible-dates t
2752 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2754 Depending on the system Emacs is running on, certain dates cannot
2755 be represented with the type used internally to represent time.
2756 Dates between 1970-1-1 and 2038-1-1 can always be represented
2757 correctly. Some systems allow for earlier dates, some for later,
2758 some for both. One way to find out it to insert any date into an
2759 Org buffer, putting the cursor on the year and hitting S-up and
2760 S-down to test the range.
2762 When this variable is set to t, the date/time prompt will not let
2763 you specify dates outside the 1970-2037 range, so it is certain that
2764 these dates will work in whatever version of Emacs you are
2765 running, and also that you can move a file from one Emacs implementation
2766 to another. WHenever Org is forcing the year for you, it will display
2767 a message and beep.
2769 When this variable is nil, Org will check if the date is
2770 representable in the specific Emacs implementation you are using.
2771 If not, it will force a year, usually the current year, and beep
2772 to remind you. Currently this setting is not recommended because
2773 the likelihood that you will open your Org files in an Emacs that
2774 has limited date range is not negligible.
2776 A workaround for this problem is to use diary sexp dates for time
2777 stamps outside of this range."
2778 :group 'org-time
2779 :version "24.1"
2780 :type 'boolean)
2782 (defcustom org-read-date-display-live t
2783 "Non-nil means display current interpretation of date prompt live.
2784 This display will be in an overlay, in the minibuffer."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defcustom org-read-date-popup-calendar t
2789 "Non-nil means pop up a calendar when prompting for a date.
2790 In the calendar, the date can be selected with mouse-1. However, the
2791 minibuffer will also be active, and you can simply enter the date as well.
2792 When nil, only the minibuffer will be available."
2793 :group 'org-time
2794 :type 'boolean)
2795 (if (fboundp 'defvaralias)
2796 (defvaralias 'org-popup-calendar-for-date-prompt
2797 'org-read-date-popup-calendar))
2799 (defcustom org-read-date-minibuffer-setup-hook nil
2800 "Hook to be used to set up keys for the date/time interface.
2801 Add key definitions to `minibuffer-local-map', which will be a temporary
2802 copy."
2803 :group 'org-time
2804 :type 'hook)
2806 (defcustom org-extend-today-until 0
2807 "The hour when your day really ends. Must be an integer.
2808 This has influence for the following applications:
2809 - When switching the agenda to \"today\". It it is still earlier than
2810 the time given here, the day recognized as TODAY is actually yesterday.
2811 - When a date is read from the user and it is still before the time given
2812 here, the current date and time will be assumed to be yesterday, 23:59.
2813 Also, timestamps inserted in capture templates follow this rule.
2815 IMPORTANT: This is a feature whose implementation is and likely will
2816 remain incomplete. Really, it is only here because past midnight seems to
2817 be the favorite working time of John Wiegley :-)"
2818 :group 'org-time
2819 :type 'integer)
2821 (defcustom org-use-effective-time nil
2822 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2823 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2824 \"effective time\" of any timestamps between midnight and 8am will be
2825 23:59 of the previous day."
2826 :group 'org-time
2827 :version "24.1"
2828 :type 'boolean)
2830 (defcustom org-use-last-clock-out-time-as-effective-time nil
2831 "When non-nil, use the last clock out time for `org-todo'.
2832 Note that this option has precedence over the combined use of
2833 `org-use-effective-time' and `org-extend-today-until'."
2834 :group 'org-time
2835 ;; :version "24.3"
2836 :type 'boolean)
2838 (defcustom org-edit-timestamp-down-means-later nil
2839 "Non-nil means S-down will increase the time in a time stamp.
2840 When nil, S-up will increase."
2841 :group 'org-time
2842 :type 'boolean)
2844 (defcustom org-calendar-follow-timestamp-change t
2845 "Non-nil means make the calendar window follow timestamp changes.
2846 When a timestamp is modified and the calendar window is visible, it will be
2847 moved to the new date."
2848 :group 'org-time
2849 :type 'boolean)
2851 (defgroup org-tags nil
2852 "Options concerning tags in Org-mode."
2853 :tag "Org Tags"
2854 :group 'org)
2856 (defcustom org-tag-alist nil
2857 "List of tags allowed in Org-mode files.
2858 When this list is nil, Org-mode will base TAG input on what is already in the
2859 buffer.
2860 The value of this variable is an alist, the car of each entry must be a
2861 keyword as a string, the cdr may be a character that is used to select
2862 that tag through the fast-tag-selection interface.
2863 See the manual for details."
2864 :group 'org-tags
2865 :type '(repeat
2866 (choice
2867 (cons (string :tag "Tag name")
2868 (character :tag "Access char"))
2869 (list :tag "Start radio group"
2870 (const :startgroup)
2871 (option (string :tag "Group description")))
2872 (list :tag "End radio group"
2873 (const :endgroup)
2874 (option (string :tag "Group description")))
2875 (const :tag "New line" (:newline)))))
2877 (defcustom org-tag-persistent-alist nil
2878 "List of tags that will always appear in all Org-mode files.
2879 This is in addition to any in buffer settings or customizations
2880 of `org-tag-alist'.
2881 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2882 The value of this variable is an alist, the car of each entry must be a
2883 keyword as a string, the cdr may be a character that is used to select
2884 that tag through the fast-tag-selection interface.
2885 See the manual for details.
2886 To disable these tags on a per-file basis, insert anywhere in the file:
2887 #+STARTUP: noptag"
2888 :group 'org-tags
2889 :type '(repeat
2890 (choice
2891 (cons (string :tag "Tag name")
2892 (character :tag "Access char"))
2893 (const :tag "Start radio group" (:startgroup))
2894 (const :tag "End radio group" (:endgroup))
2895 (const :tag "New line" (:newline)))))
2897 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2898 "If non-nil, always offer completion for all tags of all agenda files.
2899 Instead of customizing this variable directly, you might want to
2900 set it locally for capture buffers, because there no list of
2901 tags in that file can be created dynamically (there are none).
2903 (add-hook 'org-capture-mode-hook
2904 (lambda ()
2905 (set (make-local-variable
2906 'org-complete-tags-always-offer-all-agenda-tags)
2907 t)))"
2908 :group 'org-tags
2909 :version "24.1"
2910 :type 'boolean)
2912 (defvar org-file-tags nil
2913 "List of tags that can be inherited by all entries in the file.
2914 The tags will be inherited if the variable `org-use-tag-inheritance'
2915 says they should be.
2916 This variable is populated from #+FILETAGS lines.")
2918 (defcustom org-use-fast-tag-selection 'auto
2919 "Non-nil means use fast tag selection scheme.
2920 This is a special interface to select and deselect tags with single keys.
2921 When nil, fast selection is never used.
2922 When the symbol `auto', fast selection is used if and only if selection
2923 characters for tags have been configured, either through the variable
2924 `org-tag-alist' or through a #+TAGS line in the buffer.
2925 When t, fast selection is always used and selection keys are assigned
2926 automatically if necessary."
2927 :group 'org-tags
2928 :type '(choice
2929 (const :tag "Always" t)
2930 (const :tag "Never" nil)
2931 (const :tag "When selection characters are configured" 'auto)))
2933 (defcustom org-fast-tag-selection-single-key nil
2934 "Non-nil means fast tag selection exits after first change.
2935 When nil, you have to press RET to exit it.
2936 During fast tag selection, you can toggle this flag with `C-c'.
2937 This variable can also have the value `expert'. In this case, the window
2938 displaying the tags menu is not even shown, until you press C-c again."
2939 :group 'org-tags
2940 :type '(choice
2941 (const :tag "No" nil)
2942 (const :tag "Yes" t)
2943 (const :tag "Expert" expert)))
2945 (defvar org-fast-tag-selection-include-todo nil
2946 "Non-nil means fast tags selection interface will also offer TODO states.
2947 This is an undocumented feature, you should not rely on it.")
2949 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2950 "The column to which tags should be indented in a headline.
2951 If this number is positive, it specifies the column. If it is negative,
2952 it means that the tags should be flushright to that column. For example,
2953 -80 works well for a normal 80 character screen.
2954 When 0, place tags directly after headline text, with only one space in
2955 between."
2956 :group 'org-tags
2957 :type 'integer)
2959 (defcustom org-auto-align-tags t
2960 "Non-nil keeps tags aligned when modifying headlines.
2961 Some operations (i.e. demoting) change the length of a headline and
2962 therefore shift the tags around. With this option turned on, after
2963 each such operation the tags are again aligned to `org-tags-column'."
2964 :group 'org-tags
2965 :type 'boolean)
2967 (defcustom org-use-tag-inheritance t
2968 "Non-nil means tags in levels apply also for sublevels.
2969 When nil, only the tags directly given in a specific line apply there.
2970 This may also be a list of tags that should be inherited, or a regexp that
2971 matches tags that should be inherited. Additional control is possible
2972 with the variable `org-tags-exclude-from-inheritance' which gives an
2973 explicit list of tags to be excluded from inheritance., even if the value of
2974 `org-use-tag-inheritance' would select it for inheritance.
2976 If this option is t, a match early-on in a tree can lead to a large
2977 number of matches in the subtree when constructing the agenda or creating
2978 a sparse tree. If you only want to see the first match in a tree during
2979 a search, check out the variable `org-tags-match-list-sublevels'."
2980 :group 'org-tags
2981 :type '(choice
2982 (const :tag "Not" nil)
2983 (const :tag "Always" t)
2984 (repeat :tag "Specific tags" (string :tag "Tag"))
2985 (regexp :tag "Tags matched by regexp")))
2987 (defcustom org-tags-exclude-from-inheritance nil
2988 "List of tags that should never be inherited.
2989 This is a way to exclude a few tags from inheritance. For way to do
2990 the opposite, to actively allow inheritance for selected tags,
2991 see the variable `org-use-tag-inheritance'."
2992 :group 'org-tags
2993 :type '(repeat (string :tag "Tag")))
2995 (defun org-tag-inherit-p (tag)
2996 "Check if TAG is one that should be inherited."
2997 (cond
2998 ((member tag org-tags-exclude-from-inheritance) nil)
2999 ((eq org-use-tag-inheritance t) t)
3000 ((not org-use-tag-inheritance) nil)
3001 ((stringp org-use-tag-inheritance)
3002 (string-match org-use-tag-inheritance tag))
3003 ((listp org-use-tag-inheritance)
3004 (member tag org-use-tag-inheritance))
3005 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3007 (defcustom org-tags-match-list-sublevels t
3008 "Non-nil means list also sublevels of headlines matching a search.
3009 This variable applies to tags/property searches, and also to stuck
3010 projects because this search is based on a tags match as well.
3012 When set to the symbol `indented', sublevels are indented with
3013 leading dots.
3015 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3016 the sublevels of a headline matching a tag search often also match
3017 the same search. Listing all of them can create very long lists.
3018 Setting this variable to nil causes subtrees of a match to be skipped.
3020 This variable is semi-obsolete and probably should always be true. It
3021 is better to limit inheritance to certain tags using the variables
3022 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3023 :group 'org-tags
3024 :type '(choice
3025 (const :tag "No, don't list them" nil)
3026 (const :tag "Yes, do list them" t)
3027 (const :tag "List them, indented with leading dots" indented)))
3029 (defcustom org-tags-sort-function nil
3030 "When set, tags are sorted using this function as a comparator."
3031 :group 'org-tags
3032 :type '(choice
3033 (const :tag "No sorting" nil)
3034 (const :tag "Alphabetical" string<)
3035 (const :tag "Reverse alphabetical" string>)
3036 (function :tag "Custom function" nil)))
3038 (defvar org-tags-history nil
3039 "History of minibuffer reads for tags.")
3040 (defvar org-last-tags-completion-table nil
3041 "The last used completion table for tags.")
3042 (defvar org-after-tags-change-hook nil
3043 "Hook that is run after the tags in a line have changed.")
3045 (defgroup org-properties nil
3046 "Options concerning properties in Org-mode."
3047 :tag "Org Properties"
3048 :group 'org)
3050 (defcustom org-property-format "%-10s %s"
3051 "How property key/value pairs should be formatted by `indent-line'.
3052 When `indent-line' hits a property definition, it will format the line
3053 according to this format, mainly to make sure that the values are
3054 lined-up with respect to each other."
3055 :group 'org-properties
3056 :type 'string)
3058 (defcustom org-properties-postprocess-alist nil
3059 "Alist of properties and functions to adjust inserted values.
3060 Elements of this alist must be of the form
3062 ([string] [function])
3064 where [string] must be a property name and [function] must be a
3065 lambda expression: this lambda expression must take one argument,
3066 the value to adjust, and return the new value as a string.
3068 For example, this element will allow the property \"Remaining\"
3069 to be updated wrt the relation between the \"Effort\" property
3070 and the clock summary:
3072 ((\"Remaining\" (lambda(value)
3073 (let ((clocksum (org-clock-sum-current-item))
3074 (effort (org-duration-string-to-minutes
3075 (org-entry-get (point) \"Effort\"))))
3076 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3077 :group 'org-properties
3078 :version "24.1"
3079 :type '(alist :key-type (string :tag "Property")
3080 :value-type (function :tag "Function")))
3082 (defcustom org-use-property-inheritance nil
3083 "Non-nil means properties apply also for sublevels.
3085 This setting is chiefly used during property searches. Turning it on can
3086 cause significant overhead when doing a search, which is why it is not
3087 on by default.
3089 When nil, only the properties directly given in the current entry count.
3090 When t, every property is inherited. The value may also be a list of
3091 properties that should have inheritance, or a regular expression matching
3092 properties that should be inherited.
3094 However, note that some special properties use inheritance under special
3095 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3096 and the properties ending in \"_ALL\" when they are used as descriptor
3097 for valid values of a property.
3099 Note for programmers:
3100 When querying an entry with `org-entry-get', you can control if inheritance
3101 should be used. By default, `org-entry-get' looks only at the local
3102 properties. You can request inheritance by setting the inherit argument
3103 to t (to force inheritance) or to `selective' (to respect the setting
3104 in this variable)."
3105 :group 'org-properties
3106 :type '(choice
3107 (const :tag "Not" nil)
3108 (const :tag "Always" t)
3109 (repeat :tag "Specific properties" (string :tag "Property"))
3110 (regexp :tag "Properties matched by regexp")))
3112 (defun org-property-inherit-p (property)
3113 "Check if PROPERTY is one that should be inherited."
3114 (cond
3115 ((eq org-use-property-inheritance t) t)
3116 ((not org-use-property-inheritance) nil)
3117 ((stringp org-use-property-inheritance)
3118 (string-match org-use-property-inheritance property))
3119 ((listp org-use-property-inheritance)
3120 (member property org-use-property-inheritance))
3121 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3123 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3124 "The default column format, if no other format has been defined.
3125 This variable can be set on the per-file basis by inserting a line
3127 #+COLUMNS: %25ITEM ....."
3128 :group 'org-properties
3129 :type 'string)
3131 (defcustom org-columns-ellipses ".."
3132 "The ellipses to be used when a field in column view is truncated.
3133 When this is the empty string, as many characters as possible are shown,
3134 but then there will be no visual indication that the field has been truncated.
3135 When this is a string of length N, the last N characters of a truncated
3136 field are replaced by this string. If the column is narrower than the
3137 ellipses string, only part of the ellipses string will be shown."
3138 :group 'org-properties
3139 :type 'string)
3141 (defcustom org-columns-modify-value-for-display-function nil
3142 "Function that modifies values for display in column view.
3143 For example, it can be used to cut out a certain part from a time stamp.
3144 The function must take 2 arguments:
3146 column-title The title of the column (*not* the property name)
3147 value The value that should be modified.
3149 The function should return the value that should be displayed,
3150 or nil if the normal value should be used."
3151 :group 'org-properties
3152 :type 'function)
3154 (defcustom org-effort-property "Effort"
3155 "The property that is being used to keep track of effort estimates.
3156 Effort estimates given in this property need to have the format H:MM."
3157 :group 'org-properties
3158 :group 'org-progress
3159 :type '(string :tag "Property"))
3161 (defconst org-global-properties-fixed
3162 '(("VISIBILITY_ALL" . "folded children content all")
3163 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3164 "List of property/value pairs that can be inherited by any entry.
3166 These are fixed values, for the preset properties. The user variable
3167 that can be used to add to this list is `org-global-properties'.
3169 The entries in this list are cons cells where the car is a property
3170 name and cdr is a string with the value. If the value represents
3171 multiple items like an \"_ALL\" property, separate the items by
3172 spaces.")
3174 (defcustom org-global-properties nil
3175 "List of property/value pairs that can be inherited by any entry.
3177 This list will be combined with the constant `org-global-properties-fixed'.
3179 The entries in this list are cons cells where the car is a property
3180 name and cdr is a string with the value.
3182 You can set buffer-local values for the same purpose in the variable
3183 `org-file-properties' this by adding lines like
3185 #+PROPERTY: NAME VALUE"
3186 :group 'org-properties
3187 :type '(repeat
3188 (cons (string :tag "Property")
3189 (string :tag "Value"))))
3191 (defvar org-file-properties nil
3192 "List of property/value pairs that can be inherited by any entry.
3193 Valid for the current buffer.
3194 This variable is populated from #+PROPERTY lines.")
3195 (make-variable-buffer-local 'org-file-properties)
3197 (defgroup org-agenda nil
3198 "Options concerning agenda views in Org-mode."
3199 :tag "Org Agenda"
3200 :group 'org)
3202 (defvar org-category nil
3203 "Variable used by org files to set a category for agenda display.
3204 Such files should use a file variable to set it, for example
3206 # -*- mode: org; org-category: \"ELisp\"
3208 or contain a special line
3210 #+CATEGORY: ELisp
3212 If the file does not specify a category, then file's base name
3213 is used instead.")
3214 (make-variable-buffer-local 'org-category)
3215 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3217 (defcustom org-agenda-files nil
3218 "The files to be used for agenda display.
3219 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3220 \\[org-remove-file]. You can also use customize to edit the list.
3222 If an entry is a directory, all files in that directory that are matched by
3223 `org-agenda-file-regexp' will be part of the file list.
3225 If the value of the variable is not a list but a single file name, then
3226 the list of agenda files is actually stored and maintained in that file, one
3227 agenda file per line. In this file paths can be given relative to
3228 `org-directory'. Tilde expansion and environment variable substitution
3229 are also made."
3230 :group 'org-agenda
3231 :type '(choice
3232 (repeat :tag "List of files and directories" file)
3233 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3235 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3236 "Regular expression to match files for `org-agenda-files'.
3237 If any element in the list in that variable contains a directory instead
3238 of a normal file, all files in that directory that are matched by this
3239 regular expression will be included."
3240 :group 'org-agenda
3241 :type 'regexp)
3243 (defcustom org-agenda-text-search-extra-files nil
3244 "List of extra files to be searched by text search commands.
3245 These files will be search in addition to the agenda files by the
3246 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3247 Note that these files will only be searched for text search commands,
3248 not for the other agenda views like todo lists, tag searches or the weekly
3249 agenda. This variable is intended to list notes and possibly archive files
3250 that should also be searched by these two commands.
3251 In fact, if the first element in the list is the symbol `agenda-archives',
3252 than all archive files of all agenda files will be added to the search
3253 scope."
3254 :group 'org-agenda
3255 :type '(set :greedy t
3256 (const :tag "Agenda Archives" agenda-archives)
3257 (repeat :inline t (file))))
3259 (if (fboundp 'defvaralias)
3260 (defvaralias 'org-agenda-multi-occur-extra-files
3261 'org-agenda-text-search-extra-files))
3263 (defcustom org-agenda-skip-unavailable-files nil
3264 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3265 A nil value means to remove them, after a query, from the list."
3266 :group 'org-agenda
3267 :type 'boolean)
3269 (defcustom org-calendar-to-agenda-key [?c]
3270 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3271 The command `org-calendar-goto-agenda' will be bound to this key. The
3272 default is the character `c' because then `c' can be used to switch back and
3273 forth between agenda and calendar."
3274 :group 'org-agenda
3275 :type 'sexp)
3277 (defcustom org-calendar-agenda-action-key [?k]
3278 "The key to be installed in `calendar-mode-map' for agenda-action.
3279 The command `org-agenda-action' will be bound to this key. The
3280 default is the character `k' because we use the same key in the agenda."
3281 :group 'org-agenda
3282 :type 'sexp)
3284 (defcustom org-calendar-insert-diary-entry-key [?i]
3285 "The key to be installed in `calendar-mode-map' for adding diary entries.
3286 This option is irrelevant until `org-agenda-diary-file' has been configured
3287 to point to an Org-mode file. When that is the case, the command
3288 `org-agenda-diary-entry' will be bound to the key given here, by default
3289 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3290 if you want to continue doing this, you need to change this to a different
3291 key."
3292 :group 'org-agenda
3293 :type 'sexp)
3295 (defcustom org-agenda-diary-file 'diary-file
3296 "File to which to add new entries with the `i' key in agenda and calendar.
3297 When this is the symbol `diary-file', the functionality in the Emacs
3298 calendar will be used to add entries to the `diary-file'. But when this
3299 points to a file, `org-agenda-diary-entry' will be used instead."
3300 :group 'org-agenda
3301 :type '(choice
3302 (const :tag "The standard Emacs diary file" diary-file)
3303 (file :tag "Special Org file diary entries")))
3305 (eval-after-load "calendar"
3306 '(progn
3307 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3308 'org-calendar-goto-agenda)
3309 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3310 'org-agenda-action)
3311 (add-hook 'calendar-mode-hook
3312 (lambda ()
3313 (unless (eq org-agenda-diary-file 'diary-file)
3314 (define-key calendar-mode-map
3315 org-calendar-insert-diary-entry-key
3316 'org-agenda-diary-entry))))))
3318 (defgroup org-latex nil
3319 "Options for embedding LaTeX code into Org-mode."
3320 :tag "Org LaTeX"
3321 :group 'org)
3323 (defcustom org-format-latex-options
3324 '(:foreground default :background default :scale 1.0
3325 :html-foreground "Black" :html-background "Transparent"
3326 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3327 "Options for creating images from LaTeX fragments.
3328 This is a property list with the following properties:
3329 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3330 `default' means use the foreground of the default face.
3331 `auto' means use the foreground from the text face.
3332 :background the background color, or \"Transparent\".
3333 `default' means use the background of the default face.
3334 `auto' means use the background from the text face.
3335 :scale a scaling factor for the size of the images, to get more pixels
3336 :html-foreground, :html-background, :html-scale
3337 the same numbers for HTML export.
3338 :matchers a list indicating which matchers should be used to
3339 find LaTeX fragments. Valid members of this list are:
3340 \"begin\" find environments
3341 \"$1\" find single characters surrounded by $.$
3342 \"$\" find math expressions surrounded by $...$
3343 \"$$\" find math expressions surrounded by $$....$$
3344 \"\\(\" find math expressions surrounded by \\(...\\)
3345 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3346 :group 'org-latex
3347 :type 'plist)
3349 (defcustom org-format-latex-signal-error t
3350 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3351 When nil, just push out a message."
3352 :group 'org-latex
3353 :version "24.1"
3354 :type 'boolean)
3356 (defcustom org-latex-to-mathml-jar-file nil
3357 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3358 Use this to specify additional executable file say a jar file.
3360 When using MathToWeb as the converter, specify the full-path to
3361 your mathtoweb.jar file."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type '(choice
3365 (const :tag "None" nil)
3366 (file :tag "JAR file" :must-match t)))
3368 (defcustom org-latex-to-mathml-convert-command nil
3369 "Command to convert LaTeX fragments to MathML.
3370 Replace format-specifiers in the command as noted below and use
3371 `shell-command' to convert LaTeX to MathML.
3372 %j: Executable file in fully expanded form as specified by
3373 `org-latex-to-mathml-jar-file'.
3374 %I: Input LaTeX file in fully expanded form
3375 %o: Output MathML file
3376 This command is used by `org-create-math-formula'.
3378 When using MathToWeb as the converter, set this to
3379 \"java -jar %j -unicode -force -df %o %I\"."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type '(choice
3383 (const :tag "None" nil)
3384 (string :tag "\nShell command")))
3386 (defcustom org-latex-create-formula-image-program 'dvipng
3387 "Program to convert LaTeX fragments with.
3389 dvipng Process the LaTeX fragments to dvi file, then convert
3390 dvi files to png files using dvipng.
3391 This will also include processing of non-math environments.
3392 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3393 to convert pdf files to png files"
3394 :group 'org-latex
3395 :version "24.1"
3396 :type '(choice
3397 (const :tag "dvipng" dvipng)
3398 (const :tag "imagemagick" imagemagick)))
3400 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3401 "Path to store latex preview images. A relative path here creates many
3402 directories relative to the processed org files paths. An absolute path
3403 puts all preview images at the same place."
3404 :group 'org-latex
3405 ;; :version "24.3"
3406 :type 'string)
3408 (defun org-format-latex-mathml-available-p ()
3409 "Return t if `org-latex-to-mathml-convert-command' is usable."
3410 (save-match-data
3411 (when (and (boundp 'org-latex-to-mathml-convert-command)
3412 org-latex-to-mathml-convert-command)
3413 (let ((executable (car (split-string
3414 org-latex-to-mathml-convert-command))))
3415 (when (executable-find executable)
3416 (if (string-match
3417 "%j" org-latex-to-mathml-convert-command)
3418 (file-readable-p org-latex-to-mathml-jar-file)
3419 t))))))
3421 (defcustom org-format-latex-header "\\documentclass{article}
3422 \\usepackage[usenames]{color}
3423 \\usepackage{amsmath}
3424 \\usepackage[mathscr]{eucal}
3425 \\pagestyle{empty} % do not remove
3426 \[PACKAGES]
3427 \[DEFAULT-PACKAGES]
3428 % The settings below are copied from fullpage.sty
3429 \\setlength{\\textwidth}{\\paperwidth}
3430 \\addtolength{\\textwidth}{-3cm}
3431 \\setlength{\\oddsidemargin}{1.5cm}
3432 \\addtolength{\\oddsidemargin}{-2.54cm}
3433 \\setlength{\\evensidemargin}{\\oddsidemargin}
3434 \\setlength{\\textheight}{\\paperheight}
3435 \\addtolength{\\textheight}{-\\headheight}
3436 \\addtolength{\\textheight}{-\\headsep}
3437 \\addtolength{\\textheight}{-\\footskip}
3438 \\addtolength{\\textheight}{-3cm}
3439 \\setlength{\\topmargin}{1.5cm}
3440 \\addtolength{\\topmargin}{-2.54cm}"
3441 "The document header used for processing LaTeX fragments.
3442 It is imperative that this header make sure that no page number
3443 appears on the page. The package defined in the variables
3444 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3445 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3446 will be appended."
3447 :group 'org-latex
3448 :type 'string)
3450 (defvar org-format-latex-header-extra nil)
3452 (defun org-set-packages-alist (var val)
3453 "Set the packages alist and make sure it has 3 elements per entry."
3454 (set var (mapcar (lambda (x)
3455 (if (and (consp x) (= (length x) 2))
3456 (list (car x) (nth 1 x) t)
3458 val)))
3460 (defun org-get-packages-alist (var)
3462 "Get the packages alist and make sure it has 3 elements per entry."
3463 (mapcar (lambda (x)
3464 (if (and (consp x) (= (length x) 2))
3465 (list (car x) (nth 1 x) t)
3467 (default-value var)))
3469 ;; The following variables are defined here because is it also used
3470 ;; when formatting latex fragments. Originally it was part of the
3471 ;; LaTeX exporter, which is why the name includes "export".
3472 (defcustom org-export-latex-default-packages-alist
3473 '(("AUTO" "inputenc" t)
3474 ("T1" "fontenc" t)
3475 ("" "fixltx2e" nil)
3476 ("" "graphicx" t)
3477 ("" "longtable" nil)
3478 ("" "float" nil)
3479 ("" "wrapfig" nil)
3480 ("" "soul" t)
3481 ("" "textcomp" t)
3482 ("" "marvosym" t)
3483 ("" "wasysym" t)
3484 ("" "latexsym" t)
3485 ("" "amssymb" t)
3486 ("" "hyperref" nil)
3487 "\\tolerance=1000"
3489 "Alist of default packages to be inserted in the header.
3490 Change this only if one of the packages here causes an incompatibility
3491 with another package you are using.
3492 The packages in this list are needed by one part or another of Org-mode
3493 to function properly.
3495 - inputenc, fontenc: for basic font and character selection
3496 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3497 for interpreting the entities in `org-entities'. You can skip some of these
3498 packages if you don't use any of the symbols in it.
3499 - graphicx: for including images
3500 - float, wrapfig: for figure placement
3501 - longtable: for long tables
3502 - hyperref: for cross references
3504 Therefore you should not modify this variable unless you know what you
3505 are doing. The one reason to change it anyway is that you might be loading
3506 some other package that conflicts with one of the default packages.
3507 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3508 If SNIPPET-FLAG is t, the package also needs to be included when
3509 compiling LaTeX snippets into images for inclusion into HTML."
3510 :group 'org-export-latex
3511 :set 'org-set-packages-alist
3512 :get 'org-get-packages-alist
3513 :version "24.1"
3514 :type '(repeat
3515 (choice
3516 (list :tag "options/package pair"
3517 (string :tag "options")
3518 (string :tag "package")
3519 (boolean :tag "Snippet"))
3520 (string :tag "A line of LaTeX"))))
3522 (defcustom org-export-latex-packages-alist nil
3523 "Alist of packages to be inserted in every LaTeX header.
3524 These will be inserted after `org-export-latex-default-packages-alist'.
3525 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3526 SNIPPET-FLAG, when t, indicates that this package is also needed when
3527 turning LaTeX snippets into images for inclusion into HTML.
3528 Make sure that you only list packages here which:
3529 - you want in every file
3530 - do not conflict with the default packages in
3531 `org-export-latex-default-packages-alist'
3532 - do not conflict with the setup in `org-format-latex-header'."
3533 :group 'org-export-latex
3534 :set 'org-set-packages-alist
3535 :get 'org-get-packages-alist
3536 :type '(repeat
3537 (choice
3538 (list :tag "options/package pair"
3539 (string :tag "options")
3540 (string :tag "package")
3541 (boolean :tag "Snippet"))
3542 (string :tag "A line of LaTeX"))))
3545 (defgroup org-appearance nil
3546 "Settings for Org-mode appearance."
3547 :tag "Org Appearance"
3548 :group 'org)
3550 (defcustom org-level-color-stars-only nil
3551 "Non-nil means fontify only the stars in each headline.
3552 When nil, the entire headline is fontified.
3553 Changing it requires restart of `font-lock-mode' to become effective
3554 also in regions already fontified."
3555 :group 'org-appearance
3556 :type 'boolean)
3558 (defcustom org-hide-leading-stars nil
3559 "Non-nil means hide the first N-1 stars in a headline.
3560 This works by using the face `org-hide' for these stars. This
3561 face is white for a light background, and black for a dark
3562 background. You may have to customize the face `org-hide' to
3563 make this work.
3564 Changing it requires restart of `font-lock-mode' to become effective
3565 also in regions already fontified.
3566 You may also set this on a per-file basis by adding one of the following
3567 lines to the buffer:
3569 #+STARTUP: hidestars
3570 #+STARTUP: showstars"
3571 :group 'org-appearance
3572 :type 'boolean)
3574 (defcustom org-hidden-keywords nil
3575 "List of symbols corresponding to keywords to be hidden the org buffer.
3576 For example, a value '(title) for this list will make the document's title
3577 appear in the buffer without the initial #+TITLE: keyword."
3578 :group 'org-appearance
3579 :version "24.1"
3580 :type '(set (const :tag "#+AUTHOR" author)
3581 (const :tag "#+DATE" date)
3582 (const :tag "#+EMAIL" email)
3583 (const :tag "#+TITLE" title)))
3585 (defcustom org-custom-properties nil
3586 "List of properties (as strings) with a special meaning.
3587 The default use of these custom properties is to let the user
3588 hide them with `org-toggle-custom-properties-visibility'."
3589 :group 'org-properties
3590 :group 'org-appearance
3591 ;; :version "24.3"
3592 :type '(repeat (string :tag "Property Name")))
3594 (defcustom org-fontify-done-headline nil
3595 "Non-nil means change the face of a headline if it is marked DONE.
3596 Normally, only the TODO/DONE keyword indicates the state of a headline.
3597 When this is non-nil, the headline after the keyword is set to the
3598 `org-headline-done' as an additional indication."
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-fontify-emphasized-text t
3603 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3604 Changing this variable requires a restart of Emacs to take effect."
3605 :group 'org-appearance
3606 :type 'boolean)
3608 (defcustom org-fontify-whole-heading-line nil
3609 "Non-nil means fontify the whole line for headings.
3610 This is useful when setting a background color for the
3611 org-level-* faces."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-highlight-latex-fragments-and-specials nil
3616 "Non-nil means fontify what is treated specially by the exporters."
3617 :group 'org-appearance
3618 :type 'boolean)
3620 (defcustom org-hide-emphasis-markers nil
3621 "Non-nil mean font-lock should hide the emphasis marker characters."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-pretty-entities nil
3626 "Non-nil means show entities as UTF8 characters.
3627 When nil, the \\name form remains in the buffer."
3628 :group 'org-appearance
3629 :version "24.1"
3630 :type 'boolean)
3632 (defcustom org-pretty-entities-include-sub-superscripts t
3633 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3634 :group 'org-appearance
3635 :version "24.1"
3636 :type 'boolean)
3638 (defvar org-emph-re nil
3639 "Regular expression for matching emphasis.
3640 After a match, the match groups contain these elements:
3641 0 The match of the full regular expression, including the characters
3642 before and after the proper match
3643 1 The character before the proper match, or empty at beginning of line
3644 2 The proper match, including the leading and trailing markers
3645 3 The leading marker like * or /, indicating the type of highlighting
3646 4 The text between the emphasis markers, not including the markers
3647 5 The character after the match, empty at the end of a line")
3648 (defvar org-verbatim-re nil
3649 "Regular expression for matching verbatim text.")
3650 (defvar org-emphasis-regexp-components) ; defined just below
3651 (defvar org-emphasis-alist) ; defined just below
3652 (defun org-set-emph-re (var val)
3653 "Set variable and compute the emphasis regular expression."
3654 (set var val)
3655 (when (and (boundp 'org-emphasis-alist)
3656 (boundp 'org-emphasis-regexp-components)
3657 org-emphasis-alist org-emphasis-regexp-components)
3658 (let* ((e org-emphasis-regexp-components)
3659 (pre (car e))
3660 (post (nth 1 e))
3661 (border (nth 2 e))
3662 (body (nth 3 e))
3663 (nl (nth 4 e))
3664 (body1 (concat body "*?"))
3665 (markers (mapconcat 'car org-emphasis-alist ""))
3666 (vmarkers (mapconcat
3667 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3668 org-emphasis-alist "")))
3669 ;; make sure special characters appear at the right position in the class
3670 (if (string-match "\\^" markers)
3671 (setq markers (concat (replace-match "" t t markers) "^")))
3672 (if (string-match "-" markers)
3673 (setq markers (concat (replace-match "" t t markers) "-")))
3674 (if (string-match "\\^" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3676 (if (string-match "-" vmarkers)
3677 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3678 (if (> nl 0)
3679 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3680 (int-to-string nl) "\\}")))
3681 ;; Make the regexp
3682 (setq org-emph-re
3683 (concat "\\([" pre "]\\|^\\)"
3684 "\\("
3685 "\\([" markers "]\\)"
3686 "\\("
3687 "[^" border "]\\|"
3688 "[^" border "]"
3689 body1
3690 "[^" border "]"
3691 "\\)"
3692 "\\3\\)"
3693 "\\([" post "]\\|$\\)"))
3694 (setq org-verbatim-re
3695 (concat "\\([" pre "]\\|^\\)"
3696 "\\("
3697 "\\([" vmarkers "]\\)"
3698 "\\("
3699 "[^" border "]\\|"
3700 "[^" border "]"
3701 body1
3702 "[^" border "]"
3703 "\\)"
3704 "\\3\\)"
3705 "\\([" post "]\\|$\\)")))))
3707 (defcustom org-emphasis-regexp-components
3708 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3709 "Components used to build the regular expression for emphasis.
3710 This is a list with five entries. Terminology: In an emphasis string
3711 like \" *strong word* \", we call the initial space PREMATCH, the final
3712 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3713 and \"trong wor\" is the body. The different components in this variable
3714 specify what is allowed/forbidden in each part:
3716 pre Chars allowed as prematch. Beginning of line will be allowed too.
3717 post Chars allowed as postmatch. End of line will be allowed too.
3718 border The chars *forbidden* as border characters.
3719 body-regexp A regexp like \".\" to match a body character. Don't use
3720 non-shy groups here, and don't allow newline here.
3721 newline The maximum number of newlines allowed in an emphasis exp.
3723 Use customize to modify this, or restart Emacs after changing it."
3724 :group 'org-appearance
3725 :set 'org-set-emph-re
3726 :type '(list
3727 (sexp :tag "Allowed chars in pre ")
3728 (sexp :tag "Allowed chars in post ")
3729 (sexp :tag "Forbidden chars in border ")
3730 (sexp :tag "Regexp for body ")
3731 (integer :tag "number of newlines allowed")
3732 (option (boolean :tag "Please ignore this button"))))
3734 (defcustom org-emphasis-alist
3735 `(("*" bold "<b>" "</b>")
3736 ("/" italic "<i>" "</i>")
3737 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3738 ("=" org-code "<code>" "</code>" verbatim)
3739 ("~" org-verbatim "<code>" "</code>" verbatim)
3740 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3741 "<del>" "</del>")
3743 "Special syntax for emphasized text.
3744 Text starting and ending with a special character will be emphasized, for
3745 example *bold*, _underlined_ and /italic/. This variable sets the marker
3746 characters, the face to be used by font-lock for highlighting in Org-mode
3747 Emacs buffers, and the HTML tags to be used for this.
3748 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3749 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3750 Use customize to modify this, or restart Emacs after changing it."
3751 :group 'org-appearance
3752 :set 'org-set-emph-re
3753 :type '(repeat
3754 (list
3755 (string :tag "Marker character")
3756 (choice
3757 (face :tag "Font-lock-face")
3758 (plist :tag "Face property list"))
3759 (string :tag "HTML start tag")
3760 (string :tag "HTML end tag")
3761 (option (const verbatim)))))
3763 (defvar org-protecting-blocks
3764 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3765 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3766 This is needed for font-lock setup.")
3768 ;;; Miscellaneous options
3770 (defgroup org-completion nil
3771 "Completion in Org-mode."
3772 :tag "Org Completion"
3773 :group 'org)
3775 (defcustom org-completion-use-ido nil
3776 "Non-nil means use ido completion wherever possible.
3777 Note that `ido-mode' must be active for this variable to be relevant.
3778 If you decide to turn this variable on, you might well want to turn off
3779 `org-outline-path-complete-in-steps'.
3780 See also `org-completion-use-iswitchb'."
3781 :group 'org-completion
3782 :type 'boolean)
3784 (defcustom org-completion-use-iswitchb nil
3785 "Non-nil means use iswitchb completion wherever possible.
3786 Note that `iswitchb-mode' must be active for this variable to be relevant.
3787 If you decide to turn this variable on, you might well want to turn off
3788 `org-outline-path-complete-in-steps'.
3789 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3790 :group 'org-completion
3791 :type 'boolean)
3793 (defcustom org-completion-fallback-command 'hippie-expand
3794 "The expansion command called by \\[pcomplete] in normal context.
3795 Normal means, no org-mode-specific context."
3796 :group 'org-completion
3797 :type 'function)
3799 ;;; Functions and variables from their packages
3800 ;; Declared here to avoid compiler warnings
3802 ;; XEmacs only
3803 (defvar outline-mode-menu-heading)
3804 (defvar outline-mode-menu-show)
3805 (defvar outline-mode-menu-hide)
3806 (defvar zmacs-regions) ; XEmacs regions
3808 ;; Emacs only
3809 (defvar mark-active)
3811 ;; Various packages
3812 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3813 (declare-function calendar-forward-day "cal-move" (arg))
3814 (declare-function calendar-goto-date "cal-move" (date))
3815 (declare-function calendar-goto-today "cal-move" ())
3816 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3817 (defvar calc-embedded-close-formula)
3818 (defvar calc-embedded-open-formula)
3819 (declare-function cdlatex-tab "ext:cdlatex" ())
3820 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3821 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3822 (defvar font-lock-unfontify-region-function)
3823 (declare-function iswitchb-read-buffer "iswitchb"
3824 (prompt &optional default require-match start matches-set))
3825 (defvar iswitchb-temp-buflist)
3826 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3827 (defvar org-agenda-tags-todo-honor-ignore-options)
3828 (declare-function org-agenda-skip "org-agenda" ())
3829 (declare-function
3830 org-agenda-format-item "org-agenda"
3831 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3832 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3833 (declare-function org-agenda-change-all-lines "org-agenda"
3834 (newhead hdmarker &optional fixface just-this))
3835 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3836 (declare-function org-agenda-maybe-redo "org-agenda" ())
3837 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3838 (beg end))
3839 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3840 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3841 "org-agenda" (&optional end))
3842 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3843 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3844 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3845 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3846 (declare-function org-indent-mode "org-indent" (&optional arg))
3847 (declare-function parse-time-string "parse-time" (string))
3848 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3849 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3850 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3851 (defvar remember-data-file)
3852 (defvar texmathp-why)
3853 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3854 (declare-function table--at-cell-p "table" (position &optional object at-column))
3856 (defvar w3m-current-url)
3857 (defvar w3m-current-title)
3859 (defvar org-latex-regexps)
3861 ;;; Autoload and prepare some org modules
3863 ;; Some table stuff that needs to be defined here, because it is used
3864 ;; by the functions setting up org-mode or checking for table context.
3866 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3867 "Detect an org-type or table-type table.")
3868 (defconst org-table-line-regexp "^[ \t]*|"
3869 "Detect an org-type table line.")
3870 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3871 "Detect an org-type table line.")
3872 (defconst org-table-hline-regexp "^[ \t]*|-"
3873 "Detect an org-type table hline.")
3874 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3875 "Detect a table-type table hline.")
3876 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3877 "Detect the first line outside a table when searching from within it.
3878 This works for both table types.")
3880 ;; Autoload the functions in org-table.el that are needed by functions here.
3882 (eval-and-compile
3883 (org-autoload "org-table"
3884 '(org-table-align org-table-begin org-table-blank-field
3885 org-table-convert org-table-convert-region org-table-copy-down
3886 org-table-copy-region org-table-create
3887 org-table-create-or-convert-from-region
3888 org-table-create-with-table.el org-table-current-dline
3889 org-table-cut-region org-table-delete-column org-table-edit-field
3890 org-table-edit-formulas org-table-end org-table-eval-formula
3891 org-table-export org-table-field-info
3892 org-table-get-stored-formulas org-table-goto-column
3893 org-table-hline-and-move org-table-import org-table-insert-column
3894 org-table-insert-hline org-table-insert-row org-table-iterate
3895 org-table-justify-field-maybe org-table-kill-row
3896 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3897 org-table-move-column org-table-move-column-left
3898 org-table-move-column-right org-table-move-row
3899 org-table-move-row-down org-table-move-row-up
3900 org-table-next-field org-table-next-row org-table-paste-rectangle
3901 org-table-previous-field org-table-recalculate
3902 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3903 org-table-toggle-coordinate-overlays
3904 org-table-toggle-formula-debugger org-table-wrap-region
3905 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3906 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3907 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3909 (defun org-at-table-p (&optional table-type)
3910 "Return t if the cursor is inside an org-type table.
3911 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3912 (if org-enable-table-editor
3913 (save-excursion
3914 (beginning-of-line 1)
3915 (looking-at (if table-type org-table-any-line-regexp
3916 org-table-line-regexp)))
3917 nil))
3918 (defsubst org-table-p () (org-at-table-p))
3920 (defun org-at-table.el-p ()
3921 "Return t if and only if we are at a table.el table."
3922 (and (org-at-table-p 'any)
3923 (save-excursion
3924 (goto-char (org-table-begin 'any))
3925 (looking-at org-table1-hline-regexp))))
3926 (defun org-table-recognize-table.el ()
3927 "If there is a table.el table nearby, recognize it and move into it."
3928 (if org-table-tab-recognizes-table.el
3929 (if (org-at-table.el-p)
3930 (progn
3931 (beginning-of-line 1)
3932 (if (looking-at org-table-dataline-regexp)
3934 (if (looking-at org-table1-hline-regexp)
3935 (progn
3936 (beginning-of-line 2)
3937 (if (looking-at org-table-any-border-regexp)
3938 (beginning-of-line -1)))))
3939 (if (re-search-forward "|" (org-table-end t) t)
3940 (progn
3941 (require 'table)
3942 (if (table--at-cell-p (point))
3944 (message "recognizing table.el table...")
3945 (table-recognize-table)
3946 (message "recognizing table.el table...done")))
3947 (error "This should not happen"))
3949 nil)
3950 nil))
3952 (defun org-at-table-hline-p ()
3953 "Return t if the cursor is inside a hline in a table."
3954 (if org-enable-table-editor
3955 (save-excursion
3956 (beginning-of-line 1)
3957 (looking-at org-table-hline-regexp))
3958 nil))
3960 (defvar org-table-clean-did-remove-column nil)
3962 (defun org-table-map-tables (function &optional quietly)
3963 "Apply FUNCTION to the start of all tables in the buffer."
3964 (save-excursion
3965 (save-restriction
3966 (widen)
3967 (goto-char (point-min))
3968 (while (re-search-forward org-table-any-line-regexp nil t)
3969 (unless quietly
3970 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3971 (beginning-of-line 1)
3972 (when (and (looking-at org-table-line-regexp)
3973 ;; Exclude tables in src/example/verbatim/clocktable blocks
3974 (not (org-in-block-p '("src" "example"))))
3975 (save-excursion (funcall function))
3976 (or (looking-at org-table-line-regexp)
3977 (forward-char 1)))
3978 (re-search-forward org-table-any-border-regexp nil 1))))
3979 (unless quietly (message "Mapping tables: done")))
3981 ;; Declare and autoload functions from org-exp.el & Co
3983 (declare-function org-default-export-plist "org-exp")
3984 (declare-function org-infile-export-plist "org-exp")
3985 (declare-function org-get-current-options "org-exp")
3986 (eval-and-compile
3987 (org-autoload "org-exp"
3988 '(org-export org-export-visible
3989 org-insert-export-options-template
3990 org-table-clean-before-export))
3991 (org-autoload "org-ascii"
3992 '(org-export-as-ascii org-export-ascii-preprocess
3993 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3994 org-export-region-as-ascii))
3995 (org-autoload "org-latex"
3996 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3997 org-replace-region-by-latex org-export-region-as-latex
3998 org-export-as-latex org-export-as-pdf
3999 org-export-as-pdf-and-open))
4000 (org-autoload "org-html"
4001 '(org-export-as-html-and-open
4002 org-export-as-html-batch org-export-as-html-to-buffer
4003 org-replace-region-by-html org-export-region-as-html
4004 org-export-as-html))
4005 (org-autoload "org-docbook"
4006 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4007 org-replace-region-by-docbook org-export-region-as-docbook
4008 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4009 org-export-as-docbook))
4010 (org-autoload "org-icalendar"
4011 '(org-export-icalendar-this-file
4012 org-export-icalendar-all-agenda-files
4013 org-export-icalendar-combine-agenda-files))
4014 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4015 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4017 ;; Declare and autoload functions from org-agenda.el
4019 (eval-and-compile
4020 (org-autoload "org-agenda"
4021 '(org-agenda org-agenda-list org-search-view
4022 org-todo-list org-tags-view org-agenda-list-stuck-projects
4023 org-diary org-agenda-to-appt
4024 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4026 ;; Autoload org-remember
4028 (eval-and-compile
4029 (org-autoload "org-remember"
4030 '(org-remember-insinuate org-remember-annotation
4031 org-remember-apply-template org-remember org-remember-handler)))
4033 (eval-and-compile
4034 (org-autoload "org-capture"
4035 '(org-capture org-capture-insert-template-here
4036 org-capture-import-remember-templates)))
4038 ;; Autoload org-clock.el
4040 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4041 (beg end))
4042 (declare-function org-clock-update-mode-line "org-clock" ())
4043 (declare-function org-resolve-clocks "org-clock"
4044 (&optional also-non-dangling-p prompt last-valid))
4045 (defvar org-clock-start-time)
4046 (defvar org-clock-marker (make-marker)
4047 "Marker recording the last clock-in.")
4048 (defvar org-clock-hd-marker (make-marker)
4049 "Marker recording the last clock-in, but the headline position.")
4050 (defvar org-clock-heading ""
4051 "The heading of the current clock entry.")
4052 (defun org-clock-is-active ()
4053 "Return non-nil if clock is currently running.
4054 The return value is actually the clock marker."
4055 (marker-buffer org-clock-marker))
4057 (eval-and-compile
4058 (org-autoload
4059 "org-clock"
4060 '(org-clock-in org-clock-out org-clock-cancel
4061 org-clock-goto org-clock-sum org-clock-display
4062 org-clock-remove-overlays org-clock-report
4063 org-clocktable-shift org-dblock-write:clocktable
4064 org-get-clocktable org-resolve-clocks)))
4066 (defun org-clock-update-time-maybe ()
4067 "If this is a CLOCK line, update it and return t.
4068 Otherwise, return nil."
4069 (interactive)
4070 (save-excursion
4071 (beginning-of-line 1)
4072 (skip-chars-forward " \t")
4073 (when (looking-at org-clock-string)
4074 (let ((re (concat "[ \t]*" org-clock-string
4075 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4076 "\\([ \t]*=>.*\\)?\\)?"))
4077 ts te h m s neg)
4078 (cond
4079 ((not (looking-at re))
4080 nil)
4081 ((not (match-end 2))
4082 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4083 (> org-clock-marker (point))
4084 (<= org-clock-marker (point-at-eol)))
4085 ;; The clock is running here
4086 (setq org-clock-start-time
4087 (apply 'encode-time
4088 (org-parse-time-string (match-string 1))))
4089 (org-clock-update-mode-line)))
4091 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4092 (end-of-line 1)
4093 (setq ts (match-string 1)
4094 te (match-string 3))
4095 (setq s (- (org-float-time
4096 (apply 'encode-time (org-parse-time-string te)))
4097 (org-float-time
4098 (apply 'encode-time (org-parse-time-string ts))))
4099 neg (< s 0)
4100 s (abs s)
4101 h (floor (/ s 3600))
4102 s (- s (* 3600 h))
4103 m (floor (/ s 60))
4104 s (- s (* 60 s)))
4105 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4106 t))))))
4108 (defun org-check-running-clock ()
4109 "Check if the current buffer contains the running clock.
4110 If yes, offer to stop it and to save the buffer with the changes."
4111 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4112 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4113 (buffer-name))))
4114 (org-clock-out)
4115 (when (y-or-n-p "Save changed buffer?")
4116 (save-buffer))))
4118 (defun org-clocktable-try-shift (dir n)
4119 "Check if this line starts a clock table, if yes, shift the time block."
4120 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4121 (org-clocktable-shift dir n)))
4123 ;; Autoload org-timer.el
4125 (eval-and-compile
4126 (org-autoload
4127 "org-timer"
4128 '(org-timer-start org-timer org-timer-item
4129 org-timer-change-times-in-region
4130 org-timer-set-timer
4131 org-timer-reset-timers
4132 org-timer-show-remaining-time)))
4134 ;; Autoload org-feed.el
4136 (eval-and-compile
4137 (org-autoload
4138 "org-feed"
4139 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4142 ;; Autoload org-indent.el
4144 ;; Define the variable already here, to make sure we have it.
4145 (defvar org-indent-mode nil
4146 "Non-nil if Org-Indent mode is enabled.
4147 Use the command `org-indent-mode' to change this variable.")
4149 (eval-and-compile
4150 (org-autoload
4151 "org-indent"
4152 '(org-indent-mode)))
4154 ;; Autoload org-mobile.el
4156 (eval-and-compile
4157 (org-autoload
4158 "org-mobile"
4159 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4161 ;; Autoload archiving code
4162 ;; The stuff that is needed for cycling and tags has to be defined here.
4164 (defgroup org-archive nil
4165 "Options concerning archiving in Org-mode."
4166 :tag "Org Archive"
4167 :group 'org-structure)
4169 (defcustom org-archive-location "%s_archive::"
4170 "The location where subtrees should be archived.
4172 The value of this variable is a string, consisting of two parts,
4173 separated by a double-colon. The first part is a filename and
4174 the second part is a headline.
4176 When the filename is omitted, archiving happens in the same file.
4177 %s in the filename will be replaced by the current file
4178 name (without the directory part). Archiving to a different file
4179 is useful to keep archived entries from contributing to the
4180 Org-mode Agenda.
4182 The archived entries will be filed as subtrees of the specified
4183 headline. When the headline is omitted, the subtrees are simply
4184 filed away at the end of the file, as top-level entries. Also in
4185 the heading you can use %s to represent the file name, this can be
4186 useful when using the same archive for a number of different files.
4188 Here are a few examples:
4189 \"%s_archive::\"
4190 If the current file is Projects.org, archive in file
4191 Projects.org_archive, as top-level trees. This is the default.
4193 \"::* Archived Tasks\"
4194 Archive in the current file, under the top-level headline
4195 \"* Archived Tasks\".
4197 \"~/org/archive.org::\"
4198 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4200 \"~/org/archive.org::* From %s\"
4201 Archive in file ~/org/archive.org (absolute path), under headlines
4202 \"From FILENAME\" where file name is the current file name.
4204 \"~/org/datetree.org::datetree/* Finished Tasks\"
4205 The \"datetree/\" string is special, signifying to archive
4206 items to the datetree. Items are placed in either the CLOSED
4207 date of the item, or the current date if there is no CLOSED date.
4208 The heading will be a subentry to the current date. There doesn't
4209 need to be a heading, but there always needs to be a slash after
4210 datetree. For example, to store archived items directly in the
4211 datetree, use \"~/org/datetree.org::datetree/\".
4213 \"basement::** Finished Tasks\"
4214 Archive in file ./basement (relative path), as level 3 trees
4215 below the level 2 heading \"** Finished Tasks\".
4217 You may set this option on a per-file basis by adding to the buffer a
4218 line like
4220 #+ARCHIVE: basement::** Finished Tasks
4222 You may also define it locally for a subtree by setting an ARCHIVE property
4223 in the entry. If such a property is found in an entry, or anywhere up
4224 the hierarchy, it will be used."
4225 :group 'org-archive
4226 :type 'string)
4228 (defcustom org-archive-tag "ARCHIVE"
4229 "The tag that marks a subtree as archived.
4230 An archived subtree does not open during visibility cycling, and does
4231 not contribute to the agenda listings.
4232 After changing this, font-lock must be restarted in the relevant buffers to
4233 get the proper fontification."
4234 :group 'org-archive
4235 :group 'org-keywords
4236 :type 'string)
4238 (defcustom org-agenda-skip-archived-trees t
4239 "Non-nil means the agenda will skip any items located in archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4241 variable is no longer recommended, you should leave it at the value t.
4242 Instead, use the key `v' to cycle the archives-mode in the agenda."
4243 :group 'org-archive
4244 :group 'org-agenda-skip
4245 :type 'boolean)
4247 (defcustom org-columns-skip-archived-trees t
4248 "Non-nil means ignore archived trees when creating column view."
4249 :group 'org-archive
4250 :group 'org-properties
4251 :type 'boolean)
4253 (defcustom org-cycle-open-archived-trees nil
4254 "Non-nil means `org-cycle' will open archived trees.
4255 An archived tree is a tree marked with the tag ARCHIVE.
4256 When nil, archived trees will stay folded. You can still open them with
4257 normal outline commands like `show-all', but not with the cycling commands."
4258 :group 'org-archive
4259 :group 'org-cycle
4260 :type 'boolean)
4262 (defcustom org-sparse-tree-open-archived-trees nil
4263 "Non-nil means sparse tree construction shows matches in archived trees.
4264 When nil, matches in these trees are highlighted, but the trees are kept in
4265 collapsed state."
4266 :group 'org-archive
4267 :group 'org-sparse-trees
4268 :type 'boolean)
4270 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4271 "The default date type when building a sparse tree.
4272 When this is nil, a date is a scheduled or a deadline timestamp.
4273 Otherwise, these types are allowed:
4275 all: all timestamps
4276 active: only active timestamps (<...>)
4277 inactive: only inactive timestamps (<...)
4278 scheduled: only scheduled timestamps
4279 deadline: only deadline timestamps"
4280 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4281 (const :tag "All timestamps" all)
4282 (const :tag "Only active timestamps" active)
4283 (const :tag "Only inactive timestamps" inactive)
4284 (const :tag "Only scheduled timestamps" scheduled)
4285 (const :tag "Only deadline timestamps" deadline))
4286 ;; :version "24.3"
4287 :group 'org-sparse-trees)
4289 (defun org-cycle-hide-archived-subtrees (state)
4290 "Re-hide all archived subtrees after a visibility state change."
4291 (when (and (not org-cycle-open-archived-trees)
4292 (not (memq state '(overview folded))))
4293 (save-excursion
4294 (let* ((globalp (memq state '(contents all)))
4295 (beg (if globalp (point-min) (point)))
4296 (end (if globalp (point-max) (org-end-of-subtree t))))
4297 (org-hide-archived-subtrees beg end)
4298 (goto-char beg)
4299 (if (looking-at (concat ".*:" org-archive-tag ":"))
4300 (message "%s" (substitute-command-keys
4301 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4303 (defun org-force-cycle-archived ()
4304 "Cycle subtree even if it is archived."
4305 (interactive)
4306 (setq this-command 'org-cycle)
4307 (let ((org-cycle-open-archived-trees t))
4308 (call-interactively 'org-cycle)))
4310 (defun org-hide-archived-subtrees (beg end)
4311 "Re-hide all archived subtrees after a visibility state change."
4312 (save-excursion
4313 (let* ((re (concat ":" org-archive-tag ":")))
4314 (goto-char beg)
4315 (while (re-search-forward re end t)
4316 (when (org-at-heading-p)
4317 (org-flag-subtree t)
4318 (org-end-of-subtree t))))))
4320 (declare-function outline-end-of-heading "outline" ())
4321 (declare-function outline-flag-region "outline" (from to flag))
4322 (defun org-flag-subtree (flag)
4323 (save-excursion
4324 (org-back-to-heading t)
4325 (outline-end-of-heading)
4326 (outline-flag-region (point)
4327 (progn (org-end-of-subtree t) (point))
4328 flag)))
4330 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4332 (eval-and-compile
4333 (org-autoload "org-archive"
4334 '(org-add-archive-files org-archive-subtree
4335 org-archive-to-archive-sibling org-toggle-archive-tag
4336 org-archive-subtree-default
4337 org-archive-subtree-default-with-confirmation)))
4339 ;; Autoload Column View Code
4341 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4342 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4343 (declare-function org-columns-compute "org-colview" (property))
4345 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4346 '(org-columns-number-to-string org-columns-get-format-and-top-level
4347 org-columns-compute org-agenda-columns org-columns-remove-overlays
4348 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4350 ;; Autoload ID code
4352 (declare-function org-id-store-link "org-id")
4353 (declare-function org-id-locations-load "org-id")
4354 (declare-function org-id-locations-save "org-id")
4355 (defvar org-id-track-globally)
4356 (org-autoload "org-id"
4357 '(org-id-get-create org-id-new org-id-copy org-id-get
4358 org-id-get-with-outline-path-completion
4359 org-id-get-with-outline-drilling org-id-store-link
4360 org-id-goto org-id-find org-id-store-link))
4362 ;; Autoload Plotting Code
4364 (org-autoload "org-plot"
4365 '(org-plot/gnuplot))
4367 ;;; Variables for pre-computed regular expressions, all buffer local
4369 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4370 "Matches first line of a hidden block.")
4371 (make-variable-buffer-local 'org-drawer-regexp)
4372 (defvar org-todo-regexp nil
4373 "Matches any of the TODO state keywords.")
4374 (make-variable-buffer-local 'org-todo-regexp)
4375 (defvar org-not-done-regexp nil
4376 "Matches any of the TODO state keywords except the last one.")
4377 (make-variable-buffer-local 'org-not-done-regexp)
4378 (defvar org-not-done-heading-regexp nil
4379 "Matches a TODO headline that is not done.")
4380 (make-variable-buffer-local 'org-not-done-regexp)
4381 (defvar org-todo-line-regexp nil
4382 "Matches a headline and puts TODO state into group 2 if present.")
4383 (make-variable-buffer-local 'org-todo-line-regexp)
4384 (defvar org-complex-heading-regexp nil
4385 "Matches a headline and puts everything into groups:
4386 group 1: the stars
4387 group 2: The todo keyword, maybe
4388 group 3: Priority cookie
4389 group 4: True headline
4390 group 5: Tags")
4391 (make-variable-buffer-local 'org-complex-heading-regexp)
4392 (defvar org-complex-heading-regexp-format nil
4393 "Printf format to make regexp to match an exact headline.
4394 This regexp will match the headline of any node which has the
4395 exact headline text that is put into the format, but may have any
4396 TODO state, priority and tags.")
4397 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4398 (defvar org-todo-line-tags-regexp nil
4399 "Matches a headline and puts TODO state into group 2 if present.
4400 Also put tags into group 4 if tags are present.")
4401 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4402 (defvar org-ds-keyword-length 12
4403 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4404 (make-variable-buffer-local 'org-ds-keyword-length)
4405 (defvar org-deadline-regexp nil
4406 "Matches the DEADLINE keyword.")
4407 (make-variable-buffer-local 'org-deadline-regexp)
4408 (defvar org-deadline-time-regexp nil
4409 "Matches the DEADLINE keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-deadline-time-regexp)
4411 (defvar org-deadline-line-regexp nil
4412 "Matches the DEADLINE keyword and the rest of the line.")
4413 (make-variable-buffer-local 'org-deadline-line-regexp)
4414 (defvar org-scheduled-regexp nil
4415 "Matches the SCHEDULED keyword.")
4416 (make-variable-buffer-local 'org-scheduled-regexp)
4417 (defvar org-scheduled-time-regexp nil
4418 "Matches the SCHEDULED keyword together with a time stamp.")
4419 (make-variable-buffer-local 'org-scheduled-time-regexp)
4420 (defvar org-closed-time-regexp nil
4421 "Matches the CLOSED keyword together with a time stamp.")
4422 (make-variable-buffer-local 'org-closed-time-regexp)
4424 (defvar org-keyword-time-regexp nil
4425 "Matches any of the 4 keywords, together with the time stamp.")
4426 (make-variable-buffer-local 'org-keyword-time-regexp)
4427 (defvar org-keyword-time-not-clock-regexp nil
4428 "Matches any of the 3 keywords, together with the time stamp.")
4429 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4430 (defvar org-maybe-keyword-time-regexp nil
4431 "Matches a timestamp, possibly preceded by a keyword.")
4432 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4433 (defvar org-all-time-keywords nil
4434 "List of time keywords.")
4435 (make-variable-buffer-local 'org-all-time-keywords)
4437 (defconst org-plain-time-of-day-regexp
4438 (concat
4439 "\\(\\<[012]?[0-9]"
4440 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4441 "\\(--?"
4442 "\\(\\<[012]?[0-9]"
4443 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4444 "\\)?")
4445 "Regular expression to match a plain time or time range.
4446 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4447 groups carry important information:
4448 0 the full match
4449 1 the first time, range or not
4450 8 the second time, if it is a range.")
4452 (defconst org-plain-time-extension-regexp
4453 (concat
4454 "\\(\\<[012]?[0-9]"
4455 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4456 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4457 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4458 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4459 groups carry important information:
4460 0 the full match
4461 7 hours of duration
4462 9 minutes of duration")
4464 (defconst org-stamp-time-of-day-regexp
4465 (concat
4466 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4467 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4468 "\\(--?"
4469 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4470 "Regular expression to match a timestamp time or time range.
4471 After a match, the following groups carry important information:
4472 0 the full match
4473 1 date plus weekday, for back referencing to make sure both times are on the same day
4474 2 the first time, range or not
4475 4 the second time, if it is a range.")
4477 (defconst org-startup-options
4478 '(("fold" org-startup-folded t)
4479 ("overview" org-startup-folded t)
4480 ("nofold" org-startup-folded nil)
4481 ("showall" org-startup-folded nil)
4482 ("showeverything" org-startup-folded showeverything)
4483 ("content" org-startup-folded content)
4484 ("indent" org-startup-indented t)
4485 ("noindent" org-startup-indented nil)
4486 ("hidestars" org-hide-leading-stars t)
4487 ("showstars" org-hide-leading-stars nil)
4488 ("odd" org-odd-levels-only t)
4489 ("oddeven" org-odd-levels-only nil)
4490 ("align" org-startup-align-all-tables t)
4491 ("noalign" org-startup-align-all-tables nil)
4492 ("inlineimages" org-startup-with-inline-images t)
4493 ("noinlineimages" org-startup-with-inline-images nil)
4494 ("customtime" org-display-custom-times t)
4495 ("logdone" org-log-done time)
4496 ("lognotedone" org-log-done note)
4497 ("nologdone" org-log-done nil)
4498 ("lognoteclock-out" org-log-note-clock-out t)
4499 ("nolognoteclock-out" org-log-note-clock-out nil)
4500 ("logrepeat" org-log-repeat state)
4501 ("lognoterepeat" org-log-repeat note)
4502 ("nologrepeat" org-log-repeat nil)
4503 ("logreschedule" org-log-reschedule time)
4504 ("lognotereschedule" org-log-reschedule note)
4505 ("nologreschedule" org-log-reschedule nil)
4506 ("logredeadline" org-log-redeadline time)
4507 ("lognoteredeadline" org-log-redeadline note)
4508 ("nologredeadline" org-log-redeadline nil)
4509 ("logrefile" org-log-refile time)
4510 ("lognoterefile" org-log-refile note)
4511 ("nologrefile" org-log-refile nil)
4512 ("fninline" org-footnote-define-inline t)
4513 ("nofninline" org-footnote-define-inline nil)
4514 ("fnlocal" org-footnote-section nil)
4515 ("fnauto" org-footnote-auto-label t)
4516 ("fnprompt" org-footnote-auto-label nil)
4517 ("fnconfirm" org-footnote-auto-label confirm)
4518 ("fnplain" org-footnote-auto-label plain)
4519 ("fnadjust" org-footnote-auto-adjust t)
4520 ("nofnadjust" org-footnote-auto-adjust nil)
4521 ("constcgs" constants-unit-system cgs)
4522 ("constSI" constants-unit-system SI)
4523 ("noptag" org-tag-persistent-alist nil)
4524 ("hideblocks" org-hide-block-startup t)
4525 ("nohideblocks" org-hide-block-startup nil)
4526 ("beamer" org-startup-with-beamer-mode t)
4527 ("entitiespretty" org-pretty-entities t)
4528 ("entitiesplain" org-pretty-entities nil))
4529 "Variable associated with STARTUP options for org-mode.
4530 Each element is a list of three items: the startup options (as written
4531 in the #+STARTUP line), the corresponding variable, and the value to set
4532 this variable to if the option is found. An optional forth element PUSH
4533 means to push this value onto the list in the variable.")
4535 (defun org-update-property-plist (key val props)
4536 "Update PROPS with KEY and VAL."
4537 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4538 (key (if appending (substring key 0 (- (length key) 1)) key))
4539 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4540 (previous (cdr (assoc key props))))
4541 (if appending
4542 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4543 (cons (cons key val) remainder))))
4545 (defconst org-block-regexp
4546 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4547 "Regular expression for hiding blocks.")
4548 (defconst org-heading-keyword-regexp-format
4549 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4550 "Printf format for a regexp matching an headline with some keyword.
4551 This regexp will match the headline of any node which has the
4552 exact keyword that is put into the format. The keyword isn't in
4553 any group by default, but the stars and the body are.")
4554 (defconst org-heading-keyword-maybe-regexp-format
4555 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4556 "Printf format for a regexp matching an headline, possibly with some keyword.
4557 This regexp can match any headline with the specified keyword, or
4558 without a keyword. The keyword isn't in any group by default,
4559 but the stars and the body are.")
4561 (defun org-set-regexps-and-options ()
4562 "Precompute regular expressions for current buffer."
4563 (when (derived-mode-p 'org-mode)
4564 (org-set-local 'org-todo-kwd-alist nil)
4565 (org-set-local 'org-todo-key-alist nil)
4566 (org-set-local 'org-todo-key-trigger nil)
4567 (org-set-local 'org-todo-keywords-1 nil)
4568 (org-set-local 'org-done-keywords nil)
4569 (org-set-local 'org-todo-heads nil)
4570 (org-set-local 'org-todo-sets nil)
4571 (org-set-local 'org-todo-log-states nil)
4572 (org-set-local 'org-file-properties nil)
4573 (org-set-local 'org-file-tags nil)
4574 (let ((re (org-make-options-regexp
4575 '("CATEGORY" "TODO" "COLUMNS"
4576 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4577 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4578 "OPTIONS")
4579 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4580 (splitre "[ \t]+")
4581 (scripts org-use-sub-superscripts)
4582 kwds kws0 kwsa key log value cat arch tags const links hw dws
4583 tail sep kws1 prio props ftags drawers beamer-p
4584 ext-setup-or-nil setup-contents (start 0))
4585 (save-excursion
4586 (save-restriction
4587 (widen)
4588 (goto-char (point-min))
4589 (while (or (and ext-setup-or-nil
4590 (string-match re ext-setup-or-nil start)
4591 (setq start (match-end 0)))
4592 (and (setq ext-setup-or-nil nil start 0)
4593 (re-search-forward re nil t)))
4594 (setq key (upcase (match-string 1 ext-setup-or-nil))
4595 value (org-match-string-no-properties 2 ext-setup-or-nil))
4596 (if (stringp value) (setq value (org-trim value)))
4597 (cond
4598 ((equal key "CATEGORY")
4599 (setq cat value))
4600 ((member key '("SEQ_TODO" "TODO"))
4601 (push (cons 'sequence (org-split-string value splitre)) kwds))
4602 ((equal key "TYP_TODO")
4603 (push (cons 'type (org-split-string value splitre)) kwds))
4604 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4605 ;; general TODO-like setup
4606 (push (cons (intern (downcase (match-string 1 key)))
4607 (org-split-string value splitre)) kwds))
4608 ((equal key "TAGS")
4609 (setq tags (append tags (if tags '("\\n") nil)
4610 (org-split-string value splitre))))
4611 ((equal key "COLUMNS")
4612 (org-set-local 'org-columns-default-format value))
4613 ((equal key "LINK")
4614 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4615 (push (cons (match-string 1 value)
4616 (org-trim (match-string 2 value)))
4617 links)))
4618 ((equal key "PRIORITIES")
4619 (setq prio (org-split-string value " +")))
4620 ((equal key "PROPERTY")
4621 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4622 (setq props (org-update-property-plist (match-string 1 value)
4623 (match-string 2 value)
4624 props))))
4625 ((equal key "FILETAGS")
4626 (when (string-match "\\S-" value)
4627 (setq ftags
4628 (append
4629 ftags
4630 (apply 'append
4631 (mapcar (lambda (x) (org-split-string x ":"))
4632 (org-split-string value)))))))
4633 ((equal key "DRAWERS")
4634 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4635 ((equal key "CONSTANTS")
4636 (setq const (append const (org-split-string value splitre))))
4637 ((equal key "STARTUP")
4638 (let ((opts (org-split-string value splitre))
4639 l var val)
4640 (while (setq l (pop opts))
4641 (when (setq l (assoc l org-startup-options))
4642 (setq var (nth 1 l) val (nth 2 l))
4643 (if (not (nth 3 l))
4644 (set (make-local-variable var) val)
4645 (if (not (listp (symbol-value var)))
4646 (set (make-local-variable var) nil))
4647 (set (make-local-variable var) (symbol-value var))
4648 (add-to-list var val))))))
4649 ((equal key "ARCHIVE")
4650 (setq arch value)
4651 (remove-text-properties 0 (length arch)
4652 '(face t fontified t) arch))
4653 ((equal key "LATEX_CLASS")
4654 (setq beamer-p (equal value "beamer")))
4655 ((equal key "OPTIONS")
4656 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4657 (setq scripts (read (match-string 2 value)))))
4658 ((equal key "SETUPFILE")
4659 (setq setup-contents (org-file-contents
4660 (expand-file-name
4661 (org-remove-double-quotes value))
4662 'noerror))
4663 (if (not ext-setup-or-nil)
4664 (setq ext-setup-or-nil setup-contents start 0)
4665 (setq ext-setup-or-nil
4666 (concat (substring ext-setup-or-nil 0 start)
4667 "\n" setup-contents "\n"
4668 (substring ext-setup-or-nil start)))))))
4669 ;; search for property blocks
4670 (goto-char (point-min))
4671 (while (re-search-forward org-block-regexp nil t)
4672 (when (equal "PROPERTY" (upcase (match-string 1)))
4673 (setq value (replace-regexp-in-string
4674 "[\n\r]" " " (match-string 4)))
4675 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4676 (setq props (org-update-property-plist (match-string 1 value)
4677 (match-string 2 value)
4678 props)))))))
4679 (org-set-local 'org-use-sub-superscripts scripts)
4680 (when cat
4681 (org-set-local 'org-category (intern cat))
4682 (push (cons "CATEGORY" cat) props))
4683 (when prio
4684 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4685 (setq prio (mapcar 'string-to-char prio))
4686 (org-set-local 'org-highest-priority (nth 0 prio))
4687 (org-set-local 'org-lowest-priority (nth 1 prio))
4688 (org-set-local 'org-default-priority (nth 2 prio)))
4689 (and props (org-set-local 'org-file-properties (nreverse props)))
4690 (and ftags (org-set-local 'org-file-tags
4691 (mapcar 'org-add-prop-inherited ftags)))
4692 (and drawers (org-set-local 'org-drawers drawers))
4693 (and arch (org-set-local 'org-archive-location arch))
4694 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4695 ;; Process the TODO keywords
4696 (unless kwds
4697 ;; Use the global values as if they had been given locally.
4698 (setq kwds (default-value 'org-todo-keywords))
4699 (if (stringp (car kwds))
4700 (setq kwds (list (cons org-todo-interpretation
4701 (default-value 'org-todo-keywords)))))
4702 (setq kwds (reverse kwds)))
4703 (setq kwds (nreverse kwds))
4704 (let (inter kws kw)
4705 (while (setq kws (pop kwds))
4706 (let ((kws (or
4707 (run-hook-with-args-until-success
4708 'org-todo-setup-filter-hook kws)
4709 kws)))
4710 (setq inter (pop kws) sep (member "|" kws)
4711 kws0 (delete "|" (copy-sequence kws))
4712 kwsa nil
4713 kws1 (mapcar
4714 (lambda (x)
4715 ;; 1 2
4716 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4717 (progn
4718 (setq kw (match-string 1 x)
4719 key (and (match-end 2) (match-string 2 x))
4720 log (org-extract-log-state-settings x))
4721 (push (cons kw (and key (string-to-char key))) kwsa)
4722 (and log (push log org-todo-log-states))
4724 (error "Invalid TODO keyword %s" x)))
4725 kws0)
4726 kwsa (if kwsa (append '((:startgroup))
4727 (nreverse kwsa)
4728 '((:endgroup))))
4729 hw (car kws1)
4730 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4731 tail (list inter hw (car dws) (org-last dws))))
4732 (add-to-list 'org-todo-heads hw 'append)
4733 (push kws1 org-todo-sets)
4734 (setq org-done-keywords (append org-done-keywords dws nil))
4735 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4736 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4737 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4738 (setq org-todo-sets (nreverse org-todo-sets)
4739 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4740 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4741 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4742 ;; Process the constants
4743 (when const
4744 (let (e cst)
4745 (while (setq e (pop const))
4746 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4747 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4748 (setq org-table-formula-constants-local cst)))
4750 ;; Process the tags.
4751 (when tags
4752 (let (e tgs)
4753 (while (setq e (pop tags))
4754 (cond
4755 ((equal e "{") (push '(:startgroup) tgs))
4756 ((equal e "}") (push '(:endgroup) tgs))
4757 ((equal e "\\n") (push '(:newline) tgs))
4758 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4759 (push (cons (match-string 1 e)
4760 (string-to-char (match-string 2 e)))
4761 tgs))
4762 (t (push (list e) tgs))))
4763 (org-set-local 'org-tag-alist nil)
4764 (while (setq e (pop tgs))
4765 (or (and (stringp (car e))
4766 (assoc (car e) org-tag-alist))
4767 (push e org-tag-alist)))))
4769 ;; Compute the regular expressions and other local variables.
4770 ;; Using `org-outline-regexp-bol' would complicate them much,
4771 ;; because of the fixed white space at the end of that string.
4772 (if (not org-done-keywords)
4773 (setq org-done-keywords (and org-todo-keywords-1
4774 (list (org-last org-todo-keywords-1)))))
4775 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4776 (length org-scheduled-string)
4777 (length org-clock-string)
4778 (length org-closed-string)))
4779 org-drawer-regexp
4780 (concat "^[ \t]*:\\("
4781 (mapconcat 'regexp-quote org-drawers "\\|")
4782 "\\):[ \t]*$")
4783 org-not-done-keywords
4784 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4785 org-todo-regexp
4786 (concat "\\("
4787 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4788 "\\)")
4789 org-not-done-regexp
4790 (concat "\\("
4791 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4792 "\\)")
4793 org-not-done-heading-regexp
4794 (format org-heading-keyword-regexp-format org-not-done-regexp)
4795 org-todo-line-regexp
4796 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4797 org-complex-heading-regexp
4798 (concat "^\\(\\*+\\)"
4799 "\\(?: +" org-todo-regexp "\\)?"
4800 "\\(?: +\\(\\[#.\\]\\)\\)?"
4801 "\\(?: +\\(.*?\\)\\)??"
4802 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4803 "[ \t]*$")
4804 org-complex-heading-regexp-format
4805 (concat "^\\(\\*+\\)"
4806 "\\(?: +" org-todo-regexp "\\)?"
4807 "\\(?: +\\(\\[#.\\]\\)\\)?"
4808 "\\(?: +"
4809 ;; Stats cookies can be stuck to body.
4810 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4811 "\\(%s\\)"
4812 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4813 "\\)"
4814 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4815 "[ \t]*$")
4816 org-todo-line-tags-regexp
4817 (concat "^\\(\\*+\\)"
4818 "\\(?: +" org-todo-regexp "\\)?"
4819 "\\(?: +\\(.*?\\)\\)??"
4820 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4821 "[ \t]*$")
4822 org-deadline-regexp (concat "\\<" org-deadline-string)
4823 org-deadline-time-regexp
4824 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4825 org-deadline-line-regexp
4826 (concat "\\<\\(" org-deadline-string "\\).*")
4827 org-scheduled-regexp
4828 (concat "\\<" org-scheduled-string)
4829 org-scheduled-time-regexp
4830 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4831 org-closed-time-regexp
4832 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4833 org-keyword-time-regexp
4834 (concat "\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\|" org-clock-string "\\)"
4838 " *[[<]\\([^]>]+\\)[]>]")
4839 org-keyword-time-not-clock-regexp
4840 (concat "\\<\\(" org-scheduled-string
4841 "\\|" org-deadline-string
4842 "\\|" org-closed-string
4843 "\\)"
4844 " *[[<]\\([^]>]+\\)[]>]")
4845 org-maybe-keyword-time-regexp
4846 (concat "\\(\\<\\(" org-scheduled-string
4847 "\\|" org-deadline-string
4848 "\\|" org-closed-string
4849 "\\|" org-clock-string "\\)\\)?"
4850 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4851 org-all-time-keywords
4852 (mapcar (lambda (w) (substring w 0 -1))
4853 (list org-scheduled-string org-deadline-string
4854 org-clock-string org-closed-string))
4856 (org-compute-latex-and-specials-regexp)
4857 (org-set-font-lock-defaults))))
4859 (defun org-file-contents (file &optional noerror)
4860 "Return the contents of FILE, as a string."
4861 (if (or (not file)
4862 (not (file-readable-p file)))
4863 (if noerror
4864 (progn
4865 (message "Cannot read file \"%s\"" file)
4866 (ding) (sit-for 2)
4868 (error "Cannot read file \"%s\"" file))
4869 (with-temp-buffer
4870 (insert-file-contents file)
4871 (buffer-string))))
4873 (defun org-extract-log-state-settings (x)
4874 "Extract the log state setting from a TODO keyword string.
4875 This will extract info from a string like \"WAIT(w@/!)\"."
4876 (let (kw key log1 log2)
4877 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4878 (setq kw (match-string 1 x)
4879 key (and (match-end 2) (match-string 2 x))
4880 log1 (and (match-end 3) (match-string 3 x))
4881 log2 (and (match-end 4) (match-string 4 x)))
4882 (and (or log1 log2)
4883 (list kw
4884 (and log1 (if (equal log1 "!") 'time 'note))
4885 (and log2 (if (equal log2 "!") 'time 'note)))))))
4887 (defun org-remove-keyword-keys (list)
4888 "Remove a pair of parenthesis at the end of each string in LIST."
4889 (mapcar (lambda (x)
4890 (if (string-match "(.*)$" x)
4891 (substring x 0 (match-beginning 0))
4893 list))
4895 (defun org-assign-fast-keys (alist)
4896 "Assign fast keys to a keyword-key alist.
4897 Respect keys that are already there."
4898 (let (new e (alt ?0))
4899 (while (setq e (pop alist))
4900 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4901 (cdr e)) ;; Key already assigned.
4902 (push e new)
4903 (let ((clist (string-to-list (downcase (car e))))
4904 (used (append new alist)))
4905 (when (= (car clist) ?@)
4906 (pop clist))
4907 (while (and clist (rassoc (car clist) used))
4908 (pop clist))
4909 (unless clist
4910 (while (rassoc alt used)
4911 (incf alt)))
4912 (push (cons (car e) (or (car clist) alt)) new))))
4913 (nreverse new)))
4915 ;;; Some variables used in various places
4917 (defvar org-window-configuration nil
4918 "Used in various places to store a window configuration.")
4919 (defvar org-selected-window nil
4920 "Used in various places to store a window configuration.")
4921 (defvar org-finish-function nil
4922 "Function to be called when `C-c C-c' is used.
4923 This is for getting out of special buffers like capture.")
4926 ;; FIXME: Occasionally check by commenting these, to make sure
4927 ;; no other functions uses these, forgetting to let-bind them.
4928 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4929 (defvar org-last-state)
4930 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4932 ;; Defined somewhere in this file, but used before definition.
4933 (defvar org-entities) ;; defined in org-entities.el
4934 (defvar org-struct-menu)
4935 (defvar org-org-menu)
4936 (defvar org-tbl-menu)
4938 ;;;; Define the Org-mode
4940 ;; We use a before-change function to check if a table might need
4941 ;; an update.
4942 (defvar org-table-may-need-update t
4943 "Indicates that a table might need an update.
4944 This variable is set by `org-before-change-function'.
4945 `org-table-align' sets it back to nil.")
4946 (defun org-before-change-function (beg end)
4947 "Every change indicates that a table might need an update."
4948 (setq org-table-may-need-update t))
4949 (defvar org-mode-map)
4950 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4951 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4952 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4953 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4954 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4955 (defvar org-table-buffer-is-an nil)
4957 (defvar bidi-paragraph-direction)
4958 (defvar buffer-face-mode-face)
4960 (require 'outline)
4961 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4962 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4963 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4965 ;; Other stuff we need.
4966 (require 'time-date)
4967 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4968 (require 'easymenu)
4969 (require 'overlay)
4971 (require 'org-macs)
4972 (require 'org-entities)
4973 ;; (require 'org-compat) moved higher up in the file before it is first used
4974 (require 'org-faces)
4975 (require 'org-list)
4976 (require 'org-pcomplete)
4977 (require 'org-src)
4978 (require 'org-footnote)
4980 ;; babel
4981 (require 'ob)
4982 (require 'ob-table)
4983 (require 'ob-lob)
4984 (require 'ob-ref)
4985 (require 'ob-tangle)
4986 (require 'ob-comint)
4987 (require 'ob-keys)
4989 ;;;###autoload
4990 (define-derived-mode org-mode outline-mode "Org"
4991 "Outline-based notes management and organizer, alias
4992 \"Carsten's outline-mode for keeping track of everything.\"
4994 Org-mode develops organizational tasks around a NOTES file which
4995 contains information about projects as plain text. Org-mode is
4996 implemented on top of outline-mode, which is ideal to keep the content
4997 of large files well structured. It supports ToDo items, deadlines and
4998 time stamps, which magically appear in the diary listing of the Emacs
4999 calendar. Tables are easily created with a built-in table editor.
5000 Plain text URL-like links connect to websites, emails (VM), Usenet
5001 messages (Gnus), BBDB entries, and any files related to the project.
5002 For printing and sharing of notes, an Org-mode file (or a part of it)
5003 can be exported as a structured ASCII or HTML file.
5005 The following commands are available:
5007 \\{org-mode-map}"
5009 ;; Get rid of Outline menus, they are not needed
5010 ;; Need to do this here because define-derived-mode sets up
5011 ;; the keymap so late. Still, it is a waste to call this each time
5012 ;; we switch another buffer into org-mode.
5013 (if (featurep 'xemacs)
5014 (when (boundp 'outline-mode-menu-heading)
5015 ;; Assume this is Greg's port, it uses easymenu
5016 (easy-menu-remove outline-mode-menu-heading)
5017 (easy-menu-remove outline-mode-menu-show)
5018 (easy-menu-remove outline-mode-menu-hide))
5019 (define-key org-mode-map [menu-bar headings] 'undefined)
5020 (define-key org-mode-map [menu-bar hide] 'undefined)
5021 (define-key org-mode-map [menu-bar show] 'undefined))
5023 (org-load-modules-maybe)
5024 (easy-menu-add org-org-menu)
5025 (easy-menu-add org-tbl-menu)
5026 (org-install-agenda-files-menu)
5027 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5028 (add-to-invisibility-spec '(org-cwidth))
5029 (add-to-invisibility-spec '(org-hide-block . t))
5030 (when (featurep 'xemacs)
5031 (org-set-local 'line-move-ignore-invisible t))
5032 (org-set-local 'outline-regexp org-outline-regexp)
5033 (org-set-local 'outline-level 'org-outline-level)
5034 (setq bidi-paragraph-direction 'left-to-right)
5035 (when (and org-ellipsis
5036 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5037 (fboundp 'make-glyph-code))
5038 (unless org-display-table
5039 (setq org-display-table (make-display-table)))
5040 (set-display-table-slot
5041 org-display-table 4
5042 (vconcat (mapcar
5043 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5044 org-ellipsis)))
5045 (if (stringp org-ellipsis) org-ellipsis "..."))))
5046 (setq buffer-display-table org-display-table))
5047 (org-set-regexps-and-options)
5048 (when (and org-tag-faces (not org-tags-special-faces-re))
5049 ;; tag faces set outside customize.... force initialization.
5050 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5051 ;; Calc embedded
5052 (org-set-local 'calc-embedded-open-mode "# ")
5053 (modify-syntax-entry ?@ "w")
5054 (modify-syntax-entry ?\" "\"")
5055 (if org-startup-truncated (setq truncate-lines t))
5056 (org-set-local 'font-lock-unfontify-region-function
5057 'org-unfontify-region)
5058 ;; Activate before-change-function
5059 (org-set-local 'org-table-may-need-update t)
5060 (org-add-hook 'before-change-functions 'org-before-change-function nil
5061 'local)
5062 ;; Check for running clock before killing a buffer
5063 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5064 ;; Initialize macros templates.
5065 (org-macro-initialize-templates)
5066 ;; Initialize radio targets.
5067 (org-update-radio-target-regexp)
5068 ;; Indentation.
5069 (org-set-local 'indent-line-function 'org-indent-line)
5070 (org-set-local 'indent-region-function 'org-indent-region)
5071 ;; Filling and auto-filling.
5072 (org-setup-filling)
5073 ;; Comments.
5074 (org-setup-comments-handling)
5075 ;; Beginning/end of defun
5076 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5077 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5078 ;; Next error for sparse trees
5079 (org-set-local 'next-error-function 'org-occur-next-match)
5080 ;; Make sure dependence stuff works reliably, even for users who set it
5081 ;; too late :-(
5082 (if org-enforce-todo-dependencies
5083 (add-hook 'org-blocker-hook
5084 'org-block-todo-from-children-or-siblings-or-parent)
5085 (remove-hook 'org-blocker-hook
5086 'org-block-todo-from-children-or-siblings-or-parent))
5087 (if org-enforce-todo-checkbox-dependencies
5088 (add-hook 'org-blocker-hook
5089 'org-block-todo-from-checkboxes)
5090 (remove-hook 'org-blocker-hook
5091 'org-block-todo-from-checkboxes))
5093 ;; Align options lines
5094 (org-set-local
5095 'align-mode-rules-list
5096 '((org-in-buffer-settings
5097 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5098 (modes . '(org-mode)))))
5100 ;; Imenu
5101 (org-set-local 'imenu-create-index-function
5102 'org-imenu-get-tree)
5104 ;; Make isearch reveal context
5105 (if (or (featurep 'xemacs)
5106 (not (boundp 'outline-isearch-open-invisible-function)))
5107 ;; Emacs 21 and XEmacs make use of the hook
5108 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5109 ;; Emacs 22 deals with this through a special variable
5110 (org-set-local 'outline-isearch-open-invisible-function
5111 (lambda (&rest ignore) (org-show-context 'isearch))))
5113 ;; Turn on org-beamer-mode?
5114 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5116 ;; Setup the pcomplete hooks
5117 (set (make-local-variable 'pcomplete-command-completion-function)
5118 'org-pcomplete-initial)
5119 (set (make-local-variable 'pcomplete-command-name-function)
5120 'org-command-at-point)
5121 (set (make-local-variable 'pcomplete-default-completion-function)
5122 'ignore)
5123 (set (make-local-variable 'pcomplete-parse-arguments-function)
5124 'org-parse-arguments)
5125 (set (make-local-variable 'pcomplete-termination-string) "")
5126 (when (>= emacs-major-version 23)
5127 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5129 ;; If empty file that did not turn on org-mode automatically, make it to.
5130 (if (and org-insert-mode-line-in-empty-file
5131 (org-called-interactively-p 'any)
5132 (= (point-min) (point-max)))
5133 (insert "# -*- mode: org -*-\n\n"))
5134 (unless org-inhibit-startup
5135 (when org-startup-align-all-tables
5136 (let ((bmp (buffer-modified-p)))
5137 (org-table-map-tables 'org-table-align 'quietly)
5138 (set-buffer-modified-p bmp)))
5139 (when org-startup-with-inline-images
5140 (org-display-inline-images))
5141 (when org-startup-indented
5142 (require 'org-indent)
5143 (org-indent-mode 1))
5144 (unless org-inhibit-startup-visibility-stuff
5145 (org-set-startup-visibility)))
5146 ;; Try to set org-hide correctly
5147 (set-face-foreground
5148 'org-hide
5149 (or (face-background 'default)
5150 (face-background 'org-default)
5151 (cdr (assoc 'background-color default-frame-alist))
5152 (cdr (assoc 'background-color initial-frame-alist))
5153 (cdr (assoc 'background-color window-system-default-frame-alist))
5154 (face-foreground 'org-hide))))
5156 (when (fboundp 'abbrev-table-put)
5157 (abbrev-table-put org-mode-abbrev-table
5158 :parents (list text-mode-abbrev-table)))
5160 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5162 (defun org-current-time ()
5163 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5164 (if (> (car org-time-stamp-rounding-minutes) 1)
5165 (let ((r (car org-time-stamp-rounding-minutes))
5166 (time (decode-time)))
5167 (apply 'encode-time
5168 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5169 (nthcdr 2 time))))
5170 (current-time)))
5172 (defun org-today ()
5173 "Return today date, considering `org-extend-today-until'."
5174 (time-to-days
5175 (time-subtract (current-time)
5176 (list 0 (* 3600 org-extend-today-until) 0))))
5178 ;;;; Font-Lock stuff, including the activators
5180 (defvar org-mouse-map (make-sparse-keymap))
5181 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5182 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5183 (when org-mouse-1-follows-link
5184 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5185 (when org-tab-follows-link
5186 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5187 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5189 (require 'font-lock)
5191 (defconst org-non-link-chars "]\t\n\r<>")
5192 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5193 "shell" "elisp" "doi" "message"))
5194 (defvar org-link-types-re nil
5195 "Matches a link that has a url-like prefix like \"http:\"")
5196 (defvar org-link-re-with-space nil
5197 "Matches a link with spaces, optional angular brackets around it.")
5198 (defvar org-link-re-with-space2 nil
5199 "Matches a link with spaces, optional angular brackets around it.")
5200 (defvar org-link-re-with-space3 nil
5201 "Matches a link with spaces, only for internal part in bracket links.")
5202 (defvar org-angle-link-re nil
5203 "Matches link with angular brackets, spaces are allowed.")
5204 (defvar org-plain-link-re nil
5205 "Matches plain link, without spaces.")
5206 (defvar org-bracket-link-regexp nil
5207 "Matches a link in double brackets.")
5208 (defvar org-bracket-link-analytic-regexp nil
5209 "Regular expression used to analyze links.
5210 Here is what the match groups contain after a match:
5211 1: http:
5212 2: http
5213 3: path
5214 4: [desc]
5215 5: desc")
5216 (defvar org-bracket-link-analytic-regexp++ nil
5217 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5218 (defvar org-any-link-re nil
5219 "Regular expression matching any link.")
5221 (defcustom org-match-sexp-depth 3
5222 "Number of stacked braces for sub/superscript matching.
5223 This has to be set before loading org.el to be effective."
5224 :group 'org-export-translation ; ??????????????????????????/
5225 :type 'integer)
5227 (defun org-create-multibrace-regexp (left right n)
5228 "Create a regular expression which will match a balanced sexp.
5229 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5230 as single character strings.
5231 The regexp returned will match the entire expression including the
5232 delimiters. It will also define a single group which contains the
5233 match except for the outermost delimiters. The maximum depth of
5234 stacked delimiters is N. Escaping delimiters is not possible."
5235 (let* ((nothing (concat "[^" left right "]*?"))
5236 (or "\\|")
5237 (re nothing)
5238 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5239 (while (> n 1)
5240 (setq n (1- n)
5241 re (concat re or next)
5242 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5243 (concat left "\\(" re "\\)" right)))
5245 (defvar org-match-substring-regexp
5246 (concat
5247 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5248 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5249 "\\|"
5250 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5251 "\\|"
5252 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5253 "The regular expression matching a sub- or superscript.")
5255 (defvar org-match-substring-with-braces-regexp
5256 (concat
5257 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5258 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5259 "\\)")
5260 "The regular expression matching a sub- or superscript, forcing braces.")
5262 (defun org-make-link-regexps ()
5263 "Update the link regular expressions.
5264 This should be called after the variable `org-link-types' has changed."
5265 (setq org-link-types-re
5266 (concat
5267 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5268 org-link-re-with-space
5269 (concat
5270 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5271 "\\([^" org-non-link-chars " ]"
5272 "[^" org-non-link-chars "]*"
5273 "[^" org-non-link-chars " ]\\)>?")
5274 org-link-re-with-space2
5275 (concat
5276 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5277 "\\([^" org-non-link-chars " ]"
5278 "[^\t\n\r]*"
5279 "[^" org-non-link-chars " ]\\)>?")
5280 org-link-re-with-space3
5281 (concat
5282 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5283 "\\([^" org-non-link-chars " ]"
5284 "[^\t\n\r]*\\)")
5285 org-angle-link-re
5286 (concat
5287 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5288 "\\([^" org-non-link-chars " ]"
5289 "[^" org-non-link-chars "]*"
5290 "\\)>")
5291 org-plain-link-re
5292 (concat
5293 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5294 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5295 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5296 org-bracket-link-regexp
5297 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5298 org-bracket-link-analytic-regexp
5299 (concat
5300 "\\[\\["
5301 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5302 "\\([^]]+\\)"
5303 "\\]"
5304 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5305 "\\]")
5306 org-bracket-link-analytic-regexp++
5307 (concat
5308 "\\[\\["
5309 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5310 "\\([^]]+\\)"
5311 "\\]"
5312 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5313 "\\]")
5314 org-any-link-re
5315 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5316 org-angle-link-re "\\)\\|\\("
5317 org-plain-link-re "\\)")))
5319 (org-make-link-regexps)
5321 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5322 "Regular expression for fast time stamp matching.")
5323 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5324 "Regular expression for fast time stamp matching.")
5325 (defconst org-ts-regexp0
5326 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5327 "Regular expression matching time strings for analysis.
5328 This one does not require the space after the date, so it can be used
5329 on a string that terminates immediately after the date.")
5330 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5331 "Regular expression matching time strings for analysis.")
5332 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5333 "Regular expression matching time stamps, with groups.")
5334 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5335 "Regular expression matching time stamps (also [..]), with groups.")
5336 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5337 "Regular expression matching a time stamp range.")
5338 (defconst org-tr-regexp-both
5339 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5340 "Regular expression matching a time stamp range.")
5341 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5342 org-ts-regexp "\\)?")
5343 "Regular expression matching a time stamp or time stamp range.")
5344 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5345 org-ts-regexp-both "\\)?")
5346 "Regular expression matching a time stamp or time stamp range.
5347 The time stamps may be either active or inactive.")
5349 (defvar org-emph-face nil)
5351 (defun org-do-emphasis-faces (limit)
5352 "Run through the buffer and add overlays to emphasized strings."
5353 (let (rtn a)
5354 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5355 (if (not (= (char-after (match-beginning 3))
5356 (char-after (match-beginning 4))))
5357 (progn
5358 (setq rtn t)
5359 (setq a (assoc (match-string 3) org-emphasis-alist))
5360 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5361 'face
5362 (nth 1 a))
5363 (and (nth 4 a)
5364 (org-remove-flyspell-overlays-in
5365 (match-beginning 0) (match-end 0)))
5366 (add-text-properties (match-beginning 2) (match-end 2)
5367 '(font-lock-multiline t org-emphasis t))
5368 (when org-hide-emphasis-markers
5369 (add-text-properties (match-end 4) (match-beginning 5)
5370 '(invisible org-link))
5371 (add-text-properties (match-beginning 3) (match-end 3)
5372 '(invisible org-link)))))
5373 (backward-char 1))
5374 rtn))
5376 (defun org-emphasize (&optional char)
5377 "Insert or change an emphasis, i.e. a font like bold or italic.
5378 If there is an active region, change that region to a new emphasis.
5379 If there is no region, just insert the marker characters and position
5380 the cursor between them.
5381 CHAR should be either the marker character, or the first character of the
5382 HTML tag associated with that emphasis. If CHAR is a space, the means
5383 to remove the emphasis of the selected region.
5384 If char is not given (for example in an interactive call) it
5385 will be prompted for."
5386 (interactive)
5387 (let ((eal org-emphasis-alist) e det
5388 (erc org-emphasis-regexp-components)
5389 (prompt "")
5390 (string "") beg end move tag c s)
5391 (if (org-region-active-p)
5392 (setq beg (region-beginning) end (region-end)
5393 string (buffer-substring beg end))
5394 (setq move t))
5396 (while (setq e (pop eal))
5397 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5398 c (aref tag 0))
5399 (push (cons c (string-to-char (car e))) det)
5400 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5401 (substring tag 1)))))
5402 (setq det (nreverse det))
5403 (unless char
5404 (message "%s" (concat "Emphasis marker or tag:" prompt))
5405 (setq char (read-char-exclusive)))
5406 (setq char (or (cdr (assoc char det)) char))
5407 (if (equal char ?\ )
5408 (setq s "" move nil)
5409 (unless (assoc (char-to-string char) org-emphasis-alist)
5410 (error "No such emphasis marker: \"%c\"" char))
5411 (setq s (char-to-string char)))
5412 (while (and (> (length string) 1)
5413 (equal (substring string 0 1) (substring string -1))
5414 (assoc (substring string 0 1) org-emphasis-alist))
5415 (setq string (substring string 1 -1)))
5416 (setq string (concat s string s))
5417 (if beg (delete-region beg end))
5418 (unless (or (bolp)
5419 (string-match (concat "[" (nth 0 erc) "\n]")
5420 (char-to-string (char-before (point)))))
5421 (insert " "))
5422 (unless (or (eobp)
5423 (string-match (concat "[" (nth 1 erc) "\n]")
5424 (char-to-string (char-after (point)))))
5425 (insert " ") (backward-char 1))
5426 (insert string)
5427 (and move (backward-char 1))))
5429 (defconst org-nonsticky-props
5430 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5432 (defsubst org-rear-nonsticky-at (pos)
5433 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5435 (defun org-activate-plain-links (limit)
5436 "Run through the buffer and add overlays to links."
5437 (catch 'exit
5438 (let (f)
5439 (when (re-search-forward (concat org-plain-link-re) limit t)
5440 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5441 (setq f (get-text-property (match-beginning 0) 'face))
5442 (if (or (eq f 'org-tag)
5443 (and (listp f) (memq 'org-tag f)))
5445 (add-text-properties (match-beginning 0) (match-end 0)
5446 (list 'mouse-face 'highlight
5447 'face 'org-link
5448 'keymap org-mouse-map))
5449 (org-rear-nonsticky-at (match-end 0)))
5450 t))))
5452 (defun org-activate-code (limit)
5453 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (remove-text-properties (match-beginning 0) (match-end 0)
5457 '(display t invisible t intangible t))
5458 t)))
5460 (defcustom org-src-fontify-natively nil
5461 "When non-nil, fontify code in code blocks."
5462 :type 'boolean
5463 :version "24.1"
5464 :group 'org-appearance
5465 :group 'org-babel)
5467 (defcustom org-allow-promoting-top-level-subtree nil
5468 "When non-nil, allow promoting a top level subtree.
5469 The leading star of the top level headline will be replaced
5470 by a #."
5471 :type 'boolean
5472 :version "24.1"
5473 :group 'org-appearance)
5475 (defun org-fontify-meta-lines-and-blocks (limit)
5476 (condition-case nil
5477 (org-fontify-meta-lines-and-blocks-1 limit)
5478 (error (message "org-mode fontification error"))))
5480 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5481 "Fontify #+ lines and blocks, in the correct ways."
5482 (let ((case-fold-search t))
5483 (if (re-search-forward
5484 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5485 limit t)
5486 (let ((beg (match-beginning 0))
5487 (block-start (match-end 0))
5488 (block-end nil)
5489 (lang (match-string 7))
5490 (beg1 (line-beginning-position 2))
5491 (dc1 (downcase (match-string 2)))
5492 (dc3 (downcase (match-string 3)))
5493 end end1 quoting block-type ovl)
5494 (cond
5495 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5496 ;; a single line of backend-specific content
5497 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5498 (remove-text-properties (match-beginning 0) (match-end 0)
5499 '(display t invisible t intangible t))
5500 (add-text-properties (match-beginning 1) (match-end 3)
5501 '(font-lock-fontified t face org-meta-line))
5502 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5503 '(font-lock-fontified t face org-block))
5504 ; for backend-specific code
5506 ((and (match-end 4) (equal dc3 "+begin"))
5507 ;; Truly a block
5508 (setq block-type (downcase (match-string 5))
5509 quoting (member block-type org-protecting-blocks))
5510 (when (re-search-forward
5511 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5512 nil t) ;; on purpose, we look further than LIMIT
5513 (setq end (min (point-max) (match-end 0))
5514 end1 (min (point-max) (1- (match-beginning 0))))
5515 (setq block-end (match-beginning 0))
5516 (when quoting
5517 (remove-text-properties beg end
5518 '(display t invisible t intangible t)))
5519 (add-text-properties
5520 beg end
5521 '(font-lock-fontified t font-lock-multiline t))
5522 (add-text-properties beg beg1 '(face org-meta-line))
5523 (add-text-properties end1 (min (point-max) (1+ end))
5524 '(face org-meta-line)) ; for end_src
5525 (cond
5526 ((and lang (not (string= lang "")) org-src-fontify-natively)
5527 (org-src-font-lock-fontify-block lang block-start block-end)
5528 ;; remove old background overlays
5529 (mapc (lambda (ov)
5530 (if (eq (overlay-get ov 'face) 'org-block-background)
5531 (delete-overlay ov)))
5532 (overlays-at (/ (+ beg1 block-end) 2)))
5533 ;; add a background overlay
5534 (setq ovl (make-overlay beg1 block-end))
5535 (overlay-put ovl 'face 'org-block-background)
5536 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5537 (quoting
5538 (add-text-properties beg1 (min (point-max) (1+ end1))
5539 '(face org-block))) ; end of source block
5540 ((not org-fontify-quote-and-verse-blocks))
5541 ((string= block-type "quote")
5542 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5543 ((string= block-type "verse")
5544 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5545 (add-text-properties beg beg1 '(face org-block-begin-line))
5546 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5547 '(face org-block-end-line))
5549 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5550 (add-text-properties
5551 beg (match-end 3)
5552 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5553 '(font-lock-fontified t invisible t)
5554 '(font-lock-fontified t face org-document-info-keyword)))
5555 (add-text-properties
5556 (match-beginning 6) (match-end 6)
5557 (if (string-equal dc1 "+title:")
5558 '(font-lock-fontified t face org-document-title)
5559 '(font-lock-fontified t face org-document-info))))
5560 ((or (equal dc1 "+results")
5561 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5562 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5563 "+call:" "+header:" "+headers:" "+name:"))
5564 (and (match-end 4) (equal dc3 "+attr")))
5565 (add-text-properties
5566 beg (match-end 0)
5567 '(font-lock-fontified t face org-meta-line))
5569 ((member dc3 '(" " ""))
5570 (add-text-properties
5571 beg (match-end 0)
5572 '(font-lock-fontified t face font-lock-comment-face)))
5573 ((not (member (char-after beg) '(?\ ?\t)))
5574 ;; just any other in-buffer setting, but not indented
5575 (add-text-properties
5576 beg (match-end 0)
5577 '(font-lock-fontified t face org-meta-line))
5579 (t nil))))))
5581 (defun org-strip-protective-commas (beg end)
5582 "Strip protective commas between BEG and END in the current buffer."
5583 (interactive "r")
5584 (save-excursion
5585 (save-match-data
5586 (goto-char beg)
5587 (let ((front-line (save-excursion
5588 (re-search-forward
5589 "[^[:space:]]" end t)
5590 (goto-char (match-beginning 0))
5591 (current-column))))
5592 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5593 (goto-char (match-beginning 1))
5594 (when (= (current-column) front-line)
5595 (replace-match "" nil nil nil 1)))))))
5597 (defun org-activate-angle-links (limit)
5598 "Run through the buffer and add overlays to links."
5599 (if (re-search-forward org-angle-link-re limit t)
5600 (progn
5601 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5602 (add-text-properties (match-beginning 0) (match-end 0)
5603 (list 'mouse-face 'highlight
5604 'keymap org-mouse-map))
5605 (org-rear-nonsticky-at (match-end 0))
5606 t)))
5608 (defun org-activate-footnote-links (limit)
5609 "Run through the buffer and add overlays to footnotes."
5610 (let ((fn (org-footnote-next-reference-or-definition limit)))
5611 (when fn
5612 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5613 (org-remove-flyspell-overlays-in beg end)
5614 (add-text-properties beg end
5615 (list 'mouse-face 'highlight
5616 'keymap org-mouse-map
5617 'help-echo
5618 (if (= (point-at-bol) beg)
5619 "Footnote definition"
5620 "Footnote reference")
5621 'font-lock-fontified t
5622 'font-lock-multiline t
5623 'face 'org-footnote))))))
5625 (defun org-activate-bracket-links (limit)
5626 "Run through the buffer and add overlays to bracketed links."
5627 (if (re-search-forward org-bracket-link-regexp limit t)
5628 (let* ((help (concat "LINK: "
5629 (org-match-string-no-properties 1)))
5630 ;; FIXME: above we should remove the escapes.
5631 ;; but that requires another match, protecting match data,
5632 ;; a lot of overhead for font-lock.
5633 (ip (org-maybe-intangible
5634 (list 'invisible 'org-link
5635 'keymap org-mouse-map 'mouse-face 'highlight
5636 'font-lock-multiline t 'help-echo help)))
5637 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5638 'font-lock-multiline t 'help-echo help)))
5639 ;; We need to remove the invisible property here. Table narrowing
5640 ;; may have made some of this invisible.
5641 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5642 (remove-text-properties (match-beginning 0) (match-end 0)
5643 '(invisible nil))
5644 (if (match-end 3)
5645 (progn
5646 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5647 (org-rear-nonsticky-at (match-beginning 3))
5648 (add-text-properties (match-beginning 3) (match-end 3) vp)
5649 (org-rear-nonsticky-at (match-end 3))
5650 (add-text-properties (match-end 3) (match-end 0) ip)
5651 (org-rear-nonsticky-at (match-end 0)))
5652 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5653 (org-rear-nonsticky-at (match-beginning 1))
5654 (add-text-properties (match-beginning 1) (match-end 1) vp)
5655 (org-rear-nonsticky-at (match-end 1))
5656 (add-text-properties (match-end 1) (match-end 0) ip)
5657 (org-rear-nonsticky-at (match-end 0)))
5658 t)))
5660 (defun org-activate-dates (limit)
5661 "Run through the buffer and add overlays to dates."
5662 (if (re-search-forward org-tsr-regexp-both limit t)
5663 (progn
5664 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5665 (add-text-properties (match-beginning 0) (match-end 0)
5666 (list 'mouse-face 'highlight
5667 'keymap org-mouse-map))
5668 (org-rear-nonsticky-at (match-end 0))
5669 (when org-display-custom-times
5670 (if (match-end 3)
5671 (org-display-custom-time (match-beginning 3) (match-end 3)))
5672 (org-display-custom-time (match-beginning 1) (match-end 1)))
5673 t)))
5675 (defvar org-target-link-regexp nil
5676 "Regular expression matching radio targets in plain text.")
5677 (make-variable-buffer-local 'org-target-link-regexp)
5678 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5679 "Regular expression matching a link target.")
5680 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5681 "Regular expression matching a radio target.")
5682 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5683 "Regular expression matching any target.")
5685 (defun org-activate-target-links (limit)
5686 "Run through the buffer and add overlays to target matches."
5687 (when org-target-link-regexp
5688 (let ((case-fold-search t))
5689 (if (re-search-forward org-target-link-regexp limit t)
5690 (progn
5691 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5692 (add-text-properties (match-beginning 0) (match-end 0)
5693 (list 'mouse-face 'highlight
5694 'keymap org-mouse-map
5695 'help-echo "Radio target link"
5696 'org-linked-text t))
5697 (org-rear-nonsticky-at (match-end 0))
5698 t)))))
5700 (defun org-update-radio-target-regexp ()
5701 "Find all radio targets in this file and update the regular expression."
5702 (interactive)
5703 (when (memq 'radio org-activate-links)
5704 (setq org-target-link-regexp
5705 (org-make-target-link-regexp (org-all-targets 'radio)))
5706 (org-restart-font-lock)))
5708 (defun org-hide-wide-columns (limit)
5709 (let (s e)
5710 (setq s (text-property-any (point) (or limit (point-max))
5711 'org-cwidth t))
5712 (when s
5713 (setq e (next-single-property-change s 'org-cwidth))
5714 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5715 (goto-char e)
5716 t)))
5718 (defvar org-latex-and-specials-regexp nil
5719 "Regular expression for highlighting export special stuff.")
5720 (defvar org-match-substring-regexp)
5721 (defvar org-match-substring-with-braces-regexp)
5723 ;; This should be with the exporter code, but we also use if for font-locking
5724 (defconst org-export-html-special-string-regexps
5725 '(("\\\\-" . "&shy;")
5726 ("---\\([^-]\\)" . "&mdash;\\1")
5727 ("--\\([^-]\\)" . "&ndash;\\1")
5728 ("\\.\\.\\." . "&hellip;"))
5729 "Regular expressions for special string conversion.")
5732 (defun org-compute-latex-and-specials-regexp ()
5733 "Compute regular expression for stuff treated specially by exporters."
5734 (if (not org-highlight-latex-fragments-and-specials)
5735 (org-set-local 'org-latex-and-specials-regexp nil)
5736 (require 'org-exp)
5737 (let*
5738 ((matchers (plist-get org-format-latex-options :matchers))
5739 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5740 org-latex-regexps)))
5741 (org-export-allow-BIND nil)
5742 (options (org-combine-plists (org-default-export-plist)
5743 (org-infile-export-plist)))
5744 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5745 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5746 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5747 (org-export-html-expand (plist-get options :expand-quoted-html))
5748 (org-export-with-special-strings (plist-get options :special-strings))
5749 (re-sub
5750 (cond
5751 ((equal org-export-with-sub-superscripts '{})
5752 (list org-match-substring-with-braces-regexp))
5753 (org-export-with-sub-superscripts
5754 (list org-match-substring-regexp))))
5755 (re-latex
5756 (if org-export-with-LaTeX-fragments
5757 (mapcar (lambda (x) (nth 1 x)) latexs)))
5758 (re-macros
5759 (if org-export-with-TeX-macros
5760 (list (concat "\\\\"
5761 (regexp-opt
5762 (append
5764 (delq nil
5765 (mapcar 'car-safe
5766 (append org-entities-user
5767 org-entities)))
5768 (if (boundp 'org-latex-entities)
5769 (mapcar (lambda (x)
5770 (or (car-safe x) x))
5771 org-latex-entities)
5772 nil))
5773 'words))) ; FIXME
5775 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5776 (re-special (if org-export-with-special-strings
5777 (mapcar (lambda (x) (car x))
5778 org-export-html-special-string-regexps)))
5779 (re-rest
5780 (delq nil
5781 (list
5782 (if org-export-html-expand "@<[^>\n]+>")
5783 ))))
5784 (org-set-local
5785 'org-latex-and-specials-regexp
5786 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5787 re-rest) "\\|")))))
5789 (defun org-do-latex-and-special-faces (limit)
5790 "Run through the buffer and add overlays to links."
5791 (when org-latex-and-specials-regexp
5792 (let (rtn d)
5793 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5794 limit t))
5795 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5796 'face))
5797 '(org-code org-verbatim underline)))
5798 (progn
5799 (setq rtn t
5800 d (cond ((member (char-after (1+ (match-beginning 0)))
5801 '(?_ ?^)) 1)
5802 (t 0)))
5803 (font-lock-prepend-text-property
5804 (+ d (match-beginning 0)) (match-end 0)
5805 'face 'org-latex-and-export-specials)
5806 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5807 '(font-lock-multiline t)))))
5808 rtn)))
5810 (defun org-restart-font-lock ()
5811 "Restart `font-lock-mode', to force refontification."
5812 (when (and (boundp 'font-lock-mode) font-lock-mode)
5813 (font-lock-mode -1)
5814 (font-lock-mode 1)))
5816 (defun org-all-targets (&optional radio)
5817 "Return a list of all targets in this file.
5818 With optional argument RADIO, only find radio targets."
5819 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5820 rtn)
5821 (save-excursion
5822 (goto-char (point-min))
5823 (while (re-search-forward re nil t)
5824 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5825 rtn)))
5827 (defun org-make-target-link-regexp (targets)
5828 "Make regular expression matching all strings in TARGETS.
5829 The regular expression finds the targets also if there is a line break
5830 between words."
5831 (and targets
5832 (concat
5833 "\\<\\("
5834 (mapconcat
5835 (lambda (x)
5836 (setq x (regexp-quote x))
5837 (while (string-match " +" x)
5838 (setq x (replace-match "\\s-+" t t x)))
5840 targets
5841 "\\|")
5842 "\\)\\>")))
5844 (defun org-activate-tags (limit)
5845 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5846 (progn
5847 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5848 (add-text-properties (match-beginning 1) (match-end 1)
5849 (list 'mouse-face 'highlight
5850 'keymap org-mouse-map))
5851 (org-rear-nonsticky-at (match-end 1))
5852 t)))
5854 (defun org-outline-level ()
5855 "Compute the outline level of the heading at point.
5856 If this is called at a normal headline, the level is the number of stars.
5857 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5858 (save-excursion
5859 (if (not (condition-case nil
5860 (org-back-to-heading t)
5861 (error nil)))
5863 (looking-at org-outline-regexp)
5864 (1- (- (match-end 0) (match-beginning 0))))))
5866 (defvar org-font-lock-keywords nil)
5868 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5869 "Regular expression matching a property line.")
5871 (defvar org-font-lock-hook nil
5872 "Functions to be called for special font lock stuff.")
5874 (defvar org-font-lock-set-keywords-hook nil
5875 "Functions that can manipulate `org-font-lock-extra-keywords'.
5876 This is called after `org-font-lock-extra-keywords' is defined, but before
5877 it is installed to be used by font lock. This can be useful if something
5878 needs to be inserted at a specific position in the font-lock sequence.")
5880 (defun org-font-lock-hook (limit)
5881 (run-hook-with-args 'org-font-lock-hook limit))
5883 (defun org-set-font-lock-defaults ()
5884 (let* ((em org-fontify-emphasized-text)
5885 (lk org-activate-links)
5886 (org-font-lock-extra-keywords
5887 (list
5888 ;; Call the hook
5889 '(org-font-lock-hook)
5890 ;; Headlines
5891 `(,(if org-fontify-whole-heading-line
5892 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5893 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5894 (1 (org-get-level-face 1))
5895 (2 (org-get-level-face 2))
5896 (3 (org-get-level-face 3)))
5897 ;; Table lines
5898 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5899 (1 'org-table t))
5900 ;; Table internals
5901 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5902 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5903 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5904 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5905 ;; Drawers
5906 (list org-drawer-regexp '(0 'org-special-keyword t))
5907 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5908 ;; Properties
5909 (list org-property-re
5910 '(1 'org-special-keyword t)
5911 '(3 'org-property-value t))
5912 ;; Links
5913 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5914 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5915 (if (memq 'plain lk) '(org-activate-plain-links))
5916 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5917 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5918 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5919 (if (memq 'footnote lk) '(org-activate-footnote-links))
5920 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5921 '(org-hide-wide-columns (0 nil append))
5922 ;; TODO keyword
5923 (list (format org-heading-keyword-regexp-format
5924 org-todo-regexp)
5925 '(2 (org-get-todo-face 2) t))
5926 ;; DONE
5927 (if org-fontify-done-headline
5928 (list (format org-heading-keyword-regexp-format
5929 (concat
5930 "\\(?:"
5931 (mapconcat 'regexp-quote org-done-keywords "\\|")
5932 "\\)"))
5933 '(2 'org-headline-done t))
5934 nil)
5935 ;; Priorities
5936 '(org-font-lock-add-priority-faces)
5937 ;; Tags
5938 '(org-font-lock-add-tag-faces)
5939 ;; Special keywords
5940 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5941 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5942 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5943 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5944 ;; Emphasis
5945 (if em
5946 (if (featurep 'xemacs)
5947 '(org-do-emphasis-faces (0 nil append))
5948 '(org-do-emphasis-faces)))
5949 ;; Checkboxes
5950 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5951 1 'org-checkbox prepend)
5952 (if (cdr (assq 'checkbox org-list-automatic-rules))
5953 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5954 (0 (org-get-checkbox-statistics-face) t)))
5955 ;; Description list items
5956 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5957 1 'org-list-dt prepend)
5958 ;; ARCHIVEd headings
5959 (list (concat
5960 org-outline-regexp-bol
5961 "\\(.*:" org-archive-tag ":.*\\)")
5962 '(1 'org-archived prepend))
5963 ;; Specials
5964 '(org-do-latex-and-special-faces)
5965 '(org-fontify-entities)
5966 '(org-raise-scripts)
5967 ;; Code
5968 '(org-activate-code (1 'org-code t))
5969 ;; COMMENT
5970 (list (format org-heading-keyword-regexp-format
5971 (concat "\\("
5972 org-comment-string "\\|" org-quote-string
5973 "\\)"))
5974 '(2 'org-special-keyword t))
5975 ;; Blocks and meta lines
5976 '(org-fontify-meta-lines-and-blocks)
5978 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5979 (run-hooks 'org-font-lock-set-keywords-hook)
5980 ;; Now set the full font-lock-keywords
5981 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5982 (org-set-local 'font-lock-defaults
5983 '(org-font-lock-keywords t nil nil backward-paragraph))
5984 (kill-local-variable 'font-lock-keywords) nil))
5986 (defun org-toggle-pretty-entities ()
5987 "Toggle the composition display of entities as UTF8 characters."
5988 (interactive)
5989 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5990 (org-restart-font-lock)
5991 (if org-pretty-entities
5992 (message "Entities are displayed as UTF8 characters")
5993 (save-restriction
5994 (widen)
5995 (org-decompose-region (point-min) (point-max))
5996 (message "Entities are displayed plain"))))
5998 (defvar org-custom-properties-overlays nil
5999 "List of overlays used for custom properties.")
6000 (make-variable-buffer-local 'org-custom-properties-overlays)
6002 (defun org-toggle-custom-properties-visibility ()
6003 "Display or hide properties in `org-custom-properties'."
6004 (interactive)
6005 (if org-custom-properties-overlays
6006 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6007 (setq org-custom-properties-overlays nil))
6008 (unless (not org-custom-properties)
6009 (save-excursion
6010 (save-restriction
6011 (widen)
6012 (goto-char (point-min))
6013 (while (re-search-forward org-property-re nil t)
6014 (mapc (lambda(p)
6015 (when (equal p (substring (match-string 1) 1 -1))
6016 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6017 (overlay-put o 'invisible t)
6018 (overlay-put o 'org-custom-property t)
6019 (push o org-custom-properties-overlays))))
6020 org-custom-properties)))))))
6022 (defun org-fontify-entities (limit)
6023 "Find an entity to fontify."
6024 (let (ee)
6025 (when org-pretty-entities
6026 (catch 'match
6027 (while (re-search-forward
6028 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6029 limit t)
6030 (if (and (not (org-in-indented-comment-line))
6031 (setq ee (org-entity-get (match-string 1)))
6032 (= (length (nth 6 ee)) 1))
6033 (let*
6034 ((end (if (equal (match-string 2) "{}")
6035 (match-end 2)
6036 (match-end 1))))
6037 (add-text-properties
6038 (match-beginning 0) end
6039 (list 'font-lock-fontified t))
6040 (compose-region (match-beginning 0) end
6041 (nth 6 ee) nil)
6042 (backward-char 1)
6043 (throw 'match t))))
6044 nil))))
6046 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6047 "Fontify string S like in Org-mode."
6048 (with-temp-buffer
6049 (insert s)
6050 (let ((org-odd-levels-only odd-levels))
6051 (org-mode)
6052 (font-lock-fontify-buffer)
6053 (buffer-string))))
6055 (defvar org-m nil)
6056 (defvar org-l nil)
6057 (defvar org-f nil)
6058 (defun org-get-level-face (n)
6059 "Get the right face for match N in font-lock matching of headlines."
6060 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6061 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6062 (if org-cycle-level-faces
6063 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6064 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6065 (cond
6066 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6067 ((eq n 2) org-f)
6068 (t (if org-level-color-stars-only nil org-f))))
6071 (defun org-get-todo-face (kwd)
6072 "Get the right face for a TODO keyword KWD.
6073 If KWD is a number, get the corresponding match group."
6074 (if (numberp kwd) (setq kwd (match-string kwd)))
6075 (or (org-face-from-face-or-color
6076 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6077 (and (member kwd org-done-keywords) 'org-done)
6078 'org-todo))
6080 (defun org-face-from-face-or-color (context inherit face-or-color)
6081 "Create a face list that inherits INHERIT, but sets the foreground color.
6082 When FACE-OR-COLOR is not a string, just return it."
6083 (if (stringp face-or-color)
6084 (list :inherit inherit
6085 (cdr (assoc context org-faces-easy-properties))
6086 face-or-color)
6087 face-or-color))
6089 (defun org-font-lock-add-tag-faces (limit)
6090 "Add the special tag faces."
6091 (when (and org-tag-faces org-tags-special-faces-re)
6092 (while (re-search-forward org-tags-special-faces-re limit t)
6093 (add-text-properties (match-beginning 1) (match-end 1)
6094 (list 'face (org-get-tag-face 1)
6095 'font-lock-fontified t))
6096 (backward-char 1))))
6098 (defun org-font-lock-add-priority-faces (limit)
6099 "Add the special priority faces."
6100 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6101 (when (save-match-data (org-at-heading-p))
6102 (add-text-properties
6103 (match-beginning 0) (match-end 0)
6104 (list 'face (or (org-face-from-face-or-color
6105 'priority 'org-special-keyword
6106 (cdr (assoc (char-after (match-beginning 1))
6107 org-priority-faces)))
6108 'org-special-keyword)
6109 'font-lock-fontified t)))))
6111 (defun org-get-tag-face (kwd)
6112 "Get the right face for a TODO keyword KWD.
6113 If KWD is a number, get the corresponding match group."
6114 (if (numberp kwd) (setq kwd (match-string kwd)))
6115 (or (org-face-from-face-or-color
6116 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6117 'org-tag))
6119 (defun org-unfontify-region (beg end &optional maybe_loudly)
6120 "Remove fontification and activation overlays from links."
6121 (font-lock-default-unfontify-region beg end)
6122 (let* ((buffer-undo-list t)
6123 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6124 (inhibit-modification-hooks t)
6125 deactivate-mark buffer-file-name buffer-file-truename)
6126 (org-decompose-region beg end)
6127 (remove-text-properties beg end
6128 '(mouse-face t keymap t org-linked-text t
6129 invisible t intangible t
6130 org-no-flyspell t org-emphasis t))
6131 (org-remove-font-lock-display-properties beg end)))
6133 (defconst org-script-display '(((raise -0.3) (height 0.7))
6134 ((raise 0.3) (height 0.7))
6135 ((raise -0.5))
6136 ((raise 0.5)))
6137 "Display properties for showing superscripts and subscripts.")
6139 (defun org-remove-font-lock-display-properties (beg end)
6140 "Remove specific display properties that have been added by font lock.
6141 The will remove the raise properties that are used to show superscripts
6142 and subscripts."
6143 (let (next prop)
6144 (while (< beg end)
6145 (setq next (next-single-property-change beg 'display nil end)
6146 prop (get-text-property beg 'display))
6147 (if (member prop org-script-display)
6148 (put-text-property beg next 'display nil))
6149 (setq beg next))))
6151 (defun org-raise-scripts (limit)
6152 "Add raise properties to sub/superscripts."
6153 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6154 (if (re-search-forward
6155 (if (eq org-use-sub-superscripts t)
6156 org-match-substring-regexp
6157 org-match-substring-with-braces-regexp)
6158 limit t)
6159 (let* ((pos (point)) table-p comment-p
6160 (mpos (match-beginning 3))
6161 (emph-p (get-text-property mpos 'org-emphasis))
6162 (link-p (get-text-property mpos 'mouse-face))
6163 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6164 (goto-char (point-at-bol))
6165 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6166 comment-p (org-looking-at-p "[ \t]*#"))
6167 (goto-char pos)
6168 ;; FIXME: Should we go back one character here, for a_b^c
6169 ;; (goto-char (1- pos)) ;????????????????????
6170 (if (or comment-p emph-p link-p keyw-p)
6172 (put-text-property (match-beginning 3) (match-end 0)
6173 'display
6174 (if (equal (char-after (match-beginning 2)) ?^)
6175 (nth (if table-p 3 1) org-script-display)
6176 (nth (if table-p 2 0) org-script-display)))
6177 (add-text-properties (match-beginning 2) (match-end 2)
6178 (list 'invisible t
6179 'org-dwidth t 'org-dwidth-n 1))
6180 (if (and (eq (char-after (match-beginning 3)) ?{)
6181 (eq (char-before (match-end 3)) ?}))
6182 (progn
6183 (add-text-properties
6184 (match-beginning 3) (1+ (match-beginning 3))
6185 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6186 (add-text-properties
6187 (1- (match-end 3)) (match-end 3)
6188 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6189 t)))))
6191 ;;;; Visibility cycling, including org-goto and indirect buffer
6193 ;;; Cycling
6195 (defvar org-cycle-global-status nil)
6196 (make-variable-buffer-local 'org-cycle-global-status)
6197 (defvar org-cycle-subtree-status nil)
6198 (make-variable-buffer-local 'org-cycle-subtree-status)
6200 ;;;###autoload
6202 (defvar org-inlinetask-min-level)
6204 (defun org-cycle (&optional arg)
6205 "TAB-action and visibility cycling for Org-mode.
6207 This is the command invoked in Org-mode by the TAB key. Its main purpose
6208 is outline visibility cycling, but it also invokes other actions
6209 in special contexts.
6211 - When this function is called with a prefix argument, rotate the entire
6212 buffer through 3 states (global cycling)
6213 1. OVERVIEW: Show only top-level headlines.
6214 2. CONTENTS: Show all headlines of all levels, but no body text.
6215 3. SHOW ALL: Show everything.
6216 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6217 determined by the variable `org-startup-folded', and by any VISIBILITY
6218 properties in the buffer.
6219 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6220 including any drawers.
6222 - When inside a table, re-align the table and move to the next field.
6224 - When point is at the beginning of a headline, rotate the subtree started
6225 by this line through 3 different states (local cycling)
6226 1. FOLDED: Only the main headline is shown.
6227 2. CHILDREN: The main headline and the direct children are shown.
6228 From this state, you can move to one of the children
6229 and zoom in further.
6230 3. SUBTREE: Show the entire subtree, including body text.
6231 If there is no subtree, switch directly from CHILDREN to FOLDED.
6233 - When point is at the beginning of an empty headline and the variable
6234 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6235 of the headline by demoting and promoting it to likely levels. This
6236 speeds up creation document structure by pressing TAB once or several
6237 times right after creating a new headline.
6239 - When there is a numeric prefix, go up to a heading with level ARG, do
6240 a `show-subtree' and return to the previous cursor position. If ARG
6241 is negative, go up that many levels.
6243 - When point is not at the beginning of a headline, execute the global
6244 binding for TAB, which is re-indenting the line. See the option
6245 `org-cycle-emulate-tab' for details.
6247 - Special case: if point is at the beginning of the buffer and there is
6248 no headline in line 1, this function will act as if called with prefix arg
6249 (C-u TAB, same as S-TAB) also when called without prefix arg.
6250 But only if also the variable `org-cycle-global-at-bob' is t."
6251 (interactive "P")
6252 (org-load-modules-maybe)
6253 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6254 (and org-cycle-level-after-item/entry-creation
6255 (or (org-cycle-level)
6256 (org-cycle-item-indentation))))
6257 (let* ((limit-level
6258 (or org-cycle-max-level
6259 (and (boundp 'org-inlinetask-min-level)
6260 org-inlinetask-min-level
6261 (1- org-inlinetask-min-level))))
6262 (nstars (and limit-level
6263 (if org-odd-levels-only
6264 (and limit-level (1- (* limit-level 2)))
6265 limit-level)))
6266 (org-outline-regexp
6267 (if (not (derived-mode-p 'org-mode))
6268 outline-regexp
6269 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6270 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6271 (not (looking-at org-outline-regexp))))
6272 (org-cycle-hook
6273 (if bob-special
6274 (delq 'org-optimize-window-after-visibility-change
6275 (copy-sequence org-cycle-hook))
6276 org-cycle-hook))
6277 (pos (point)))
6279 (if (or bob-special (equal arg '(4)))
6280 ;; special case: use global cycling
6281 (setq arg t))
6283 (cond
6285 ((equal arg '(16))
6286 (setq last-command 'dummy)
6287 (org-set-startup-visibility)
6288 (message "Startup visibility, plus VISIBILITY properties"))
6290 ((equal arg '(64))
6291 (show-all)
6292 (message "Entire buffer visible, including drawers"))
6294 ;; Table: enter it or move to the next field.
6295 ((org-at-table-p 'any)
6296 (if (org-at-table.el-p)
6297 (message "Use C-c ' to edit table.el tables")
6298 (if arg (org-table-edit-field t)
6299 (org-table-justify-field-maybe)
6300 (call-interactively 'org-table-next-field))))
6302 ((run-hook-with-args-until-success
6303 'org-tab-after-check-for-table-hook))
6305 ;; Global cycling: delegate to `org-cycle-internal-global'.
6306 ((eq arg t) (org-cycle-internal-global))
6308 ;; Drawers: delegate to `org-flag-drawer'.
6309 ((and org-drawers org-drawer-regexp
6310 (save-excursion
6311 (beginning-of-line 1)
6312 (looking-at org-drawer-regexp)))
6313 (org-flag-drawer ; toggle block visibility
6314 (not (get-char-property (match-end 0) 'invisible))))
6316 ;; Show-subtree, ARG levels up from here.
6317 ((integerp arg)
6318 (save-excursion
6319 (org-back-to-heading)
6320 (outline-up-heading (if (< arg 0) (- arg)
6321 (- (funcall outline-level) arg)))
6322 (org-show-subtree)))
6324 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6325 ((and (featurep 'org-inlinetask)
6326 (org-inlinetask-at-task-p)
6327 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6328 (org-inlinetask-toggle-visibility))
6330 ((org-try-cdlatex-tab))
6332 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6333 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6334 (save-excursion (beginning-of-line 1)
6335 (looking-at org-outline-regexp)))
6336 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6337 (org-cycle-internal-local))
6339 ;; From there: TAB emulation and template completion.
6340 (buffer-read-only (org-back-to-heading))
6342 ((run-hook-with-args-until-success
6343 'org-tab-after-check-for-cycling-hook))
6345 ((org-try-structure-completion))
6347 ((run-hook-with-args-until-success
6348 'org-tab-before-tab-emulation-hook))
6350 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6351 (or (not (bolp))
6352 (not (looking-at org-outline-regexp))))
6353 (call-interactively (global-key-binding "\t")))
6355 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6356 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6357 (or (and (eq org-cycle-emulate-tab 'white)
6358 (= (match-end 0) (point-at-eol)))
6359 (and (eq org-cycle-emulate-tab 'whitestart)
6360 (>= (match-end 0) pos))))
6362 (eq org-cycle-emulate-tab t))
6363 (call-interactively (global-key-binding "\t")))
6365 (t (save-excursion
6366 (org-back-to-heading)
6367 (org-cycle)))))))
6369 (defun org-cycle-internal-global ()
6370 "Do the global cycling action."
6371 ;; Hack to avoid display of messages for .org attachments in Gnus
6372 (let ((ga (string-match "\\*fontification" (buffer-name))))
6373 (cond
6374 ((and (eq last-command this-command)
6375 (eq org-cycle-global-status 'overview))
6376 ;; We just created the overview - now do table of contents
6377 ;; This can be slow in very large buffers, so indicate action
6378 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6379 (unless ga (message "CONTENTS..."))
6380 (org-content)
6381 (unless ga (message "CONTENTS...done"))
6382 (setq org-cycle-global-status 'contents)
6383 (run-hook-with-args 'org-cycle-hook 'contents))
6385 ((and (eq last-command this-command)
6386 (eq org-cycle-global-status 'contents))
6387 ;; We just showed the table of contents - now show everything
6388 (run-hook-with-args 'org-pre-cycle-hook 'all)
6389 (show-all)
6390 (unless ga (message "SHOW ALL"))
6391 (setq org-cycle-global-status 'all)
6392 (run-hook-with-args 'org-cycle-hook 'all))
6395 ;; Default action: go to overview
6396 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6397 (org-overview)
6398 (unless ga (message "OVERVIEW"))
6399 (setq org-cycle-global-status 'overview)
6400 (run-hook-with-args 'org-cycle-hook 'overview)))))
6402 (defun org-cycle-internal-local ()
6403 "Do the local cycling action."
6404 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6405 ;; First, determine end of headline (EOH), end of subtree or item
6406 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6407 (save-excursion
6408 (if (org-at-item-p)
6409 (progn
6410 (beginning-of-line)
6411 (setq struct (org-list-struct))
6412 (setq eoh (point-at-eol))
6413 (setq eos (org-list-get-item-end-before-blank (point) struct))
6414 (setq has-children (org-list-has-child-p (point) struct)))
6415 (org-back-to-heading)
6416 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6417 (setq eos (save-excursion
6418 (org-end-of-subtree t)
6419 (unless (eobp)
6420 (skip-chars-forward " \t\n"))
6421 (if (eobp) (point) (1- (point)))))
6422 (setq has-children
6423 (or (save-excursion
6424 (let ((level (funcall outline-level)))
6425 (outline-next-heading)
6426 (and (org-at-heading-p t)
6427 (> (funcall outline-level) level))))
6428 (save-excursion
6429 (org-list-search-forward (org-item-beginning-re) eos t)))))
6430 ;; Determine end invisible part of buffer (EOL)
6431 (beginning-of-line 2)
6432 ;; XEmacs doesn't have `next-single-char-property-change'
6433 (if (featurep 'xemacs)
6434 (while (and (not (eobp)) ;; this is like `next-line'
6435 (get-char-property (1- (point)) 'invisible))
6436 (beginning-of-line 2))
6437 (while (and (not (eobp)) ;; this is like `next-line'
6438 (get-char-property (1- (point)) 'invisible))
6439 (goto-char (next-single-char-property-change (point) 'invisible))
6440 (and (eolp) (beginning-of-line 2))))
6441 (setq eol (point)))
6442 ;; Find out what to do next and set `this-command'
6443 (cond
6444 ((= eos eoh)
6445 ;; Nothing is hidden behind this heading
6446 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6447 (message "EMPTY ENTRY")
6448 (setq org-cycle-subtree-status nil)
6449 (save-excursion
6450 (goto-char eos)
6451 (outline-next-heading)
6452 (if (outline-invisible-p) (org-flag-heading nil))))
6453 ((and (or (>= eol eos)
6454 (not (string-match "\\S-" (buffer-substring eol eos))))
6455 (or has-children
6456 (not (setq children-skipped
6457 org-cycle-skip-children-state-if-no-children))))
6458 ;; Entire subtree is hidden in one line: children view
6459 (run-hook-with-args 'org-pre-cycle-hook 'children)
6460 (if (org-at-item-p)
6461 (org-list-set-item-visibility (point-at-bol) struct 'children)
6462 (org-show-entry)
6463 (org-with-limited-levels (show-children))
6464 ;; FIXME: This slows down the func way too much.
6465 ;; How keep drawers hidden in subtree anyway?
6466 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6467 ;; (org-cycle-hide-drawers 'subtree))
6469 ;; Fold every list in subtree to top-level items.
6470 (when (eq org-cycle-include-plain-lists 'integrate)
6471 (save-excursion
6472 (org-back-to-heading)
6473 (while (org-list-search-forward (org-item-beginning-re) eos t)
6474 (beginning-of-line 1)
6475 (let* ((struct (org-list-struct))
6476 (prevs (org-list-prevs-alist struct))
6477 (end (org-list-get-bottom-point struct)))
6478 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6479 (org-list-get-all-items (point) struct prevs))
6480 (goto-char end))))))
6481 (message "CHILDREN")
6482 (save-excursion
6483 (goto-char eos)
6484 (outline-next-heading)
6485 (if (outline-invisible-p) (org-flag-heading nil)))
6486 (setq org-cycle-subtree-status 'children)
6487 (run-hook-with-args 'org-cycle-hook 'children))
6488 ((or children-skipped
6489 (and (eq last-command this-command)
6490 (eq org-cycle-subtree-status 'children)))
6491 ;; We just showed the children, or no children are there,
6492 ;; now show everything.
6493 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6494 (outline-flag-region eoh eos nil)
6495 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6496 (setq org-cycle-subtree-status 'subtree)
6497 (run-hook-with-args 'org-cycle-hook 'subtree))
6499 ;; Default action: hide the subtree.
6500 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6501 (outline-flag-region eoh eos t)
6502 (message "FOLDED")
6503 (setq org-cycle-subtree-status 'folded)
6504 (run-hook-with-args 'org-cycle-hook 'folded)))))
6506 ;;;###autoload
6507 (defun org-global-cycle (&optional arg)
6508 "Cycle the global visibility. For details see `org-cycle'.
6509 With \\[universal-argument] prefix arg, switch to startup visibility.
6510 With a numeric prefix, show all headlines up to that level."
6511 (interactive "P")
6512 (let ((org-cycle-include-plain-lists
6513 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6514 (cond
6515 ((integerp arg)
6516 (show-all)
6517 (hide-sublevels arg)
6518 (setq org-cycle-global-status 'contents))
6519 ((equal arg '(4))
6520 (org-set-startup-visibility)
6521 (message "Startup visibility, plus VISIBILITY properties."))
6523 (org-cycle '(4))))))
6525 (defun org-set-startup-visibility ()
6526 "Set the visibility required by startup options and properties."
6527 (cond
6528 ((eq org-startup-folded t)
6529 (org-cycle '(4)))
6530 ((eq org-startup-folded 'content)
6531 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6532 (org-cycle '(4)) (org-cycle '(4)))))
6533 (unless (eq org-startup-folded 'showeverything)
6534 (if org-hide-block-startup (org-hide-block-all))
6535 (org-set-visibility-according-to-property 'no-cleanup)
6536 (org-cycle-hide-archived-subtrees 'all)
6537 (org-cycle-hide-drawers 'all)
6538 (org-cycle-show-empty-lines t)))
6540 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6541 "Switch subtree visibilities according to :VISIBILITY: property."
6542 (interactive)
6543 (let (org-show-entry-below state)
6544 (save-excursion
6545 (goto-char (point-min))
6546 (while (re-search-forward
6547 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6548 nil t)
6549 (setq state (match-string 1))
6550 (save-excursion
6551 (org-back-to-heading t)
6552 (hide-subtree)
6553 (org-reveal)
6554 (cond
6555 ((equal state '("fold" "folded"))
6556 (hide-subtree))
6557 ((equal state "children")
6558 (org-show-hidden-entry)
6559 (show-children))
6560 ((equal state "content")
6561 (save-excursion
6562 (save-restriction
6563 (org-narrow-to-subtree)
6564 (org-content))))
6565 ((member state '("all" "showall"))
6566 (show-subtree)))))
6567 (unless no-cleanup
6568 (org-cycle-hide-archived-subtrees 'all)
6569 (org-cycle-hide-drawers 'all)
6570 (org-cycle-show-empty-lines 'all)))))
6572 ;; This function uses outline-regexp instead of the more fundamental
6573 ;; org-outline-regexp so that org-cycle-global works outside of Org
6574 ;; buffers, where outline-regexp is needed.
6575 (defun org-overview ()
6576 "Switch to overview mode, showing only top-level headlines.
6577 Really, this shows all headlines with level equal or greater than the level
6578 of the first headline in the buffer. This is important, because if the
6579 first headline is not level one, then (hide-sublevels 1) gives confusing
6580 results."
6581 (interactive)
6582 (let ((level (save-excursion
6583 (goto-char (point-min))
6584 (if (re-search-forward (concat "^" outline-regexp) nil t)
6585 (progn
6586 (goto-char (match-beginning 0))
6587 (funcall outline-level))))))
6588 (and level (hide-sublevels level))))
6590 (defun org-content (&optional arg)
6591 "Show all headlines in the buffer, like a table of contents.
6592 With numerical argument N, show content up to level N."
6593 (interactive "P")
6594 (save-excursion
6595 ;; Visit all headings and show their offspring
6596 (and (integerp arg) (org-overview))
6597 (goto-char (point-max))
6598 (catch 'exit
6599 (while (and (progn (condition-case nil
6600 (outline-previous-visible-heading 1)
6601 (error (goto-char (point-min))))
6603 (looking-at org-outline-regexp))
6604 (if (integerp arg)
6605 (show-children (1- arg))
6606 (show-branches))
6607 (if (bobp) (throw 'exit nil))))))
6610 (defun org-optimize-window-after-visibility-change (state)
6611 "Adjust the window after a change in outline visibility.
6612 This function is the default value of the hook `org-cycle-hook'."
6613 (when (get-buffer-window (current-buffer))
6614 (cond
6615 ((eq state 'content) nil)
6616 ((eq state 'all) nil)
6617 ((eq state 'folded) nil)
6618 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6619 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6621 (defun org-remove-empty-overlays-at (pos)
6622 "Remove outline overlays that do not contain non-white stuff."
6623 (mapc
6624 (lambda (o)
6625 (and (eq 'outline (overlay-get o 'invisible))
6626 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6627 (overlay-end o))))
6628 (delete-overlay o)))
6629 (overlays-at pos)))
6631 (defun org-clean-visibility-after-subtree-move ()
6632 "Fix visibility issues after moving a subtree."
6633 ;; First, find a reasonable region to look at:
6634 ;; Start two siblings above, end three below
6635 (let* ((beg (save-excursion
6636 (and (org-get-last-sibling)
6637 (org-get-last-sibling))
6638 (point)))
6639 (end (save-excursion
6640 (and (org-get-next-sibling)
6641 (org-get-next-sibling)
6642 (org-get-next-sibling))
6643 (if (org-at-heading-p)
6644 (point-at-eol)
6645 (point))))
6646 (level (looking-at "\\*+"))
6647 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6648 (save-excursion
6649 (save-restriction
6650 (narrow-to-region beg end)
6651 (when re
6652 ;; Properly fold already folded siblings
6653 (goto-char (point-min))
6654 (while (re-search-forward re nil t)
6655 (if (and (not (outline-invisible-p))
6656 (save-excursion
6657 (goto-char (point-at-eol)) (outline-invisible-p)))
6658 (hide-entry))))
6659 (org-cycle-show-empty-lines 'overview)
6660 (org-cycle-hide-drawers 'overview)))))
6662 (defun org-cycle-show-empty-lines (state)
6663 "Show empty lines above all visible headlines.
6664 The region to be covered depends on STATE when called through
6665 `org-cycle-hook'. Lisp program can use t for STATE to get the
6666 entire buffer covered. Note that an empty line is only shown if there
6667 are at least `org-cycle-separator-lines' empty lines before the headline."
6668 (when (not (= org-cycle-separator-lines 0))
6669 (save-excursion
6670 (let* ((n (abs org-cycle-separator-lines))
6671 (re (cond
6672 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6673 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6674 (t (let ((ns (number-to-string (- n 2))))
6675 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6676 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6677 beg end b e)
6678 (cond
6679 ((memq state '(overview contents t))
6680 (setq beg (point-min) end (point-max)))
6681 ((memq state '(children folded))
6682 (setq beg (point) end (progn (org-end-of-subtree t t)
6683 (beginning-of-line 2)
6684 (point)))))
6685 (when beg
6686 (goto-char beg)
6687 (while (re-search-forward re end t)
6688 (unless (get-char-property (match-end 1) 'invisible)
6689 (setq e (match-end 1))
6690 (if (< org-cycle-separator-lines 0)
6691 (setq b (save-excursion
6692 (goto-char (match-beginning 0))
6693 (org-back-over-empty-lines)
6694 (if (save-excursion
6695 (goto-char (max (point-min) (1- (point))))
6696 (org-at-heading-p))
6697 (1- (point))
6698 (point))))
6699 (setq b (match-beginning 1)))
6700 (outline-flag-region b e nil)))))))
6701 ;; Never hide empty lines at the end of the file.
6702 (save-excursion
6703 (goto-char (point-max))
6704 (outline-previous-heading)
6705 (outline-end-of-heading)
6706 (if (and (looking-at "[ \t\n]+")
6707 (= (match-end 0) (point-max)))
6708 (outline-flag-region (point) (match-end 0) nil))))
6710 (defun org-show-empty-lines-in-parent ()
6711 "Move to the parent and re-show empty lines before visible headlines."
6712 (save-excursion
6713 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6714 (org-cycle-show-empty-lines context))))
6716 (defun org-files-list ()
6717 "Return `org-agenda-files' list, plus all open org-mode files.
6718 This is useful for operations that need to scan all of a user's
6719 open and agenda-wise Org files."
6720 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6721 (dolist (buf (buffer-list))
6722 (with-current-buffer buf
6723 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6724 (let ((file (expand-file-name (buffer-file-name))))
6725 (unless (member file files)
6726 (push file files))))))
6727 files))
6729 (defsubst org-entry-beginning-position ()
6730 "Return the beginning position of the current entry."
6731 (save-excursion (outline-back-to-heading t) (point)))
6733 (defsubst org-entry-end-position ()
6734 "Return the end position of the current entry."
6735 (save-excursion (outline-next-heading) (point)))
6737 (defun org-cycle-hide-drawers (state)
6738 "Re-hide all drawers after a visibility state change."
6739 (when (and (derived-mode-p 'org-mode)
6740 (not (memq state '(overview folded contents))))
6741 (save-excursion
6742 (let* ((globalp (memq state '(contents all)))
6743 (beg (if globalp (point-min) (point)))
6744 (end (if globalp (point-max)
6745 (if (eq state 'children)
6746 (save-excursion (outline-next-heading) (point))
6747 (org-end-of-subtree t)))))
6748 (goto-char beg)
6749 (while (re-search-forward org-drawer-regexp end t)
6750 (org-flag-drawer t))))))
6752 (defun org-cycle-hide-inline-tasks (state)
6753 "Re-hide inline task when switching to 'contents visibility state."
6754 (when (and (eq state 'contents)
6755 (boundp 'org-inlinetask-min-level)
6756 org-inlinetask-min-level)
6757 (hide-sublevels (1- org-inlinetask-min-level))))
6759 (defun org-flag-drawer (flag)
6760 "When FLAG is non-nil, hide the drawer we are within.
6761 Otherwise make it visible."
6762 (save-excursion
6763 (beginning-of-line 1)
6764 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6765 (let ((b (match-end 0)))
6766 (if (re-search-forward
6767 "^[ \t]*:END:"
6768 (save-excursion (outline-next-heading) (point)) t)
6769 (outline-flag-region b (point-at-eol) flag)
6770 (error ":END: line missing at position %s" b))))))
6772 (defun org-subtree-end-visible-p ()
6773 "Is the end of the current subtree visible?"
6774 (pos-visible-in-window-p
6775 (save-excursion (org-end-of-subtree t) (point))))
6777 (defun org-first-headline-recenter (&optional N)
6778 "Move cursor to the first headline and recenter the headline.
6779 Optional argument N means put the headline into the Nth line of the window."
6780 (goto-char (point-min))
6781 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6782 (beginning-of-line)
6783 (recenter (prefix-numeric-value N))))
6785 ;;; Saving and restoring visibility
6787 (defun org-outline-overlay-data (&optional use-markers)
6788 "Return a list of the locations of all outline overlays.
6789 These are overlays with the `invisible' property value `outline'.
6790 The return value is a list of cons cells, with start and stop
6791 positions for each overlay.
6792 If USE-MARKERS is set, return the positions as markers."
6793 (let (beg end)
6794 (save-excursion
6795 (save-restriction
6796 (widen)
6797 (delq nil
6798 (mapcar (lambda (o)
6799 (when (eq (overlay-get o 'invisible) 'outline)
6800 (setq beg (overlay-start o)
6801 end (overlay-end o))
6802 (and beg end (> end beg)
6803 (if use-markers
6804 (cons (move-marker (make-marker) beg)
6805 (move-marker (make-marker) end))
6806 (cons beg end)))))
6807 (overlays-in (point-min) (point-max))))))))
6809 (defun org-set-outline-overlay-data (data)
6810 "Create visibility overlays for all positions in DATA.
6811 DATA should have been made by `org-outline-overlay-data'."
6812 (let (o)
6813 (save-excursion
6814 (save-restriction
6815 (widen)
6816 (show-all)
6817 (mapc (lambda (c)
6818 (outline-flag-region (car c) (cdr c) t))
6819 data)))))
6821 ;;; Folding of blocks
6823 (defvar org-hide-block-overlays nil
6824 "Overlays hiding blocks.")
6825 (make-variable-buffer-local 'org-hide-block-overlays)
6827 (defun org-block-map (function &optional start end)
6828 "Call FUNCTION at the head of all source blocks in the current buffer.
6829 Optional arguments START and END can be used to limit the range."
6830 (let ((start (or start (point-min)))
6831 (end (or end (point-max))))
6832 (save-excursion
6833 (goto-char start)
6834 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6835 (save-excursion
6836 (save-match-data
6837 (goto-char (match-beginning 0))
6838 (funcall function)))))))
6840 (defun org-hide-block-toggle-all ()
6841 "Toggle the visibility of all blocks in the current buffer."
6842 (org-block-map #'org-hide-block-toggle))
6844 (defun org-hide-block-all ()
6845 "Fold all blocks in the current buffer."
6846 (interactive)
6847 (org-show-block-all)
6848 (org-block-map #'org-hide-block-toggle-maybe))
6850 (defun org-show-block-all ()
6851 "Unfold all blocks in the current buffer."
6852 (interactive)
6853 (mapc 'delete-overlay org-hide-block-overlays)
6854 (setq org-hide-block-overlays nil))
6856 (defun org-hide-block-toggle-maybe ()
6857 "Toggle visibility of block at point."
6858 (interactive)
6859 (let ((case-fold-search t))
6860 (if (save-excursion
6861 (beginning-of-line 1)
6862 (looking-at org-block-regexp))
6863 (progn (org-hide-block-toggle)
6864 t) ;; to signal that we took action
6865 nil))) ;; to signal that we did not
6867 (defun org-hide-block-toggle (&optional force)
6868 "Toggle the visibility of the current block."
6869 (interactive)
6870 (save-excursion
6871 (beginning-of-line)
6872 (if (re-search-forward org-block-regexp nil t)
6873 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6874 (end (match-end 0)) ;; end of entire body
6876 (if (memq t (mapcar (lambda (overlay)
6877 (eq (overlay-get overlay 'invisible)
6878 'org-hide-block))
6879 (overlays-at start)))
6880 (if (or (not force) (eq force 'off))
6881 (mapc (lambda (ov)
6882 (when (member ov org-hide-block-overlays)
6883 (setq org-hide-block-overlays
6884 (delq ov org-hide-block-overlays)))
6885 (when (eq (overlay-get ov 'invisible)
6886 'org-hide-block)
6887 (delete-overlay ov)))
6888 (overlays-at start)))
6889 (setq ov (make-overlay start end))
6890 (overlay-put ov 'invisible 'org-hide-block)
6891 ;; make the block accessible to isearch
6892 (overlay-put
6893 ov 'isearch-open-invisible
6894 (lambda (ov)
6895 (when (member ov org-hide-block-overlays)
6896 (setq org-hide-block-overlays
6897 (delq ov org-hide-block-overlays)))
6898 (when (eq (overlay-get ov 'invisible)
6899 'org-hide-block)
6900 (delete-overlay ov))))
6901 (push ov org-hide-block-overlays)))
6902 (error "Not looking at a source block"))))
6904 ;; org-tab-after-check-for-cycling-hook
6905 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6906 ;; Remove overlays when changing major mode
6907 (add-hook 'org-mode-hook
6908 (lambda () (org-add-hook 'change-major-mode-hook
6909 'org-show-block-all 'append 'local)))
6911 ;;; Org-goto
6913 (defvar org-goto-window-configuration nil)
6914 (defvar org-goto-marker nil)
6915 (defvar org-goto-map
6916 (let ((map (make-sparse-keymap)))
6917 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6918 (while (setq cmd (pop cmds))
6919 (substitute-key-definition cmd cmd map global-map)))
6920 (suppress-keymap map)
6921 (org-defkey map "\C-m" 'org-goto-ret)
6922 (org-defkey map [(return)] 'org-goto-ret)
6923 (org-defkey map [(left)] 'org-goto-left)
6924 (org-defkey map [(right)] 'org-goto-right)
6925 (org-defkey map [(control ?g)] 'org-goto-quit)
6926 (org-defkey map "\C-i" 'org-cycle)
6927 (org-defkey map [(tab)] 'org-cycle)
6928 (org-defkey map [(down)] 'outline-next-visible-heading)
6929 (org-defkey map [(up)] 'outline-previous-visible-heading)
6930 (if org-goto-auto-isearch
6931 (if (fboundp 'define-key-after)
6932 (define-key-after map [t] 'org-goto-local-auto-isearch)
6933 nil)
6934 (org-defkey map "q" 'org-goto-quit)
6935 (org-defkey map "n" 'outline-next-visible-heading)
6936 (org-defkey map "p" 'outline-previous-visible-heading)
6937 (org-defkey map "f" 'outline-forward-same-level)
6938 (org-defkey map "b" 'outline-backward-same-level)
6939 (org-defkey map "u" 'outline-up-heading))
6940 (org-defkey map "/" 'org-occur)
6941 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6942 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6943 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6944 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6945 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6946 map))
6948 (defconst org-goto-help
6949 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6950 RET=jump to location [Q]uit and return to previous location
6951 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6953 (defvar org-goto-start-pos) ; dynamically scoped parameter
6955 ;; FIXME: Docstring does not mention both interfaces
6956 (defun org-goto (&optional alternative-interface)
6957 "Look up a different location in the current file, keeping current visibility.
6959 When you want look-up or go to a different location in a
6960 document, the fastest way is often to fold the entire buffer and
6961 then dive into the tree. This method has the disadvantage, that
6962 the previous location will be folded, which may not be what you
6963 want.
6965 This command works around this by showing a copy of the current
6966 buffer in an indirect buffer, in overview mode. You can dive
6967 into the tree in that copy, use org-occur and incremental search
6968 to find a location. When pressing RET or `Q', the command
6969 returns to the original buffer in which the visibility is still
6970 unchanged. After RET it will also jump to the location selected
6971 in the indirect buffer and expose the headline hierarchy above.
6973 With a prefix argument, use the alternative interface: e.g. if
6974 `org-goto-interface' is 'outline use 'outline-path-completion."
6975 (interactive "P")
6976 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6977 (org-refile-use-outline-path t)
6978 (org-refile-target-verify-function nil)
6979 (interface
6980 (if (not alternative-interface)
6981 org-goto-interface
6982 (if (eq org-goto-interface 'outline)
6983 'outline-path-completion
6984 'outline)))
6985 (org-goto-start-pos (point))
6986 (selected-point
6987 (if (eq interface 'outline)
6988 (car (org-get-location (current-buffer) org-goto-help))
6989 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6990 (org-refile-check-position pa)
6991 (nth 3 pa)))))
6992 (if selected-point
6993 (progn
6994 (org-mark-ring-push org-goto-start-pos)
6995 (goto-char selected-point)
6996 (if (or (outline-invisible-p) (org-invisible-p2))
6997 (org-show-context 'org-goto)))
6998 (message "Quit"))))
7000 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7001 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7002 (defvar org-goto-local-auto-isearch-map) ; defined below
7004 (defun org-get-location (buf help)
7005 "Let the user select a location in the Org-mode buffer BUF.
7006 This function uses a recursive edit. It returns the selected position
7007 or nil."
7008 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7009 (isearch-hide-immediately nil)
7010 (isearch-search-fun-function
7011 (lambda () 'org-goto-local-search-headings))
7012 (org-goto-selected-point org-goto-exit-command)
7013 (pop-up-frames nil)
7014 (special-display-buffer-names nil)
7015 (special-display-regexps nil)
7016 (special-display-function nil))
7017 (save-excursion
7018 (save-window-excursion
7019 (delete-other-windows)
7020 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7021 (org-pop-to-buffer-same-window
7022 (condition-case nil
7023 (make-indirect-buffer (current-buffer) "*org-goto*")
7024 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7025 (with-output-to-temp-buffer "*Help*"
7026 (princ help))
7027 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7028 (setq buffer-read-only nil)
7029 (let ((org-startup-truncated t)
7030 (org-startup-folded nil)
7031 (org-startup-align-all-tables nil))
7032 (org-mode)
7033 (org-overview))
7034 (setq buffer-read-only t)
7035 (if (and (boundp 'org-goto-start-pos)
7036 (integer-or-marker-p org-goto-start-pos))
7037 (let ((org-show-hierarchy-above t)
7038 (org-show-siblings t)
7039 (org-show-following-heading t))
7040 (goto-char org-goto-start-pos)
7041 (and (outline-invisible-p) (org-show-context)))
7042 (goto-char (point-min)))
7043 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7044 (message "Select location and press RET")
7045 (use-local-map org-goto-map)
7046 (recursive-edit)
7048 (kill-buffer "*org-goto*")
7049 (cons org-goto-selected-point org-goto-exit-command)))
7051 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7052 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7053 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7054 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7056 (defun org-goto-local-search-headings (string bound noerror)
7057 "Search and make sure that any matches are in headlines."
7058 (catch 'return
7059 (while (if isearch-forward
7060 (search-forward string bound noerror)
7061 (search-backward string bound noerror))
7062 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7063 (and (member :headline context)
7064 (not (member :tags context))))
7065 (throw 'return (point))))))
7067 (defun org-goto-local-auto-isearch ()
7068 "Start isearch."
7069 (interactive)
7070 (goto-char (point-min))
7071 (let ((keys (this-command-keys)))
7072 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7073 (isearch-mode t)
7074 (isearch-process-search-char (string-to-char keys)))))
7076 (defun org-goto-ret (&optional arg)
7077 "Finish `org-goto' by going to the new location."
7078 (interactive "P")
7079 (setq org-goto-selected-point (point)
7080 org-goto-exit-command 'return)
7081 (throw 'exit nil))
7083 (defun org-goto-left ()
7084 "Finish `org-goto' by going to the new location."
7085 (interactive)
7086 (if (org-at-heading-p)
7087 (progn
7088 (beginning-of-line 1)
7089 (setq org-goto-selected-point (point)
7090 org-goto-exit-command 'left)
7091 (throw 'exit nil))
7092 (error "Not on a heading")))
7094 (defun org-goto-right ()
7095 "Finish `org-goto' by going to the new location."
7096 (interactive)
7097 (if (org-at-heading-p)
7098 (progn
7099 (setq org-goto-selected-point (point)
7100 org-goto-exit-command 'right)
7101 (throw 'exit nil))
7102 (error "Not on a heading")))
7104 (defun org-goto-quit ()
7105 "Finish `org-goto' without cursor motion."
7106 (interactive)
7107 (setq org-goto-selected-point nil)
7108 (setq org-goto-exit-command 'quit)
7109 (throw 'exit nil))
7111 ;;; Indirect buffer display of subtrees
7113 (defvar org-indirect-dedicated-frame nil
7114 "This is the frame being used for indirect tree display.")
7115 (defvar org-last-indirect-buffer nil)
7117 (defun org-tree-to-indirect-buffer (&optional arg)
7118 "Create indirect buffer and narrow it to current subtree.
7119 With numerical prefix ARG, go up to this level and then take that tree.
7120 If ARG is negative, go up that many levels.
7121 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7122 indirect buffer previously made with this command, to avoid proliferation of
7123 indirect buffers. However, when you call the command with a \
7124 \\[universal-argument] prefix, or
7125 when `org-indirect-buffer-display' is `new-frame', the last buffer
7126 is kept so that you can work with several indirect buffers at the same time.
7127 If `org-indirect-buffer-display' is `dedicated-frame', the \
7128 \\[universal-argument] prefix also
7129 requests that a new frame be made for the new buffer, so that the dedicated
7130 frame is not changed."
7131 (interactive "P")
7132 (let ((cbuf (current-buffer))
7133 (cwin (selected-window))
7134 (pos (point))
7135 beg end level heading ibuf)
7136 (save-excursion
7137 (org-back-to-heading t)
7138 (when (numberp arg)
7139 (setq level (org-outline-level))
7140 (if (< arg 0) (setq arg (+ level arg)))
7141 (while (> (setq level (org-outline-level)) arg)
7142 (outline-up-heading 1 t)))
7143 (setq beg (point)
7144 heading (org-get-heading))
7145 (org-end-of-subtree t t)
7146 (if (org-at-heading-p) (backward-char 1))
7147 (setq end (point)))
7148 (if (and (buffer-live-p org-last-indirect-buffer)
7149 (not (eq org-indirect-buffer-display 'new-frame))
7150 (not arg))
7151 (kill-buffer org-last-indirect-buffer))
7152 (setq ibuf (org-get-indirect-buffer cbuf)
7153 org-last-indirect-buffer ibuf)
7154 (cond
7155 ((or (eq org-indirect-buffer-display 'new-frame)
7156 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7157 (select-frame (make-frame))
7158 (delete-other-windows)
7159 (org-pop-to-buffer-same-window ibuf)
7160 (org-set-frame-title heading))
7161 ((eq org-indirect-buffer-display 'dedicated-frame)
7162 (raise-frame
7163 (select-frame (or (and org-indirect-dedicated-frame
7164 (frame-live-p org-indirect-dedicated-frame)
7165 org-indirect-dedicated-frame)
7166 (setq org-indirect-dedicated-frame (make-frame)))))
7167 (delete-other-windows)
7168 (org-pop-to-buffer-same-window ibuf)
7169 (org-set-frame-title (concat "Indirect: " heading)))
7170 ((eq org-indirect-buffer-display 'current-window)
7171 (org-pop-to-buffer-same-window ibuf))
7172 ((eq org-indirect-buffer-display 'other-window)
7173 (pop-to-buffer ibuf))
7174 (t (error "Invalid value")))
7175 (if (featurep 'xemacs)
7176 (save-excursion (org-mode) (turn-on-font-lock)))
7177 (narrow-to-region beg end)
7178 (show-all)
7179 (goto-char pos)
7180 (run-hook-with-args 'org-cycle-hook 'all)
7181 (and (window-live-p cwin) (select-window cwin))))
7183 (defun org-get-indirect-buffer (&optional buffer)
7184 (setq buffer (or buffer (current-buffer)))
7185 (let ((n 1) (base (buffer-name buffer)) bname)
7186 (while (buffer-live-p
7187 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7188 (setq n (1+ n)))
7189 (condition-case nil
7190 (make-indirect-buffer buffer bname 'clone)
7191 (error (make-indirect-buffer buffer bname)))))
7193 (defun org-set-frame-title (title)
7194 "Set the title of the current frame to the string TITLE."
7195 ;; FIXME: how to name a single frame in XEmacs???
7196 (unless (featurep 'xemacs)
7197 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7199 ;;;; Structure editing
7201 ;;; Inserting headlines
7203 (defun org-previous-line-empty-p ()
7204 (save-excursion
7205 (and (not (bobp))
7206 (or (beginning-of-line 0) t)
7207 (save-match-data
7208 (looking-at "[ \t]*$")))))
7210 (defun org-insert-heading (&optional force-heading invisible-ok)
7211 "Insert a new heading or item with same depth at point.
7212 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7213 If point is at the beginning of a headline, insert a sibling before the
7214 current headline. If point is not at the beginning, split the line,
7215 create the new headline with the text in the current line after point
7216 \(but see also the variable `org-M-RET-may-split-line').
7218 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7219 This is important for non-interactive uses of the command."
7220 (interactive "P")
7221 (if (or (= (buffer-size) 0)
7222 (and (not (save-excursion
7223 (and (ignore-errors (org-back-to-heading invisible-ok))
7224 (org-at-heading-p))))
7225 (or force-heading (not (org-in-item-p)))))
7226 (progn
7227 (insert "\n* ")
7228 (run-hooks 'org-insert-heading-hook))
7229 (when (or force-heading (not (org-insert-item)))
7230 (let* ((empty-line-p nil)
7231 (level nil)
7232 (on-heading (org-at-heading-p))
7233 (head (save-excursion
7234 (condition-case nil
7235 (progn
7236 (org-back-to-heading invisible-ok)
7237 (when (and (not on-heading)
7238 (featurep 'org-inlinetask)
7239 (integerp org-inlinetask-min-level)
7240 (>= (length (match-string 0))
7241 org-inlinetask-min-level))
7242 ;; Find a heading level before the inline task
7243 (while (and (setq level (org-up-heading-safe))
7244 (>= level org-inlinetask-min-level)))
7245 (if (org-at-heading-p)
7246 (org-back-to-heading invisible-ok)
7247 (error "This should not happen")))
7248 (setq empty-line-p (org-previous-line-empty-p))
7249 (match-string 0))
7250 (error "*"))))
7251 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7252 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7253 pos hide-previous previous-pos)
7254 (cond
7255 ((and (org-at-heading-p) (bolp)
7256 (or (bobp)
7257 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7258 ;; insert before the current line
7259 (open-line (if blank 2 1)))
7260 ((and (bolp)
7261 (not org-insert-heading-respect-content)
7262 (or (bobp)
7263 (save-excursion
7264 (backward-char 1) (not (outline-invisible-p)))))
7265 ;; insert right here
7266 nil)
7268 ;; somewhere in the line
7269 (save-excursion
7270 (setq previous-pos (point-at-bol))
7271 (end-of-line)
7272 (setq hide-previous (outline-invisible-p)))
7273 (and org-insert-heading-respect-content (org-show-subtree))
7274 (let ((split
7275 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7276 (save-excursion
7277 (let ((p (point)))
7278 (goto-char (point-at-bol))
7279 (and (looking-at org-complex-heading-regexp)
7280 (match-beginning 4)
7281 (> p (match-beginning 4)))))))
7282 tags pos)
7283 (cond
7284 (org-insert-heading-respect-content
7285 (org-end-of-subtree nil t)
7286 (when (featurep 'org-inlinetask)
7287 (while (and (not (eobp))
7288 (looking-at "\\(\\*+\\)[ \t]+")
7289 (>= (length (match-string 1))
7290 org-inlinetask-min-level))
7291 (org-end-of-subtree nil t)))
7292 (or (bolp) (newline))
7293 (or (org-previous-line-empty-p)
7294 (and blank (newline)))
7295 (open-line 1))
7296 ((org-at-heading-p)
7297 (when hide-previous
7298 (show-children)
7299 (org-show-entry))
7300 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7301 (setq tags (and (match-end 2) (match-string 2)))
7302 (and (match-end 1)
7303 (delete-region (match-beginning 1) (match-end 1)))
7304 (setq pos (point-at-bol))
7305 (or split (end-of-line 1))
7306 (delete-horizontal-space)
7307 (if (string-match "\\`\\*+\\'"
7308 (buffer-substring (point-at-bol) (point)))
7309 (insert " "))
7310 (newline (if blank 2 1))
7311 (when tags
7312 (save-excursion
7313 (goto-char pos)
7314 (end-of-line 1)
7315 (insert " " tags)
7316 (org-set-tags nil 'align))))
7318 (or split (end-of-line 1))
7319 (newline (if blank 2 1)))))))
7320 (insert head) (just-one-space)
7321 (setq pos (point))
7322 (end-of-line 1)
7323 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7324 (when (and org-insert-heading-respect-content hide-previous)
7325 (save-excursion
7326 (goto-char previous-pos)
7327 (hide-subtree)))
7328 (run-hooks 'org-insert-heading-hook)))))
7330 (defun org-get-heading (&optional no-tags no-todo)
7331 "Return the heading of the current entry, without the stars.
7332 When NO-TAGS is non-nil, don't include tags.
7333 When NO-TODO is non-nil, don't include TODO keywords."
7334 (save-excursion
7335 (org-back-to-heading t)
7336 (cond
7337 ((and no-tags no-todo)
7338 (looking-at org-complex-heading-regexp)
7339 (match-string 4))
7340 (no-tags
7341 (looking-at (concat org-outline-regexp
7342 "\\(.*?\\)"
7343 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7344 (match-string 1))
7345 (no-todo
7346 (looking-at org-todo-line-regexp)
7347 (match-string 3))
7348 (t (looking-at org-heading-regexp)
7349 (match-string 2)))))
7351 (defun org-heading-components ()
7352 "Return the components of the current heading.
7353 This is a list with the following elements:
7354 - the level as an integer
7355 - the reduced level, different if `org-odd-levels-only' is set.
7356 - the TODO keyword, or nil
7357 - the priority character, like ?A, or nil if no priority is given
7358 - the headline text itself, or the tags string if no headline text
7359 - the tags string, or nil."
7360 (save-excursion
7361 (org-back-to-heading t)
7362 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7363 (list (length (match-string 1))
7364 (org-reduced-level (length (match-string 1)))
7365 (org-match-string-no-properties 2)
7366 (and (match-end 3) (aref (match-string 3) 2))
7367 (org-match-string-no-properties 4)
7368 (org-match-string-no-properties 5)))))
7370 (defun org-get-entry ()
7371 "Get the entry text, after heading, entire subtree."
7372 (save-excursion
7373 (org-back-to-heading t)
7374 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7376 (defun org-insert-heading-after-current ()
7377 "Insert a new heading with same level as current, after current subtree."
7378 (interactive)
7379 (org-back-to-heading)
7380 (org-insert-heading)
7381 (org-move-subtree-down)
7382 (end-of-line 1))
7384 (defun org-insert-heading-respect-content ()
7385 (interactive)
7386 (let ((org-insert-heading-respect-content t))
7387 (org-insert-heading t)))
7389 (defun org-insert-todo-heading-respect-content (&optional force-state)
7390 (interactive "P")
7391 (let ((org-insert-heading-respect-content t))
7392 (org-insert-todo-heading force-state t)))
7394 (defun org-insert-todo-heading (arg &optional force-heading)
7395 "Insert a new heading with the same level and TODO state as current heading.
7396 If the heading has no TODO state, or if the state is DONE, use the first
7397 state (TODO by default). Also with prefix arg, force first state."
7398 (interactive "P")
7399 (when (or force-heading (not (org-insert-item 'checkbox)))
7400 (org-insert-heading force-heading)
7401 (save-excursion
7402 (org-back-to-heading)
7403 (outline-previous-heading)
7404 (looking-at org-todo-line-regexp))
7405 (let*
7406 ((new-mark-x
7407 (if (or arg
7408 (not (match-beginning 2))
7409 (member (match-string 2) org-done-keywords))
7410 (car org-todo-keywords-1)
7411 (match-string 2)))
7412 (new-mark
7414 (run-hook-with-args-until-success
7415 'org-todo-get-default-hook new-mark-x nil)
7416 new-mark-x)))
7417 (beginning-of-line 1)
7418 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7419 (if org-treat-insert-todo-heading-as-state-change
7420 (org-todo new-mark)
7421 (insert new-mark " "))))
7422 (when org-provide-todo-statistics
7423 (org-update-parent-todo-statistics))))
7425 (defun org-insert-subheading (arg)
7426 "Insert a new subheading and demote it.
7427 Works for outline headings and for plain lists alike."
7428 (interactive "P")
7429 (org-insert-heading arg)
7430 (cond
7431 ((org-at-heading-p) (org-do-demote))
7432 ((org-at-item-p) (org-indent-item))))
7434 (defun org-insert-todo-subheading (arg)
7435 "Insert a new subheading with TODO keyword or checkbox and demote it.
7436 Works for outline headings and for plain lists alike."
7437 (interactive "P")
7438 (org-insert-todo-heading arg)
7439 (cond
7440 ((org-at-heading-p) (org-do-demote))
7441 ((org-at-item-p) (org-indent-item))))
7443 ;;; Promotion and Demotion
7445 (defvar org-after-demote-entry-hook nil
7446 "Hook run after an entry has been demoted.
7447 The cursor will be at the beginning of the entry.
7448 When a subtree is being demoted, the hook will be called for each node.")
7450 (defvar org-after-promote-entry-hook nil
7451 "Hook run after an entry has been promoted.
7452 The cursor will be at the beginning of the entry.
7453 When a subtree is being promoted, the hook will be called for each node.")
7455 (defun org-promote-subtree ()
7456 "Promote the entire subtree.
7457 See also `org-promote'."
7458 (interactive)
7459 (save-excursion
7460 (org-with-limited-levels (org-map-tree 'org-promote)))
7461 (org-fix-position-after-promote))
7463 (defun org-demote-subtree ()
7464 "Demote the entire subtree. See `org-demote'.
7465 See also `org-promote'."
7466 (interactive)
7467 (save-excursion
7468 (org-with-limited-levels (org-map-tree 'org-demote)))
7469 (org-fix-position-after-promote))
7472 (defun org-do-promote ()
7473 "Promote the current heading higher up the tree.
7474 If the region is active in `transient-mark-mode', promote all headings
7475 in the region."
7476 (interactive)
7477 (save-excursion
7478 (if (org-region-active-p)
7479 (org-map-region 'org-promote (region-beginning) (region-end))
7480 (org-promote)))
7481 (org-fix-position-after-promote))
7483 (defun org-do-demote ()
7484 "Demote the current heading lower down the tree.
7485 If the region is active in `transient-mark-mode', demote all headings
7486 in the region."
7487 (interactive)
7488 (save-excursion
7489 (if (org-region-active-p)
7490 (org-map-region 'org-demote (region-beginning) (region-end))
7491 (org-demote)))
7492 (org-fix-position-after-promote))
7494 (defun org-fix-position-after-promote ()
7495 "Make sure that after pro/demotion cursor position is right."
7496 (let ((pos (point)))
7497 (when (save-excursion
7498 (beginning-of-line 1)
7499 (looking-at org-todo-line-regexp)
7500 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7501 (cond ((eobp) (insert " "))
7502 ((eolp) (insert " "))
7503 ((equal (char-after) ?\ ) (forward-char 1))))))
7505 (defun org-current-level ()
7506 "Return the level of the current entry, or nil if before the first headline.
7507 The level is the number of stars at the beginning of the headline."
7508 (save-excursion
7509 (org-with-limited-levels
7510 (if (ignore-errors (org-back-to-heading t))
7511 (funcall outline-level)))))
7513 (defun org-get-previous-line-level ()
7514 "Return the outline depth of the last headline before the current line.
7515 Returns 0 for the first headline in the buffer, and nil if before the
7516 first headline."
7517 (let ((current-level (org-current-level))
7518 (prev-level (when (> (line-number-at-pos) 1)
7519 (save-excursion
7520 (beginning-of-line 0)
7521 (org-current-level)))))
7522 (cond ((null current-level) nil) ; Before first headline
7523 ((null prev-level) 0) ; At first headline
7524 (prev-level))))
7526 (defun org-reduced-level (l)
7527 "Compute the effective level of a heading.
7528 This takes into account the setting of `org-odd-levels-only'."
7529 (cond
7530 ((zerop l) 0)
7531 (org-odd-levels-only (1+ (floor (/ l 2))))
7532 (t l)))
7534 (defun org-level-increment ()
7535 "Return the number of stars that will be added or removed at a
7536 time to headlines when structure editing, based on the value of
7537 `org-odd-levels-only'."
7538 (if org-odd-levels-only 2 1))
7540 (defun org-get-valid-level (level &optional change)
7541 "Rectify a level change under the influence of `org-odd-levels-only'
7542 LEVEL is a current level, CHANGE is by how much the level should be
7543 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7544 even level numbers will become the next higher odd number."
7545 (if org-odd-levels-only
7546 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7547 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7548 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7549 (max 1 (+ level (or change 0)))))
7551 (if (boundp 'define-obsolete-function-alias)
7552 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7553 (define-obsolete-function-alias 'org-get-legal-level
7554 'org-get-valid-level)
7555 (define-obsolete-function-alias 'org-get-legal-level
7556 'org-get-valid-level "23.1")))
7558 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7559 ;; ̀org-with-limited-levels'
7560 (defun org-promote ()
7561 "Promote the current heading higher up the tree.
7562 If the region is active in `transient-mark-mode', promote all headings
7563 in the region."
7564 (org-back-to-heading t)
7565 (let* ((level (save-match-data (funcall outline-level)))
7566 (after-change-functions (remove 'flyspell-after-change-function
7567 after-change-functions))
7568 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7569 (diff (abs (- level (length up-head) -1))))
7570 (cond ((and (= level 1) org-called-with-limited-levels
7571 org-allow-promoting-top-level-subtree)
7572 (replace-match "# " nil t))
7573 ((= level 1)
7574 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7575 (t (replace-match up-head nil t)))
7576 ;; Fixup tag positioning
7577 (unless (= level 1)
7578 (and org-auto-align-tags (org-set-tags nil t))
7579 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7580 (run-hooks 'org-after-promote-entry-hook)))
7582 (defun org-demote ()
7583 "Demote the current heading lower down the tree.
7584 If the region is active in `transient-mark-mode', demote all headings
7585 in the region."
7586 (org-back-to-heading t)
7587 (let* ((level (save-match-data (funcall outline-level)))
7588 (after-change-functions (remove 'flyspell-after-change-function
7589 after-change-functions))
7590 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7591 (diff (abs (- level (length down-head) -1))))
7592 (replace-match down-head nil t)
7593 ;; Fixup tag positioning
7594 (and org-auto-align-tags (org-set-tags nil t))
7595 (if org-adapt-indentation (org-fixup-indentation diff))
7596 (run-hooks 'org-after-demote-entry-hook)))
7598 (defun org-cycle-level ()
7599 "Cycle the level of an empty headline through possible states.
7600 This goes first to child, then to parent, level, then up the hierarchy.
7601 After top level, it switches back to sibling level."
7602 (interactive)
7603 (let ((org-adapt-indentation nil))
7604 (when (org-point-at-end-of-empty-headline)
7605 (setq this-command 'org-cycle-level) ; Only needed for caching
7606 (let ((cur-level (org-current-level))
7607 (prev-level (org-get-previous-line-level)))
7608 (cond
7609 ;; If first headline in file, promote to top-level.
7610 ((= prev-level 0)
7611 (loop repeat (/ (- cur-level 1) (org-level-increment))
7612 do (org-do-promote)))
7613 ;; If same level as prev, demote one.
7614 ((= prev-level cur-level)
7615 (org-do-demote))
7616 ;; If parent is top-level, promote to top level if not already.
7617 ((= prev-level 1)
7618 (loop repeat (/ (- cur-level 1) (org-level-increment))
7619 do (org-do-promote)))
7620 ;; If top-level, return to prev-level.
7621 ((= cur-level 1)
7622 (loop repeat (/ (- prev-level 1) (org-level-increment))
7623 do (org-do-demote)))
7624 ;; If less than prev-level, promote one.
7625 ((< cur-level prev-level)
7626 (org-do-promote))
7627 ;; If deeper than prev-level, promote until higher than
7628 ;; prev-level.
7629 ((> cur-level prev-level)
7630 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7631 do (org-do-promote))))
7632 t))))
7634 (defun org-map-tree (fun)
7635 "Call FUN for every heading underneath the current one."
7636 (org-back-to-heading)
7637 (let ((level (funcall outline-level)))
7638 (save-excursion
7639 (funcall fun)
7640 (while (and (progn
7641 (outline-next-heading)
7642 (> (funcall outline-level) level))
7643 (not (eobp)))
7644 (funcall fun)))))
7646 (defun org-map-region (fun beg end)
7647 "Call FUN for every heading between BEG and END."
7648 (let ((org-ignore-region t))
7649 (save-excursion
7650 (setq end (copy-marker end))
7651 (goto-char beg)
7652 (if (and (re-search-forward org-outline-regexp-bol nil t)
7653 (< (point) end))
7654 (funcall fun))
7655 (while (and (progn
7656 (outline-next-heading)
7657 (< (point) end))
7658 (not (eobp)))
7659 (funcall fun)))))
7661 (defvar org-property-end-re) ; silence byte-compiler
7662 (defun org-fixup-indentation (diff)
7663 "Change the indentation in the current entry by DIFF.
7664 However, if any line in the current entry has no indentation, or if it
7665 would end up with no indentation after the change, nothing at all is done."
7666 (save-excursion
7667 (let ((end (save-excursion (outline-next-heading)
7668 (point-marker)))
7669 (prohibit (if (> diff 0)
7670 "^\\S-"
7671 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7672 col)
7673 (unless (save-excursion (end-of-line 1)
7674 (re-search-forward prohibit end t))
7675 (while (and (< (point) end)
7676 (re-search-forward "^[ \t]+" end t))
7677 (goto-char (match-end 0))
7678 (setq col (current-column))
7679 (if (< diff 0) (replace-match ""))
7680 (org-indent-to-column (+ diff col))))
7681 (move-marker end nil))))
7683 (defun org-convert-to-odd-levels ()
7684 "Convert an org-mode file with all levels allowed to one with odd levels.
7685 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7686 level 5 etc."
7687 (interactive)
7688 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7689 (let ((outline-level 'org-outline-level)
7690 (org-odd-levels-only nil) n)
7691 (save-excursion
7692 (goto-char (point-min))
7693 (while (re-search-forward "^\\*\\*+ " nil t)
7694 (setq n (- (length (match-string 0)) 2))
7695 (while (>= (setq n (1- n)) 0)
7696 (org-demote))
7697 (end-of-line 1))))))
7699 (defun org-convert-to-oddeven-levels ()
7700 "Convert an org-mode file with only odd levels to one with odd/even levels.
7701 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7702 file contains a section with an even level, conversion would
7703 destroy the structure of the file. An error is signaled in this
7704 case."
7705 (interactive)
7706 (goto-char (point-min))
7707 ;; First check if there are no even levels
7708 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7709 (org-show-context t)
7710 (error "Not all levels are odd in this file. Conversion not possible"))
7711 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7712 (let ((outline-regexp org-outline-regexp)
7713 (outline-level 'org-outline-level)
7714 (org-odd-levels-only nil) n)
7715 (save-excursion
7716 (goto-char (point-min))
7717 (while (re-search-forward "^\\*\\*+ " nil t)
7718 (setq n (/ (1- (length (match-string 0))) 2))
7719 (while (>= (setq n (1- n)) 0)
7720 (org-promote))
7721 (end-of-line 1))))))
7723 (defun org-tr-level (n)
7724 "Make N odd if required."
7725 (if org-odd-levels-only (1+ (/ n 2)) n))
7727 ;;; Vertical tree motion, cutting and pasting of subtrees
7729 (defun org-move-subtree-up (&optional arg)
7730 "Move the current subtree up past ARG headlines of the same level."
7731 (interactive "p")
7732 (org-move-subtree-down (- (prefix-numeric-value arg))))
7734 (defun org-move-subtree-down (&optional arg)
7735 "Move the current subtree down past ARG headlines of the same level."
7736 (interactive "p")
7737 (setq arg (prefix-numeric-value arg))
7738 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7739 'org-get-last-sibling))
7740 (ins-point (make-marker))
7741 (cnt (abs arg))
7742 (col (current-column))
7743 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7744 ;; Select the tree
7745 (org-back-to-heading)
7746 (setq beg0 (point))
7747 (save-excursion
7748 (setq ne-beg (org-back-over-empty-lines))
7749 (setq beg (point)))
7750 (save-match-data
7751 (save-excursion (outline-end-of-heading)
7752 (setq folded (outline-invisible-p)))
7753 (outline-end-of-subtree))
7754 (outline-next-heading)
7755 (setq ne-end (org-back-over-empty-lines))
7756 (setq end (point))
7757 (goto-char beg0)
7758 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7759 ;; include less whitespace
7760 (save-excursion
7761 (goto-char beg)
7762 (forward-line (- ne-beg ne-end))
7763 (setq beg (point))))
7764 ;; Find insertion point, with error handling
7765 (while (> cnt 0)
7766 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7767 (progn (goto-char beg0)
7768 (error "Cannot move past superior level or buffer limit")))
7769 (setq cnt (1- cnt)))
7770 (if (> arg 0)
7771 ;; Moving forward - still need to move over subtree
7772 (progn (org-end-of-subtree t t)
7773 (save-excursion
7774 (org-back-over-empty-lines)
7775 (or (bolp) (newline)))))
7776 (setq ne-ins (org-back-over-empty-lines))
7777 (move-marker ins-point (point))
7778 (setq txt (buffer-substring beg end))
7779 (org-save-markers-in-region beg end)
7780 (delete-region beg end)
7781 (org-remove-empty-overlays-at beg)
7782 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7783 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7784 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7785 (let ((bbb (point)))
7786 (insert-before-markers txt)
7787 (org-reinstall-markers-in-region bbb)
7788 (move-marker ins-point bbb))
7789 (or (bolp) (insert "\n"))
7790 (setq ins-end (point))
7791 (goto-char ins-point)
7792 (org-skip-whitespace)
7793 (when (and (< arg 0)
7794 (org-first-sibling-p)
7795 (> ne-ins ne-beg))
7796 ;; Move whitespace back to beginning
7797 (save-excursion
7798 (goto-char ins-end)
7799 (let ((kill-whole-line t))
7800 (kill-line (- ne-ins ne-beg)) (point)))
7801 (insert (make-string (- ne-ins ne-beg) ?\n)))
7802 (move-marker ins-point nil)
7803 (if folded
7804 (hide-subtree)
7805 (org-show-entry)
7806 (show-children)
7807 (org-cycle-hide-drawers 'children))
7808 (org-clean-visibility-after-subtree-move)
7809 ;; move back to the initial column we were at
7810 (move-to-column col)))
7812 (defvar org-subtree-clip ""
7813 "Clipboard for cut and paste of subtrees.
7814 This is actually only a copy of the kill, because we use the normal kill
7815 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7817 (defvar org-subtree-clip-folded nil
7818 "Was the last copied subtree folded?
7819 This is used to fold the tree back after pasting.")
7821 (defun org-cut-subtree (&optional n)
7822 "Cut the current subtree into the clipboard.
7823 With prefix arg N, cut this many sequential subtrees.
7824 This is a short-hand for marking the subtree and then cutting it."
7825 (interactive "p")
7826 (org-copy-subtree n 'cut))
7828 (defun org-copy-subtree (&optional n cut force-store-markers)
7829 "Cut the current subtree into the clipboard.
7830 With prefix arg N, cut this many sequential subtrees.
7831 This is a short-hand for marking the subtree and then copying it.
7832 If CUT is non-nil, actually cut the subtree.
7833 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7834 of some markers in the region, even if CUT is non-nil. This is
7835 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7836 (interactive "p")
7837 (let (beg end folded (beg0 (point)))
7838 (if (org-called-interactively-p 'any)
7839 (org-back-to-heading nil) ; take what looks like a subtree
7840 (org-back-to-heading t)) ; take what is really there
7841 (org-back-over-empty-lines)
7842 (setq beg (point))
7843 (skip-chars-forward " \t\r\n")
7844 (save-match-data
7845 (save-excursion (outline-end-of-heading)
7846 (setq folded (outline-invisible-p)))
7847 (condition-case nil
7848 (org-forward-heading-same-level (1- n) t)
7849 (error nil))
7850 (org-end-of-subtree t t))
7851 (org-back-over-empty-lines)
7852 (setq end (point))
7853 (goto-char beg0)
7854 (when (> end beg)
7855 (setq org-subtree-clip-folded folded)
7856 (when (or cut force-store-markers)
7857 (org-save-markers-in-region beg end))
7858 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7859 (setq org-subtree-clip (current-kill 0))
7860 (message "%s: Subtree(s) with %d characters"
7861 (if cut "Cut" "Copied")
7862 (length org-subtree-clip)))))
7864 (defun org-paste-subtree (&optional level tree for-yank)
7865 "Paste the clipboard as a subtree, with modification of headline level.
7866 The entire subtree is promoted or demoted in order to match a new headline
7867 level.
7869 If the cursor is at the beginning of a headline, the same level as
7870 that headline is used to paste the tree
7872 If not, the new level is derived from the *visible* headings
7873 before and after the insertion point, and taken to be the inferior headline
7874 level of the two. So if the previous visible heading is level 3 and the
7875 next is level 4 (or vice versa), level 4 will be used for insertion.
7876 This makes sure that the subtree remains an independent subtree and does
7877 not swallow low level entries.
7879 You can also force a different level, either by using a numeric prefix
7880 argument, or by inserting the heading marker by hand. For example, if the
7881 cursor is after \"*****\", then the tree will be shifted to level 5.
7883 If optional TREE is given, use this text instead of the kill ring.
7885 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7886 move back over whitespace before inserting, and move point to the end of
7887 the inserted text when done."
7888 (interactive "P")
7889 (setq tree (or tree (and kill-ring (current-kill 0))))
7890 (unless (org-kill-is-subtree-p tree)
7891 (error "%s"
7892 (substitute-command-keys
7893 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7894 (org-with-limited-levels
7895 (let* ((visp (not (outline-invisible-p)))
7896 (txt tree)
7897 (^re_ "\\(\\*+\\)[ \t]*")
7898 (old-level (if (string-match org-outline-regexp-bol txt)
7899 (- (match-end 0) (match-beginning 0) 1)
7900 -1))
7901 (force-level (cond (level (prefix-numeric-value level))
7902 ((and (looking-at "[ \t]*$")
7903 (string-match
7904 "^\\*+$" (buffer-substring
7905 (point-at-bol) (point))))
7906 (- (match-end 1) (match-beginning 1)))
7907 ((and (bolp)
7908 (looking-at org-outline-regexp))
7909 (- (match-end 0) (point) 1))))
7910 (previous-level (save-excursion
7911 (condition-case nil
7912 (progn
7913 (outline-previous-visible-heading 1)
7914 (if (looking-at ^re_)
7915 (- (match-end 0) (match-beginning 0) 1)
7917 (error 1))))
7918 (next-level (save-excursion
7919 (condition-case nil
7920 (progn
7921 (or (looking-at org-outline-regexp)
7922 (outline-next-visible-heading 1))
7923 (if (looking-at ^re_)
7924 (- (match-end 0) (match-beginning 0) 1)
7926 (error 1))))
7927 (new-level (or force-level (max previous-level next-level)))
7928 (shift (if (or (= old-level -1)
7929 (= new-level -1)
7930 (= old-level new-level))
7932 (- new-level old-level)))
7933 (delta (if (> shift 0) -1 1))
7934 (func (if (> shift 0) 'org-demote 'org-promote))
7935 (org-odd-levels-only nil)
7936 beg end newend)
7937 ;; Remove the forced level indicator
7938 (if force-level
7939 (delete-region (point-at-bol) (point)))
7940 ;; Paste
7941 (beginning-of-line (if (bolp) 1 2))
7942 (unless for-yank (org-back-over-empty-lines))
7943 (setq beg (point))
7944 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7945 (insert-before-markers txt)
7946 (unless (string-match "\n\\'" txt) (insert "\n"))
7947 (setq newend (point))
7948 (org-reinstall-markers-in-region beg)
7949 (setq end (point))
7950 (goto-char beg)
7951 (skip-chars-forward " \t\n\r")
7952 (setq beg (point))
7953 (if (and (outline-invisible-p) visp)
7954 (save-excursion (outline-show-heading)))
7955 ;; Shift if necessary
7956 (unless (= shift 0)
7957 (save-restriction
7958 (narrow-to-region beg end)
7959 (while (not (= shift 0))
7960 (org-map-region func (point-min) (point-max))
7961 (setq shift (+ delta shift)))
7962 (goto-char (point-min))
7963 (setq newend (point-max))))
7964 (when (or (org-called-interactively-p 'interactive) for-yank)
7965 (message "Clipboard pasted as level %d subtree" new-level))
7966 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7967 kill-ring
7968 (eq org-subtree-clip (current-kill 0))
7969 org-subtree-clip-folded)
7970 ;; The tree was folded before it was killed/copied
7971 (hide-subtree))
7972 (and for-yank (goto-char newend)))))
7974 (defun org-kill-is-subtree-p (&optional txt)
7975 "Check if the current kill is an outline subtree, or a set of trees.
7976 Returns nil if kill does not start with a headline, or if the first
7977 headline level is not the largest headline level in the tree.
7978 So this will actually accept several entries of equal levels as well,
7979 which is OK for `org-paste-subtree'.
7980 If optional TXT is given, check this string instead of the current kill."
7981 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7982 (re (org-get-limited-outline-regexp))
7983 (^re (concat "^" re))
7984 (start-level (and kill
7985 (string-match
7986 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7987 kill)
7988 (- (match-end 2) (match-beginning 2) 1)))
7989 (start (1+ (or (match-beginning 2) -1))))
7990 (if (not start-level)
7991 (progn
7992 nil) ;; does not even start with a heading
7993 (catch 'exit
7994 (while (setq start (string-match ^re kill (1+ start)))
7995 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7996 (throw 'exit nil)))
7997 t))))
7999 (defvar org-markers-to-move nil
8000 "Markers that should be moved with a cut-and-paste operation.
8001 Those markers are stored together with their positions relative to
8002 the start of the region.")
8004 (defun org-save-markers-in-region (beg end)
8005 "Check markers in region.
8006 If these markers are between BEG and END, record their position relative
8007 to BEG, so that after moving the block of text, we can put the markers back
8008 into place.
8009 This function gets called just before an entry or tree gets cut from the
8010 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8011 called immediately, to move the markers with the entries."
8012 (setq org-markers-to-move nil)
8013 (when (featurep 'org-clock)
8014 (org-clock-save-markers-for-cut-and-paste beg end))
8015 (when (featurep 'org-agenda)
8016 (org-agenda-save-markers-for-cut-and-paste beg end)))
8018 (defun org-check-and-save-marker (marker beg end)
8019 "Check if MARKER is between BEG and END.
8020 If yes, remember the marker and the distance to BEG."
8021 (when (and (marker-buffer marker)
8022 (equal (marker-buffer marker) (current-buffer)))
8023 (if (and (>= marker beg) (< marker end))
8024 (push (cons marker (- marker beg)) org-markers-to-move))))
8026 (defun org-reinstall-markers-in-region (beg)
8027 "Move all remembered markers to their position relative to BEG."
8028 (mapc (lambda (x)
8029 (move-marker (car x) (+ beg (cdr x))))
8030 org-markers-to-move)
8031 (setq org-markers-to-move nil))
8033 (defun org-narrow-to-subtree ()
8034 "Narrow buffer to the current subtree."
8035 (interactive)
8036 (save-excursion
8037 (save-match-data
8038 (org-with-limited-levels
8039 (narrow-to-region
8040 (progn (org-back-to-heading t) (point))
8041 (progn (org-end-of-subtree t t)
8042 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8043 (point)))))))
8045 (defun org-narrow-to-block ()
8046 "Narrow buffer to the current block."
8047 (interactive)
8048 (let* ((case-fold-search t)
8049 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8050 "^[ \t]*#\\+end_.*")))
8051 (if blockp
8052 (narrow-to-region (car blockp) (cdr blockp))
8053 (error "Not in a block"))))
8055 (eval-when-compile
8056 (defvar org-property-drawer-re))
8058 (defvar org-property-start-re) ;; defined below
8059 (defun org-clone-subtree-with-time-shift (n &optional shift)
8060 "Clone the task (subtree) at point N times.
8061 The clones will be inserted as siblings.
8063 In interactive use, the user will be prompted for the number of
8064 clones to be produced, and for a time SHIFT, which may be a
8065 repeater as used in time stamps, for example `+3d'.
8067 When a valid repeater is given and the entry contains any time
8068 stamps, the clones will become a sequence in time, with time
8069 stamps in the subtree shifted for each clone produced. If SHIFT
8070 is nil or the empty string, time stamps will be left alone. The
8071 ID property of the original subtree is removed.
8073 If the original subtree did contain time stamps with a repeater,
8074 the following will happen:
8075 - the repeater will be removed in each clone
8076 - an additional clone will be produced, with the current, unshifted
8077 date(s) in the entry.
8078 - the original entry will be placed *after* all the clones, with
8079 repeater intact.
8080 - the start days in the repeater in the original entry will be shifted
8081 to past the last clone.
8082 In this way you can spell out a number of instances of a repeating task,
8083 and still retain the repeater to cover future instances of the task."
8084 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8085 (let (beg end template task idprop
8086 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8087 (drawer-re org-drawer-regexp))
8088 (if (not (and (integerp n) (> n 0)))
8089 (error "Invalid number of replications %s" n))
8090 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8091 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8092 shift)))
8093 (error "Invalid shift specification %s" shift))
8094 (when doshift
8095 (setq shift-n (string-to-number (match-string 1 shift))
8096 shift-what (cdr (assoc (match-string 2 shift)
8097 '(("d" . day) ("w" . week)
8098 ("m" . month) ("y" . year))))))
8099 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8100 (setq nmin 1 nmax n)
8101 (org-back-to-heading t)
8102 (setq beg (point))
8103 (setq idprop (org-entry-get nil "ID"))
8104 (org-end-of-subtree t t)
8105 (or (bolp) (insert "\n"))
8106 (setq end (point))
8107 (setq template (buffer-substring beg end))
8108 (when (and doshift
8109 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8110 (delete-region beg end)
8111 (setq end beg)
8112 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8113 (goto-char end)
8114 (loop for n from nmin to nmax do
8115 ;; prepare clone
8116 (with-temp-buffer
8117 (insert template)
8118 (org-mode)
8119 (goto-char (point-min))
8120 (org-show-subtree)
8121 (and idprop (if org-clone-delete-id
8122 (org-entry-delete nil "ID")
8123 (org-id-get-create t)))
8124 (unless (= n 0)
8125 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8126 (kill-whole-line))
8127 (goto-char (point-min))
8128 (while (re-search-forward drawer-re nil t)
8129 (mapc (lambda (d)
8130 (org-remove-empty-drawer-at d (point))) org-drawers)))
8131 (goto-char (point-min))
8132 (when doshift
8133 (while (re-search-forward org-ts-regexp-both nil t)
8134 (org-timestamp-change (* n shift-n) shift-what))
8135 (unless (= n n-no-remove)
8136 (goto-char (point-min))
8137 (while (re-search-forward org-ts-regexp nil t)
8138 (save-excursion
8139 (goto-char (match-beginning 0))
8140 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8141 (delete-region (match-beginning 1) (match-end 1)))))))
8142 (setq task (buffer-string)))
8143 (insert task))
8144 (goto-char beg)))
8146 ;;; Outline Sorting
8148 (defun org-sort (with-case)
8149 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8150 Optional argument WITH-CASE means sort case-sensitively."
8151 (interactive "P")
8152 (cond
8153 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8154 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8156 (org-call-with-arg 'org-sort-entries with-case))))
8158 (defun org-sort-remove-invisible (s)
8159 (remove-text-properties 0 (length s) org-rm-props s)
8160 (while (string-match org-bracket-link-regexp s)
8161 (setq s (replace-match (if (match-end 2)
8162 (match-string 3 s)
8163 (match-string 1 s)) t t s)))
8166 (defvar org-priority-regexp) ; defined later in the file
8168 (defvar org-after-sorting-entries-or-items-hook nil
8169 "Hook that is run after a bunch of entries or items have been sorted.
8170 When children are sorted, the cursor is in the parent line when this
8171 hook gets called. When a region or a plain list is sorted, the cursor
8172 will be in the first entry of the sorted region/list.")
8174 (defun org-sort-entries
8175 (&optional with-case sorting-type getkey-func compare-func property)
8176 "Sort entries on a certain level of an outline tree.
8177 If there is an active region, the entries in the region are sorted.
8178 Else, if the cursor is before the first entry, sort the top-level items.
8179 Else, the children of the entry at point are sorted.
8181 Sorting can be alphabetically, numerically, by date/time as given by
8182 a time stamp, by a property or by priority.
8184 The command prompts for the sorting type unless it has been given to the
8185 function through the SORTING-TYPE argument, which needs to be a character,
8186 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8187 precise meaning of each character:
8189 n Numerically, by converting the beginning of the entry/item to a number.
8190 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8191 t By date/time, either the first active time stamp in the entry, or, if
8192 none exist, by the first inactive one.
8193 s By the scheduled date/time.
8194 d By deadline date/time.
8195 c By creation time, which is assumed to be the first inactive time stamp
8196 at the beginning of a line.
8197 p By priority according to the cookie.
8198 r By the value of a property.
8200 Capital letters will reverse the sort order.
8202 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8203 called with point at the beginning of the record. It must return either
8204 a string or a number that should serve as the sorting key for that record.
8206 Comparing entries ignores case by default. However, with an optional argument
8207 WITH-CASE, the sorting considers case as well."
8208 (interactive "P")
8209 (let ((case-func (if with-case 'identity 'downcase))
8210 start beg end stars re re2
8211 txt what tmp)
8212 ;; Find beginning and end of region to sort
8213 (cond
8214 ((org-region-active-p)
8215 ;; we will sort the region
8216 (setq end (region-end)
8217 what "region")
8218 (goto-char (region-beginning))
8219 (if (not (org-at-heading-p)) (outline-next-heading))
8220 (setq start (point)))
8221 ((or (org-at-heading-p)
8222 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8223 ;; we will sort the children of the current headline
8224 (org-back-to-heading)
8225 (setq start (point)
8226 end (progn (org-end-of-subtree t t)
8227 (or (bolp) (insert "\n"))
8228 (org-back-over-empty-lines)
8229 (point))
8230 what "children")
8231 (goto-char start)
8232 (show-subtree)
8233 (outline-next-heading))
8235 ;; we will sort the top-level entries in this file
8236 (goto-char (point-min))
8237 (or (org-at-heading-p) (outline-next-heading))
8238 (setq start (point))
8239 (goto-char (point-max))
8240 (beginning-of-line 1)
8241 (when (looking-at ".*?\\S-")
8242 ;; File ends in a non-white line
8243 (end-of-line 1)
8244 (insert "\n"))
8245 (setq end (point-max))
8246 (setq what "top-level")
8247 (goto-char start)
8248 (show-all)))
8250 (setq beg (point))
8251 (if (>= beg end) (error "Nothing to sort"))
8253 (looking-at "\\(\\*+\\)")
8254 (setq stars (match-string 1)
8255 re (concat "^" (regexp-quote stars) " +")
8256 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8257 txt (buffer-substring beg end))
8258 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8259 (if (and (not (equal stars "*")) (string-match re2 txt))
8260 (error "Region to sort contains a level above the first entry"))
8262 (unless sorting-type
8263 (message
8264 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8265 [t]ime [s]cheduled [d]eadline [c]reated
8266 A/N/T/S/D/C/P/O/F means reversed:"
8267 what)
8268 (setq sorting-type (read-char-exclusive))
8270 (and (= (downcase sorting-type) ?f)
8271 (setq getkey-func
8272 (org-icompleting-read "Sort using function: "
8273 obarray 'fboundp t nil nil))
8274 (setq getkey-func (intern getkey-func)))
8276 (and (= (downcase sorting-type) ?r)
8277 (setq property
8278 (org-icompleting-read "Property: "
8279 (mapcar 'list (org-buffer-property-keys t))
8280 nil t))))
8282 (message "Sorting entries...")
8284 (save-restriction
8285 (narrow-to-region start end)
8286 (let ((dcst (downcase sorting-type))
8287 (case-fold-search nil)
8288 (now (current-time)))
8289 (sort-subr
8290 (/= dcst sorting-type)
8291 ;; This function moves to the beginning character of the "record" to
8292 ;; be sorted.
8293 (lambda nil
8294 (if (re-search-forward re nil t)
8295 (goto-char (match-beginning 0))
8296 (goto-char (point-max))))
8297 ;; This function moves to the last character of the "record" being
8298 ;; sorted.
8299 (lambda nil
8300 (save-match-data
8301 (condition-case nil
8302 (outline-forward-same-level 1)
8303 (error
8304 (goto-char (point-max))))))
8305 ;; This function returns the value that gets sorted against.
8306 (lambda nil
8307 (cond
8308 ((= dcst ?n)
8309 (if (looking-at org-complex-heading-regexp)
8310 (string-to-number (match-string 4))
8311 nil))
8312 ((= dcst ?a)
8313 (if (looking-at org-complex-heading-regexp)
8314 (funcall case-func (match-string 4))
8315 nil))
8316 ((= dcst ?t)
8317 (let ((end (save-excursion (outline-next-heading) (point))))
8318 (if (or (re-search-forward org-ts-regexp end t)
8319 (re-search-forward org-ts-regexp-both end t))
8320 (org-time-string-to-seconds (match-string 0))
8321 (org-float-time now))))
8322 ((= dcst ?c)
8323 (let ((end (save-excursion (outline-next-heading) (point))))
8324 (if (re-search-forward
8325 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8326 end t)
8327 (org-time-string-to-seconds (match-string 0))
8328 (org-float-time now))))
8329 ((= dcst ?s)
8330 (let ((end (save-excursion (outline-next-heading) (point))))
8331 (if (re-search-forward org-scheduled-time-regexp end t)
8332 (org-time-string-to-seconds (match-string 1))
8333 (org-float-time now))))
8334 ((= dcst ?d)
8335 (let ((end (save-excursion (outline-next-heading) (point))))
8336 (if (re-search-forward org-deadline-time-regexp end t)
8337 (org-time-string-to-seconds (match-string 1))
8338 (org-float-time now))))
8339 ((= dcst ?p)
8340 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8341 (string-to-char (match-string 2))
8342 org-default-priority))
8343 ((= dcst ?r)
8344 (or (org-entry-get nil property) ""))
8345 ((= dcst ?o)
8346 (if (looking-at org-complex-heading-regexp)
8347 (- 9999 (length (member (match-string 2)
8348 org-todo-keywords-1)))))
8349 ((= dcst ?f)
8350 (if getkey-func
8351 (progn
8352 (setq tmp (funcall getkey-func))
8353 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8354 tmp)
8355 (error "Invalid key function `%s'" getkey-func)))
8356 (t (error "Invalid sorting type `%c'" sorting-type))))
8358 (cond
8359 ((= dcst ?a) 'string<)
8360 ((= dcst ?f) compare-func)
8361 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8362 (run-hooks 'org-after-sorting-entries-or-items-hook)
8363 (message "Sorting entries...done")))
8365 (defun org-do-sort (table what &optional with-case sorting-type)
8366 "Sort TABLE of WHAT according to SORTING-TYPE.
8367 The user will be prompted for the SORTING-TYPE if the call to this
8368 function does not specify it. WHAT is only for the prompt, to indicate
8369 what is being sorted. The sorting key will be extracted from
8370 the car of the elements of the table.
8371 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8372 (unless sorting-type
8373 (message
8374 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8375 what)
8376 (setq sorting-type (read-char-exclusive)))
8377 (let ((dcst (downcase sorting-type))
8378 extractfun comparefun)
8379 ;; Define the appropriate functions
8380 (cond
8381 ((= dcst ?n)
8382 (setq extractfun 'string-to-number
8383 comparefun (if (= dcst sorting-type) '< '>)))
8384 ((= dcst ?a)
8385 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8386 (lambda(x) (downcase (org-sort-remove-invisible x))))
8387 comparefun (if (= dcst sorting-type)
8388 'string<
8389 (lambda (a b) (and (not (string< a b))
8390 (not (string= a b)))))))
8391 ((= dcst ?t)
8392 (setq extractfun
8393 (lambda (x)
8394 (if (or (string-match org-ts-regexp x)
8395 (string-match org-ts-regexp-both x))
8396 (org-float-time
8397 (org-time-string-to-time (match-string 0 x)))
8399 comparefun (if (= dcst sorting-type) '< '>)))
8400 (t (error "Invalid sorting type `%c'" sorting-type)))
8402 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8403 table)
8404 (lambda (a b) (funcall comparefun (car a) (car b))))))
8407 ;;; The orgstruct minor mode
8409 ;; Define a minor mode which can be used in other modes in order to
8410 ;; integrate the org-mode structure editing commands.
8412 ;; This is really a hack, because the org-mode structure commands use
8413 ;; keys which normally belong to the major mode. Here is how it
8414 ;; works: The minor mode defines all the keys necessary to operate the
8415 ;; structure commands, but wraps the commands into a function which
8416 ;; tests if the cursor is currently at a headline or a plain list
8417 ;; item. If that is the case, the structure command is used,
8418 ;; temporarily setting many Org-mode variables like regular
8419 ;; expressions for filling etc. However, when any of those keys is
8420 ;; used at a different location, function uses `key-binding' to look
8421 ;; up if the key has an associated command in another currently active
8422 ;; keymap (minor modes, major mode, global), and executes that
8423 ;; command. There might be problems if any of the keys is otherwise
8424 ;; used as a prefix key.
8426 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8427 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8428 ;; addresses this by checking explicitly for both bindings.
8430 (defvar orgstruct-mode-map (make-sparse-keymap)
8431 "Keymap for the minor `orgstruct-mode'.")
8433 (defvar org-local-vars nil
8434 "List of local variables, for use by `orgstruct-mode'.")
8436 ;;;###autoload
8437 (define-minor-mode orgstruct-mode
8438 "Toggle the minor mode `orgstruct-mode'.
8439 This mode is for using Org-mode structure commands in other
8440 modes. The following keys behave as if Org-mode were active, if
8441 the cursor is on a headline, or on a plain list item (both as
8442 defined by Org-mode).
8444 M-up Move entry/item up
8445 M-down Move entry/item down
8446 M-left Promote
8447 M-right Demote
8448 M-S-up Move entry/item up
8449 M-S-down Move entry/item down
8450 M-S-left Promote subtree
8451 M-S-right Demote subtree
8452 M-q Fill paragraph and items like in Org-mode
8453 C-c ^ Sort entries
8454 C-c - Cycle list bullet
8455 TAB Cycle item visibility
8456 M-RET Insert new heading/item
8457 S-M-RET Insert new TODO heading / Checkbox item
8458 C-c C-c Set tags / toggle checkbox"
8459 nil " OrgStruct" nil
8460 (org-load-modules-maybe)
8461 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8463 ;;;###autoload
8464 (defun turn-on-orgstruct ()
8465 "Unconditionally turn on `orgstruct-mode'."
8466 (orgstruct-mode 1))
8468 (defvar org-fb-vars nil)
8469 (make-variable-buffer-local 'org-fb-vars)
8470 (defun orgstruct++-mode (&optional arg)
8471 "Toggle `orgstruct-mode', the enhanced version of it.
8472 In addition to setting orgstruct-mode, this also exports all
8473 indentation and autofilling variables from org-mode into the
8474 buffer. It will also recognize item context in multiline items."
8475 (interactive "P")
8476 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8477 (if (< arg 1)
8478 (progn (orgstruct-mode -1)
8479 (mapc (lambda(v)
8480 (org-set-local (car v)
8481 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8482 org-fb-vars))
8483 (orgstruct-mode 1)
8484 (setq org-fb-vars nil)
8485 (let (var val)
8486 (mapc
8487 (lambda (x)
8488 (when (string-match
8489 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8490 (symbol-name (car x)))
8491 (setq var (car x) val (nth 1 x))
8492 (push (list var `(quote ,(eval var))) org-fb-vars)
8493 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8494 org-local-vars)
8495 (org-set-local 'orgstruct-is-++ t))))
8497 (defvar orgstruct-is-++ nil
8498 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8499 (make-variable-buffer-local 'orgstruct-is-++)
8501 ;;;###autoload
8502 (defun turn-on-orgstruct++ ()
8503 "Unconditionally turn on `orgstruct++-mode'."
8504 (orgstruct++-mode 1))
8506 (defun orgstruct-error ()
8507 "Error when there is no default binding for a structure key."
8508 (interactive)
8509 (error "This key has no function outside structure elements"))
8511 (defun orgstruct-setup ()
8512 "Setup orgstruct keymaps."
8513 (let ((nfunc 0)
8514 (bindings
8515 (list
8516 '([(meta up)] org-metaup)
8517 '([(meta down)] org-metadown)
8518 '([(meta left)] org-metaleft)
8519 '([(meta right)] org-metaright)
8520 '([(meta shift up)] org-shiftmetaup)
8521 '([(meta shift down)] org-shiftmetadown)
8522 '([(meta shift left)] org-shiftmetaleft)
8523 '([(meta shift right)] org-shiftmetaright)
8524 '([?\e (up)] org-metaup)
8525 '([?\e (down)] org-metadown)
8526 '([?\e (left)] org-metaleft)
8527 '([?\e (right)] org-metaright)
8528 '([?\e (shift up)] org-shiftmetaup)
8529 '([?\e (shift down)] org-shiftmetadown)
8530 '([?\e (shift left)] org-shiftmetaleft)
8531 '([?\e (shift right)] org-shiftmetaright)
8532 '([(shift up)] org-shiftup)
8533 '([(shift down)] org-shiftdown)
8534 '([(shift left)] org-shiftleft)
8535 '([(shift right)] org-shiftright)
8536 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8537 '("\M-q" fill-paragraph)
8538 '("\C-c^" org-sort)
8539 '("\C-c-" org-cycle-list-bullet)))
8540 elt key fun cmd)
8541 (while (setq elt (pop bindings))
8542 (setq nfunc (1+ nfunc))
8543 (setq key (org-key (car elt))
8544 fun (nth 1 elt)
8545 cmd (orgstruct-make-binding fun nfunc key))
8546 (org-defkey orgstruct-mode-map key cmd))
8548 ;; Prevent an error for users who forgot to make autoloads
8549 (require 'org-element)
8551 ;; Special treatment needed for TAB and RET
8552 (org-defkey orgstruct-mode-map [(tab)]
8553 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8554 (org-defkey orgstruct-mode-map "\C-i"
8555 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8557 (org-defkey orgstruct-mode-map "\M-\C-m"
8558 (orgstruct-make-binding 'org-insert-heading 105
8559 "\M-\C-m" [(meta return)]))
8560 (org-defkey orgstruct-mode-map [(meta return)]
8561 (orgstruct-make-binding 'org-insert-heading 106
8562 [(meta return)] "\M-\C-m"))
8564 (org-defkey orgstruct-mode-map [(shift meta return)]
8565 (orgstruct-make-binding 'org-insert-todo-heading 107
8566 [(meta return)] "\M-\C-m"))
8568 (org-defkey orgstruct-mode-map "\e\C-m"
8569 (orgstruct-make-binding 'org-insert-heading 108
8570 "\e\C-m" [?\e (return)]))
8571 (org-defkey orgstruct-mode-map [?\e (return)]
8572 (orgstruct-make-binding 'org-insert-heading 109
8573 [?\e (return)] "\e\C-m"))
8574 (org-defkey orgstruct-mode-map [?\e (shift return)]
8575 (orgstruct-make-binding 'org-insert-todo-heading 110
8576 [?\e (return)] "\e\C-m"))
8578 (unless org-local-vars
8579 (setq org-local-vars (org-get-local-variables)))
8583 (defun orgstruct-make-binding (fun n &rest keys)
8584 "Create a function for binding in the structure minor mode.
8585 FUN is the command to call inside a table. N is used to create a unique
8586 command name. KEYS are keys that should be checked in for a command
8587 to execute outside of tables."
8588 (eval
8589 (list 'defun
8590 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8591 '(arg)
8592 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8593 "Outside of structure, run the binding of `"
8594 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8595 "'.")
8596 '(interactive "p")
8597 (list 'if
8598 `(org-context-p 'headline 'item
8599 (and orgstruct-is-++
8600 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8601 'item-body))
8602 (list 'org-run-like-in-org-mode (list 'quote fun))
8603 (list 'let '(orgstruct-mode)
8604 (list 'call-interactively
8605 (append '(or)
8606 (mapcar (lambda (k)
8607 (list 'key-binding k))
8608 keys)
8609 '('orgstruct-error))))))))
8611 (defun org-contextualize-keys (alist contexts)
8612 "Return valid elements in ALIST depending on CONTEXTS.
8614 `org-agenda-custom-commands' or `org-capture-templates' are the
8615 values used for ALIST, and `org-agenda-custom-commands-contexts'
8616 or `org-capture-templates-contexts' are the associated contexts
8617 definitions."
8618 (let ((contexts
8619 ;; normalize contexts
8620 (mapcar
8621 (lambda(c) (cond ((listp (cadr c))
8622 (list (car c) (car c) (cadr c)))
8623 ((string= "" (cadr c))
8624 (list (car c) (car c) (caddr c)))
8625 (t c))) contexts))
8626 (a alist) c r s)
8627 ;; loop over all commands or templates
8628 (while (setq c (pop a))
8629 (let (vrules repl)
8630 (cond
8631 ((not (assoc (car c) contexts))
8632 (push c r))
8633 ((and (assoc (car c) contexts)
8634 (setq vrules (org-contextualize-validate-key
8635 (car c) contexts)))
8636 (mapc (lambda (vr)
8637 (when (not (equal (car vr) (cadr vr)))
8638 (setq repl vr))) vrules)
8639 (if (not repl) (push c r)
8640 (push (cadr repl) s)
8641 (push
8642 (cons (car c)
8643 (cdr (or (assoc (cadr repl) alist)
8644 (error "Undefined key `%s' as contextual replacement for `%s'"
8645 (cadr repl) (car c)))))
8646 r))))))
8647 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8648 (delq
8650 (delete-dups
8651 (mapcar (lambda (x)
8652 (let ((tpl (car x)))
8653 (when (not (delq
8655 (mapcar (lambda(y)
8656 (equal y tpl)) s))) x)))
8657 (reverse r))))))
8659 (defun org-contextualize-validate-key (key contexts)
8660 "Check CONTEXTS for agenda or capture KEY."
8661 (let (r rr res)
8662 (while (setq r (pop contexts))
8663 (mapc
8664 (lambda (rr)
8665 (when
8666 (and (equal key (car r))
8667 (if (functionp rr) (funcall rr)
8668 (or (and (eq (car rr) 'in-file)
8669 (buffer-file-name)
8670 (string-match (cdr rr) (buffer-file-name)))
8671 (and (eq (car rr) 'in-mode)
8672 (string-match (cdr rr) (symbol-name major-mode)))
8673 (when (and (eq (car rr) 'not-in-file)
8674 (buffer-file-name))
8675 (not (string-match (cdr rr) (buffer-file-name))))
8676 (when (eq (car rr) 'not-in-mode)
8677 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8678 (push r res)))
8679 (car (last r))))
8680 (delete-dups (delq nil res))))
8682 (defun org-context-p (&rest contexts)
8683 "Check if local context is any of CONTEXTS.
8684 Possible values in the list of contexts are `table', `headline', and `item'."
8685 (let ((pos (point)))
8686 (goto-char (point-at-bol))
8687 (prog1 (or (and (memq 'table contexts)
8688 (looking-at "[ \t]*|"))
8689 (and (memq 'headline contexts)
8690 (looking-at org-outline-regexp))
8691 (and (memq 'item contexts)
8692 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8693 (and (memq 'item-body contexts)
8694 (org-in-item-p)))
8695 (goto-char pos))))
8697 (defun org-get-local-variables ()
8698 "Return a list of all local variables in an Org mode buffer."
8699 (let (varlist)
8700 (with-current-buffer (get-buffer-create "*Org tmp*")
8701 (erase-buffer)
8702 (org-mode)
8703 (setq varlist (buffer-local-variables)))
8704 (kill-buffer "*Org tmp*")
8705 (delq nil
8706 (mapcar
8707 (lambda (x)
8708 (setq x
8709 (if (symbolp x)
8710 (list x)
8711 (list (car x) (list 'quote (cdr x)))))
8712 (if (string-match
8713 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8714 (symbol-name (car x)))
8715 x nil))
8716 varlist))))
8718 (defun org-clone-local-variables (from-buffer &optional regexp)
8719 "Clone local variables from FROM-BUFFER.
8720 Optional argument REGEXP selects variables to clone."
8721 (mapc
8722 (lambda (pair)
8723 (and (symbolp (car pair))
8724 (or (null regexp)
8725 (string-match regexp (symbol-name (car pair))))
8726 (set (make-local-variable (car pair))
8727 (cdr pair))))
8728 (buffer-local-variables from-buffer)))
8730 ;;;###autoload
8731 (defun org-run-like-in-org-mode (cmd)
8732 "Run a command, pretending that the current buffer is in Org-mode.
8733 This will temporarily bind local variables that are typically bound in
8734 Org-mode to the values they have in Org-mode, and then interactively
8735 call CMD."
8736 (org-load-modules-maybe)
8737 (unless org-local-vars
8738 (setq org-local-vars (org-get-local-variables)))
8739 (eval (list 'let org-local-vars
8740 (list 'call-interactively (list 'quote cmd)))))
8742 ;;;; Archiving
8744 (defun org-get-category (&optional pos force-refresh)
8745 "Get the category applying to position POS."
8746 (save-match-data
8747 (if force-refresh (org-refresh-category-properties))
8748 (let ((pos (or pos (point))))
8749 (or (get-text-property pos 'org-category)
8750 (progn (org-refresh-category-properties)
8751 (get-text-property pos 'org-category))))))
8753 (defun org-refresh-category-properties ()
8754 "Refresh category text properties in the buffer."
8755 (let ((case-fold-search t)
8756 (inhibit-read-only t)
8757 (def-cat (cond
8758 ((null org-category)
8759 (if buffer-file-name
8760 (file-name-sans-extension
8761 (file-name-nondirectory buffer-file-name))
8762 "???"))
8763 ((symbolp org-category) (symbol-name org-category))
8764 (t org-category)))
8765 beg end cat pos optionp)
8766 (org-unmodified
8767 (save-excursion
8768 (save-restriction
8769 (widen)
8770 (goto-char (point-min))
8771 (put-text-property (point) (point-max) 'org-category def-cat)
8772 (while (re-search-forward
8773 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8774 (setq pos (match-end 0)
8775 optionp (equal (char-after (match-beginning 0)) ?#)
8776 cat (org-trim (match-string 2)))
8777 (if optionp
8778 (setq beg (point-at-bol) end (point-max))
8779 (org-back-to-heading t)
8780 (setq beg (point) end (org-end-of-subtree t t)))
8781 (put-text-property beg end 'org-category cat)
8782 (put-text-property beg end 'org-category-position beg)
8783 (goto-char pos)))))))
8786 ;;;; Link Stuff
8788 ;;; Link abbreviations
8790 (defun org-link-expand-abbrev (link)
8791 "Apply replacements as defined in `org-link-abbrev-alist'."
8792 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8793 (let* ((key (match-string 1 link))
8794 (as (or (assoc key org-link-abbrev-alist-local)
8795 (assoc key org-link-abbrev-alist)))
8796 (tag (and (match-end 2) (match-string 3 link)))
8797 rpl)
8798 (if (not as)
8799 link
8800 (setq rpl (cdr as))
8801 (cond
8802 ((symbolp rpl) (funcall rpl tag))
8803 ((string-match "%(\\([^)]+\\))" rpl)
8804 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8805 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8806 ((string-match "%h" rpl)
8807 (replace-match (url-hexify-string (or tag "")) t t rpl))
8808 (t (concat rpl tag)))))
8809 link))
8811 ;;; Storing and inserting links
8813 (defvar org-insert-link-history nil
8814 "Minibuffer history for links inserted with `org-insert-link'.")
8816 (defvar org-stored-links nil
8817 "Contains the links stored with `org-store-link'.")
8819 (defvar org-store-link-plist nil
8820 "Plist with info about the most recently link created with `org-store-link'.")
8822 (defvar org-link-protocols nil
8823 "Link protocols added to Org-mode using `org-add-link-type'.")
8825 (defvar org-store-link-functions nil
8826 "List of functions that are called to create and store a link.
8827 Each function will be called in turn until one returns a non-nil
8828 value. Each function should check if it is responsible for creating
8829 this link (for example by looking at the major mode).
8830 If not, it must exit and return nil.
8831 If yes, it should return a non-nil value after a calling
8832 `org-store-link-props' with a list of properties and values.
8833 Special properties are:
8835 :type The link prefix, like \"http\". This must be given.
8836 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8837 This is obligatory as well.
8838 :description Optional default description for the second pair
8839 of brackets in an Org-mode link. The user can still change
8840 this when inserting this link into an Org-mode buffer.
8842 In addition to these, any additional properties can be specified
8843 and then used in capture templates.")
8845 (defun org-add-link-type (type &optional follow export)
8846 "Add TYPE to the list of `org-link-types'.
8847 Re-compute all regular expressions depending on `org-link-types'
8849 FOLLOW and EXPORT are two functions.
8851 FOLLOW should take the link path as the single argument and do whatever
8852 is necessary to follow the link, for example find a file or display
8853 a mail message.
8855 EXPORT should format the link path for export to one of the export formats.
8856 It should be a function accepting three arguments:
8858 path the path of the link, the text after the prefix (like \"http:\")
8859 desc the description of the link, if any, or a description added by
8860 org-export-normalize-links if there is none
8861 format the export format, a symbol like `html' or `latex' or `ascii'..
8863 The function may use the FORMAT information to return different values
8864 depending on the format. The return value will be put literally into
8865 the exported file. If the return value is nil, this means Org should
8866 do what it normally does with links which do not have EXPORT defined.
8868 Org-mode has a built-in default for exporting links. If you are happy with
8869 this default, there is no need to define an export function for the link
8870 type. For a simple example of an export function, see `org-bbdb.el'."
8871 (add-to-list 'org-link-types type t)
8872 (org-make-link-regexps)
8873 (if (assoc type org-link-protocols)
8874 (setcdr (assoc type org-link-protocols) (list follow export))
8875 (push (list type follow export) org-link-protocols)))
8877 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8878 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8880 ;;;###autoload
8881 (defun org-store-link (arg)
8882 "\\<org-mode-map>Store an org-link to the current location.
8883 This link is added to `org-stored-links' and can later be inserted
8884 into an org-buffer with \\[org-insert-link].
8886 For some link types, a prefix arg is interpreted:
8887 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8888 For file links, arg negates `org-context-in-file-links'."
8889 (interactive "P")
8890 (org-load-modules-maybe)
8891 (setq org-store-link-plist nil) ; reset
8892 (org-with-limited-levels
8893 (let (link cpltxt desc description search txt custom-id agenda-link)
8894 (cond
8896 ((run-hook-with-args-until-success 'org-store-link-functions)
8897 (setq link (plist-get org-store-link-plist :link)
8898 desc (or (plist-get org-store-link-plist :description) link)))
8900 ((org-src-edit-buffer-p)
8901 (let (label gc)
8902 (while (or (not label)
8903 (save-excursion
8904 (save-restriction
8905 (widen)
8906 (goto-char (point-min))
8907 (re-search-forward
8908 (regexp-quote (format org-coderef-label-format label))
8909 nil t))))
8910 (when label (message "Label exists already") (sit-for 2))
8911 (setq label (read-string "Code line label: " label)))
8912 (end-of-line 1)
8913 (setq link (format org-coderef-label-format label))
8914 (setq gc (- 79 (length link)))
8915 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8916 (insert link)
8917 (setq link (concat "(" label ")") desc nil)))
8919 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8920 ;; We are in the agenda, link to referenced location
8921 (let ((m (or (get-text-property (point) 'org-hd-marker)
8922 (get-text-property (point) 'org-marker))))
8923 (when m
8924 (org-with-point-at m
8925 (setq agenda-link
8926 (if (org-called-interactively-p 'any)
8927 (call-interactively 'org-store-link)
8928 (org-store-link nil)))))))
8930 ((eq major-mode 'calendar-mode)
8931 (let ((cd (calendar-cursor-to-date)))
8932 (setq link
8933 (format-time-string
8934 (car org-time-stamp-formats)
8935 (apply 'encode-time
8936 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8937 nil nil nil))))
8938 (org-store-link-props :type "calendar" :date cd)))
8940 ((eq major-mode 'help-mode)
8941 (setq link (concat "help:" (save-excursion
8942 (goto-char (point-min))
8943 (looking-at "^[^ ]+")
8944 (match-string 0))))
8945 (org-store-link-props :type "help"))
8947 ((eq major-mode 'w3-mode)
8948 (setq cpltxt (if (and (buffer-name)
8949 (not (string-match "Untitled" (buffer-name))))
8950 (buffer-name)
8951 (url-view-url t))
8952 link (url-view-url t))
8953 (org-store-link-props :type "w3" :url (url-view-url t)))
8955 ((eq major-mode 'w3m-mode)
8956 (setq cpltxt (or w3m-current-title w3m-current-url)
8957 link w3m-current-url)
8958 (org-store-link-props :type "w3m" :url (url-view-url t)))
8960 ((setq search (run-hook-with-args-until-success
8961 'org-create-file-search-functions))
8962 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8963 "::" search))
8964 (setq cpltxt (or description link)))
8966 ((eq major-mode 'image-mode)
8967 (setq cpltxt (concat "file:"
8968 (abbreviate-file-name buffer-file-name))
8969 link cpltxt)
8970 (org-store-link-props :type "image" :file buffer-file-name))
8972 ((eq major-mode 'dired-mode)
8973 ;; link to the file in the current line
8974 (let ((file (dired-get-filename nil t)))
8975 (setq file (if file
8976 (abbreviate-file-name
8977 (expand-file-name (dired-get-filename nil t)))
8978 ;; otherwise, no file so use current directory.
8979 default-directory))
8980 (setq cpltxt (concat "file:" file)
8981 link cpltxt)))
8983 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8984 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8985 (cond
8986 ((org-in-regexp "<<\\(.*?\\)>>")
8987 (setq cpltxt
8988 (concat "file:"
8989 (abbreviate-file-name
8990 (buffer-file-name (buffer-base-buffer)))
8991 "::" (match-string 1))
8992 link cpltxt))
8993 ((and (featurep 'org-id)
8994 (or (eq org-link-to-org-use-id t)
8995 (and (org-called-interactively-p 'any)
8996 (or (eq org-link-to-org-use-id 'create-if-interactive)
8997 (and (eq org-link-to-org-use-id
8998 'create-if-interactive-and-no-custom-id)
8999 (not custom-id))))
9000 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9001 ;; We can make a link using the ID.
9002 (setq link (condition-case nil
9003 (prog1 (org-id-store-link)
9004 (setq desc (plist-get org-store-link-plist :description)))
9005 (error
9006 ;; probably before first headline, link to file only
9007 (concat "file:"
9008 (abbreviate-file-name
9009 (buffer-file-name (buffer-base-buffer))))))))
9011 ;; Just link to current headline
9012 (setq cpltxt (concat "file:"
9013 (abbreviate-file-name
9014 (buffer-file-name (buffer-base-buffer)))))
9015 ;; Add a context search string
9016 (when (org-xor org-context-in-file-links arg)
9017 (setq txt (cond
9018 ((org-at-heading-p) nil)
9019 ((org-region-active-p)
9020 (buffer-substring (region-beginning) (region-end)))))
9021 (when (or (null txt) (string-match "\\S-" txt))
9022 (setq cpltxt
9023 (concat cpltxt "::"
9024 (condition-case nil
9025 (org-make-org-heading-search-string txt)
9026 (error "")))
9027 desc (or (nth 4 (ignore-errors
9028 (org-heading-components))) "NONE"))))
9029 (if (string-match "::\\'" cpltxt)
9030 (setq cpltxt (substring cpltxt 0 -2)))
9031 (setq link cpltxt))))
9033 ((buffer-file-name (buffer-base-buffer))
9034 ;; Just link to this file here.
9035 (setq cpltxt (concat "file:"
9036 (abbreviate-file-name
9037 (buffer-file-name (buffer-base-buffer)))))
9038 ;; Add a context string
9039 (when (org-xor org-context-in-file-links arg)
9040 (setq txt (if (org-region-active-p)
9041 (buffer-substring (region-beginning) (region-end))
9042 (buffer-substring (point-at-bol) (point-at-eol))))
9043 ;; Only use search option if there is some text.
9044 (when (string-match "\\S-" txt)
9045 (setq cpltxt
9046 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9047 desc "NONE")))
9048 (setq link cpltxt))
9050 ((org-called-interactively-p 'interactive)
9051 (error "Cannot link to a buffer which is not visiting a file"))
9053 (t (setq link nil)))
9055 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9056 (setq link (or link cpltxt)
9057 desc (or desc cpltxt))
9058 (if (equal desc "NONE") (setq desc nil))
9060 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9061 (progn
9062 (setq org-stored-links
9063 (cons (list link desc) org-stored-links))
9064 (message "Stored: %s" (or desc link))
9065 (when custom-id
9066 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9067 "::#" custom-id))
9068 (setq org-stored-links
9069 (cons (list link desc) org-stored-links))))
9070 (or agenda-link (and link (org-make-link-string link desc)))))))
9072 (defun org-store-link-props (&rest plist)
9073 "Store link properties, extract names and addresses."
9074 (let (x adr)
9075 (when (setq x (plist-get plist :from))
9076 (setq adr (mail-extract-address-components x))
9077 (setq plist (plist-put plist :fromname (car adr)))
9078 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9079 (when (setq x (plist-get plist :to))
9080 (setq adr (mail-extract-address-components x))
9081 (setq plist (plist-put plist :toname (car adr)))
9082 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9083 (let ((from (plist-get plist :from))
9084 (to (plist-get plist :to)))
9085 (when (and from to org-from-is-user-regexp)
9086 (setq plist
9087 (plist-put plist :fromto
9088 (if (string-match org-from-is-user-regexp from)
9089 (concat "to %t")
9090 (concat "from %f"))))))
9091 (setq org-store-link-plist plist))
9093 (defun org-add-link-props (&rest plist)
9094 "Add these properties to the link property list."
9095 (let (key value)
9096 (while plist
9097 (setq key (pop plist) value (pop plist))
9098 (setq org-store-link-plist
9099 (plist-put org-store-link-plist key value)))))
9101 (defun org-email-link-description (&optional fmt)
9102 "Return the description part of an email link.
9103 This takes information from `org-store-link-plist' and formats it
9104 according to FMT (default from `org-email-link-description-format')."
9105 (setq fmt (or fmt org-email-link-description-format))
9106 (let* ((p org-store-link-plist)
9107 (to (plist-get p :toaddress))
9108 (from (plist-get p :fromaddress))
9109 (table
9110 (list
9111 (cons "%c" (plist-get p :fromto))
9112 (cons "%F" (plist-get p :from))
9113 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9114 (cons "%T" (plist-get p :to))
9115 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9116 (cons "%s" (plist-get p :subject))
9117 (cons "%d" (plist-get p :date))
9118 (cons "%m" (plist-get p :message-id)))))
9119 (when (string-match "%c" fmt)
9120 ;; Check if the user wrote this message
9121 (if (and org-from-is-user-regexp from to
9122 (save-match-data (string-match org-from-is-user-regexp from)))
9123 (setq fmt (replace-match "to %t" t t fmt))
9124 (setq fmt (replace-match "from %f" t t fmt))))
9125 (org-replace-escapes fmt table)))
9127 (defun org-make-org-heading-search-string (&optional string heading)
9128 "Make search string for STRING or current headline."
9129 (interactive)
9130 (let ((s (or string (org-get-heading)))
9131 (lines org-context-in-file-links))
9132 (unless (and string (not heading))
9133 ;; We are using a headline, clean up garbage in there.
9134 (if (string-match org-todo-regexp s)
9135 (setq s (replace-match "" t t s)))
9136 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9137 (setq s (replace-match "" t t s)))
9138 (setq s (org-trim s))
9139 (if (string-match (concat "^\\(" org-quote-string "\\|"
9140 org-comment-string "\\)") s)
9141 (setq s (replace-match "" t t s)))
9142 (while (string-match org-ts-regexp s)
9143 (setq s (replace-match "" t t s))))
9144 (or string (setq s (concat "*" s))) ; Add * for headlines
9145 (when (and string (integerp lines) (> lines 0))
9146 (let ((slines (org-split-string s "\n")))
9147 (when (< lines (length slines))
9148 (setq s (mapconcat
9149 'identity
9150 (reverse (nthcdr (- (length slines) lines)
9151 (reverse slines))) "\n")))))
9152 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9154 (defun org-make-link-string (link &optional description)
9155 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9156 (unless (string-match "\\S-" link)
9157 (error "Empty link"))
9158 (when (and description
9159 (stringp description)
9160 (not (string-match "\\S-" description)))
9161 (setq description nil))
9162 (when (stringp description)
9163 ;; Remove brackets from the description, they are fatal.
9164 (while (string-match "\\[" description)
9165 (setq description (replace-match "{" t t description)))
9166 (while (string-match "\\]" description)
9167 (setq description (replace-match "}" t t description))))
9168 (when (equal link description)
9169 ;; No description needed, it is identical
9170 (setq description nil))
9171 (when (and (not description)
9172 (not (string-match (org-image-file-name-regexp) link))
9173 (not (equal link (org-link-escape link))))
9174 (setq description (org-extract-attributes link)))
9175 (setq link
9176 (cond ((string-match (org-image-file-name-regexp) link) link)
9177 ((string-match org-link-types-re link)
9178 (concat (match-string 1 link)
9179 (org-link-escape (substring link (match-end 1)))))
9180 (t (org-link-escape link))))
9181 (concat "[[" link "]"
9182 (if description (concat "[" description "]") "")
9183 "]"))
9185 (defconst org-link-escape-chars
9186 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9187 "List of characters that should be escaped in link.
9188 This is the list that is used for internal purposes.")
9190 (defconst org-link-escape-chars-browser
9191 '(?\ )
9192 "List of escapes for characters that are problematic in links.
9193 This is the list that is used before handing over to the browser.")
9195 (defun org-link-escape (text &optional table merge)
9196 "Return percent escaped representation of TEXT.
9197 TEXT is a string with the text to escape.
9198 Optional argument TABLE is a list with characters that should be
9199 escaped. When nil, `org-link-escape-chars' is used.
9200 If optional argument MERGE is set, merge TABLE into
9201 `org-link-escape-chars'."
9202 (cond
9203 ((and table merge)
9204 (mapc (lambda (defchr)
9205 (unless (member defchr table)
9206 (setq table (cons defchr table)))) org-link-escape-chars))
9207 ((null table)
9208 (setq table org-link-escape-chars)))
9209 (mapconcat
9210 (lambda (char)
9211 (if (or (member char table)
9212 (and (or (< char 32) (= char 37) (> char 126))
9213 org-url-hexify-p))
9214 (mapconcat (lambda (sequence-element)
9215 (format "%%%.2X" sequence-element))
9216 (or (encode-coding-char char 'utf-8)
9217 (error "Unable to percent escape character: %s"
9218 (char-to-string char))) "")
9219 (char-to-string char))) text ""))
9221 (defun org-link-unescape (str)
9222 "Unhex hexified Unicode strings as returned from the JavaScript function
9223 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9224 (unless (and (null str) (string= "" str))
9225 (let ((pos 0) (case-fold-search t) unhexed)
9226 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9227 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9228 (setq str (replace-match unhexed t t str))
9229 (setq pos (+ pos (length unhexed))))))
9230 str)
9232 (defun org-link-unescape-compound (hex)
9233 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9234 Note: this function also decodes single byte encodings like
9235 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9236 (save-match-data
9237 (let* ((bytes (cdr (split-string hex "%")))
9238 (ret "")
9239 (eat 0)
9240 (sum 0))
9241 (while bytes
9242 (let* ((val (string-to-number (pop bytes) 16))
9243 (shift-xor
9244 (if (= 0 eat)
9245 (cond
9246 ((>= val 252) (cons 6 252))
9247 ((>= val 248) (cons 5 248))
9248 ((>= val 240) (cons 4 240))
9249 ((>= val 224) (cons 3 224))
9250 ((>= val 192) (cons 2 192))
9251 (t (cons 0 0)))
9252 (cons 6 128))))
9253 (if (>= val 192) (setq eat (car shift-xor)))
9254 (setq val (logxor val (cdr shift-xor)))
9255 (setq sum (+ (lsh sum (car shift-xor)) val))
9256 (if (> eat 0) (setq eat (- eat 1)))
9257 (cond
9258 ((= 0 eat) ;multi byte
9259 (setq ret (concat ret (org-char-to-string sum)))
9260 (setq sum 0))
9261 ((not bytes) ; single byte(s)
9262 (setq ret (org-link-unescape-single-byte-sequence hex))))
9263 )) ;; end (while bytes
9264 ret )))
9266 (defun org-link-unescape-single-byte-sequence (hex)
9267 "Unhexify hex-encoded single byte character sequences."
9268 (mapconcat (lambda (byte)
9269 (char-to-string (string-to-number byte 16)))
9270 (cdr (split-string hex "%")) ""))
9272 (defun org-xor (a b)
9273 "Exclusive or."
9274 (if a (not b) b))
9276 (defun org-fixup-message-id-for-http (s)
9277 "Replace special characters in a message id, so it can be used in an http query."
9278 (when (string-match "%" s)
9279 (setq s (mapconcat (lambda (c)
9280 (if (eq c ?%)
9281 "%25"
9282 (char-to-string c)))
9283 s "")))
9284 (while (string-match "<" s)
9285 (setq s (replace-match "%3C" t t s)))
9286 (while (string-match ">" s)
9287 (setq s (replace-match "%3E" t t s)))
9288 (while (string-match "@" s)
9289 (setq s (replace-match "%40" t t s)))
9292 (defun org-link-prettify (link)
9293 "Return a human-readable representation of LINK.
9294 The car of LINK must be a raw link the cdr of LINK must be either
9295 a link description or nil."
9296 (let ((desc (or (cadr link) "<no description>")))
9297 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9298 "<" (car link) ">")))
9300 ;;;###autoload
9301 (defun org-insert-link-global ()
9302 "Insert a link like Org-mode does.
9303 This command can be called in any mode to insert a link in Org-mode syntax."
9304 (interactive)
9305 (org-load-modules-maybe)
9306 (org-run-like-in-org-mode 'org-insert-link))
9308 (defun org-insert-all-links (&optional keep)
9309 "Insert all links in `org-stored-links'."
9310 (interactive "P")
9311 (let ((links (copy-sequence org-stored-links)) l)
9312 (while (setq l (if keep (pop links) (pop org-stored-links)))
9313 (insert "- ")
9314 (org-insert-link nil (car l) (cadr l))
9315 (insert "\n"))))
9317 (defun org-link-fontify-links-to-this-file ()
9318 "Fontify links to the current file in `org-stored-links'."
9319 (let ((f (buffer-file-name)) a b)
9320 (setq a (mapcar (lambda(l)
9321 (let ((ll (car l)))
9322 (when (and (string-match "^file:\\(.+\\)::" ll)
9323 (equal f (expand-file-name (match-string 1 ll))))
9324 ll)))
9325 org-stored-links))
9326 (when (featurep 'org-id)
9327 (setq b (mapcar (lambda(l)
9328 (let ((ll (car l)))
9329 (when (and (string-match "^id:\\(.+\\)$" ll)
9330 (equal f (expand-file-name
9331 (or (org-id-find-id-file
9332 (match-string 1 ll)) ""))))
9333 ll)))
9334 org-stored-links)))
9335 (mapcar (lambda(l)
9336 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9337 (delq nil (append a b)))))
9339 (defvar org-link-links-in-this-file nil)
9340 (defun org-insert-link (&optional complete-file link-location default-description)
9341 "Insert a link. At the prompt, enter the link.
9343 Completion can be used to insert any of the link protocol prefixes like
9344 http or ftp in use.
9346 The history can be used to select a link previously stored with
9347 `org-store-link'. When the empty string is entered (i.e. if you just
9348 press RET at the prompt), the link defaults to the most recently
9349 stored link. As SPC triggers completion in the minibuffer, you need to
9350 use M-SPC or C-q SPC to force the insertion of a space character.
9352 You will also be prompted for a description, and if one is given, it will
9353 be displayed in the buffer instead of the link.
9355 If there is already a link at point, this command will allow you to edit link
9356 and description parts.
9358 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9359 be selected using completion. The path to the file will be relative to the
9360 current directory if the file is in the current directory or a subdirectory.
9361 Otherwise, the link will be the absolute path as completed in the minibuffer
9362 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9363 option `org-link-file-path-type'.
9365 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9366 the current directory or below.
9368 With three \\[universal-argument] prefixes, negate the meaning of
9369 `org-keep-stored-link-after-insertion'.
9371 If `org-make-link-description-function' is non-nil, this function will be
9372 called with the link target, and the result will be the default
9373 link description.
9375 If the LINK-LOCATION parameter is non-nil, this value will be
9376 used as the link location instead of reading one interactively.
9378 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9379 be used as the default description."
9380 (interactive "P")
9381 (let* ((wcf (current-window-configuration))
9382 (origbuf (current-buffer))
9383 (region (if (org-region-active-p)
9384 (buffer-substring (region-beginning) (region-end))))
9385 (remove (and region (list (region-beginning) (region-end))))
9386 (desc region)
9387 tmphist ; byte-compile incorrectly complains about this
9388 (link link-location)
9389 (abbrevs org-link-abbrev-alist-local)
9390 entry file all-prefixes auto-desc)
9391 (cond
9392 (link-location) ; specified by arg, just use it.
9393 ((org-in-regexp org-bracket-link-regexp 1)
9394 ;; We do have a link at point, and we are going to edit it.
9395 (setq remove (list (match-beginning 0) (match-end 0)))
9396 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9397 (setq link (read-string "Link: "
9398 (org-link-unescape
9399 (org-match-string-no-properties 1)))))
9400 ((or (org-in-regexp org-angle-link-re)
9401 (org-in-regexp org-plain-link-re))
9402 ;; Convert to bracket link
9403 (setq remove (list (match-beginning 0) (match-end 0))
9404 link (read-string "Link: "
9405 (org-remove-angle-brackets (match-string 0)))))
9406 ((member complete-file '((4) (16)))
9407 ;; Completing read for file names.
9408 (setq link (org-file-complete-link complete-file)))
9410 ;; Read link, with completion for stored links.
9411 (org-link-fontify-links-to-this-file)
9412 (org-switch-to-buffer-other-window "*Org Links*")
9413 (with-current-buffer "*Org Links*"
9414 (erase-buffer)
9415 (insert "Insert a link.
9416 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9417 (when org-stored-links
9418 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9419 (insert (mapconcat 'org-link-prettify
9420 (reverse org-stored-links) "\n")))
9421 (goto-char (point-min)))
9422 (let ((cw (selected-window)))
9423 (select-window (get-buffer-window "*Org Links*" 'visible))
9424 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9425 (unless (pos-visible-in-window-p (point-max))
9426 (org-fit-window-to-buffer))
9427 (and (window-live-p cw) (select-window cw)))
9428 ;; Fake a link history, containing the stored links.
9429 (setq tmphist (append (mapcar 'car org-stored-links)
9430 org-insert-link-history))
9431 (setq all-prefixes (append (mapcar 'car abbrevs)
9432 (mapcar 'car org-link-abbrev-alist)
9433 org-link-types))
9434 (unwind-protect
9435 (progn
9436 (setq link
9437 (let ((org-completion-use-ido nil)
9438 (org-completion-use-iswitchb nil))
9439 (org-completing-read
9440 "Link: "
9441 (append
9442 (mapcar (lambda (x) (list (concat x ":")))
9443 all-prefixes)
9444 (mapcar 'car org-stored-links)
9445 (mapcar 'cadr org-stored-links))
9446 nil nil nil
9447 'tmphist
9448 (caar org-stored-links))))
9449 (if (not (string-match "\\S-" link))
9450 (error "No link selected"))
9451 (mapc (lambda(l)
9452 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9453 org-stored-links)
9454 (if (or (member link all-prefixes)
9455 (and (equal ":" (substring link -1))
9456 (member (substring link 0 -1) all-prefixes)
9457 (setq link (substring link 0 -1))))
9458 (setq link (with-current-buffer origbuf
9459 (org-link-try-special-completion link)))))
9460 (set-window-configuration wcf)
9461 (kill-buffer "*Org Links*"))
9462 (setq entry (assoc link org-stored-links))
9463 (or entry (push link org-insert-link-history))
9464 (setq desc (or desc (nth 1 entry)))))
9466 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9467 (not org-keep-stored-link-after-insertion))
9468 (setq org-stored-links (delq (assoc link org-stored-links)
9469 org-stored-links)))
9471 (if (string-match org-plain-link-re link)
9472 ;; URL-like link, normalize the use of angular brackets.
9473 (setq link (org-remove-angle-brackets link)))
9475 ;; Check if we are linking to the current file with a search option
9476 ;; If yes, simplify the link by using only the search option.
9477 (when (and buffer-file-name
9478 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9479 (let* ((path (match-string 1 link))
9480 (case-fold-search nil)
9481 (search (match-string 2 link)))
9482 (save-match-data
9483 (if (equal (file-truename buffer-file-name) (file-truename path))
9484 ;; We are linking to this same file, with a search option
9485 (setq link search)))))
9487 ;; Check if we can/should use a relative path. If yes, simplify the link
9488 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9489 (let* ((type (match-string 1 link))
9490 (path (match-string 2 link))
9491 (origpath path)
9492 (case-fold-search nil))
9493 (cond
9494 ((or (eq org-link-file-path-type 'absolute)
9495 (equal complete-file '(16)))
9496 (setq path (abbreviate-file-name (expand-file-name path))))
9497 ((eq org-link-file-path-type 'noabbrev)
9498 (setq path (expand-file-name path)))
9499 ((eq org-link-file-path-type 'relative)
9500 (setq path (file-relative-name path)))
9502 (save-match-data
9503 (if (string-match (concat "^" (regexp-quote
9504 (expand-file-name
9505 (file-name-as-directory
9506 default-directory))))
9507 (expand-file-name path))
9508 ;; We are linking a file with relative path name.
9509 (setq path (substring (expand-file-name path)
9510 (match-end 0)))
9511 (setq path (abbreviate-file-name (expand-file-name path)))))))
9512 (setq link (concat type path))
9513 (if (equal desc origpath)
9514 (setq desc path))))
9516 (if org-make-link-description-function
9517 (setq desc (funcall org-make-link-description-function link desc))
9518 (if default-description (setq desc default-description)
9519 (setq desc (or (and auto-desc desc)
9520 (read-string "Description: " desc)))))
9522 (unless (string-match "\\S-" desc) (setq desc nil))
9523 (if remove (apply 'delete-region remove))
9524 (insert (org-make-link-string link desc))))
9526 (defun org-link-try-special-completion (type)
9527 "If there is completion support for link type TYPE, offer it."
9528 (let ((fun (intern (concat "org-" type "-complete-link"))))
9529 (if (functionp fun)
9530 (funcall fun)
9531 (read-string "Link (no completion support): " (concat type ":")))))
9533 (defun org-file-complete-link (&optional arg)
9534 "Create a file link using completion."
9535 (let (file link)
9536 (setq file (read-file-name "File: "))
9537 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9538 (pwd1 (file-name-as-directory (abbreviate-file-name
9539 (expand-file-name ".")))))
9540 (cond
9541 ((equal arg '(16))
9542 (setq link (concat
9543 "file:"
9544 (abbreviate-file-name (expand-file-name file)))))
9545 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9546 (setq link (concat "file:" (match-string 1 file))))
9547 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9548 (expand-file-name file))
9549 (setq link (concat
9550 "file:" (match-string 1 (expand-file-name file)))))
9551 (t (setq link (concat "file:" file)))))
9552 link))
9554 (defun org-completing-read (&rest args)
9555 "Completing-read with SPACE being a normal character."
9556 (let ((enable-recursive-minibuffers t)
9557 (minibuffer-local-completion-map
9558 (copy-keymap minibuffer-local-completion-map)))
9559 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9560 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9561 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9562 (apply 'org-icompleting-read args)))
9564 (defun org-completing-read-no-i (&rest args)
9565 (let (org-completion-use-ido org-completion-use-iswitchb)
9566 (apply 'org-completing-read args)))
9568 (defun org-iswitchb-completing-read (prompt choices &rest args)
9569 "Use iswitch as a completing-read replacement to choose from choices.
9570 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9571 from."
9572 (let* ((iswitchb-use-virtual-buffers nil)
9573 (iswitchb-make-buflist-hook
9574 (lambda ()
9575 (setq iswitchb-temp-buflist choices))))
9576 (iswitchb-read-buffer prompt)))
9578 (defun org-icompleting-read (&rest args)
9579 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9580 (org-without-partial-completion
9581 (if (and org-completion-use-ido
9582 (fboundp 'ido-completing-read)
9583 (boundp 'ido-mode) ido-mode
9584 (listp (second args)))
9585 (let ((ido-enter-matching-directory nil))
9586 (apply 'ido-completing-read (concat (car args))
9587 (if (consp (car (nth 1 args)))
9588 (mapcar 'car (nth 1 args))
9589 (nth 1 args))
9590 (cddr args)))
9591 (if (and org-completion-use-iswitchb
9592 (boundp 'iswitchb-mode) iswitchb-mode
9593 (listp (second args)))
9594 (apply 'org-iswitchb-completing-read (concat (car args))
9595 (if (consp (car (nth 1 args)))
9596 (mapcar 'car (nth 1 args))
9597 (nth 1 args))
9598 (cddr args))
9599 (apply 'completing-read args)))))
9601 (defun org-extract-attributes (s)
9602 "Extract the attributes cookie from a string and set as text property."
9603 (let (a attr (start 0) key value)
9604 (save-match-data
9605 (when (string-match "{{\\([^}]+\\)}}$" s)
9606 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9607 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9608 (setq key (match-string 1 a) value (match-string 2 a)
9609 start (match-end 0)
9610 attr (plist-put attr (intern key) value))))
9611 (org-add-props s nil 'org-attr attr))
9614 (defun org-extract-attributes-from-string (tag)
9615 (let (key value attr)
9616 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9617 (setq key (match-string 1 tag) value (match-string 2 tag)
9618 tag (replace-match "" t t tag)
9619 attr (plist-put attr (intern key) value)))
9620 (cons tag attr)))
9622 (defun org-attributes-to-string (plist)
9623 "Format a property list into an HTML attribute list."
9624 (let ((s "") key value)
9625 (while plist
9626 (setq key (pop plist) value (pop plist))
9627 (and value
9628 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9631 ;;; Opening/following a link
9633 (defvar org-link-search-failed nil)
9635 (defvar org-open-link-functions nil
9636 "Hook for functions finding a plain text link.
9637 These functions must take a single argument, the link content.
9638 They will be called for links that look like [[link text][description]]
9639 when LINK TEXT does not have a protocol like \"http:\" and does not look
9640 like a filename (e.g. \"./blue.png\").
9642 These functions will be called *before* Org attempts to resolve the
9643 link by doing text searches in the current buffer - so if you want a
9644 link \"[[target]]\" to still find \"<<target>>\", your function should
9645 handle this as a special case.
9647 When the function does handle the link, it must return a non-nil value.
9648 If it decides that it is not responsible for this link, it must return
9649 nil to indicate that that Org-mode can continue with other options
9650 like exact and fuzzy text search.")
9652 (defun org-next-link ()
9653 "Move forward to the next link.
9654 If the link is in hidden text, expose it."
9655 (interactive)
9656 (when (and org-link-search-failed (eq this-command last-command))
9657 (goto-char (point-min))
9658 (message "Link search wrapped back to beginning of buffer"))
9659 (setq org-link-search-failed nil)
9660 (let* ((pos (point))
9661 (ct (org-context))
9662 (a (assoc :link ct)))
9663 (if a (goto-char (nth 2 a)))
9664 (if (re-search-forward org-any-link-re nil t)
9665 (progn
9666 (goto-char (match-beginning 0))
9667 (if (outline-invisible-p) (org-show-context)))
9668 (goto-char pos)
9669 (setq org-link-search-failed t)
9670 (error "No further link found"))))
9672 (defun org-previous-link ()
9673 "Move backward to the previous link.
9674 If the link is in hidden text, expose it."
9675 (interactive)
9676 (when (and org-link-search-failed (eq this-command last-command))
9677 (goto-char (point-max))
9678 (message "Link search wrapped back to end of buffer"))
9679 (setq org-link-search-failed nil)
9680 (let* ((pos (point))
9681 (ct (org-context))
9682 (a (assoc :link ct)))
9683 (if a (goto-char (nth 1 a)))
9684 (if (re-search-backward org-any-link-re nil t)
9685 (progn
9686 (goto-char (match-beginning 0))
9687 (if (outline-invisible-p) (org-show-context)))
9688 (goto-char pos)
9689 (setq org-link-search-failed t)
9690 (error "No further link found"))))
9692 (defun org-translate-link (s)
9693 "Translate a link string if a translation function has been defined."
9694 (if (and org-link-translation-function
9695 (fboundp org-link-translation-function)
9696 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9697 (progn
9698 (setq s (funcall org-link-translation-function
9699 (match-string 1 s) (match-string 2 s)))
9700 (concat (car s) ":" (cdr s)))
9703 (defun org-translate-link-from-planner (type path)
9704 "Translate a link from Emacs Planner syntax so that Org can follow it.
9705 This is still an experimental function, your mileage may vary."
9706 (cond
9707 ((member type '("http" "https" "news" "ftp"))
9708 ;; standard Internet links are the same.
9709 nil)
9710 ((and (equal type "irc") (string-match "^//" path))
9711 ;; Planner has two / at the beginning of an irc link, we have 1.
9712 ;; We should have zero, actually....
9713 (setq path (substring path 1)))
9714 ((and (equal type "lisp") (string-match "^/" path))
9715 ;; Planner has a slash, we do not.
9716 (setq type "elisp" path (substring path 1)))
9717 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9718 ;; A typical message link. Planner has the id after the final slash,
9719 ;; we separate it with a hash mark
9720 (setq path (concat (match-string 1 path) "#"
9721 (org-remove-angle-brackets (match-string 2 path)))))
9723 (cons type path))
9725 (defun org-find-file-at-mouse (ev)
9726 "Open file link or URL at mouse."
9727 (interactive "e")
9728 (mouse-set-point ev)
9729 (org-open-at-point 'in-emacs))
9731 (defun org-open-at-mouse (ev)
9732 "Open file link or URL at mouse.
9733 See the docstring of `org-open-file' for details."
9734 (interactive "e")
9735 (mouse-set-point ev)
9736 (if (eq major-mode 'org-agenda-mode)
9737 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9738 (org-open-at-point))
9740 (defvar org-window-config-before-follow-link nil
9741 "The window configuration before following a link.
9742 This is saved in case the need arises to restore it.")
9744 (defvar org-open-link-marker (make-marker)
9745 "Marker pointing to the location where `org-open-at-point; was called.")
9747 ;;;###autoload
9748 (defun org-open-at-point-global ()
9749 "Follow a link like Org-mode does.
9750 This command can be called in any mode to follow a link that has
9751 Org-mode syntax."
9752 (interactive)
9753 (org-run-like-in-org-mode 'org-open-at-point))
9755 ;;;###autoload
9756 (defun org-open-link-from-string (s &optional arg reference-buffer)
9757 "Open a link in the string S, as if it was in Org-mode."
9758 (interactive "sLink: \nP")
9759 (let ((reference-buffer (or reference-buffer (current-buffer))))
9760 (with-temp-buffer
9761 (let ((org-inhibit-startup (not reference-buffer)))
9762 (org-mode)
9763 (insert s)
9764 (goto-char (point-min))
9765 (when reference-buffer
9766 (setq org-link-abbrev-alist-local
9767 (with-current-buffer reference-buffer
9768 org-link-abbrev-alist-local)))
9769 (org-open-at-point arg reference-buffer)))))
9771 (defvar org-open-at-point-functions nil
9772 "Hook that is run when following a link at point.
9774 Functions in this hook must return t if they identify and follow
9775 a link at point. If they don't find anything interesting at point,
9776 they must return nil.")
9778 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9779 (defun org-open-at-point (&optional arg reference-buffer)
9780 "Open link at or after point.
9781 If there is no link at point, this function will search forward up to
9782 the end of the current line.
9783 Normally, files will be opened by an appropriate application. If the
9784 optional prefix argument ARG is non-nil, Emacs will visit the file.
9785 With a double prefix argument, try to open outside of Emacs, in the
9786 application the system uses for this file type."
9787 (interactive "P")
9788 ;; if in a code block, then open the block's results
9789 (unless (call-interactively #'org-babel-open-src-block-result)
9790 (org-load-modules-maybe)
9791 (move-marker org-open-link-marker (point))
9792 (setq org-window-config-before-follow-link (current-window-configuration))
9793 (org-remove-occur-highlights nil nil t)
9794 (cond
9795 ((and (org-at-heading-p)
9796 (not (org-at-timestamp-p t))
9797 (not (org-in-regexp
9798 (concat org-plain-link-re "\\|"
9799 org-bracket-link-regexp "\\|"
9800 org-angle-link-re "\\|"
9801 "[ \t]:[^ \t\n]+:[ \t]*$")))
9802 (not (get-text-property (point) 'org-linked-text)))
9803 (or (org-offer-links-in-entry arg)
9804 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9805 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9806 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9807 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9808 (not (org-in-regexp org-bracket-link-regexp)))
9809 (org-footnote-action))
9811 (let (type path link line search (pos (point)))
9812 (catch 'match
9813 (save-excursion
9814 (skip-chars-forward "^]\n\r")
9815 (when (org-in-regexp org-bracket-link-regexp 1)
9816 (setq link (org-extract-attributes
9817 (org-link-unescape (org-match-string-no-properties 1))))
9818 (while (string-match " *\n *" link)
9819 (setq link (replace-match " " t t link)))
9820 (setq link (org-link-expand-abbrev link))
9821 (cond
9822 ((or (file-name-absolute-p link)
9823 (string-match "^\\.\\.?/" link))
9824 (setq type "file" path link))
9825 ((string-match org-link-re-with-space3 link)
9826 (setq type (match-string 1 link) path (match-string 2 link)))
9827 ((string-match "^help:+\\(.+\\)" link)
9828 (setq type "help" path (match-string 1 link)))
9829 (t (setq type "thisfile" path link)))
9830 (throw 'match t)))
9832 (when (get-text-property (point) 'org-linked-text)
9833 (setq type "thisfile"
9834 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9835 (1+ (point)) (point))
9836 path (buffer-substring
9837 (or (previous-single-property-change pos 'org-linked-text)
9838 (point-min))
9839 (or (next-single-property-change pos 'org-linked-text)
9840 (point-max))))
9841 (throw 'match t))
9843 (save-excursion
9844 (when (or (org-in-regexp org-angle-link-re)
9845 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9846 (save-match-data (not (looking-back "\\[\\[")))))
9847 (setq type (match-string 1)
9848 path (org-link-unescape (match-string 2)))
9849 (throw 'match t)))
9850 (save-excursion
9851 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9852 (setq type "tags"
9853 path (match-string 1))
9854 (while (string-match ":" path)
9855 (setq path (replace-match "+" t t path)))
9856 (throw 'match t)))
9857 (when (org-in-regexp "<\\([^><\n]+\\)>")
9858 (setq type "tree-match"
9859 path (match-string 1))
9860 (throw 'match t)))
9861 (unless path
9862 (error "No link found"))
9864 ;; switch back to reference buffer
9865 ;; needed when if called in a temporary buffer through
9866 ;; org-open-link-from-string
9867 (with-current-buffer (or reference-buffer (current-buffer))
9869 ;; Remove any trailing spaces in path
9870 (if (string-match " +\\'" path)
9871 (setq path (replace-match "" t t path)))
9872 (if (and org-link-translation-function
9873 (fboundp org-link-translation-function))
9874 ;; Check if we need to translate the link
9875 (let ((tmp (funcall org-link-translation-function type path)))
9876 (setq type (car tmp) path (cdr tmp))))
9878 (cond
9880 ((assoc type org-link-protocols)
9881 (funcall (nth 1 (assoc type org-link-protocols)) path))
9883 ((equal type "help")
9884 (let ((f-or-v (intern path)))
9885 (cond ((fboundp f-or-v)
9886 (describe-function f-or-v))
9887 ((boundp f-or-v)
9888 (describe-variable f-or-v))
9889 (t (error "Not a known function or variable")))))
9891 ((equal type "mailto")
9892 (let ((cmd (car org-link-mailto-program))
9893 (args (cdr org-link-mailto-program)) args1
9894 (address path) (subject "") a)
9895 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9896 (setq address (match-string 1 path)
9897 subject (org-link-escape (match-string 2 path))))
9898 (while args
9899 (cond
9900 ((not (stringp (car args))) (push (pop args) args1))
9901 (t (setq a (pop args))
9902 (if (string-match "%a" a)
9903 (setq a (replace-match address t t a)))
9904 (if (string-match "%s" a)
9905 (setq a (replace-match subject t t a)))
9906 (push a args1))))
9907 (apply cmd (nreverse args1))))
9909 ((member type '("http" "https" "ftp" "news"))
9910 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9911 (org-link-escape
9912 path org-link-escape-chars-browser)
9913 path))))
9915 ((string= type "doi")
9916 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9917 (org-link-escape
9918 path org-link-escape-chars-browser)
9919 path))))
9921 ((member type '("message"))
9922 (browse-url (concat type ":" path)))
9924 ((string= type "tags")
9925 (org-tags-view arg path))
9927 ((string= type "tree-match")
9928 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9930 ((string= type "file")
9931 (if (string-match "::\\([0-9]+\\)\\'" path)
9932 (setq line (string-to-number (match-string 1 path))
9933 path (substring path 0 (match-beginning 0)))
9934 (if (string-match "::\\(.+\\)\\'" path)
9935 (setq search (match-string 1 path)
9936 path (substring path 0 (match-beginning 0)))))
9937 (if (string-match "[*?{]" (file-name-nondirectory path))
9938 (dired path)
9939 (org-open-file path arg line search)))
9941 ((string= type "shell")
9942 (let ((buf (generate-new-buffer "*Org Shell Output"))
9943 (cmd path))
9944 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9945 (string-match org-confirm-shell-link-not-regexp cmd))
9946 (not org-confirm-shell-link-function)
9947 (funcall org-confirm-shell-link-function
9948 (format "Execute \"%s\" in shell? "
9949 (org-add-props cmd nil
9950 'face 'org-warning))))
9951 (progn
9952 (message "Executing %s" cmd)
9953 (shell-command cmd buf)
9954 (if (featurep 'midnight)
9955 (setq clean-buffer-list-kill-buffer-names
9956 (cons buf clean-buffer-list-kill-buffer-names))))
9957 (error "Abort"))))
9959 ((string= type "elisp")
9960 (let ((cmd path))
9961 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9962 (string-match org-confirm-elisp-link-not-regexp cmd))
9963 (not org-confirm-elisp-link-function)
9964 (funcall org-confirm-elisp-link-function
9965 (format "Execute \"%s\" as elisp? "
9966 (org-add-props cmd nil
9967 'face 'org-warning))))
9968 (message "%s => %s" cmd
9969 (if (equal (string-to-char cmd) ?\()
9970 (eval (read cmd))
9971 (call-interactively (read cmd))))
9972 (error "Abort"))))
9974 ((and (string= type "thisfile")
9975 (run-hook-with-args-until-success
9976 'org-open-link-functions path)))
9978 ((string= type "thisfile")
9979 (if arg
9980 (switch-to-buffer-other-window
9981 (org-get-buffer-for-internal-link (current-buffer)))
9982 (org-mark-ring-push))
9983 (let ((cmd `(org-link-search
9984 ,path
9985 ,(cond ((equal arg '(4)) ''occur)
9986 ((equal arg '(16)) ''org-occur))
9987 ,pos)))
9988 (condition-case nil (let ((org-link-search-inhibit-query t))
9989 (eval cmd))
9990 (error (progn (widen) (eval cmd))))))
9992 (t (browse-url-at-point)))))))
9993 (move-marker org-open-link-marker nil)
9994 (run-hook-with-args 'org-follow-link-hook)))
9996 (defun org-offer-links-in-entry (&optional nth zero)
9997 "Offer links in the current entry and follow the selected link.
9998 If there is only one link, follow it immediately as well.
9999 If NTH is an integer, immediately pick the NTH link found.
10000 If ZERO is a string, check also this string for a link, and if
10001 there is one, offer it as link number zero."
10002 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10003 "\\(" org-angle-link-re "\\)\\|"
10004 "\\(" org-plain-link-re "\\)"))
10005 (cnt ?0)
10006 (in-emacs (if (integerp nth) nil nth))
10007 have-zero end links link c)
10008 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10009 (push (match-string 0 zero) links)
10010 (setq cnt (1- cnt) have-zero t))
10011 (save-excursion
10012 (org-back-to-heading t)
10013 (setq end (save-excursion (outline-next-heading) (point)))
10014 (while (re-search-forward re end t)
10015 (push (match-string 0) links))
10016 (setq links (org-uniquify (reverse links))))
10018 (cond
10019 ((null links)
10020 (message "No links"))
10021 ((equal (length links) 1)
10022 (setq link (list (car links))))
10023 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10024 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10025 (t ; we have to select a link
10026 (save-excursion
10027 (save-window-excursion
10028 (delete-other-windows)
10029 (with-output-to-temp-buffer "*Select Link*"
10030 (mapc (lambda (l)
10031 (if (not (string-match org-bracket-link-regexp l))
10032 (princ (format "[%c] %s\n" (incf cnt)
10033 (org-remove-angle-brackets l)))
10034 (if (match-end 3)
10035 (princ (format "[%c] %s (%s)\n" (incf cnt)
10036 (match-string 3 l) (match-string 1 l)))
10037 (princ (format "[%c] %s\n" (incf cnt)
10038 (match-string 1 l))))))
10039 links))
10040 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10041 (message "Select link to open, RET to open all:")
10042 (setq c (read-char-exclusive))
10043 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10044 (when (equal c ?q) (error "Abort"))
10045 (if (equal c ?\C-m)
10046 (setq link links)
10047 (setq nth (- c ?0))
10048 (if have-zero (setq nth (1+ nth)))
10049 (unless (and (integerp nth) (>= (length links) nth))
10050 (error "Invalid link selection"))
10051 (setq link (list (nth (1- nth) links))))))
10052 (if link
10053 (let ((buf (current-buffer)))
10054 (dolist (l link)
10055 (org-open-link-from-string l in-emacs buf))
10057 nil)))
10059 ;; Add special file links that specify the way of opening
10061 (org-add-link-type "file+sys" 'org-open-file-with-system)
10062 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10063 (defun org-open-file-with-system (path)
10064 "Open file at PATH using the system way of opening it."
10065 (org-open-file path 'system))
10066 (defun org-open-file-with-emacs (path)
10067 "Open file at PATH in Emacs."
10068 (org-open-file path 'emacs))
10069 (defun org-remove-file-link-modifiers ()
10070 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10071 (goto-char (point-min))
10072 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10073 (org-if-unprotected
10074 (replace-match "file:" t t))))
10075 (eval-after-load "org-exp"
10076 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10077 'org-remove-file-link-modifiers))
10079 ;;;; Time estimates
10081 (defun org-get-effort (&optional pom)
10082 "Get the effort estimate for the current entry."
10083 (org-entry-get pom org-effort-property))
10085 ;;; File search
10087 (defvar org-create-file-search-functions nil
10088 "List of functions to construct the right search string for a file link.
10089 These functions are called in turn with point at the location to
10090 which the link should point.
10092 A function in the hook should first test if it would like to
10093 handle this file type, for example by checking the `major-mode'
10094 or the file extension. If it decides not to handle this file, it
10095 should just return nil to give other functions a chance. If it
10096 does handle the file, it must return the search string to be used
10097 when following the link. The search string will be part of the
10098 file link, given after a double colon, and `org-open-at-point'
10099 will automatically search for it. If special measures must be
10100 taken to make the search successful, another function should be
10101 added to the companion hook `org-execute-file-search-functions',
10102 which see.
10104 A function in this hook may also use `setq' to set the variable
10105 `description' to provide a suggestion for the descriptive text to
10106 be used for this link when it gets inserted into an Org-mode
10107 buffer with \\[org-insert-link].")
10109 (defvar org-execute-file-search-functions nil
10110 "List of functions to execute a file search triggered by a link.
10112 Functions added to this hook must accept a single argument, the
10113 search string that was part of the file link, the part after the
10114 double colon. The function must first check if it would like to
10115 handle this search, for example by checking the `major-mode' or
10116 the file extension. If it decides not to handle this search, it
10117 should just return nil to give other functions a chance. If it
10118 does handle the search, it must return a non-nil value to keep
10119 other functions from trying.
10121 Each function can access the current prefix argument through the
10122 variable `current-prefix-argument'. Note that a single prefix is
10123 used to force opening a link in Emacs, so it may be good to only
10124 use a numeric or double prefix to guide the search function.
10126 In case this is needed, a function in this hook can also restore
10127 the window configuration before `org-open-at-point' was called using:
10129 (set-window-configuration org-window-config-before-follow-link)")
10131 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10132 (defun org-link-search (s &optional type avoid-pos stealth)
10133 "Search for a link search option.
10134 If S is surrounded by forward slashes, it is interpreted as a
10135 regular expression. In org-mode files, this will create an `org-occur'
10136 sparse tree. In ordinary files, `occur' will be used to list matches.
10137 If the current buffer is in `dired-mode', grep will be used to search
10138 in all files. If AVOID-POS is given, ignore matches near that position.
10140 When optional argument STEALTH is non-nil, do not modify
10141 visibility around point, thus ignoring
10142 `org-show-hierarchy-above', `org-show-following-heading' and
10143 `org-show-siblings' variables."
10144 (let ((case-fold-search t)
10145 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10146 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10147 (append '(("") (" ") ("\t") ("\n"))
10148 org-emphasis-alist)
10149 "\\|") "\\)"))
10150 (pos (point))
10151 (pre nil) (post nil)
10152 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10153 (cond
10154 ;; First check if there are any special search functions
10155 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10156 ;; Now try the builtin stuff
10157 ((and (equal (string-to-char s0) ?#)
10158 (> (length s0) 1)
10159 (save-excursion
10160 (goto-char (point-min))
10161 (and
10162 (re-search-forward
10163 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10164 (setq type 'dedicated
10165 pos (match-beginning 0))))
10166 ;; There is an exact target for this
10167 (goto-char pos)
10168 (org-back-to-heading t)))
10169 ((save-excursion
10170 (goto-char (point-min))
10171 (and
10172 (re-search-forward
10173 (concat "<<" (regexp-quote s0) ">>") nil t)
10174 (setq type 'dedicated
10175 pos (match-beginning 0))))
10176 ;; There is an exact target for this
10177 (goto-char pos))
10178 ((save-excursion
10179 (goto-char (point-min))
10180 (and
10181 (re-search-forward
10182 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10183 (setq type 'dedicated pos (match-beginning 0))))
10184 ;; Found an invisible target.
10185 (goto-char pos))
10186 ((save-excursion
10187 (goto-char (point-min))
10188 (and
10189 (re-search-forward
10190 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10191 (setq type 'dedicated pos (match-beginning 0))))
10192 ;; Found an element with a matching #+name affiliated keyword.
10193 (goto-char pos))
10194 ((and (string-match "^(\\(.*\\))$" s0)
10195 (save-excursion
10196 (goto-char (point-min))
10197 (and
10198 (re-search-forward
10199 (concat "[^[]" (regexp-quote
10200 (format org-coderef-label-format
10201 (match-string 1 s0))))
10202 nil t)
10203 (setq type 'dedicated
10204 pos (1+ (match-beginning 0))))))
10205 ;; There is a coderef target for this
10206 (goto-char pos))
10207 ((string-match "^/\\(.*\\)/$" s)
10208 ;; A regular expression
10209 (cond
10210 ((derived-mode-p 'org-mode)
10211 (org-occur (match-string 1 s)))
10212 ;;((eq major-mode 'dired-mode)
10213 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10214 (t (org-do-occur (match-string 1 s)))))
10215 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10216 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10217 (goto-char (point-min))
10218 (cond
10219 ((let (case-fold-search)
10220 (re-search-forward (format org-complex-heading-regexp-format
10221 (regexp-quote s))
10222 nil t))
10223 ;; OK, found a match
10224 (setq type 'dedicated)
10225 (goto-char (match-beginning 0)))
10226 ((and (not org-link-search-inhibit-query)
10227 (eq org-link-search-must-match-exact-headline 'query-to-create)
10228 (y-or-n-p "No match - create this as a new heading? "))
10229 (goto-char (point-max))
10230 (or (bolp) (newline))
10231 (insert "* " s "\n")
10232 (beginning-of-line 0))
10234 (goto-char pos)
10235 (error "No match"))))
10237 ;; A normal search string
10238 (when (equal (string-to-char s) ?*)
10239 ;; Anchor on headlines, post may include tags.
10240 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10241 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10242 s (substring s 1)))
10243 (remove-text-properties
10244 0 (length s)
10245 '(face nil mouse-face nil keymap nil fontified nil) s)
10246 ;; Make a series of regular expressions to find a match
10247 (setq words (org-split-string s "[ \n\r\t]+")
10249 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10250 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10251 "\\)" markers)
10252 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10253 re2a (concat "[ \t\r\n]" re2a_)
10254 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10255 re4 (concat "[^a-zA-Z_]" re4_)
10257 re1 (concat pre re2 post)
10258 re3 (concat pre (if pre re4_ re4) post)
10259 re5 (concat pre ".*" re4)
10260 re2 (concat pre re2)
10261 re2a (concat pre (if pre re2a_ re2a))
10262 re4 (concat pre (if pre re4_ re4))
10263 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10264 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10265 re5 "\\)"
10267 (cond
10268 ((eq type 'org-occur) (org-occur reall))
10269 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10270 (t (goto-char (point-min))
10271 (setq type 'fuzzy)
10272 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10273 (org-search-not-self 1 re1 nil t)
10274 (org-search-not-self 1 re2 nil t)
10275 (org-search-not-self 1 re2a nil t)
10276 (org-search-not-self 1 re3 nil t)
10277 (org-search-not-self 1 re4 nil t)
10278 (org-search-not-self 1 re5 nil t)
10280 (goto-char (match-beginning 1))
10281 (goto-char pos)
10282 (error "No match"))))))
10283 (and (derived-mode-p 'org-mode)
10284 (not stealth)
10285 (org-show-context 'link-search))
10286 type))
10288 (defun org-search-not-self (group &rest args)
10289 "Execute `re-search-forward', but only accept matches that do not
10290 enclose the position of `org-open-link-marker'."
10291 (let ((m org-open-link-marker))
10292 (catch 'exit
10293 (while (apply 're-search-forward args)
10294 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10295 (goto-char (match-end group))
10296 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10297 (> (match-beginning 0) (marker-position m))
10298 (< (match-end 0) (marker-position m)))
10299 (save-match-data
10300 (or (not (org-in-regexp
10301 org-bracket-link-analytic-regexp 1))
10302 (not (match-end 4)) ; no description
10303 (and (<= (match-beginning 4) (point))
10304 (>= (match-end 4) (point))))))
10305 (throw 'exit (point))))))))
10307 (defun org-get-buffer-for-internal-link (buffer)
10308 "Return a buffer to be used for displaying the link target of internal links."
10309 (cond
10310 ((not org-display-internal-link-with-indirect-buffer)
10311 buffer)
10312 ((string-match "(Clone)$" (buffer-name buffer))
10313 (message "Buffer is already a clone, not making another one")
10314 ;; we also do not modify visibility in this case
10315 buffer)
10316 (t ; make a new indirect buffer for displaying the link
10317 (let* ((bn (buffer-name buffer))
10318 (ibn (concat bn "(Clone)"))
10319 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10320 (with-current-buffer ib (org-overview))
10321 ib))))
10323 (defun org-do-occur (regexp &optional cleanup)
10324 "Call the Emacs command `occur'.
10325 If CLEANUP is non-nil, remove the printout of the regular expression
10326 in the *Occur* buffer. This is useful if the regex is long and not useful
10327 to read."
10328 (occur regexp)
10329 (when cleanup
10330 (let ((cwin (selected-window)) win beg end)
10331 (when (setq win (get-buffer-window "*Occur*"))
10332 (select-window win))
10333 (goto-char (point-min))
10334 (when (re-search-forward "match[a-z]+" nil t)
10335 (setq beg (match-end 0))
10336 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10337 (setq end (1- (match-beginning 0)))))
10338 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10339 (goto-char (point-min))
10340 (select-window cwin))))
10342 ;;; The mark ring for links jumps
10344 (defvar org-mark-ring nil
10345 "Mark ring for positions before jumps in Org-mode.")
10346 (defvar org-mark-ring-last-goto nil
10347 "Last position in the mark ring used to go back.")
10348 ;; Fill and close the ring
10349 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10350 (loop for i from 1 to org-mark-ring-length do
10351 (push (make-marker) org-mark-ring))
10352 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10353 org-mark-ring)
10355 (defun org-mark-ring-push (&optional pos buffer)
10356 "Put the current position or POS into the mark ring and rotate it."
10357 (interactive)
10358 (setq pos (or pos (point)))
10359 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10360 (move-marker (car org-mark-ring)
10361 (or pos (point))
10362 (or buffer (current-buffer)))
10363 (message "%s"
10364 (substitute-command-keys
10365 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10367 (defun org-mark-ring-goto (&optional n)
10368 "Jump to the previous position in the mark ring.
10369 With prefix arg N, jump back that many stored positions. When
10370 called several times in succession, walk through the entire ring.
10371 Org-mode commands jumping to a different position in the current file,
10372 or to another Org-mode file, automatically push the old position
10373 onto the ring."
10374 (interactive "p")
10375 (let (p m)
10376 (if (eq last-command this-command)
10377 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10378 (setq p org-mark-ring))
10379 (setq org-mark-ring-last-goto p)
10380 (setq m (car p))
10381 (org-pop-to-buffer-same-window (marker-buffer m))
10382 (goto-char m)
10383 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10385 (defun org-remove-angle-brackets (s)
10386 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10387 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10389 (defun org-add-angle-brackets (s)
10390 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10391 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10393 (defun org-remove-double-quotes (s)
10394 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10395 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10398 ;;; Following specific links
10400 (defun org-follow-timestamp-link ()
10401 (cond
10402 ((org-at-date-range-p t)
10403 (let ((org-agenda-start-on-weekday)
10404 (t1 (match-string 1))
10405 (t2 (match-string 2)))
10406 (setq t1 (time-to-days (org-time-string-to-time t1))
10407 t2 (time-to-days (org-time-string-to-time t2)))
10408 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10409 ((org-at-timestamp-p t)
10410 (org-agenda-list nil (time-to-days (org-time-string-to-time
10411 (substring (match-string 1) 0 10)))
10413 (t (error "This should not happen"))))
10416 ;;; Following file links
10417 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10418 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10419 (declare-function mailcap-mime-info
10420 "mailcap" (string &optional request no-decode))
10421 (defvar org-wait nil)
10422 (defun org-open-file (path &optional in-emacs line search)
10423 "Open the file at PATH.
10424 First, this expands any special file name abbreviations. Then the
10425 configuration variable `org-file-apps' is checked if it contains an
10426 entry for this file type, and if yes, the corresponding command is launched.
10428 If no application is found, Emacs simply visits the file.
10430 With optional prefix argument IN-EMACS, Emacs will visit the file.
10431 With a double \\[universal-argument] \\[universal-argument] \
10432 prefix arg, Org tries to avoid opening in Emacs
10433 and to use an external application to visit the file.
10435 Optional LINE specifies a line to go to, optional SEARCH a string
10436 to search for. If LINE or SEARCH is given, the file will be
10437 opened in Emacs, unless an entry from org-file-apps that makes
10438 use of groups in a regexp matches.
10440 If you want to change the way frames are used when following a
10441 link, please customize `org-link-frame-setup'.
10443 If the file does not exist, an error is thrown."
10444 (let* ((file (if (equal path "")
10445 buffer-file-name
10446 (substitute-in-file-name (expand-file-name path))))
10447 (file-apps (append org-file-apps (org-default-apps)))
10448 (apps (org-remove-if
10449 'org-file-apps-entry-match-against-dlink-p file-apps))
10450 (apps-dlink (org-remove-if-not
10451 'org-file-apps-entry-match-against-dlink-p file-apps))
10452 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10453 (dirp (if remp nil (file-directory-p file)))
10454 (file (if (and dirp org-open-directory-means-index-dot-org)
10455 (concat (file-name-as-directory file) "index.org")
10456 file))
10457 (a-m-a-p (assq 'auto-mode apps))
10458 (dfile (downcase file))
10459 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10460 (link (cond ((and (eq line nil)
10461 (eq search nil))
10462 file)
10463 (line
10464 (concat file "::" (number-to-string line)))
10465 (search
10466 (concat file "::" search))))
10467 (dlink (downcase link))
10468 (old-buffer (current-buffer))
10469 (old-pos (point))
10470 (old-mode major-mode)
10471 ext cmd link-match-data)
10472 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10473 (setq ext (match-string 1 dfile))
10474 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10475 (setq ext (match-string 1 dfile))))
10476 (cond
10477 ((member in-emacs '((16) system))
10478 (setq cmd (cdr (assoc 'system apps))))
10479 (in-emacs (setq cmd 'emacs))
10481 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10482 (and dirp (cdr (assoc 'directory apps)))
10483 ; first, try matching against apps-dlink
10484 ; if we get a match here, store the match data for later
10485 (let ((match (assoc-default dlink apps-dlink
10486 'string-match)))
10487 (if match
10488 (progn (setq link-match-data (match-data))
10489 match)
10490 (progn (setq in-emacs (or in-emacs line search))
10491 nil))) ; if we have no match in apps-dlink,
10492 ; always open the file in emacs if line or search
10493 ; is given (for backwards compatibility)
10494 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10495 'string-match)
10496 (cdr (assoc ext apps))
10497 (cdr (assoc t apps))))))
10498 (when (eq cmd 'system)
10499 (setq cmd (cdr (assoc 'system apps))))
10500 (when (eq cmd 'default)
10501 (setq cmd (cdr (assoc t apps))))
10502 (when (eq cmd 'mailcap)
10503 (require 'mailcap)
10504 (mailcap-parse-mailcaps)
10505 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10506 (command (mailcap-mime-info mime-type)))
10507 (if (stringp command)
10508 (setq cmd command)
10509 (setq cmd 'emacs))))
10510 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10511 (not (file-exists-p file))
10512 (not org-open-non-existing-files))
10513 (error "No such file: %s" file))
10514 (cond
10515 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10516 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10517 (while (string-match "['\"]%s['\"]" cmd)
10518 (setq cmd (replace-match "%s" t t cmd)))
10519 (while (string-match "%s" cmd)
10520 (setq cmd (replace-match
10521 (save-match-data
10522 (shell-quote-argument
10523 (convert-standard-filename file)))
10524 t t cmd)))
10526 ;; Replace "%1", "%2" etc. in command with group matches from regex
10527 (save-match-data
10528 (let ((match-index 1)
10529 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10530 (set-match-data link-match-data)
10531 (while (<= match-index number-of-groups)
10532 (let ((regex (concat "%" (number-to-string match-index)))
10533 (replace-with (match-string match-index dlink)))
10534 (while (string-match regex cmd)
10535 (setq cmd (replace-match replace-with t t cmd))))
10536 (setq match-index (+ match-index 1)))))
10538 (save-window-excursion
10539 (message "Running %s...done" cmd)
10540 (start-process-shell-command cmd nil cmd)
10541 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10542 ((or (stringp cmd)
10543 (eq cmd 'emacs))
10544 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10545 (widen)
10546 (if line (org-goto-line line)
10547 (if search (org-link-search search))))
10548 ((consp cmd)
10549 (let ((file (convert-standard-filename file)))
10550 (save-match-data
10551 (set-match-data link-match-data)
10552 (eval cmd))))
10553 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10554 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10555 (or (not (equal old-buffer (current-buffer)))
10556 (not (equal old-pos (point))))
10557 (org-mark-ring-push old-pos old-buffer))))
10559 (defun org-file-apps-entry-match-against-dlink-p (entry)
10560 "This function returns non-nil if `entry' uses a regular
10561 expression which should be matched against the whole link by
10562 org-open-file.
10564 It assumes that is the case when the entry uses a regular
10565 expression which has at least one grouping construct and the
10566 action is either a lisp form or a command string containing
10567 '%1', i.e. using at least one subexpression match as a
10568 parameter."
10569 (let ((selector (car entry))
10570 (action (cdr entry)))
10571 (if (stringp selector)
10572 (and (> (regexp-opt-depth selector) 0)
10573 (or (and (stringp action)
10574 (string-match "%[0-9]" action))
10575 (consp action)))
10576 nil)))
10578 (defun org-default-apps ()
10579 "Return the default applications for this operating system."
10580 (cond
10581 ((eq system-type 'darwin)
10582 org-file-apps-defaults-macosx)
10583 ((eq system-type 'windows-nt)
10584 org-file-apps-defaults-windowsnt)
10585 (t org-file-apps-defaults-gnu)))
10587 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10588 "Convert extensions to regular expressions in the cars of LIST.
10589 Also, weed out any non-string entries, because the return value is used
10590 only for regexp matching.
10591 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10592 point to the symbol `emacs', indicating that the file should
10593 be opened in Emacs."
10594 (append
10595 (delq nil
10596 (mapcar (lambda (x)
10597 (if (not (stringp (car x)))
10599 (if (string-match "\\W" (car x))
10601 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10602 list))
10603 (if add-auto-mode
10604 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10606 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10607 (defun org-file-remote-p (file)
10608 "Test whether FILE specifies a location on a remote system.
10609 Return non-nil if the location is indeed remote.
10611 For example, the filename \"/user@host:/foo\" specifies a location
10612 on the system \"/user@host:\"."
10613 (cond ((fboundp 'file-remote-p)
10614 (file-remote-p file))
10615 ((fboundp 'tramp-handle-file-remote-p)
10616 (tramp-handle-file-remote-p file))
10617 ((and (boundp 'ange-ftp-name-format)
10618 (string-match (car ange-ftp-name-format) file))
10619 t)))
10622 ;;;; Refiling
10624 (defun org-get-org-file ()
10625 "Read a filename, with default directory `org-directory'."
10626 (let ((default (or org-default-notes-file remember-data-file)))
10627 (read-file-name (format "File name [%s]: " default)
10628 (file-name-as-directory org-directory)
10629 default)))
10631 (defun org-notes-order-reversed-p ()
10632 "Check if the current file should receive notes in reversed order."
10633 (cond
10634 ((not org-reverse-note-order) nil)
10635 ((eq t org-reverse-note-order) t)
10636 ((not (listp org-reverse-note-order)) nil)
10637 (t (catch 'exit
10638 (let ((all org-reverse-note-order)
10639 entry)
10640 (while (setq entry (pop all))
10641 (if (string-match (car entry) buffer-file-name)
10642 (throw 'exit (cdr entry))))
10643 nil)))))
10645 (defvar org-refile-target-table nil
10646 "The list of refile targets, created by `org-refile'.")
10648 (defvar org-agenda-new-buffers nil
10649 "Buffers created to visit agenda files.")
10651 (defvar org-refile-cache nil
10652 "Cache for refile targets.")
10654 (defvar org-refile-markers nil
10655 "All the markers used for caching refile locations.")
10657 (defun org-refile-marker (pos)
10658 "Get a new refile marker, but only if caching is in use."
10659 (if (not org-refile-use-cache)
10661 (let ((m (make-marker)))
10662 (move-marker m pos)
10663 (push m org-refile-markers)
10664 m)))
10666 (defun org-refile-cache-clear ()
10667 "Clear the refile cache and disable all the markers."
10668 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10669 (setq org-refile-markers nil)
10670 (setq org-refile-cache nil)
10671 (message "Refile cache has been cleared"))
10673 (defun org-refile-cache-check-set (set)
10674 "Check if all the markers in the cache still have live buffers."
10675 (let (marker)
10676 (catch 'exit
10677 (while (and set (setq marker (nth 3 (pop set))))
10678 ;; if org-refile-use-outline-path is 'file, marker may be nil
10679 (when (and marker (null (marker-buffer marker)))
10680 (message "not found") (sit-for 3)
10681 (throw 'exit nil)))
10682 t)))
10684 (defun org-refile-cache-put (set &rest identifiers)
10685 "Push the refile targets SET into the cache, under IDENTIFIERS."
10686 (let* ((key (sha1 (prin1-to-string identifiers)))
10687 (entry (assoc key org-refile-cache)))
10688 (if entry
10689 (setcdr entry set)
10690 (push (cons key set) org-refile-cache))))
10692 (defun org-refile-cache-get (&rest identifiers)
10693 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10694 (cond
10695 ((not org-refile-cache) nil)
10696 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10698 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10699 org-refile-cache))))
10700 (and set (org-refile-cache-check-set set) set)))))
10702 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10703 "Produce a table with refile targets."
10704 (let ((case-fold-search nil)
10705 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10706 (entries (or org-refile-targets '((nil . (:level . 1)))))
10707 targets tgs txt re files f desc descre fast-path-p level pos0)
10708 (message "Getting targets...")
10709 (with-current-buffer (or default-buffer (current-buffer))
10710 (while (setq entry (pop entries))
10711 (setq files (car entry) desc (cdr entry))
10712 (setq fast-path-p nil)
10713 (cond
10714 ((null files) (setq files (list (current-buffer))))
10715 ((eq files 'org-agenda-files)
10716 (setq files (org-agenda-files 'unrestricted)))
10717 ((and (symbolp files) (fboundp files))
10718 (setq files (funcall files)))
10719 ((and (symbolp files) (boundp files))
10720 (setq files (symbol-value files))))
10721 (if (stringp files) (setq files (list files)))
10722 (cond
10723 ((eq (car desc) :tag)
10724 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10725 ((eq (car desc) :todo)
10726 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10727 ((eq (car desc) :regexp)
10728 (setq descre (cdr desc)))
10729 ((eq (car desc) :level)
10730 (setq descre (concat "^\\*\\{" (number-to-string
10731 (if org-odd-levels-only
10732 (1- (* 2 (cdr desc)))
10733 (cdr desc)))
10734 "\\}[ \t]")))
10735 ((eq (car desc) :maxlevel)
10736 (setq fast-path-p t)
10737 (setq descre (concat "^\\*\\{1," (number-to-string
10738 (if org-odd-levels-only
10739 (1- (* 2 (cdr desc)))
10740 (cdr desc)))
10741 "\\}[ \t]")))
10742 (t (error "Bad refiling target description %s" desc)))
10743 (while (setq f (pop files))
10744 (with-current-buffer
10745 (if (bufferp f) f (org-get-agenda-file-buffer f))
10747 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10748 (progn
10749 (if (bufferp f) (setq f (buffer-file-name
10750 (buffer-base-buffer f))))
10751 (setq f (and f (expand-file-name f)))
10752 (if (eq org-refile-use-outline-path 'file)
10753 (push (list (file-name-nondirectory f) f nil nil) tgs))
10754 (save-excursion
10755 (save-restriction
10756 (widen)
10757 (goto-char (point-min))
10758 (while (re-search-forward descre nil t)
10759 (goto-char (setq pos0 (point-at-bol)))
10760 (catch 'next
10761 (when org-refile-target-verify-function
10762 (save-match-data
10763 (or (funcall org-refile-target-verify-function)
10764 (throw 'next t))))
10765 (when (and (looking-at org-complex-heading-regexp)
10766 (not (member (match-string 4) excluded-entries))
10767 (match-string 4))
10768 (setq level (org-reduced-level
10769 (- (match-end 1) (match-beginning 1)))
10770 txt (org-link-display-format (match-string 4))
10771 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10772 re (format org-complex-heading-regexp-format
10773 (regexp-quote (match-string 4))))
10774 (when org-refile-use-outline-path
10775 (setq txt (mapconcat
10776 'org-protect-slash
10777 (append
10778 (if (eq org-refile-use-outline-path
10779 'file)
10780 (list (file-name-nondirectory
10781 (buffer-file-name
10782 (buffer-base-buffer))))
10783 (if (eq org-refile-use-outline-path
10784 'full-file-path)
10785 (list (buffer-file-name
10786 (buffer-base-buffer)))))
10787 (org-get-outline-path fast-path-p
10788 level txt)
10789 (list txt))
10790 "/")))
10791 (push (list txt f re (org-refile-marker (point)))
10792 tgs)))
10793 (when (= (point) pos0)
10794 ;; verification function has not moved point
10795 (goto-char (point-at-eol))))))))
10796 (when org-refile-use-cache
10797 (org-refile-cache-put tgs (buffer-file-name) descre))
10798 (setq targets (append tgs targets))
10799 ))))
10800 (message "Getting targets...done")
10801 (nreverse targets)))
10803 (defun org-protect-slash (s)
10804 (while (string-match "/" s)
10805 (setq s (replace-match "\\" t t s)))
10808 (defvar org-olpa (make-vector 20 nil))
10810 (defun org-get-outline-path (&optional fastp level heading)
10811 "Return the outline path to the current entry, as a list.
10813 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10814 routine which makes outline path derivations for an entire file,
10815 avoiding backtracing. Refile target collection makes use of that."
10816 (if fastp
10817 (progn
10818 (if (> level 19)
10819 (error "Outline path failure, more than 19 levels"))
10820 (loop for i from level upto 19 do
10821 (aset org-olpa i nil))
10822 (prog1
10823 (delq nil (append org-olpa nil))
10824 (aset org-olpa level heading)))
10825 (let (rtn case-fold-search)
10826 (save-excursion
10827 (save-restriction
10828 (widen)
10829 (while (org-up-heading-safe)
10830 (when (looking-at org-complex-heading-regexp)
10831 (push (org-match-string-no-properties 4) rtn)))
10832 rtn)))))
10834 (defun org-format-outline-path (path &optional width prefix)
10835 "Format the outline path PATH for display.
10836 Width is the maximum number of characters that is available.
10837 Prefix is a prefix to be included in the returned string,
10838 such as the file name."
10839 (setq width (or width 79))
10840 (if prefix (setq width (- width (length prefix))))
10841 (if (not path)
10842 (or prefix "")
10843 (let* ((nsteps (length path))
10844 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10845 (maxwidth (if (<= total-width width)
10846 10000 ;; everything fits
10847 ;; we need to shorten the level headings
10848 (/ (- width nsteps) nsteps)))
10849 (org-odd-levels-only nil)
10850 (n 0)
10851 (total (1+ (length prefix))))
10852 (setq maxwidth (max maxwidth 10))
10853 (concat prefix
10854 (mapconcat
10855 (lambda (h)
10856 (setq n (1+ n))
10857 (if (and (= n nsteps) (< maxwidth 10000))
10858 (setq maxwidth (- total-width total)))
10859 (if (< (length h) maxwidth)
10860 (progn (setq total (+ total (length h) 1)) h)
10861 (setq h (substring h 0 (- maxwidth 2))
10862 total (+ total maxwidth 1))
10863 (if (string-match "[ \t]+\\'" h)
10864 (setq h (substring h 0 (match-beginning 0))))
10865 (setq h (concat h "..")))
10866 (org-add-props h nil 'face
10867 (nth (% (1- n) org-n-level-faces)
10868 org-level-faces))
10870 path "/")))))
10872 (defun org-display-outline-path (&optional file current)
10873 "Display the current outline path in the echo area."
10874 (interactive "P")
10875 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10876 (case-fold-search nil)
10877 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10878 (if current (setq path (append path
10879 (save-excursion
10880 (org-back-to-heading t)
10881 (if (looking-at org-complex-heading-regexp)
10882 (list (match-string 4)))))))
10883 (message "%s"
10884 (org-format-outline-path
10885 path
10886 (1- (frame-width))
10887 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10889 (defvar org-refile-history nil
10890 "History for refiling operations.")
10892 (defvar org-after-refile-insert-hook nil
10893 "Hook run after `org-refile' has inserted its stuff at the new location.
10894 Note that this is still *before* the stuff will be removed from
10895 the *old* location.")
10897 (defvar org-capture-last-stored-marker)
10898 (defvar org-refile-keep nil
10899 "Non-nil means `org-refile' will copy instead of refile.")
10901 (defun org-copy ()
10902 "Like `org-refile', but copy."
10903 (interactive)
10904 (let ((org-refile-keep t))
10905 (funcall 'org-refile nil nil nil "Copy")))
10907 (defun org-refile (&optional goto default-buffer rfloc msg)
10908 "Move the entry or entries at point to another heading.
10909 The list of target headings is compiled using the information in
10910 `org-refile-targets', which see.
10912 At the target location, the entry is filed as a subitem of the target
10913 heading. Depending on `org-reverse-note-order', the new subitem will
10914 either be the first or the last subitem.
10916 If there is an active region, all entries in that region will be moved.
10917 However, the region must fulfill the requirement that the first heading
10918 is the first one sets the top-level of the moved text - at most siblings
10919 below it are allowed.
10921 With prefix arg GOTO, the command will only visit the target location
10922 and not actually move anything.
10924 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10925 go to the location where the last refiling operation has put the subtree.
10926 With a prefix argument of `2', refile to the running clock.
10928 RFLOC can be a refile location obtained in a different way.
10930 MSG is a string to replace \"Refile\" in the default prompt with
10931 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10933 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10935 If you are using target caching (see `org-refile-use-cache'),
10936 you have to clear the target cache in order to find new targets.
10937 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10938 prefix argument (`C-u C-u C-u C-c C-w')."
10940 (interactive "P")
10941 (if (member goto '(0 (64)))
10942 (org-refile-cache-clear)
10943 (let* ((actionmsg (or msg "Refile"))
10944 (cbuf (current-buffer))
10945 (regionp (org-region-active-p))
10946 (region-start (and regionp (region-beginning)))
10947 (region-end (and regionp (region-end)))
10948 (region-length (and regionp (- region-end region-start)))
10949 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10950 pos it nbuf file re level reversed)
10951 (setq last-command nil)
10952 (when regionp
10953 (goto-char region-start)
10954 (or (bolp) (goto-char (point-at-bol)))
10955 (setq region-start (point))
10956 (unless (or (org-kill-is-subtree-p
10957 (buffer-substring region-start region-end))
10958 (prog1 org-refile-active-region-within-subtree
10959 (org-toggle-heading)))
10960 (error "The region is not a (sequence of) subtree(s)")))
10961 (if (equal goto '(16))
10962 (org-refile-goto-last-stored)
10963 (when (or
10964 (and (equal goto 2)
10965 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10966 (prog1
10967 (setq it (list (or org-clock-heading "running clock")
10968 (buffer-file-name
10969 (marker-buffer org-clock-hd-marker))
10971 (marker-position org-clock-hd-marker)))
10972 (setq goto nil)))
10973 (setq it (or rfloc
10974 (let (heading-text)
10975 (save-excursion
10976 (unless goto
10977 (org-back-to-heading t)
10978 (setq heading-text
10979 (nth 4 (org-heading-components))))
10981 (org-refile-get-location
10982 (cond (goto "Goto")
10983 (regionp (concat actionmsg " region to"))
10984 (t (concat actionmsg " subtree \""
10985 heading-text "\" to")))
10986 default-buffer
10987 (and (not (equal '(4) goto))
10988 org-refile-allow-creating-parent-nodes)
10989 goto))))))
10990 (setq file (nth 1 it)
10991 re (nth 2 it)
10992 pos (nth 3 it))
10993 (if (and (not goto)
10995 (equal (buffer-file-name) file)
10996 (if regionp
10997 (and (>= pos region-start)
10998 (<= pos region-end))
10999 (and (>= pos (point))
11000 (< pos (save-excursion
11001 (org-end-of-subtree t t))))))
11002 (error "Cannot refile to position inside the tree or region"))
11004 (setq nbuf (or (find-buffer-visiting file)
11005 (find-file-noselect file)))
11006 (if goto
11007 (progn
11008 (org-pop-to-buffer-same-window nbuf)
11009 (goto-char pos)
11010 (org-show-context 'org-goto))
11011 (if regionp
11012 (progn
11013 (org-kill-new (buffer-substring region-start region-end))
11014 (org-save-markers-in-region region-start region-end))
11015 (org-copy-subtree 1 nil t))
11016 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11017 (find-file-noselect file)))
11018 (setq reversed (org-notes-order-reversed-p))
11019 (save-excursion
11020 (save-restriction
11021 (widen)
11022 (if pos
11023 (progn
11024 (goto-char pos)
11025 (looking-at org-outline-regexp)
11026 (setq level (org-get-valid-level (funcall outline-level) 1))
11027 (goto-char
11028 (if reversed
11029 (or (outline-next-heading) (point-max))
11030 (or (save-excursion (org-get-next-sibling))
11031 (org-end-of-subtree t t)
11032 (point-max)))))
11033 (setq level 1)
11034 (if (not reversed)
11035 (goto-char (point-max))
11036 (goto-char (point-min))
11037 (or (outline-next-heading) (goto-char (point-max)))))
11038 (if (not (bolp)) (newline))
11039 (org-paste-subtree level)
11040 (when org-log-refile
11041 (org-add-log-setup 'refile nil nil 'findpos
11042 org-log-refile)
11043 (unless (eq org-log-refile 'note)
11044 (save-excursion (org-add-log-note))))
11045 (and org-auto-align-tags
11046 (let ((org-loop-over-headlines-in-active-region nil))
11047 (org-set-tags nil t)))
11048 (bookmark-set "org-refile-last-stored")
11049 ;; If we are refiling for capture, make sure that the
11050 ;; last-capture pointers point here
11051 (when (org-bound-and-true-p org-refile-for-capture)
11052 (bookmark-set "org-capture-last-stored-marker")
11053 (move-marker org-capture-last-stored-marker (point)))
11054 (if (fboundp 'deactivate-mark) (deactivate-mark))
11055 (run-hooks 'org-after-refile-insert-hook))))
11056 (unless org-refile-keep
11057 (if regionp
11058 (delete-region (point) (+ (point) region-length))
11059 (org-cut-subtree)))
11060 (when (featurep 'org-inlinetask)
11061 (org-inlinetask-remove-END-maybe))
11062 (setq org-markers-to-move nil)
11063 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11065 (defun org-refile-goto-last-stored ()
11066 "Go to the location where the last refile was stored."
11067 (interactive)
11068 (bookmark-jump "org-refile-last-stored")
11069 (message "This is the location of the last refile"))
11071 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11072 no-exclude)
11073 "Prompt the user for a refile location, using PROMPT.
11074 PROMPT should not be suffixed with a colon and a space, because
11075 this function appends the default value from
11076 `org-refile-history' automatically, if that is not empty.
11077 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11078 this is used for the GOTO interface."
11079 (let ((org-refile-targets org-refile-targets)
11080 (org-refile-use-outline-path org-refile-use-outline-path)
11081 excluded-entries)
11082 (when (and (derived-mode-p 'org-mode)
11083 (not org-refile-use-cache)
11084 (not no-exclude))
11085 (org-map-tree
11086 (lambda()
11087 (setq excluded-entries
11088 (append excluded-entries (list (org-get-heading t t)))))))
11089 (setq org-refile-target-table
11090 (org-refile-get-targets default-buffer excluded-entries)))
11091 (unless org-refile-target-table
11092 (error "No refile targets"))
11093 (let* ((cbuf (current-buffer))
11094 (partial-completion-mode nil)
11095 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11096 (cfunc (if (and org-refile-use-outline-path
11097 org-outline-path-complete-in-steps)
11098 'org-olpath-completing-read
11099 'org-icompleting-read))
11100 (extra (if org-refile-use-outline-path "/" ""))
11101 (cbnex (concat (buffer-name) extra))
11102 (filename (and cfn (expand-file-name cfn)))
11103 (tbl (mapcar
11104 (lambda (x)
11105 (if (and (not (member org-refile-use-outline-path
11106 '(file full-file-path)))
11107 (not (equal filename (nth 1 x))))
11108 (cons (concat (car x) extra " ("
11109 (file-name-nondirectory (nth 1 x)) ")")
11110 (cdr x))
11111 (cons (concat (car x) extra) (cdr x))))
11112 org-refile-target-table))
11113 (completion-ignore-case t)
11114 cdef
11115 (prompt (concat prompt
11116 (or (and (car org-refile-history)
11117 (concat " (default " (car org-refile-history) ")"))
11118 (and (assoc cbnex tbl) (setq cdef cbnex)
11119 (concat " (default " cbnex ")"))) ": "))
11120 pa answ parent-target child parent old-hist)
11121 (setq old-hist org-refile-history)
11122 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11123 nil 'org-refile-history (or cdef (car org-refile-history))))
11124 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11125 (org-refile-check-position pa)
11126 (if pa
11127 (progn
11128 (when (or (not org-refile-history)
11129 (not (eq old-hist org-refile-history))
11130 (not (equal (car pa) (car org-refile-history))))
11131 (setq org-refile-history
11132 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11133 org-refile-history
11134 (cdr org-refile-history))))
11135 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11136 (pop org-refile-history)))
11138 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11139 (progn
11140 (setq parent (match-string 1 answ)
11141 child (match-string 2 answ))
11142 (setq parent-target (or (assoc parent tbl)
11143 (assoc (concat parent "/") tbl)))
11144 (when (and parent-target
11145 (or (eq new-nodes t)
11146 (and (eq new-nodes 'confirm)
11147 (y-or-n-p (format "Create new node \"%s\"? "
11148 child)))))
11149 (org-refile-new-child parent-target child)))
11150 (error "Invalid target location")))))
11152 (declare-function org-string-nw-p "org-macs.el" (s))
11153 (defun org-refile-check-position (refile-pointer)
11154 "Check if the refile pointer matches the readline to which it points."
11155 (let* ((file (nth 1 refile-pointer))
11156 (re (nth 2 refile-pointer))
11157 (pos (nth 3 refile-pointer))
11158 buffer)
11159 (when (org-string-nw-p re)
11160 (setq buffer (if (markerp pos)
11161 (marker-buffer pos)
11162 (or (find-buffer-visiting file)
11163 (find-file-noselect file))))
11164 (with-current-buffer buffer
11165 (save-excursion
11166 (save-restriction
11167 (widen)
11168 (goto-char pos)
11169 (beginning-of-line 1)
11170 (unless (org-looking-at-p re)
11171 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11173 (defun org-refile-new-child (parent-target child)
11174 "Use refile target PARENT-TARGET to add new CHILD below it."
11175 (unless parent-target
11176 (error "Cannot find parent for new node"))
11177 (let ((file (nth 1 parent-target))
11178 (pos (nth 3 parent-target))
11179 level)
11180 (with-current-buffer (or (find-buffer-visiting file)
11181 (find-file-noselect file))
11182 (save-excursion
11183 (save-restriction
11184 (widen)
11185 (if pos
11186 (goto-char pos)
11187 (goto-char (point-max))
11188 (if (not (bolp)) (newline)))
11189 (when (looking-at org-outline-regexp)
11190 (setq level (funcall outline-level))
11191 (org-end-of-subtree t t))
11192 (org-back-over-empty-lines)
11193 (insert "\n" (make-string
11194 (if pos (org-get-valid-level level 1) 1) ?*)
11195 " " child "\n")
11196 (beginning-of-line 0)
11197 (list (concat (car parent-target) "/" child) file "" (point)))))))
11199 (defun org-olpath-completing-read (prompt collection &rest args)
11200 "Read an outline path like a file name."
11201 (let ((thetable collection)
11202 (org-completion-use-ido nil) ; does not work with ido.
11203 (org-completion-use-iswitchb nil)) ; or iswitchb
11204 (apply
11205 'org-icompleting-read prompt
11206 (lambda (string predicate &optional flag)
11207 (let (rtn r f (l (length string)))
11208 (cond
11209 ((eq flag nil)
11210 ;; try completion
11211 (try-completion string thetable))
11212 ((eq flag t)
11213 ;; all-completions
11214 (setq rtn (all-completions string thetable predicate))
11215 (mapcar
11216 (lambda (x)
11217 (setq r (substring x l))
11218 (if (string-match " ([^)]*)$" x)
11219 (setq f (match-string 0 x))
11220 (setq f ""))
11221 (if (string-match "/" r)
11222 (concat string (substring r 0 (match-end 0)) f)
11224 rtn))
11225 ((eq flag 'lambda)
11226 ;; exact match?
11227 (assoc string thetable)))))
11228 args)))
11230 ;;;; Dynamic blocks
11232 (defun org-find-dblock (name)
11233 "Find the first dynamic block with name NAME in the buffer.
11234 If not found, stay at current position and return nil."
11235 (let ((case-fold-search t) pos)
11236 (save-excursion
11237 (goto-char (point-min))
11238 (setq pos (and (re-search-forward
11239 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11240 (match-beginning 0))))
11241 (if pos (goto-char pos))
11242 pos))
11244 (defconst org-dblock-start-re
11245 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11246 "Matches the start line of a dynamic block, with parameters.")
11248 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11249 "Matches the end of a dynamic block.")
11251 (defun org-create-dblock (plist)
11252 "Create a dynamic block section, with parameters taken from PLIST.
11253 PLIST must contain a :name entry which is used as name of the block."
11254 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11255 (end-of-line 1)
11256 (newline))
11257 (let ((col (current-column))
11258 (name (plist-get plist :name)))
11259 (insert "#+BEGIN: " name)
11260 (while plist
11261 (if (eq (car plist) :name)
11262 (setq plist (cddr plist))
11263 (insert " " (prin1-to-string (pop plist)))))
11264 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11265 (beginning-of-line -2)))
11267 (defun org-prepare-dblock ()
11268 "Prepare dynamic block for refresh.
11269 This empties the block, puts the cursor at the insert position and returns
11270 the property list including an extra property :name with the block name."
11271 (unless (looking-at org-dblock-start-re)
11272 (error "Not at a dynamic block"))
11273 (let* ((begdel (1+ (match-end 0)))
11274 (name (org-no-properties (match-string 1)))
11275 (params (append (list :name name)
11276 (read (concat "(" (match-string 3) ")")))))
11277 (save-excursion
11278 (beginning-of-line 1)
11279 (skip-chars-forward " \t")
11280 (setq params (plist-put params :indentation-column (current-column))))
11281 (unless (re-search-forward org-dblock-end-re nil t)
11282 (error "Dynamic block not terminated"))
11283 (setq params
11284 (append params
11285 (list :content (buffer-substring
11286 begdel (match-beginning 0)))))
11287 (delete-region begdel (match-beginning 0))
11288 (goto-char begdel)
11289 (open-line 1)
11290 params))
11292 (defun org-map-dblocks (&optional command)
11293 "Apply COMMAND to all dynamic blocks in the current buffer.
11294 If COMMAND is not given, use `org-update-dblock'."
11295 (let ((cmd (or command 'org-update-dblock)))
11296 (save-excursion
11297 (goto-char (point-min))
11298 (while (re-search-forward org-dblock-start-re nil t)
11299 (goto-char (match-beginning 0))
11300 (save-excursion
11301 (condition-case nil
11302 (funcall cmd)
11303 (error (message "Error during update of dynamic block"))))
11304 (unless (re-search-forward org-dblock-end-re nil t)
11305 (error "Dynamic block not terminated"))))))
11307 (defun org-dblock-update (&optional arg)
11308 "User command for updating dynamic blocks.
11309 Update the dynamic block at point. With prefix ARG, update all dynamic
11310 blocks in the buffer."
11311 (interactive "P")
11312 (if arg
11313 (org-update-all-dblocks)
11314 (or (looking-at org-dblock-start-re)
11315 (org-beginning-of-dblock))
11316 (org-update-dblock)))
11318 (defun org-update-dblock ()
11319 "Update the dynamic block at point.
11320 This means to empty the block, parse for parameters and then call
11321 the correct writing function."
11322 (interactive)
11323 (save-window-excursion
11324 (let* ((pos (point))
11325 (line (org-current-line))
11326 (params (org-prepare-dblock))
11327 (name (plist-get params :name))
11328 (indent (plist-get params :indentation-column))
11329 (cmd (intern (concat "org-dblock-write:" name))))
11330 (message "Updating dynamic block `%s' at line %d..." name line)
11331 (funcall cmd params)
11332 (message "Updating dynamic block `%s' at line %d...done" name line)
11333 (goto-char pos)
11334 (when (and indent (> indent 0))
11335 (setq indent (make-string indent ?\ ))
11336 (save-excursion
11337 (org-beginning-of-dblock)
11338 (forward-line 1)
11339 (while (not (looking-at org-dblock-end-re))
11340 (insert indent)
11341 (beginning-of-line 2))
11342 (when (looking-at org-dblock-end-re)
11343 (and (looking-at "[ \t]+")
11344 (replace-match ""))
11345 (insert indent)))))))
11347 (defun org-beginning-of-dblock ()
11348 "Find the beginning of the dynamic block at point.
11349 Error if there is no such block at point."
11350 (let ((pos (point))
11351 beg)
11352 (end-of-line 1)
11353 (if (and (re-search-backward org-dblock-start-re nil t)
11354 (setq beg (match-beginning 0))
11355 (re-search-forward org-dblock-end-re nil t)
11356 (> (match-end 0) pos))
11357 (goto-char beg)
11358 (goto-char pos)
11359 (error "Not in a dynamic block"))))
11361 ;;;###autoload
11362 (defun org-update-all-dblocks ()
11363 "Update all dynamic blocks in the buffer.
11364 This function can be used in a hook."
11365 (interactive)
11366 (when (derived-mode-p 'org-mode)
11367 (org-map-dblocks 'org-update-dblock)))
11370 ;;;; Completion
11372 (defconst org-additional-option-like-keywords
11373 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11374 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11375 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11376 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11377 "BEGIN:" "END:"
11378 "ORGTBL" "TBLFM:" "TBLNAME:"
11379 "BEGIN_EXAMPLE" "END_EXAMPLE"
11380 "BEGIN_VERBATIM" "END_VERBATIM"
11381 "BEGIN_QUOTE" "END_QUOTE"
11382 "BEGIN_VERSE" "END_VERSE"
11383 "BEGIN_CENTER" "END_CENTER"
11384 "BEGIN_SRC" "END_SRC"
11385 "BEGIN_RESULT" "END_RESULT"
11386 "BEGIN_lstlisting" "END_lstlisting"
11387 "NAME:" "RESULTS:"
11388 "HEADER:" "HEADERS:"
11389 "COLUMNS:" "PROPERTY:"
11390 "CAPTION:" "LABEL:"
11391 "SETUPFILE:"
11392 "INCLUDE:"
11393 "BIND:"
11394 "MACRO:"))
11396 (defconst org-options-keywords
11397 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11398 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11399 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11400 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11401 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11402 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11403 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11405 (defconst org-additional-option-like-keywords-for-flyspell
11406 (delete-dups
11407 (split-string
11408 (mapconcat (lambda(k)
11409 (replace-regexp-in-string
11410 "_\\|:" " "
11411 (concat k " " (downcase k) " " (upcase k))))
11412 (append org-options-keywords org-additional-option-like-keywords)
11413 " ")
11414 " +" t)))
11416 (defcustom org-structure-template-alist
11418 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11419 "<src lang=\"?\">\n\n</src>")
11420 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11421 "<example>\n?\n</example>")
11422 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11423 "<quote>\n?\n</quote>")
11424 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11425 "<verse>\n?\n</verse>")
11426 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11427 "<center>\n?\n</center>")
11428 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11429 "<literal style=\"latex\">\n?\n</literal>")
11430 ("L" "#+LaTeX: "
11431 "<literal style=\"latex\">?</literal>")
11432 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11433 "<literal style=\"html\">\n?\n</literal>")
11434 ("H" "#+HTML: "
11435 "<literal style=\"html\">?</literal>")
11436 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11437 ("A" "#+ASCII: ")
11438 ("i" "#+INDEX: ?"
11439 "#+INDEX: ?")
11440 ("I" "#+INCLUDE: %file ?"
11441 "<include file=%file markup=\"?\">")
11443 "Structure completion elements.
11444 This is a list of abbreviation keys and values. The value gets inserted
11445 if you type `<' followed by the key and then press the completion key,
11446 usually `M-TAB'. %file will be replaced by a file name after prompting
11447 for the file using completion. The cursor will be placed at the position
11448 of the `?` in the template.
11449 There are two templates for each key, the first uses the original Org syntax,
11450 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11451 the default when the /org-mtags.el/ module has been loaded. See also the
11452 variable `org-mtags-prefer-muse-templates'."
11453 :group 'org-completion
11454 :type '(repeat
11455 (string :tag "Key")
11456 (string :tag "Template")
11457 (string :tag "Muse Template")))
11459 (defun org-try-structure-completion ()
11460 "Try to complete a structure template before point.
11461 This looks for strings like \"<e\" on an otherwise empty line and
11462 expands them."
11463 (let ((l (buffer-substring (point-at-bol) (point)))
11465 (when (and (looking-at "[ \t]*$")
11466 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11467 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11468 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11469 (match-beginning 1)) a)
11470 t)))
11472 (defun org-complete-expand-structure-template (start cell)
11473 "Expand a structure template."
11474 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11475 (rpl (nth (if musep 2 1) cell))
11476 (ind ""))
11477 (delete-region start (point))
11478 (when (string-match "\\`#\\+" rpl)
11479 (cond
11480 ((bolp))
11481 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11482 (setq ind (buffer-substring (point-at-bol) (point))))
11483 (t (newline))))
11484 (setq start (point))
11485 (if (string-match "%file" rpl)
11486 (setq rpl (replace-match
11487 (concat
11488 "\""
11489 (save-match-data
11490 (abbreviate-file-name (read-file-name "Include file: ")))
11491 "\"")
11492 t t rpl)))
11493 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11494 (concat "\n" ind)))
11495 (insert rpl)
11496 (if (re-search-backward "\\?" start t) (delete-char 1))))
11498 ;;;; TODO, DEADLINE, Comments
11500 (defun org-toggle-comment ()
11501 "Change the COMMENT state of an entry."
11502 (interactive)
11503 (save-excursion
11504 (org-back-to-heading)
11505 (let (case-fold-search)
11506 (cond
11507 ((looking-at (format org-heading-keyword-regexp-format
11508 org-comment-string))
11509 (goto-char (match-end 1))
11510 (looking-at (concat " +" org-comment-string))
11511 (replace-match "" t t)
11512 (when (eolp) (insert " ")))
11513 ((looking-at org-outline-regexp)
11514 (goto-char (match-end 0))
11515 (insert org-comment-string " "))))))
11517 (defvar org-last-todo-state-is-todo nil
11518 "This is non-nil when the last TODO state change led to a TODO state.
11519 If the last change removed the TODO tag or switched to DONE, then
11520 this is nil.")
11522 (defvar org-setting-tags nil) ; dynamically skipped
11524 (defvar org-todo-setup-filter-hook nil
11525 "Hook for functions that pre-filter todo specs.
11526 Each function takes a todo spec and returns either nil or the spec
11527 transformed into canonical form." )
11529 (defvar org-todo-get-default-hook nil
11530 "Hook for functions that get a default item for todo.
11531 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11532 nil or a string to be used for the todo mark." )
11534 (defvar org-agenda-headline-snapshot-before-repeat)
11536 (defun org-current-effective-time ()
11537 "Return current time adjusted for `org-extend-today-until' variable."
11538 (let* ((ct (org-current-time))
11539 (dct (decode-time ct))
11540 (ct1
11541 (cond
11542 (org-use-last-clock-out-time-as-effective-time
11543 (or (org-clock-get-last-clock-out-time) ct))
11544 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11545 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11546 (t ct))))
11547 ct1))
11549 (defun org-todo-yesterday (&optional arg)
11550 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11551 (interactive "P")
11552 (if (eq major-mode 'org-agenda-mode)
11553 (apply 'org-agenda-todo-yesterday arg)
11554 (let* ((hour (third (decode-time
11555 (org-current-time))))
11556 (org-extend-today-until (1+ hour)))
11557 (org-todo arg))))
11559 (defun org-todo (&optional arg)
11560 "Change the TODO state of an item.
11561 The state of an item is given by a keyword at the start of the heading,
11562 like
11563 *** TODO Write paper
11564 *** DONE Call mom
11566 The different keywords are specified in the variable `org-todo-keywords'.
11567 By default the available states are \"TODO\" and \"DONE\".
11568 So for this example: when the item starts with TODO, it is changed to DONE.
11569 When it starts with DONE, the DONE is removed. And when neither TODO nor
11570 DONE are present, add TODO at the beginning of the heading.
11572 With \\[universal-argument] prefix arg, use completion to determine the new \
11573 state.
11574 With numeric prefix arg, switch to that state.
11575 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11576 keywords (nextset).
11577 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11578 With a numeric prefix arg of 0, inhibit note taking for the change.
11580 For calling through lisp, arg is also interpreted in the following way:
11581 'none -> empty state
11582 \"\"(empty string) -> switch to empty state
11583 'done -> switch to DONE
11584 'nextset -> switch to the next set of keywords
11585 'previousset -> switch to the previous set of keywords
11586 \"WAITING\" -> switch to the specified keyword, but only if it
11587 really is a member of `org-todo-keywords'."
11588 (interactive "P")
11589 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11590 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11591 'region-start-level 'region))
11592 org-loop-over-headlines-in-active-region)
11593 (org-map-entries
11594 `(org-todo ,arg)
11595 org-loop-over-headlines-in-active-region
11596 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11597 (if (equal arg '(16)) (setq arg 'nextset))
11598 (let ((org-blocker-hook org-blocker-hook)
11599 (case-fold-search nil))
11600 (when (equal arg '(64))
11601 (setq arg nil org-blocker-hook nil))
11602 (when (and org-blocker-hook
11603 (or org-inhibit-blocking
11604 (org-entry-get nil "NOBLOCKING")))
11605 (setq org-blocker-hook nil))
11606 (save-excursion
11607 (catch 'exit
11608 (org-back-to-heading t)
11609 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11610 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11611 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11612 (let* ((match-data (match-data))
11613 (startpos (point-at-bol))
11614 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11615 (org-log-done org-log-done)
11616 (org-log-repeat org-log-repeat)
11617 (org-todo-log-states org-todo-log-states)
11618 (org-inhibit-logging
11619 (if (equal arg 0)
11620 (progn (setq arg nil) 'note) org-inhibit-logging))
11621 (this (match-string 1))
11622 (hl-pos (match-beginning 0))
11623 (head (org-get-todo-sequence-head this))
11624 (ass (assoc head org-todo-kwd-alist))
11625 (interpret (nth 1 ass))
11626 (done-word (nth 3 ass))
11627 (final-done-word (nth 4 ass))
11628 (org-last-state (or this ""))
11629 (completion-ignore-case t)
11630 (member (member this org-todo-keywords-1))
11631 (tail (cdr member))
11632 (org-state (cond
11633 ((and org-todo-key-trigger
11634 (or (and (equal arg '(4))
11635 (eq org-use-fast-todo-selection 'prefix))
11636 (and (not arg) org-use-fast-todo-selection
11637 (not (eq org-use-fast-todo-selection
11638 'prefix)))))
11639 ;; Use fast selection
11640 (org-fast-todo-selection))
11641 ((and (equal arg '(4))
11642 (or (not org-use-fast-todo-selection)
11643 (not org-todo-key-trigger)))
11644 ;; Read a state with completion
11645 (org-icompleting-read
11646 "State: " (mapcar (lambda(x) (list x))
11647 org-todo-keywords-1)
11648 nil t))
11649 ((eq arg 'right)
11650 (if this
11651 (if tail (car tail) nil)
11652 (car org-todo-keywords-1)))
11653 ((eq arg 'left)
11654 (if (equal member org-todo-keywords-1)
11656 (if this
11657 (nth (- (length org-todo-keywords-1)
11658 (length tail) 2)
11659 org-todo-keywords-1)
11660 (org-last org-todo-keywords-1))))
11661 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11662 (setq arg nil))) ; hack to fall back to cycling
11663 (arg
11664 ;; user or caller requests a specific state
11665 (cond
11666 ((equal arg "") nil)
11667 ((eq arg 'none) nil)
11668 ((eq arg 'done) (or done-word (car org-done-keywords)))
11669 ((eq arg 'nextset)
11670 (or (car (cdr (member head org-todo-heads)))
11671 (car org-todo-heads)))
11672 ((eq arg 'previousset)
11673 (let ((org-todo-heads (reverse org-todo-heads)))
11674 (or (car (cdr (member head org-todo-heads)))
11675 (car org-todo-heads))))
11676 ((car (member arg org-todo-keywords-1)))
11677 ((stringp arg)
11678 (error "State `%s' not valid in this file" arg))
11679 ((nth (1- (prefix-numeric-value arg))
11680 org-todo-keywords-1))))
11681 ((null member) (or head (car org-todo-keywords-1)))
11682 ((equal this final-done-word) nil) ;; -> make empty
11683 ((null tail) nil) ;; -> first entry
11684 ((memq interpret '(type priority))
11685 (if (eq this-command last-command)
11686 (car tail)
11687 (if (> (length tail) 0)
11688 (or done-word (car org-done-keywords))
11689 nil)))
11691 (car tail))))
11692 (org-state (or
11693 (run-hook-with-args-until-success
11694 'org-todo-get-default-hook org-state org-last-state)
11695 org-state))
11696 (next (if org-state (concat " " org-state " ") " "))
11697 (change-plist (list :type 'todo-state-change :from this :to org-state
11698 :position startpos))
11699 dolog now-done-p)
11700 (when org-blocker-hook
11701 (setq org-last-todo-state-is-todo
11702 (not (member this org-done-keywords)))
11703 (unless (save-excursion
11704 (save-match-data
11705 (org-with-wide-buffer
11706 (run-hook-with-args-until-failure
11707 'org-blocker-hook change-plist))))
11708 (if (org-called-interactively-p 'interactive)
11709 (error "TODO state change from %s to %s blocked" this org-state)
11710 ;; fail silently
11711 (message "TODO state change from %s to %s blocked" this org-state)
11712 (throw 'exit nil))))
11713 (store-match-data match-data)
11714 (replace-match next t t)
11715 (unless (pos-visible-in-window-p hl-pos)
11716 (message "TODO state changed to %s" (org-trim next)))
11717 (unless head
11718 (setq head (org-get-todo-sequence-head org-state)
11719 ass (assoc head org-todo-kwd-alist)
11720 interpret (nth 1 ass)
11721 done-word (nth 3 ass)
11722 final-done-word (nth 4 ass)))
11723 (when (memq arg '(nextset previousset))
11724 (message "Keyword-Set %d/%d: %s"
11725 (- (length org-todo-sets) -1
11726 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11727 (length org-todo-sets)
11728 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11729 (setq org-last-todo-state-is-todo
11730 (not (member org-state org-done-keywords)))
11731 (setq now-done-p (and (member org-state org-done-keywords)
11732 (not (member this org-done-keywords))))
11733 (and logging (org-local-logging logging))
11734 (when (and (or org-todo-log-states org-log-done)
11735 (not (eq org-inhibit-logging t))
11736 (not (memq arg '(nextset previousset))))
11737 ;; we need to look at recording a time and note
11738 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11739 (nth 2 (assoc this org-todo-log-states))))
11740 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11741 (setq dolog 'time))
11742 (when (and org-state
11743 (member org-state org-not-done-keywords)
11744 (not (member this org-not-done-keywords)))
11745 ;; This is now a todo state and was not one before
11746 ;; If there was a CLOSED time stamp, get rid of it.
11747 (org-add-planning-info nil nil 'closed))
11748 (when (and now-done-p org-log-done)
11749 ;; It is now done, and it was not done before
11750 (org-add-planning-info 'closed (org-current-effective-time))
11751 (if (and (not dolog) (eq 'note org-log-done))
11752 (org-add-log-setup 'done org-state this 'findpos 'note)))
11753 (when (and org-state dolog)
11754 ;; This is a non-nil state, and we need to log it
11755 (org-add-log-setup 'state org-state this 'findpos dolog)))
11756 ;; Fixup tag positioning
11757 (org-todo-trigger-tag-changes org-state)
11758 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11759 (when org-provide-todo-statistics
11760 (org-update-parent-todo-statistics))
11761 (run-hooks 'org-after-todo-state-change-hook)
11762 (if (and arg (not (member org-state org-done-keywords)))
11763 (setq head (org-get-todo-sequence-head org-state)))
11764 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11765 ;; Do we need to trigger a repeat?
11766 (when now-done-p
11767 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11768 ;; This is for the agenda, take a snapshot of the headline.
11769 (save-match-data
11770 (setq org-agenda-headline-snapshot-before-repeat
11771 (org-get-heading))))
11772 (org-auto-repeat-maybe org-state))
11773 ;; Fixup cursor location if close to the keyword
11774 (if (and (outline-on-heading-p)
11775 (not (bolp))
11776 (save-excursion (beginning-of-line 1)
11777 (looking-at org-todo-line-regexp))
11778 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11779 (progn
11780 (goto-char (or (match-end 2) (match-end 1)))
11781 (and (looking-at " ") (just-one-space))))
11782 (when org-trigger-hook
11783 (save-excursion
11784 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11786 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11787 "Block turning an entry into a TODO, using the hierarchy.
11788 This checks whether the current task should be blocked from state
11789 changes. Such blocking occurs when:
11791 1. The task has children which are not all in a completed state.
11793 2. A task has a parent with the property :ORDERED:, and there
11794 are siblings prior to the current task with incomplete
11795 status.
11797 3. The parent of the task is blocked because it has siblings that should
11798 be done first, or is child of a block grandparent TODO entry."
11800 (if (not org-enforce-todo-dependencies)
11801 t ; if locally turned off don't block
11802 (catch 'dont-block
11803 ;; If this is not a todo state change, or if this entry is already DONE,
11804 ;; do not block
11805 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11806 (member (plist-get change-plist :from)
11807 (cons 'done org-done-keywords))
11808 (member (plist-get change-plist :to)
11809 (cons 'todo org-not-done-keywords))
11810 (not (plist-get change-plist :to)))
11811 (throw 'dont-block t))
11812 ;; If this task has children, and any are undone, it's blocked
11813 (save-excursion
11814 (org-back-to-heading t)
11815 (let ((this-level (funcall outline-level)))
11816 (outline-next-heading)
11817 (let ((child-level (funcall outline-level)))
11818 (while (and (not (eobp))
11819 (> child-level this-level))
11820 ;; this todo has children, check whether they are all
11821 ;; completed
11822 (if (and (not (org-entry-is-done-p))
11823 (org-entry-is-todo-p))
11824 (throw 'dont-block nil))
11825 (outline-next-heading)
11826 (setq child-level (funcall outline-level))))))
11827 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11828 ;; any previous siblings are undone, it's blocked
11829 (save-excursion
11830 (org-back-to-heading t)
11831 (let* ((pos (point))
11832 (parent-pos (and (org-up-heading-safe) (point))))
11833 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11834 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11835 (forward-line 1)
11836 (re-search-forward org-not-done-heading-regexp pos t))
11837 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11838 ;; Search further up the hierarchy, to see if an ancestor is blocked
11839 (while t
11840 (goto-char parent-pos)
11841 (if (not (looking-at org-not-done-heading-regexp))
11842 (throw 'dont-block t)) ; do not block, parent is not a TODO
11843 (setq pos (point))
11844 (setq parent-pos (and (org-up-heading-safe) (point)))
11845 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11846 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11847 (forward-line 1)
11848 (re-search-forward org-not-done-heading-regexp pos t))
11849 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11851 (defcustom org-track-ordered-property-with-tag nil
11852 "Should the ORDERED property also be shown as a tag?
11853 The ORDERED property decides if an entry should require subtasks to be
11854 completed in sequence. Since a property is not very visible, setting
11855 this option means that toggling the ORDERED property with the command
11856 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11857 not relevant for the behavior, but it makes things more visible.
11859 Note that toggling the tag with tags commands will not change the property
11860 and therefore not influence behavior!
11862 This can be t, meaning the tag ORDERED should be used, It can also be a
11863 string to select a different tag for this task."
11864 :group 'org-todo
11865 :type '(choice
11866 (const :tag "No tracking" nil)
11867 (const :tag "Track with ORDERED tag" t)
11868 (string :tag "Use other tag")))
11870 (defun org-toggle-ordered-property ()
11871 "Toggle the ORDERED property of the current entry.
11872 For better visibility, you can track the value of this property with a tag.
11873 See variable `org-track-ordered-property-with-tag'."
11874 (interactive)
11875 (let* ((t1 org-track-ordered-property-with-tag)
11876 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11877 (save-excursion
11878 (org-back-to-heading)
11879 (if (org-entry-get nil "ORDERED")
11880 (progn
11881 (org-delete-property "ORDERED")
11882 (and tag (org-toggle-tag tag 'off))
11883 (message "Subtasks can be completed in arbitrary order"))
11884 (org-entry-put nil "ORDERED" "t")
11885 (and tag (org-toggle-tag tag 'on))
11886 (message "Subtasks must be completed in sequence")))))
11888 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11889 (defun org-block-todo-from-checkboxes (change-plist)
11890 "Block turning an entry into a TODO, using checkboxes.
11891 This checks whether the current task should be blocked from state
11892 changes because there are unchecked boxes in this entry."
11893 (if (not org-enforce-todo-checkbox-dependencies)
11894 t ; if locally turned off don't block
11895 (catch 'dont-block
11896 ;; If this is not a todo state change, or if this entry is already DONE,
11897 ;; do not block
11898 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11899 (member (plist-get change-plist :from)
11900 (cons 'done org-done-keywords))
11901 (member (plist-get change-plist :to)
11902 (cons 'todo org-not-done-keywords))
11903 (not (plist-get change-plist :to)))
11904 (throw 'dont-block t))
11905 ;; If this task has checkboxes that are not checked, it's blocked
11906 (save-excursion
11907 (org-back-to-heading t)
11908 (let ((beg (point)) end)
11909 (outline-next-heading)
11910 (setq end (point))
11911 (goto-char beg)
11912 (if (org-list-search-forward
11913 (concat (org-item-beginning-re)
11914 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11915 "\\[[- ]\\]")
11916 end t)
11917 (progn
11918 (if (boundp 'org-blocked-by-checkboxes)
11919 (setq org-blocked-by-checkboxes t))
11920 (throw 'dont-block nil)))))
11921 t))) ; do not block
11923 (defun org-entry-blocked-p ()
11924 "Is the current entry blocked?"
11925 (if (org-entry-get nil "NOBLOCKING")
11926 nil ;; Never block this entry
11927 (not
11928 (run-hook-with-args-until-failure
11929 'org-blocker-hook
11930 (list :type 'todo-state-change
11931 :position (point)
11932 :from 'todo
11933 :to 'done)))))
11935 (defun org-update-statistics-cookies (all)
11936 "Update the statistics cookie, either from TODO or from checkboxes.
11937 This should be called with the cursor in a line with a statistics cookie."
11938 (interactive "P")
11939 (if all
11940 (progn
11941 (org-update-checkbox-count 'all)
11942 (org-map-entries 'org-update-parent-todo-statistics))
11943 (if (not (org-at-heading-p))
11944 (org-update-checkbox-count)
11945 (let ((pos (move-marker (make-marker) (point)))
11946 end l1 l2)
11947 (ignore-errors (org-back-to-heading t))
11948 (if (not (org-at-heading-p))
11949 (org-update-checkbox-count)
11950 (setq l1 (org-outline-level))
11951 (setq end (save-excursion
11952 (outline-next-heading)
11953 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11954 (point)))
11955 (if (and (save-excursion
11956 (re-search-forward
11957 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11958 (not (save-excursion (re-search-forward
11959 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11960 (org-update-checkbox-count)
11961 (if (and l2 (> l2 l1))
11962 (progn
11963 (goto-char end)
11964 (org-update-parent-todo-statistics))
11965 (goto-char pos)
11966 (beginning-of-line 1)
11967 (while (re-search-forward
11968 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11969 (point-at-eol) t)
11970 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11971 (goto-char pos)
11972 (move-marker pos nil)))))
11974 (defvar org-entry-property-inherited-from) ;; defined below
11975 (defun org-update-parent-todo-statistics ()
11976 "Update any statistics cookie in the parent of the current headline.
11977 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11978 the entire subtree and this will travel up the hierarchy and update
11979 statistics everywhere."
11980 (let* ((prop (save-excursion (org-up-heading-safe)
11981 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11982 (recursive (or (not org-hierarchical-todo-statistics)
11983 (and prop (string-match "\\<recursive\\>" prop))))
11984 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11986 (first t)
11987 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11988 level ltoggle l1 new ndel
11989 (cnt-all 0) (cnt-done 0) is-percent kwd
11990 checkbox-beg ov ovs ove cookie-present)
11991 (catch 'exit
11992 (save-excursion
11993 (beginning-of-line 1)
11994 (setq ltoggle (funcall outline-level))
11995 ;; Three situations are to consider:
11997 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11998 ;; to the top-level ancestor on the headline;
12000 ;; 2. If parent has "recursive" property, repeat up to the
12001 ;; headline setting that property, taking inheritance into
12002 ;; account;
12004 ;; 3. Else, move up to direct parent and proceed only once.
12005 (while (and (setq level (org-up-heading-safe))
12006 (or recursive first)
12007 (>= (point) lim))
12008 (setq first nil cookie-present nil)
12009 (unless (and level
12010 (not (string-match
12011 "\\<checkbox\\>"
12012 (downcase (or (org-entry-get nil "COOKIE_DATA")
12013 "")))))
12014 (throw 'exit nil))
12015 (while (re-search-forward box-re (point-at-eol) t)
12016 (setq cnt-all 0 cnt-done 0 cookie-present t)
12017 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12018 (save-match-data
12019 (unless (outline-next-heading) (throw 'exit nil))
12020 (while (and (looking-at org-complex-heading-regexp)
12021 (> (setq l1 (length (match-string 1))) level))
12022 (setq kwd (and (or recursive (= l1 ltoggle))
12023 (match-string 2)))
12024 (if (or (eq org-provide-todo-statistics 'all-headlines)
12025 (and (listp org-provide-todo-statistics)
12026 (or (member kwd org-provide-todo-statistics)
12027 (member kwd org-done-keywords))))
12028 (setq cnt-all (1+ cnt-all))
12029 (if (eq org-provide-todo-statistics t)
12030 (and kwd (setq cnt-all (1+ cnt-all)))))
12031 (and (member kwd org-done-keywords)
12032 (setq cnt-done (1+ cnt-done)))
12033 (outline-next-heading)))
12034 (setq new
12035 (if is-percent
12036 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12037 (format "[%d/%d]" cnt-done cnt-all))
12038 ndel (- (match-end 0) checkbox-beg))
12039 ;; handle overlays when updating cookie from column view
12040 (when (setq ov (car (overlays-at checkbox-beg)))
12041 (setq ovs (overlay-start ov) ove (overlay-end ov))
12042 (delete-overlay ov))
12043 (goto-char checkbox-beg)
12044 (insert new)
12045 (delete-region (point) (+ (point) ndel))
12046 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12047 (when ov (move-overlay ov ovs ove)))
12048 (when cookie-present
12049 (run-hook-with-args 'org-after-todo-statistics-hook
12050 cnt-done (- cnt-all cnt-done))))))
12051 (run-hooks 'org-todo-statistics-hook)))
12053 (defvar org-after-todo-statistics-hook nil
12054 "Hook that is called after a TODO statistics cookie has been updated.
12055 Each function is called with two arguments: the number of not-done entries
12056 and the number of done entries.
12058 For example, the following function, when added to this hook, will switch
12059 an entry to DONE when all children are done, and back to TODO when new
12060 entries are set to a TODO status. Note that this hook is only called
12061 when there is a statistics cookie in the headline!
12063 (defun org-summary-todo (n-done n-not-done)
12064 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12065 (let (org-log-done org-log-states) ; turn off logging
12066 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12069 (defvar org-todo-statistics-hook nil
12070 "Hook that is run whenever Org thinks TODO statistics should be updated.
12071 This hook runs even if there is no statistics cookie present, in which case
12072 `org-after-todo-statistics-hook' would not run.")
12074 (defun org-todo-trigger-tag-changes (state)
12075 "Apply the changes defined in `org-todo-state-tags-triggers'."
12076 (let ((l org-todo-state-tags-triggers)
12077 changes)
12078 (when (or (not state) (equal state ""))
12079 (setq changes (append changes (cdr (assoc "" l)))))
12080 (when (and (stringp state) (> (length state) 0))
12081 (setq changes (append changes (cdr (assoc state l)))))
12082 (when (member state org-not-done-keywords)
12083 (setq changes (append changes (cdr (assoc 'todo l)))))
12084 (when (member state org-done-keywords)
12085 (setq changes (append changes (cdr (assoc 'done l)))))
12086 (dolist (c changes)
12087 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12089 (defun org-local-logging (value)
12090 "Get logging settings from a property VALUE."
12091 (let* (words w a)
12092 ;; directly set the variables, they are already local.
12093 (setq org-log-done nil
12094 org-log-repeat nil
12095 org-todo-log-states nil)
12096 (setq words (org-split-string value))
12097 (while (setq w (pop words))
12098 (cond
12099 ((setq a (assoc w org-startup-options))
12100 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12101 (set (nth 1 a) (nth 2 a))))
12102 ((setq a (org-extract-log-state-settings w))
12103 (and (member (car a) org-todo-keywords-1)
12104 (push a org-todo-log-states)))))))
12106 (defun org-get-todo-sequence-head (kwd)
12107 "Return the head of the TODO sequence to which KWD belongs.
12108 If KWD is not set, check if there is a text property remembering the
12109 right sequence."
12110 (let (p)
12111 (cond
12112 ((not kwd)
12113 (or (get-text-property (point-at-bol) 'org-todo-head)
12114 (progn
12115 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12116 nil (point-at-eol)))
12117 (get-text-property p 'org-todo-head))))
12118 ((not (member kwd org-todo-keywords-1))
12119 (car org-todo-keywords-1))
12120 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12122 (defun org-fast-todo-selection ()
12123 "Fast TODO keyword selection with single keys.
12124 Returns the new TODO keyword, or nil if no state change should occur."
12125 (let* ((fulltable org-todo-key-alist)
12126 (done-keywords org-done-keywords) ;; needed for the faces.
12127 (maxlen (apply 'max (mapcar
12128 (lambda (x)
12129 (if (stringp (car x)) (string-width (car x)) 0))
12130 fulltable)))
12131 (expert nil)
12132 (fwidth (+ maxlen 3 1 3))
12133 (ncol (/ (- (window-width) 4) fwidth))
12134 tg cnt e c tbl
12135 groups ingroup)
12136 (save-excursion
12137 (save-window-excursion
12138 (if expert
12139 (set-buffer (get-buffer-create " *Org todo*"))
12140 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12141 (erase-buffer)
12142 (org-set-local 'org-done-keywords done-keywords)
12143 (setq tbl fulltable cnt 0)
12144 (while (setq e (pop tbl))
12145 (cond
12146 ((equal e '(:startgroup))
12147 (push '() groups) (setq ingroup t)
12148 (when (not (= cnt 0))
12149 (setq cnt 0)
12150 (insert "\n"))
12151 (insert "{ "))
12152 ((equal e '(:endgroup))
12153 (setq ingroup nil cnt 0)
12154 (insert "}\n"))
12155 ((equal e '(:newline))
12156 (when (not (= cnt 0))
12157 (setq cnt 0)
12158 (insert "\n")
12159 (setq e (car tbl))
12160 (while (equal (car tbl) '(:newline))
12161 (insert "\n")
12162 (setq tbl (cdr tbl)))))
12164 (setq tg (car e) c (cdr e))
12165 (if ingroup (push tg (car groups)))
12166 (setq tg (org-add-props tg nil 'face
12167 (org-get-todo-face tg)))
12168 (if (and (= cnt 0) (not ingroup)) (insert " "))
12169 (insert "[" c "] " tg (make-string
12170 (- fwidth 4 (length tg)) ?\ ))
12171 (when (= (setq cnt (1+ cnt)) ncol)
12172 (insert "\n")
12173 (if ingroup (insert " "))
12174 (setq cnt 0)))))
12175 (insert "\n")
12176 (goto-char (point-min))
12177 (if (not expert) (org-fit-window-to-buffer))
12178 (message "[a-z..]:Set [SPC]:clear")
12179 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12180 (cond
12181 ((or (= c ?\C-g)
12182 (and (= c ?q) (not (rassoc c fulltable))))
12183 (setq quit-flag t))
12184 ((= c ?\ ) nil)
12185 ((setq e (rassoc c fulltable) tg (car e))
12187 (t (setq quit-flag t)))))))
12189 (defun org-entry-is-todo-p ()
12190 (member (org-get-todo-state) org-not-done-keywords))
12192 (defun org-entry-is-done-p ()
12193 (member (org-get-todo-state) org-done-keywords))
12195 (defun org-get-todo-state ()
12196 (save-excursion
12197 (org-back-to-heading t)
12198 (and (looking-at org-todo-line-regexp)
12199 (match-end 2)
12200 (match-string 2))))
12202 (defun org-at-date-range-p (&optional inactive-ok)
12203 "Is the cursor inside a date range?"
12204 (interactive)
12205 (save-excursion
12206 (catch 'exit
12207 (let ((pos (point)))
12208 (skip-chars-backward "^[<\r\n")
12209 (skip-chars-backward "<[")
12210 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12211 (>= (match-end 0) pos)
12212 (throw 'exit t))
12213 (skip-chars-backward "^<[\r\n")
12214 (skip-chars-backward "<[")
12215 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12216 (>= (match-end 0) pos)
12217 (throw 'exit t)))
12218 nil)))
12220 (defun org-get-repeat (&optional tagline)
12221 "Check if there is a deadline/schedule with repeater in this entry."
12222 (save-match-data
12223 (save-excursion
12224 (org-back-to-heading t)
12225 (and (re-search-forward (if tagline
12226 (concat tagline "\\s-*" org-repeat-re)
12227 org-repeat-re)
12228 (org-entry-end-position) t)
12229 (match-string-no-properties 1)))))
12231 (defvar org-last-changed-timestamp)
12232 (defvar org-last-inserted-timestamp)
12233 (defvar org-log-post-message)
12234 (defvar org-log-note-purpose)
12235 (defvar org-log-note-how)
12236 (defvar org-log-note-extra)
12237 (defun org-auto-repeat-maybe (done-word)
12238 "Check if the current headline contains a repeated deadline/schedule.
12239 If yes, set TODO state back to what it was and change the base date
12240 of repeating deadline/scheduled time stamps to new date.
12241 This function is run automatically after each state change to a DONE state."
12242 ;; last-state is dynamically scoped into this function
12243 (let* ((repeat (org-get-repeat))
12244 (aa (assoc org-last-state org-todo-kwd-alist))
12245 (interpret (nth 1 aa))
12246 (head (nth 2 aa))
12247 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12248 (msg "Entry repeats: ")
12249 (org-log-done nil)
12250 (org-todo-log-states nil)
12251 re type n what ts time to-state)
12252 (when repeat
12253 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12254 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12255 org-todo-repeat-to-state))
12256 (unless (and to-state (member to-state org-todo-keywords-1))
12257 (setq to-state (if (eq interpret 'type) org-last-state head)))
12258 (org-todo to-state)
12259 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12260 (org-entry-put nil "LAST_REPEAT" (format-time-string
12261 (org-time-stamp-format t t))))
12262 (when org-log-repeat
12263 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12264 (memq 'org-add-log-note post-command-hook))
12265 ;; OK, we are already setup for some record
12266 (if (eq org-log-repeat 'note)
12267 ;; make sure we take a note, not only a time stamp
12268 (setq org-log-note-how 'note))
12269 ;; Set up for taking a record
12270 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12271 org-last-state
12272 'findpos org-log-repeat)))
12273 (org-back-to-heading t)
12274 (org-add-planning-info nil nil 'closed)
12275 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12276 org-deadline-time-regexp "\\)\\|\\("
12277 org-ts-regexp "\\)"))
12278 (while (re-search-forward
12279 re (save-excursion (outline-next-heading) (point)) t)
12280 (setq type (if (match-end 1) org-scheduled-string
12281 (if (match-end 3) org-deadline-string "Plain:"))
12282 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12283 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12284 (setq n (string-to-number (match-string 2 ts))
12285 what (match-string 3 ts))
12286 (if (equal what "w") (setq n (* n 7) what "d"))
12287 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12288 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12289 ;; Preparation, see if we need to modify the start date for the change
12290 (when (match-end 1)
12291 (setq time (save-match-data (org-time-string-to-time ts)))
12292 (cond
12293 ((equal (match-string 1 ts) ".")
12294 ;; Shift starting date to today
12295 (org-timestamp-change
12296 (- (org-today) (time-to-days time))
12297 'day))
12298 ((equal (match-string 1 ts) "+")
12299 (let ((nshiftmax 10) (nshift 0))
12300 (while (or (= nshift 0)
12301 (<= (time-to-days time)
12302 (time-to-days (current-time))))
12303 (when (= (incf nshift) nshiftmax)
12304 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12305 (error "Abort")))
12306 (org-timestamp-change n (cdr (assoc what whata)))
12307 (org-at-timestamp-p t)
12308 (setq ts (match-string 1))
12309 (setq time (save-match-data (org-time-string-to-time ts)))))
12310 (org-timestamp-change (- n) (cdr (assoc what whata)))
12311 ;; rematch, so that we have everything in place for the real shift
12312 (org-at-timestamp-p t)
12313 (setq ts (match-string 1))
12314 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12315 (org-timestamp-change n (cdr (assoc what whata)))
12316 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12317 (setq org-log-post-message msg)
12318 (message "%s" msg))))
12320 (defun org-show-todo-tree (arg)
12321 "Make a compact tree which shows all headlines marked with TODO.
12322 The tree will show the lines where the regexp matches, and all higher
12323 headlines above the match.
12324 With a \\[universal-argument] prefix, prompt for a regexp to match.
12325 With a numeric prefix N, construct a sparse tree for the Nth element
12326 of `org-todo-keywords-1'."
12327 (interactive "P")
12328 (let ((case-fold-search nil)
12329 (kwd-re
12330 (cond ((null arg) org-not-done-regexp)
12331 ((equal arg '(4))
12332 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12333 (mapcar 'list org-todo-keywords-1))))
12334 (concat "\\("
12335 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12336 "\\)\\>")))
12337 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12338 (regexp-quote (nth (1- (prefix-numeric-value arg))
12339 org-todo-keywords-1)))
12340 (t (error "Invalid prefix argument: %s" arg)))))
12341 (message "%d TODO entries found"
12342 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12344 (defun org-deadline (&optional remove time)
12345 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12346 With argument REMOVE, remove any deadline from the item.
12347 With argument TIME, set the deadline at the corresponding date. TIME
12348 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12349 (interactive "P")
12350 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12351 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12352 'region-start-level 'region))
12353 org-loop-over-headlines-in-active-region)
12354 (org-map-entries
12355 `(org-deadline ',remove ,time)
12356 org-loop-over-headlines-in-active-region
12357 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12358 (let* ((old-date (org-entry-get nil "DEADLINE"))
12359 (repeater (and old-date
12360 (string-match
12361 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12362 old-date)
12363 (match-string 1 old-date))))
12364 (if remove
12365 (progn
12366 (when (and old-date org-log-redeadline)
12367 (org-add-log-setup 'deldeadline nil old-date 'findpos
12368 org-log-redeadline))
12369 (org-remove-timestamp-with-keyword org-deadline-string)
12370 (message "Item no longer has a deadline."))
12371 (org-add-planning-info 'deadline time 'closed)
12372 (when (and old-date org-log-redeadline
12373 (not (equal old-date
12374 (substring org-last-inserted-timestamp 1 -1))))
12375 (org-add-log-setup 'redeadline nil old-date 'findpos
12376 org-log-redeadline))
12377 (when repeater
12378 (save-excursion
12379 (org-back-to-heading t)
12380 (when (re-search-forward (concat org-deadline-string " "
12381 org-last-inserted-timestamp)
12382 (save-excursion
12383 (outline-next-heading) (point)) t)
12384 (goto-char (1- (match-end 0)))
12385 (insert " " repeater)
12386 (setq org-last-inserted-timestamp
12387 (concat (substring org-last-inserted-timestamp 0 -1)
12388 " " repeater
12389 (substring org-last-inserted-timestamp -1))))))
12390 (message "Deadline on %s" org-last-inserted-timestamp)))))
12392 (defun org-schedule (&optional remove time)
12393 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12394 With argument REMOVE, remove any scheduling date from the item.
12395 With argument TIME, scheduled at the corresponding date. TIME can
12396 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12397 (interactive "P")
12398 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12399 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12400 'region-start-level 'region))
12401 org-loop-over-headlines-in-active-region)
12402 (org-map-entries
12403 `(org-schedule ',remove ,time)
12404 org-loop-over-headlines-in-active-region
12405 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12406 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12407 (repeater (and old-date
12408 (string-match
12409 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12410 old-date)
12411 (match-string 1 old-date))))
12412 (if remove
12413 (progn
12414 (when (and old-date org-log-reschedule)
12415 (org-add-log-setup 'delschedule nil old-date 'findpos
12416 org-log-reschedule))
12417 (org-remove-timestamp-with-keyword org-scheduled-string)
12418 (message "Item is no longer scheduled."))
12419 (org-add-planning-info 'scheduled time 'closed)
12420 (when (and old-date org-log-reschedule
12421 (not (equal old-date
12422 (substring org-last-inserted-timestamp 1 -1))))
12423 (org-add-log-setup 'reschedule nil old-date 'findpos
12424 org-log-reschedule))
12425 (when repeater
12426 (save-excursion
12427 (org-back-to-heading t)
12428 (when (re-search-forward (concat org-scheduled-string " "
12429 org-last-inserted-timestamp)
12430 (save-excursion
12431 (outline-next-heading) (point)) t)
12432 (goto-char (1- (match-end 0)))
12433 (insert " " repeater)
12434 (setq org-last-inserted-timestamp
12435 (concat (substring org-last-inserted-timestamp 0 -1)
12436 " " repeater
12437 (substring org-last-inserted-timestamp -1))))))
12438 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12440 (defun org-get-scheduled-time (pom &optional inherit)
12441 "Get the scheduled time as a time tuple, of a format suitable
12442 for calling org-schedule with, or if there is no scheduling,
12443 returns nil."
12444 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12445 (when time
12446 (apply 'encode-time (org-parse-time-string time)))))
12448 (defun org-get-deadline-time (pom &optional inherit)
12449 "Get the deadline as a time tuple, of a format suitable for
12450 calling org-deadline with, or if there is no scheduling, returns
12451 nil."
12452 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12453 (when time
12454 (apply 'encode-time (org-parse-time-string time)))))
12456 (defun org-remove-timestamp-with-keyword (keyword)
12457 "Remove all time stamps with KEYWORD in the current entry."
12458 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12459 beg)
12460 (save-excursion
12461 (org-back-to-heading t)
12462 (setq beg (point))
12463 (outline-next-heading)
12464 (while (re-search-backward re beg t)
12465 (replace-match "")
12466 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12467 (equal (char-before) ?\ ))
12468 (backward-delete-char 1)
12469 (if (string-match "^[ \t]*$" (buffer-substring
12470 (point-at-bol) (point-at-eol)))
12471 (delete-region (point-at-bol)
12472 (min (point-max) (1+ (point-at-eol))))))))))
12474 (defun org-add-planning-info (what &optional time &rest remove)
12475 "Insert new timestamp with keyword in the line directly after the headline.
12476 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12477 If non is given, the user is prompted for a date.
12478 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12479 be removed."
12480 (interactive)
12481 (let (org-time-was-given org-end-time-was-given ts
12482 end default-time default-input)
12484 (catch 'exit
12485 (when (and (memq what '(scheduled deadline))
12486 (or (not time)
12487 (and (stringp time)
12488 (string-match "^[-+]+[0-9]" time))))
12489 ;; Try to get a default date/time from existing timestamp
12490 (save-excursion
12491 (org-back-to-heading t)
12492 (setq end (save-excursion (outline-next-heading) (point)))
12493 (when (re-search-forward (if (eq what 'scheduled)
12494 org-scheduled-time-regexp
12495 org-deadline-time-regexp)
12496 end t)
12497 (setq ts (match-string 1)
12498 default-time
12499 (apply 'encode-time (org-parse-time-string ts))
12500 default-input (and ts (org-get-compact-tod ts))))))
12501 (when what
12502 (setq time
12503 (if (stringp time)
12504 ;; This is a string (relative or absolute), set proper date
12505 (apply 'encode-time
12506 (org-read-date-analyze
12507 time default-time (decode-time default-time)))
12508 ;; If necessary, get the time from the user
12509 (or time (org-read-date nil 'to-time nil nil
12510 default-time default-input)))))
12512 (when (and org-insert-labeled-timestamps-at-point
12513 (member what '(scheduled deadline)))
12514 (insert
12515 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12516 (org-insert-time-stamp time org-time-was-given
12517 nil nil nil (list org-end-time-was-given))
12518 (setq what nil))
12519 (save-excursion
12520 (save-restriction
12521 (let (col list elt ts buffer-invisibility-spec)
12522 (org-back-to-heading t)
12523 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12524 (goto-char (match-end 1))
12525 (setq col (current-column))
12526 (goto-char (match-end 0))
12527 (if (eobp) (insert "\n") (forward-char 1))
12528 (when (and (not what)
12529 (not (looking-at
12530 (concat "[ \t]*"
12531 org-keyword-time-not-clock-regexp))))
12532 ;; Nothing to add, nothing to remove...... :-)
12533 (throw 'exit nil))
12534 (if (and (not (looking-at org-outline-regexp))
12535 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12536 "[^\r\n]*"))
12537 (not (equal (match-string 1) org-clock-string)))
12538 (narrow-to-region (match-beginning 0) (match-end 0))
12539 (insert-before-markers "\n")
12540 (backward-char 1)
12541 (narrow-to-region (point) (point))
12542 (and org-adapt-indentation (org-indent-to-column col)))
12543 ;; Check if we have to remove something.
12544 (setq list (cons what remove))
12545 (while list
12546 (setq elt (pop list))
12547 (when (or (and (eq elt 'scheduled)
12548 (re-search-forward org-scheduled-time-regexp nil t))
12549 (and (eq elt 'deadline)
12550 (re-search-forward org-deadline-time-regexp nil t))
12551 (and (eq elt 'closed)
12552 (re-search-forward org-closed-time-regexp nil t)))
12553 (replace-match "")
12554 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12555 (and (looking-at "[ \t]+") (replace-match ""))
12556 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12557 (when what
12558 (insert
12559 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12560 (cond ((eq what 'scheduled) org-scheduled-string)
12561 ((eq what 'deadline) org-deadline-string)
12562 ((eq what 'closed) org-closed-string))
12563 " ")
12564 (setq ts (org-insert-time-stamp
12565 time
12566 (or org-time-was-given
12567 (and (eq what 'closed) org-log-done-with-time))
12568 (eq what 'closed)
12569 nil nil (list org-end-time-was-given)))
12570 (insert
12571 (if (not (or (bolp) (eq (char-before) ?\ )
12572 (memq (char-after) '(32 10))
12573 (eobp))) " " ""))
12574 (end-of-line 1))
12575 (goto-char (point-min))
12576 (widen)
12577 (if (and (looking-at "[ \t]*\n")
12578 (equal (char-before) ?\n))
12579 (delete-region (1- (point)) (point-at-eol)))
12580 ts))))))
12582 (defvar org-log-note-marker (make-marker))
12583 (defvar org-log-note-purpose nil)
12584 (defvar org-log-note-state nil)
12585 (defvar org-log-note-previous-state nil)
12586 (defvar org-log-note-how nil)
12587 (defvar org-log-note-extra nil)
12588 (defvar org-log-note-window-configuration nil)
12589 (defvar org-log-note-return-to (make-marker))
12590 (defvar org-log-note-effective-time nil
12591 "Remembered current time so that dynamically scoped
12592 `org-extend-today-until' affects tha timestamps in state change
12593 log")
12595 (defvar org-log-post-message nil
12596 "Message to be displayed after a log note has been stored.
12597 The auto-repeater uses this.")
12599 (defun org-add-note ()
12600 "Add a note to the current entry.
12601 This is done in the same way as adding a state change note."
12602 (interactive)
12603 (org-add-log-setup 'note nil nil 'findpos nil))
12605 (defvar org-property-end-re)
12606 (defun org-add-log-setup (&optional purpose state prev-state
12607 findpos how extra)
12608 "Set up the post command hook to take a note.
12609 If this is about to TODO state change, the new state is expected in STATE.
12610 When FINDPOS is non-nil, find the correct position for the note in
12611 the current entry. If not, assume that it can be inserted at point.
12612 HOW is an indicator what kind of note should be created.
12613 EXTRA is additional text that will be inserted into the notes buffer."
12614 (let* ((org-log-into-drawer (org-log-into-drawer))
12615 (drawer (cond ((stringp org-log-into-drawer)
12616 org-log-into-drawer)
12617 (org-log-into-drawer "LOGBOOK"))))
12618 (save-restriction
12619 (save-excursion
12620 (when findpos
12621 (org-back-to-heading t)
12622 (narrow-to-region (point) (save-excursion
12623 (outline-next-heading) (point)))
12624 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12625 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12626 "[^\r\n]*\\)?"))
12627 (goto-char (match-end 0))
12628 (cond
12629 (drawer
12630 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12631 nil t)
12632 (progn
12633 (goto-char (match-end 0))
12634 (or org-log-states-order-reversed
12635 (and (re-search-forward org-property-end-re nil t)
12636 (goto-char (1- (match-beginning 0))))))
12637 (insert "\n:" drawer ":\n:END:")
12638 (beginning-of-line 0)
12639 (org-indent-line)
12640 (beginning-of-line 2)
12641 (org-indent-line)
12642 (end-of-line 0)))
12643 ((and org-log-state-notes-insert-after-drawers
12644 (save-excursion
12645 (forward-line) (looking-at org-drawer-regexp)))
12646 (forward-line)
12647 (while (looking-at org-drawer-regexp)
12648 (goto-char (match-end 0))
12649 (re-search-forward org-property-end-re (point-max) t)
12650 (forward-line))
12651 (forward-line -1)))
12652 (unless org-log-states-order-reversed
12653 (and (= (char-after) ?\n) (forward-char 1))
12654 (org-skip-over-state-notes)
12655 (skip-chars-backward " \t\n\r")))
12656 (move-marker org-log-note-marker (point))
12657 (setq org-log-note-purpose purpose
12658 org-log-note-state state
12659 org-log-note-previous-state prev-state
12660 org-log-note-how how
12661 org-log-note-extra extra
12662 org-log-note-effective-time (org-current-effective-time))
12663 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12665 (defun org-skip-over-state-notes ()
12666 "Skip past the list of State notes in an entry."
12667 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12668 (when (ignore-errors (goto-char (org-in-item-p)))
12669 (let* ((struct (org-list-struct))
12670 (prevs (org-list-prevs-alist struct)))
12671 (while (looking-at "[ \t]*- State")
12672 (goto-char (or (org-list-get-next-item (point) struct prevs)
12673 (org-list-get-item-end (point) struct)))))))
12675 (defun org-add-log-note (&optional purpose)
12676 "Pop up a window for taking a note, and add this note later at point."
12677 (remove-hook 'post-command-hook 'org-add-log-note)
12678 (setq org-log-note-window-configuration (current-window-configuration))
12679 (delete-other-windows)
12680 (move-marker org-log-note-return-to (point))
12681 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12682 (goto-char org-log-note-marker)
12683 (org-switch-to-buffer-other-window "*Org Note*")
12684 (erase-buffer)
12685 (if (memq org-log-note-how '(time state))
12686 (let (current-prefix-arg) (org-store-log-note))
12687 (let ((org-inhibit-startup t)) (org-mode))
12688 (insert (format "# Insert note for %s.
12689 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12690 (cond
12691 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12692 ((eq org-log-note-purpose 'done) "closed todo item")
12693 ((eq org-log-note-purpose 'state)
12694 (format "state change from \"%s\" to \"%s\""
12695 (or org-log-note-previous-state "")
12696 (or org-log-note-state "")))
12697 ((eq org-log-note-purpose 'reschedule)
12698 "rescheduling")
12699 ((eq org-log-note-purpose 'delschedule)
12700 "no longer scheduled")
12701 ((eq org-log-note-purpose 'redeadline)
12702 "changing deadline")
12703 ((eq org-log-note-purpose 'deldeadline)
12704 "removing deadline")
12705 ((eq org-log-note-purpose 'refile)
12706 "refiling")
12707 ((eq org-log-note-purpose 'note)
12708 "this entry")
12709 (t (error "This should not happen")))))
12710 (if org-log-note-extra (insert org-log-note-extra))
12711 (org-set-local 'org-finish-function 'org-store-log-note)
12712 (run-hooks 'org-log-buffer-setup-hook)))
12714 (defvar org-note-abort nil) ; dynamically scoped
12715 (defun org-store-log-note ()
12716 "Finish taking a log note, and insert it to where it belongs."
12717 (let ((txt (buffer-string))
12718 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12719 lines ind bul)
12720 (kill-buffer (current-buffer))
12721 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12722 (setq txt (replace-match "" t t txt)))
12723 (if (string-match "\\s-+\\'" txt)
12724 (setq txt (replace-match "" t t txt)))
12725 (setq lines (org-split-string txt "\n"))
12726 (when (and note (string-match "\\S-" note))
12727 (setq note
12728 (org-replace-escapes
12729 note
12730 (list (cons "%u" (user-login-name))
12731 (cons "%U" user-full-name)
12732 (cons "%t" (format-time-string
12733 (org-time-stamp-format 'long 'inactive)
12734 org-log-note-effective-time))
12735 (cons "%T" (format-time-string
12736 (org-time-stamp-format 'long nil)
12737 org-log-note-effective-time))
12738 (cons "%d" (format-time-string
12739 (org-time-stamp-format nil 'inactive)
12740 org-log-note-effective-time))
12741 (cons "%D" (format-time-string
12742 (org-time-stamp-format nil nil)
12743 org-log-note-effective-time))
12744 (cons "%s" (if org-log-note-state
12745 (concat "\"" org-log-note-state "\"")
12746 ""))
12747 (cons "%S" (if org-log-note-previous-state
12748 (concat "\"" org-log-note-previous-state "\"")
12749 "\"\"")))))
12750 (if lines (setq note (concat note " \\\\")))
12751 (push note lines))
12752 (when (or current-prefix-arg org-note-abort)
12753 (when org-log-into-drawer
12754 (org-remove-empty-drawer-at
12755 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12756 org-log-note-marker))
12757 (setq lines nil))
12758 (when lines
12759 (with-current-buffer (marker-buffer org-log-note-marker)
12760 (save-excursion
12761 (goto-char org-log-note-marker)
12762 (move-marker org-log-note-marker nil)
12763 (end-of-line 1)
12764 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12765 (setq ind (save-excursion
12766 (if (ignore-errors (goto-char (org-in-item-p)))
12767 (let ((struct (org-list-struct)))
12768 (org-list-get-ind
12769 (org-list-get-top-point struct) struct))
12770 (skip-chars-backward " \r\t\n")
12771 (cond
12772 ((and (org-at-heading-p)
12773 org-adapt-indentation)
12774 (1+ (org-current-level)))
12775 ((org-at-heading-p) 0)
12776 (t (org-get-indentation))))))
12777 (setq bul (org-list-bullet-string "-"))
12778 (org-indent-line-to ind)
12779 (insert bul (pop lines))
12780 (let ((ind-body (+ (length bul) ind)))
12781 (while lines
12782 (insert "\n")
12783 (org-indent-line-to ind-body)
12784 (insert (pop lines))))
12785 (message "Note stored")
12786 (org-back-to-heading t)
12787 (org-cycle-hide-drawers 'children)))))
12788 (set-window-configuration org-log-note-window-configuration)
12789 (with-current-buffer (marker-buffer org-log-note-return-to)
12790 (goto-char org-log-note-return-to))
12791 (move-marker org-log-note-return-to nil)
12792 (and org-log-post-message (message "%s" org-log-post-message)))
12794 (defun org-remove-empty-drawer-at (drawer pos)
12795 "Remove an empty drawer DRAWER at position POS.
12796 POS may also be a marker."
12797 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12798 (save-excursion
12799 (save-restriction
12800 (widen)
12801 (goto-char pos)
12802 (if (org-in-regexp
12803 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12804 (replace-match ""))))))
12806 (defvar org-ts-type nil)
12807 (defun org-sparse-tree (&optional arg type)
12808 "Create a sparse tree, prompt for the details.
12809 This command can create sparse trees. You first need to select the type
12810 of match used to create the tree:
12812 t Show all TODO entries.
12813 T Show entries with a specific TODO keyword.
12814 m Show entries selected by a tags/property match.
12815 p Enter a property name and its value (both with completion on existing
12816 names/values) and show entries with that property.
12817 r Show entries matching a regular expression (`/' can be used as well).
12818 b Show deadlines and scheduled items before a date.
12819 a Show deadlines and scheduled items after a date.
12820 d Show deadlines due within `org-deadline-warning-days'.
12821 D Show deadlines and scheduled items between a date range."
12822 (interactive "P")
12823 (let (ans kwd value ts-type)
12824 (setq type (or type org-sparse-tree-default-date-type))
12825 (setq org-ts-type type)
12826 (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"
12827 (cond ((eq type 'all) "all timestamps")
12828 ((eq type 'scheduled) "only scheduled")
12829 ((eq type 'deadline) "only deadline")
12830 ((eq type 'active) "only active timestamps")
12831 ((eq type 'inactive) "only inactive timestamps")
12832 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12833 (t "scheduled/deadline")))
12834 (setq ans (read-char-exclusive))
12835 (cond
12836 ((equal ans ?c)
12837 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12838 ((equal ans ?d)
12839 (call-interactively 'org-check-deadlines))
12840 ((equal ans ?b)
12841 (call-interactively 'org-check-before-date))
12842 ((equal ans ?a)
12843 (call-interactively 'org-check-after-date))
12844 ((equal ans ?D)
12845 (call-interactively 'org-check-dates-range))
12846 ((equal ans ?t)
12847 (org-show-todo-tree nil))
12848 ((equal ans ?T)
12849 (org-show-todo-tree '(4)))
12850 ((member ans '(?T ?m))
12851 (call-interactively 'org-match-sparse-tree))
12852 ((member ans '(?p ?P))
12853 (setq kwd (org-icompleting-read "Property: "
12854 (mapcar 'list (org-buffer-property-keys))))
12855 (setq value (org-icompleting-read "Value: "
12856 (mapcar 'list (org-property-values kwd))))
12857 (unless (string-match "\\`{.*}\\'" value)
12858 (setq value (concat "\"" value "\"")))
12859 (org-match-sparse-tree arg (concat kwd "=" value)))
12860 ((member ans '(?r ?R ?/))
12861 (call-interactively 'org-occur))
12862 (t (error "No such sparse tree command \"%c\"" ans)))))
12864 (defvar org-occur-highlights nil
12865 "List of overlays used for occur matches.")
12866 (make-variable-buffer-local 'org-occur-highlights)
12867 (defvar org-occur-parameters nil
12868 "Parameters of the active org-occur calls.
12869 This is a list, each call to org-occur pushes as cons cell,
12870 containing the regular expression and the callback, onto the list.
12871 The list can contain several entries if `org-occur' has been called
12872 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12873 will only contain one set of parameters. When the highlights are
12874 removed (for example with `C-c C-c', or with the next edit (depending
12875 on `org-remove-highlights-with-change'), this variable is emptied
12876 as well.")
12877 (make-variable-buffer-local 'org-occur-parameters)
12879 (defun org-occur (regexp &optional keep-previous callback)
12880 "Make a compact tree which shows all matches of REGEXP.
12881 The tree will show the lines where the regexp matches, and all higher
12882 headlines above the match. It will also show the heading after the match,
12883 to make sure editing the matching entry is easy.
12884 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12885 call to `org-occur' will be kept, to allow stacking of calls to this
12886 command.
12887 If CALLBACK is non-nil, it is a function which is called to confirm
12888 that the match should indeed be shown."
12889 (interactive "sRegexp: \nP")
12890 (when (equal regexp "")
12891 (error "Regexp cannot be empty"))
12892 (unless keep-previous
12893 (org-remove-occur-highlights nil nil t))
12894 (push (cons regexp callback) org-occur-parameters)
12895 (let ((cnt 0))
12896 (save-excursion
12897 (goto-char (point-min))
12898 (if (or (not keep-previous) ; do not want to keep
12899 (not org-occur-highlights)) ; no previous matches
12900 ;; hide everything
12901 (org-overview))
12902 (while (re-search-forward regexp nil t)
12903 (when (or (not callback)
12904 (save-match-data (funcall callback)))
12905 (setq cnt (1+ cnt))
12906 (when org-highlight-sparse-tree-matches
12907 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12908 (org-show-context 'occur-tree))))
12909 (when org-remove-highlights-with-change
12910 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12911 nil 'local))
12912 (unless org-sparse-tree-open-archived-trees
12913 (org-hide-archived-subtrees (point-min) (point-max)))
12914 (run-hooks 'org-occur-hook)
12915 (if (org-called-interactively-p 'interactive)
12916 (message "%d match(es) for regexp %s" cnt regexp))
12917 cnt))
12919 (defun org-occur-next-match (&optional n reset)
12920 "Function for `next-error-function' to find sparse tree matches.
12921 N is the number of matches to move, when negative move backwards.
12922 RESET is entirely ignored - this function always goes back to the
12923 starting point when no match is found."
12924 (let* ((limit (if (< n 0) (point-min) (point-max)))
12925 (search-func (if (< n 0)
12926 'previous-single-char-property-change
12927 'next-single-char-property-change))
12928 (n (abs n))
12929 (pos (point))
12931 (catch 'exit
12932 (while (setq p1 (funcall search-func (point) 'org-type))
12933 (when (equal p1 limit)
12934 (goto-char pos)
12935 (error "No more matches"))
12936 (when (equal (get-char-property p1 'org-type) 'org-occur)
12937 (setq n (1- n))
12938 (when (= n 0)
12939 (goto-char p1)
12940 (throw 'exit (point))))
12941 (goto-char p1))
12942 (goto-char p1)
12943 (error "No more matches"))))
12945 (defun org-show-context (&optional key)
12946 "Make sure point and context are visible.
12947 How much context is shown depends upon the variables
12948 `org-show-hierarchy-above', `org-show-following-heading',
12949 `org-show-entry-below' and `org-show-siblings'."
12950 (let ((heading-p (org-at-heading-p t))
12951 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12952 (following-p (org-get-alist-option org-show-following-heading key))
12953 (entry-p (org-get-alist-option org-show-entry-below key))
12954 (siblings-p (org-get-alist-option org-show-siblings key)))
12955 (catch 'exit
12956 ;; Show heading or entry text
12957 (if (and heading-p (not entry-p))
12958 (org-flag-heading nil) ; only show the heading
12959 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12960 (org-show-hidden-entry))) ; show entire entry
12961 (when following-p
12962 ;; Show next sibling, or heading below text
12963 (save-excursion
12964 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12965 (org-flag-heading nil))))
12966 (when siblings-p (org-show-siblings))
12967 (when hierarchy-p
12968 ;; show all higher headings, possibly with siblings
12969 (save-excursion
12970 (while (and (condition-case nil
12971 (progn (org-up-heading-all 1) t)
12972 (error nil))
12973 (not (bobp)))
12974 (org-flag-heading nil)
12975 (when siblings-p (org-show-siblings))))))))
12977 (defvar org-reveal-start-hook nil
12978 "Hook run before revealing a location.")
12980 (defun org-reveal (&optional siblings)
12981 "Show current entry, hierarchy above it, and the following headline.
12982 This can be used to show a consistent set of context around locations
12983 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12984 not t for the search context.
12986 With optional argument SIBLINGS, on each level of the hierarchy all
12987 siblings are shown. This repairs the tree structure to what it would
12988 look like when opened with hierarchical calls to `org-cycle'.
12989 With double optional argument \\[universal-argument] \\[universal-argument], \
12990 go to the parent and show the
12991 entire tree."
12992 (interactive "P")
12993 (run-hooks 'org-reveal-start-hook)
12994 (let ((org-show-hierarchy-above t)
12995 (org-show-following-heading t)
12996 (org-show-siblings (if siblings t org-show-siblings)))
12997 (org-show-context nil))
12998 (when (equal siblings '(16))
12999 (save-excursion
13000 (when (org-up-heading-safe)
13001 (org-show-subtree)
13002 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13004 (defun org-highlight-new-match (beg end)
13005 "Highlight from BEG to END and mark the highlight is an occur headline."
13006 (let ((ov (make-overlay beg end)))
13007 (overlay-put ov 'face 'secondary-selection)
13008 (overlay-put ov 'org-type 'org-occur)
13009 (push ov org-occur-highlights)))
13011 (defun org-remove-occur-highlights (&optional beg end noremove)
13012 "Remove the occur highlights from the buffer.
13013 BEG and END are ignored. If NOREMOVE is nil, remove this function
13014 from the `before-change-functions' in the current buffer."
13015 (interactive)
13016 (unless org-inhibit-highlight-removal
13017 (mapc 'delete-overlay org-occur-highlights)
13018 (setq org-occur-highlights nil)
13019 (setq org-occur-parameters nil)
13020 (unless noremove
13021 (remove-hook 'before-change-functions
13022 'org-remove-occur-highlights 'local))))
13024 ;;;; Priorities
13026 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13027 "Regular expression matching the priority indicator.")
13029 (defvar org-remove-priority-next-time nil)
13031 (defun org-priority-up ()
13032 "Increase the priority of the current item."
13033 (interactive)
13034 (org-priority 'up))
13036 (defun org-priority-down ()
13037 "Decrease the priority of the current item."
13038 (interactive)
13039 (org-priority 'down))
13041 (defun org-priority (&optional action)
13042 "Change the priority of an item.
13043 ACTION can be `set', `up', `down', or a character."
13044 (interactive)
13045 (unless org-enable-priority-commands
13046 (error "Priority commands are disabled"))
13047 (setq action (or action 'set))
13048 (let (current new news have remove)
13049 (save-excursion
13050 (org-back-to-heading t)
13051 (if (looking-at org-priority-regexp)
13052 (setq current (string-to-char (match-string 2))
13053 have t))
13054 (cond
13055 ((eq action 'remove)
13056 (setq remove t new ?\ ))
13057 ((or (eq action 'set)
13058 (if (featurep 'xemacs) (characterp action) (integerp action)))
13059 (if (not (eq action 'set))
13060 (setq new action)
13061 (message "Priority %c-%c, SPC to remove: "
13062 org-highest-priority org-lowest-priority)
13063 (save-match-data
13064 (setq new (read-char-exclusive))))
13065 (if (and (= (upcase org-highest-priority) org-highest-priority)
13066 (= (upcase org-lowest-priority) org-lowest-priority))
13067 (setq new (upcase new)))
13068 (cond ((equal new ?\ ) (setq remove t))
13069 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13070 (error "Priority must be between `%c' and `%c'"
13071 org-highest-priority org-lowest-priority))))
13072 ((eq action 'up)
13073 (setq new (if have
13074 (1- current) ; normal cycling
13075 ;; last priority was empty
13076 (if (eq last-command this-command)
13077 org-lowest-priority ; wrap around empty to lowest
13078 ;; default
13079 (if org-priority-start-cycle-with-default
13080 org-default-priority
13081 (1- org-default-priority))))))
13082 ((eq action 'down)
13083 (setq new (if have
13084 (1+ current) ; normal cycling
13085 ;; last priority was empty
13086 (if (eq last-command this-command)
13087 org-highest-priority ; wrap around empty to highest
13088 ;; default
13089 (if org-priority-start-cycle-with-default
13090 org-default-priority
13091 (1+ org-default-priority))))))
13092 (t (error "Invalid action")))
13093 (if (or (< (upcase new) org-highest-priority)
13094 (> (upcase new) org-lowest-priority))
13095 (if (and (memq action '(up down))
13096 (not have) (not (eq last-command this-command)))
13097 ;; `new' is from default priority
13098 (error
13099 "The default can not be set, see `org-default-priority' why")
13100 ;; normal cycling: `new' is beyond highest/lowest priority
13101 ;; and is wrapped around to the empty priority
13102 (setq remove t)))
13103 (setq news (format "%c" new))
13104 (if have
13105 (if remove
13106 (replace-match "" t t nil 1)
13107 (replace-match news t t nil 2))
13108 (if remove
13109 (error "No priority cookie found in line")
13110 (let ((case-fold-search nil))
13111 (looking-at org-todo-line-regexp))
13112 (if (match-end 2)
13113 (progn
13114 (goto-char (match-end 2))
13115 (insert " [#" news "]"))
13116 (goto-char (match-beginning 3))
13117 (insert "[#" news "] "))))
13118 (org-preserve-lc (org-set-tags nil 'align)))
13119 (if remove
13120 (message "Priority removed")
13121 (message "Priority of current item set to %s" news))))
13123 (defun org-get-priority (s)
13124 "Find priority cookie and return priority."
13125 (if (functionp org-get-priority-function)
13126 (funcall org-get-priority-function)
13127 (save-match-data
13128 (if (not (string-match org-priority-regexp s))
13129 (* 1000 (- org-lowest-priority org-default-priority))
13130 (* 1000 (- org-lowest-priority
13131 (string-to-char (match-string 2 s))))))))
13133 ;;;; Tags
13135 (defvar org-agenda-archives-mode)
13136 (defvar org-map-continue-from nil
13137 "Position from where mapping should continue.
13138 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13140 (defvar org-scanner-tags nil
13141 "The current tag list while the tags scanner is running.")
13142 (defvar org-trust-scanner-tags nil
13143 "Should `org-get-tags-at' use the tags for the scanner.
13144 This is for internal dynamical scoping only.
13145 When this is non-nil, the function `org-get-tags-at' will return the value
13146 of `org-scanner-tags' instead of building the list by itself. This
13147 can lead to large speed-ups when the tags scanner is used in a file with
13148 many entries, and when the list of tags is retrieved, for example to
13149 obtain a list of properties. Building the tags list for each entry in such
13150 a file becomes an N^2 operation - but with this variable set, it scales
13151 as N.")
13153 (defun org-scan-tags (action matcher todo-only &optional start-level)
13154 "Scan headline tags with inheritance and produce output ACTION.
13156 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13157 or `agenda' to produce an entry list for an agenda view. It can also be
13158 a Lisp form or a function that should be called at each matched headline, in
13159 this case the return value is a list of all return values from these calls.
13161 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13162 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13163 only lines with a not-done TODO keyword are included in the output.
13164 This should be the same variable that was scoped into
13165 and set by `org-make-tags-matcher' when it constructed MATCHER.
13167 START-LEVEL can be a string with asterisks, reducing the scope to
13168 headlines matching this string."
13169 (require 'org-agenda)
13170 (let* ((re (concat "^"
13171 (if start-level
13172 ;; Get the correct level to match
13173 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13174 org-outline-regexp)
13175 " *\\(\\<\\("
13176 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13177 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13178 (props (list 'face 'default
13179 'done-face 'org-agenda-done
13180 'undone-face 'default
13181 'mouse-face 'highlight
13182 'org-not-done-regexp org-not-done-regexp
13183 'org-todo-regexp org-todo-regexp
13184 'org-complex-heading-regexp org-complex-heading-regexp
13185 'help-echo
13186 (format "mouse-2 or RET jump to org file %s"
13187 (abbreviate-file-name
13188 (or (buffer-file-name (buffer-base-buffer))
13189 (buffer-name (buffer-base-buffer)))))))
13190 (case-fold-search nil)
13191 (org-map-continue-from nil)
13192 lspos tags tags-list
13193 (tags-alist (list (cons 0 org-file-tags)))
13194 (llast 0) rtn rtn1 level category i txt
13195 todo marker entry priority)
13196 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13197 (setq action (list 'lambda nil action)))
13198 (save-excursion
13199 (goto-char (point-min))
13200 (when (eq action 'sparse-tree)
13201 (org-overview)
13202 (org-remove-occur-highlights))
13203 (while (re-search-forward re nil t)
13204 (setq org-map-continue-from nil)
13205 (catch :skip
13206 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13207 tags (if (match-end 4) (org-match-string-no-properties 4)))
13208 (goto-char (setq lspos (match-beginning 0)))
13209 (setq level (org-reduced-level (org-outline-level))
13210 category (org-get-category))
13211 (setq i llast llast level)
13212 ;; remove tag lists from same and sublevels
13213 (while (>= i level)
13214 (when (setq entry (assoc i tags-alist))
13215 (setq tags-alist (delete entry tags-alist)))
13216 (setq i (1- i)))
13217 ;; add the next tags
13218 (when tags
13219 (setq tags (org-split-string tags ":")
13220 tags-alist
13221 (cons (cons level tags) tags-alist)))
13222 ;; compile tags for current headline
13223 (setq tags-list
13224 (if org-use-tag-inheritance
13225 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13226 tags)
13227 org-scanner-tags tags-list)
13228 (when org-use-tag-inheritance
13229 (setcdr (car tags-alist)
13230 (mapcar (lambda (x)
13231 (setq x (copy-sequence x))
13232 (org-add-prop-inherited x))
13233 (cdar tags-alist))))
13234 (when (and tags org-use-tag-inheritance
13235 (or (not (eq t org-use-tag-inheritance))
13236 org-tags-exclude-from-inheritance))
13237 ;; selective inheritance, remove uninherited ones
13238 (setcdr (car tags-alist)
13239 (org-remove-uninherited-tags (cdar tags-alist))))
13240 (when (and
13242 ;; eval matcher only when the todo condition is OK
13243 (and (or (not todo-only) (member todo org-not-done-keywords))
13244 (let ((case-fold-search t) (org-trust-scanner-tags t))
13245 (eval matcher)))
13247 ;; Call the skipper, but return t if it does not skip,
13248 ;; so that the `and' form continues evaluating
13249 (progn
13250 (unless (eq action 'sparse-tree) (org-agenda-skip))
13253 ;; Check if timestamps are deselecting this entry
13254 (or (not todo-only)
13255 (and (member todo org-not-done-keywords)
13256 (or (not org-agenda-tags-todo-honor-ignore-options)
13257 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13259 ;; Extra check for the archive tag
13260 ;; FIXME: Does the skipper already do this????
13262 (not (member org-archive-tag tags-list))
13263 ;; we have an archive tag, should we use this anyway?
13264 (or (not org-agenda-skip-archived-trees)
13265 (and (eq action 'agenda) org-agenda-archives-mode))))
13267 ;; select this headline
13268 (cond
13269 ((eq action 'sparse-tree)
13270 (and org-highlight-sparse-tree-matches
13271 (org-get-heading) (match-end 0)
13272 (org-highlight-new-match
13273 (match-beginning 1) (match-end 1)))
13274 (org-show-context 'tags-tree))
13275 ((eq action 'agenda)
13276 (setq txt (org-agenda-format-item
13278 (concat
13279 (if (eq org-tags-match-list-sublevels 'indented)
13280 (make-string (1- level) ?.) "")
13281 (org-get-heading))
13282 level category
13283 tags-list)
13284 priority (org-get-priority txt))
13285 (goto-char lspos)
13286 (setq marker (org-agenda-new-marker))
13287 (org-add-props txt props
13288 'org-marker marker 'org-hd-marker marker 'org-category category
13289 'todo-state todo
13290 'priority priority 'type "tagsmatch")
13291 (push txt rtn))
13292 ((functionp action)
13293 (setq org-map-continue-from nil)
13294 (save-excursion
13295 (setq rtn1 (funcall action))
13296 (push rtn1 rtn)))
13297 (t (error "Invalid action")))
13299 ;; if we are to skip sublevels, jump to end of subtree
13300 (unless org-tags-match-list-sublevels
13301 (org-end-of-subtree t)
13302 (backward-char 1))))
13303 ;; Get the correct position from where to continue
13304 (if org-map-continue-from
13305 (goto-char org-map-continue-from)
13306 (and (= (point) lspos) (end-of-line 1)))))
13307 (when (and (eq action 'sparse-tree)
13308 (not org-sparse-tree-open-archived-trees))
13309 (org-hide-archived-subtrees (point-min) (point-max)))
13310 (nreverse rtn)))
13312 (defun org-remove-uninherited-tags (tags)
13313 "Remove all tags that are not inherited from the list TAGS."
13314 (cond
13315 ((eq org-use-tag-inheritance t)
13316 (if org-tags-exclude-from-inheritance
13317 (org-delete-all org-tags-exclude-from-inheritance tags)
13318 tags))
13319 ((not org-use-tag-inheritance) nil)
13320 ((stringp org-use-tag-inheritance)
13321 (delq nil (mapcar
13322 (lambda (x)
13323 (if (and (string-match org-use-tag-inheritance x)
13324 (not (member x org-tags-exclude-from-inheritance)))
13325 x nil))
13326 tags)))
13327 ((listp org-use-tag-inheritance)
13328 (delq nil (mapcar
13329 (lambda (x)
13330 (if (member x org-use-tag-inheritance) x nil))
13331 tags)))))
13333 (defun org-match-sparse-tree (&optional todo-only match)
13334 "Create a sparse tree according to tags string MATCH.
13335 MATCH can contain positive and negative selection of tags, like
13336 \"+WORK+URGENT-WITHBOSS\".
13337 If optional argument TODO-ONLY is non-nil, only select lines that are
13338 also TODO lines."
13339 (interactive "P")
13340 (org-agenda-prepare-buffers (list (current-buffer)))
13341 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13343 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13345 (defvar org-cached-props nil)
13346 (defun org-cached-entry-get (pom property)
13347 (if (or (eq t org-use-property-inheritance)
13348 (and (stringp org-use-property-inheritance)
13349 (string-match org-use-property-inheritance property))
13350 (and (listp org-use-property-inheritance)
13351 (member property org-use-property-inheritance)))
13352 ;; Caching is not possible, check it directly
13353 (org-entry-get pom property 'inherit)
13354 ;; Get all properties, so that we can do complicated checks easily
13355 (cdr (assoc property (or org-cached-props
13356 (setq org-cached-props
13357 (org-entry-properties pom)))))))
13359 (defun org-global-tags-completion-table (&optional files)
13360 "Return the list of all tags in all agenda buffer/files.
13361 Optional FILES argument is a list of files which can be used
13362 instead of the agenda files."
13363 (save-excursion
13364 (org-uniquify
13365 (delq nil
13366 (apply 'append
13367 (mapcar
13368 (lambda (file)
13369 (set-buffer (find-file-noselect file))
13370 (append (org-get-buffer-tags)
13371 (mapcar (lambda (x) (if (stringp (car-safe x))
13372 (list (car-safe x)) nil))
13373 org-tag-alist)))
13374 (if (and files (car files))
13375 files
13376 (org-agenda-files))))))))
13378 (defun org-make-tags-matcher (match)
13379 "Create the TAGS/TODO matcher form for the selection string MATCH.
13381 The variable `todo-only' is scoped dynamically into this function.
13382 It will be set to t if the matcher restricts matching to TODO entries,
13383 otherwise will not be touched.
13385 Returns a cons of the selection string MATCH and the constructed
13386 lisp form implementing the matcher. The matcher is to be evaluated
13387 at an Org entry, with point on the headline, and returns t if the
13388 entry matches the selection string MATCH. The returned lisp form
13389 references two variables with information about the entry, which
13390 must be bound around the form's evaluation: todo, the TODO keyword
13391 at the entry (or nil of none); and tags-list, the list of all tags
13392 at the entry including inherited ones. Additionally, the category
13393 of the entry (if any) must be specified as the text property
13394 'org-category on the headline.
13396 See also `org-scan-tags'.
13398 (declare (special todo-only))
13399 (unless (boundp 'todo-only)
13400 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13401 (unless match
13402 ;; Get a new match request, with completion
13403 (let ((org-last-tags-completion-table
13404 (org-global-tags-completion-table)))
13405 (setq match (org-completing-read-no-i
13406 "Match: " 'org-tags-completion-function nil nil nil
13407 'org-tags-history))))
13409 ;; Parse the string and create a lisp form
13410 (let ((match0 match)
13411 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13412 minus tag mm
13413 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13414 orterms term orlist re-p str-p level-p level-op time-p
13415 prop-p pn pv po gv rest)
13416 (if (string-match "/+" match)
13417 ;; match contains also a todo-matching request
13418 (progn
13419 (setq tagsmatch (substring match 0 (match-beginning 0))
13420 todomatch (substring match (match-end 0)))
13421 (if (string-match "^!" todomatch)
13422 (setq todo-only t todomatch (substring todomatch 1)))
13423 (if (string-match "^\\s-*$" todomatch)
13424 (setq todomatch nil)))
13425 ;; only matching tags
13426 (setq tagsmatch match todomatch nil))
13428 ;; Make the tags matcher
13429 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13430 (setq tagsmatcher t)
13431 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13432 (while (setq term (pop orterms))
13433 (while (and (equal (substring term -1) "\\") orterms)
13434 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13435 (while (string-match re term)
13436 (setq rest (substring term (match-end 0))
13437 minus (and (match-end 1)
13438 (equal (match-string 1 term) "-"))
13439 tag (save-match-data (replace-regexp-in-string
13440 "\\\\-" "-"
13441 (match-string 2 term)))
13442 re-p (equal (string-to-char tag) ?{)
13443 level-p (match-end 4)
13444 prop-p (match-end 5)
13445 mm (cond
13446 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13447 (level-p
13448 (setq level-op (org-op-to-function (match-string 3 term)))
13449 `(,level-op level ,(string-to-number
13450 (match-string 4 term))))
13451 (prop-p
13452 (setq pn (match-string 5 term)
13453 po (match-string 6 term)
13454 pv (match-string 7 term)
13455 re-p (equal (string-to-char pv) ?{)
13456 str-p (equal (string-to-char pv) ?\")
13457 time-p (save-match-data
13458 (string-match "^\"[[<].*[]>]\"$" pv))
13459 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13460 (if time-p (setq pv (org-matcher-time pv)))
13461 (setq po (org-op-to-function po (if time-p 'time str-p)))
13462 (cond
13463 ((equal pn "CATEGORY")
13464 (setq gv '(get-text-property (point) 'org-category)))
13465 ((equal pn "TODO")
13466 (setq gv 'todo))
13468 (setq gv `(org-cached-entry-get nil ,pn))))
13469 (if re-p
13470 (if (eq po 'org<>)
13471 `(not (string-match ,pv (or ,gv "")))
13472 `(string-match ,pv (or ,gv "")))
13473 (if str-p
13474 `(,po (or ,gv "") ,pv)
13475 `(,po (string-to-number (or ,gv ""))
13476 ,(string-to-number pv) ))))
13477 (t `(member ,tag tags-list)))
13478 mm (if minus (list 'not mm) mm)
13479 term rest)
13480 (push mm tagsmatcher))
13481 (push (if (> (length tagsmatcher) 1)
13482 (cons 'and tagsmatcher)
13483 (car tagsmatcher))
13484 orlist)
13485 (setq tagsmatcher nil))
13486 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13487 (setq tagsmatcher
13488 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13489 ;; Make the todo matcher
13490 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13491 (setq todomatcher t)
13492 (setq orterms (org-split-string todomatch "|") orlist nil)
13493 (while (setq term (pop orterms))
13494 (while (string-match re term)
13495 (setq minus (and (match-end 1)
13496 (equal (match-string 1 term) "-"))
13497 kwd (match-string 2 term)
13498 re-p (equal (string-to-char kwd) ?{)
13499 term (substring term (match-end 0))
13500 mm (if re-p
13501 `(string-match ,(substring kwd 1 -1) todo)
13502 (list 'equal 'todo kwd))
13503 mm (if minus (list 'not mm) mm))
13504 (push mm todomatcher))
13505 (push (if (> (length todomatcher) 1)
13506 (cons 'and todomatcher)
13507 (car todomatcher))
13508 orlist)
13509 (setq todomatcher nil))
13510 (setq todomatcher (if (> (length orlist) 1)
13511 (cons 'or orlist) (car orlist))))
13513 ;; Return the string and lisp forms of the matcher
13514 (setq matcher (if todomatcher
13515 (list 'and tagsmatcher todomatcher)
13516 tagsmatcher))
13517 (when todo-only
13518 (setq matcher (list 'and '(member todo org-not-done-keywords)
13519 matcher)))
13520 (cons match0 matcher)))
13522 (defun org-op-to-function (op &optional stringp)
13523 "Turn an operator into the appropriate function."
13524 (setq op
13525 (cond
13526 ((equal op "<" ) '(< string< org-time<))
13527 ((equal op ">" ) '(> org-string> org-time>))
13528 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13529 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13530 ((member op '("=" "==")) '(= string= org-time=))
13531 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13532 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13534 (defun org<> (a b) (not (= a b)))
13535 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13536 (defun org-string>= (a b) (not (string< a b)))
13537 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13538 (defun org-string<> (a b) (not (string= a b)))
13539 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13540 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13541 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13542 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13543 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13544 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13545 (defun org-2ft (s)
13546 "Convert S to a floating point time.
13547 If S is already a number, just return it. If it is a string, parse
13548 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13549 (cond
13550 ((numberp s) s)
13551 ((stringp s)
13552 (condition-case nil
13553 (float-time (apply 'encode-time (org-parse-time-string s)))
13554 (error 0.)))
13555 (t 0.)))
13557 (defun org-time-today ()
13558 "Time in seconds today at 0:00.
13559 Returns the float number of seconds since the beginning of the
13560 epoch to the beginning of today (00:00)."
13561 (float-time (apply 'encode-time
13562 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13564 (defun org-matcher-time (s)
13565 "Interpret a time comparison value."
13566 (save-match-data
13567 (cond
13568 ((string= s "<now>") (float-time))
13569 ((string= s "<today>") (org-time-today))
13570 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13571 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13572 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13573 (+ (org-time-today)
13574 (* (string-to-number (match-string 1 s))
13575 (cdr (assoc (match-string 2 s)
13576 '(("d" . 86400.0) ("w" . 604800.0)
13577 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13578 (t (org-2ft s)))))
13580 (defun org-match-any-p (re list)
13581 "Does re match any element of list?"
13582 (setq list (mapcar (lambda (x) (string-match re x)) list))
13583 (delq nil list))
13585 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13586 (defvar org-tags-overlay (make-overlay 1 1))
13587 (org-detach-overlay org-tags-overlay)
13589 (defun org-get-local-tags-at (&optional pos)
13590 "Get a list of tags defined in the current headline."
13591 (org-get-tags-at pos 'local))
13593 (defun org-get-local-tags ()
13594 "Get a list of tags defined in the current headline."
13595 (org-get-tags-at nil 'local))
13597 (defun org-get-tags-at (&optional pos local)
13598 "Get a list of all headline tags applicable at POS.
13599 POS defaults to point. If tags are inherited, the list contains
13600 the targets in the same sequence as the headlines appear, i.e.
13601 the tags of the current headline come last.
13602 When LOCAL is non-nil, only return tags from the current headline,
13603 ignore inherited ones."
13604 (interactive)
13605 (if (and org-trust-scanner-tags
13606 (or (not pos) (equal pos (point)))
13607 (not local))
13608 org-scanner-tags
13609 (let (tags ltags lastpos parent)
13610 (save-excursion
13611 (save-restriction
13612 (widen)
13613 (goto-char (or pos (point)))
13614 (save-match-data
13615 (catch 'done
13616 (condition-case nil
13617 (progn
13618 (org-back-to-heading t)
13619 (while (not (equal lastpos (point)))
13620 (setq lastpos (point))
13621 (when (looking-at
13622 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13623 (setq ltags (org-split-string
13624 (org-match-string-no-properties 1) ":"))
13625 (when parent
13626 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13627 (setq tags (append
13628 (if parent
13629 (org-remove-uninherited-tags ltags)
13630 ltags)
13631 tags)))
13632 (or org-use-tag-inheritance (throw 'done t))
13633 (if local (throw 'done t))
13634 (or (org-up-heading-safe) (error nil))
13635 (setq parent t)))
13636 (error nil)))))
13637 (if local
13638 tags
13639 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13641 (defun org-add-prop-inherited (s)
13642 (add-text-properties 0 (length s) '(inherited t) s)
13645 (defun org-toggle-tag (tag &optional onoff)
13646 "Toggle the tag TAG for the current line.
13647 If ONOFF is `on' or `off', don't toggle but set to this state."
13648 (let (res current)
13649 (save-excursion
13650 (org-back-to-heading t)
13651 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13652 (point-at-eol) t)
13653 (progn
13654 (setq current (match-string 1))
13655 (replace-match ""))
13656 (setq current ""))
13657 (setq current (nreverse (org-split-string current ":")))
13658 (cond
13659 ((eq onoff 'on)
13660 (setq res t)
13661 (or (member tag current) (push tag current)))
13662 ((eq onoff 'off)
13663 (or (not (member tag current)) (setq current (delete tag current))))
13664 (t (if (member tag current)
13665 (setq current (delete tag current))
13666 (setq res t)
13667 (push tag current))))
13668 (end-of-line 1)
13669 (if current
13670 (progn
13671 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13672 (org-set-tags nil t))
13673 (delete-horizontal-space))
13674 (run-hooks 'org-after-tags-change-hook))
13675 res))
13677 (defun org-align-tags-here (to-col)
13678 ;; Assumes that this is a headline
13679 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13680 (beginning-of-line 1)
13681 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13682 (< pos (match-beginning 2)))
13683 (progn
13684 (setq tags-l (- (match-end 2) (match-beginning 2)))
13685 (goto-char (match-beginning 1))
13686 (insert " ")
13687 (delete-region (point) (1+ (match-beginning 2)))
13688 (setq ncol (max (current-column)
13689 (1+ col)
13690 (if (> to-col 0)
13691 to-col
13692 (- (abs to-col) tags-l))))
13693 (setq p (point))
13694 (insert (make-string (- ncol (current-column)) ?\ ))
13695 (setq ncol (current-column))
13696 (when indent-tabs-mode (tabify p (point-at-eol)))
13697 (org-move-to-column (min ncol col) t))
13698 (goto-char pos))))
13700 (defun org-set-tags-command (&optional arg just-align)
13701 "Call the set-tags command for the current entry."
13702 (interactive "P")
13703 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13704 (org-set-tags arg just-align)
13705 (save-excursion
13706 (org-back-to-heading t)
13707 (org-set-tags arg just-align))))
13709 (defun org-set-tags-to (data)
13710 "Set the tags of the current entry to DATA, replacing the current tags.
13711 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13712 If DATA is nil or the empty string, any tags will be removed."
13713 (interactive "sTags: ")
13714 (setq data
13715 (cond
13716 ((eq data nil) "")
13717 ((equal data "") "")
13718 ((stringp data)
13719 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13720 ":"))
13721 ((listp data)
13722 (concat ":" (mapconcat 'identity data ":") ":"))))
13723 (when data
13724 (save-excursion
13725 (org-back-to-heading t)
13726 (when (looking-at org-complex-heading-regexp)
13727 (if (match-end 5)
13728 (progn
13729 (goto-char (match-beginning 5))
13730 (insert data)
13731 (delete-region (point) (point-at-eol))
13732 (org-set-tags nil 'align))
13733 (goto-char (point-at-eol))
13734 (insert " " data)
13735 (org-set-tags nil 'align)))
13736 (beginning-of-line 1)
13737 (if (looking-at ".*?\\([ \t]+\\)$")
13738 (delete-region (match-beginning 1) (match-end 1))))))
13740 (defun org-align-all-tags ()
13741 "Align the tags i all headings."
13742 (interactive)
13743 (save-excursion
13744 (or (ignore-errors (org-back-to-heading t))
13745 (outline-next-heading))
13746 (if (org-at-heading-p)
13747 (org-set-tags t)
13748 (message "No headings"))))
13750 (defvar org-indent-indentation-per-level)
13751 (defun org-set-tags (&optional arg just-align)
13752 "Set the tags for the current headline.
13753 With prefix ARG, realign all tags in headings in the current buffer."
13754 (interactive "P")
13755 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13756 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13757 'region-start-level 'region))
13758 org-loop-over-headlines-in-active-region)
13759 (org-map-entries
13760 ;; We don't use ARG and JUST-ALIGN here these args are not
13761 ;; useful when looping over headlines
13762 `(org-set-tags)
13763 org-loop-over-headlines-in-active-region
13764 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13765 (let* ((re org-outline-regexp-bol)
13766 (current (unless arg (org-get-tags-string)))
13767 (col (current-column))
13768 (org-setting-tags t)
13769 table current-tags inherited-tags ; computed below when needed
13770 tags p0 c0 c1 rpl di tc level)
13771 (if arg
13772 (save-excursion
13773 (goto-char (point-min))
13774 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13775 (while (re-search-forward re nil t)
13776 (org-set-tags nil t)
13777 (end-of-line 1)))
13778 (message "All tags realigned to column %d" org-tags-column))
13779 (if just-align
13780 (setq tags current)
13781 ;; Get a new set of tags from the user
13782 (save-excursion
13783 (setq table (append org-tag-persistent-alist
13784 (or org-tag-alist (org-get-buffer-tags))
13785 (and
13786 org-complete-tags-always-offer-all-agenda-tags
13787 (org-global-tags-completion-table
13788 (org-agenda-files))))
13789 org-last-tags-completion-table table
13790 current-tags (org-split-string current ":")
13791 inherited-tags (nreverse
13792 (nthcdr (length current-tags)
13793 (nreverse (org-get-tags-at))))
13794 tags
13795 (if (or (eq t org-use-fast-tag-selection)
13796 (and org-use-fast-tag-selection
13797 (delq nil (mapcar 'cdr table))))
13798 (org-fast-tag-selection
13799 current-tags inherited-tags table
13800 (if org-fast-tag-selection-include-todo
13801 org-todo-key-alist))
13802 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13803 (org-trim
13804 (org-icompleting-read "Tags: "
13805 'org-tags-completion-function
13806 nil nil current 'org-tags-history))))))
13807 (while (string-match "[-+&]+" tags)
13808 ;; No boolean logic, just a list
13809 (setq tags (replace-match ":" t t tags))))
13811 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13813 (if org-tags-sort-function
13814 (setq tags (mapconcat 'identity
13815 (sort (org-split-string
13816 tags (org-re "[^[:alnum:]_@#%]+"))
13817 org-tags-sort-function) ":")))
13819 (if (string-match "\\`[\t ]*\\'" tags)
13820 (setq tags "")
13821 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13822 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13824 ;; Insert new tags at the correct column
13825 (beginning-of-line 1)
13826 (setq level (or (and (looking-at org-outline-regexp)
13827 (- (match-end 0) (point) 1))
13829 (cond
13830 ((and (equal current "") (equal tags "")))
13831 ((re-search-forward
13832 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13833 (point-at-eol) t)
13834 (if (equal tags "")
13835 (setq rpl "")
13836 (goto-char (match-beginning 0))
13837 (setq c0 (current-column)
13838 ;; compute offset for the case of org-indent-mode active
13839 di (if org-indent-mode
13840 (* (1- org-indent-indentation-per-level) (1- level))
13842 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13843 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13844 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13845 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13846 (replace-match rpl t t)
13847 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13848 tags)
13849 (t (error "Tags alignment failed")))
13850 (org-move-to-column col)
13851 (unless just-align
13852 (run-hooks 'org-after-tags-change-hook))))))
13854 (defun org-change-tag-in-region (beg end tag off)
13855 "Add or remove TAG for each entry in the region.
13856 This works in the agenda, and also in an org-mode buffer."
13857 (interactive
13858 (list (region-beginning) (region-end)
13859 (let ((org-last-tags-completion-table
13860 (if (derived-mode-p 'org-mode)
13861 (org-get-buffer-tags)
13862 (org-global-tags-completion-table))))
13863 (org-icompleting-read
13864 "Tag: " 'org-tags-completion-function nil nil nil
13865 'org-tags-history))
13866 (progn
13867 (message "[s]et or [r]emove? ")
13868 (equal (read-char-exclusive) ?r))))
13869 (if (fboundp 'deactivate-mark) (deactivate-mark))
13870 (let ((agendap (equal major-mode 'org-agenda-mode))
13871 l1 l2 m buf pos newhead (cnt 0))
13872 (goto-char end)
13873 (setq l2 (1- (org-current-line)))
13874 (goto-char beg)
13875 (setq l1 (org-current-line))
13876 (loop for l from l1 to l2 do
13877 (org-goto-line l)
13878 (setq m (get-text-property (point) 'org-hd-marker))
13879 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13880 (and agendap m))
13881 (setq buf (if agendap (marker-buffer m) (current-buffer))
13882 pos (if agendap m (point)))
13883 (with-current-buffer buf
13884 (save-excursion
13885 (save-restriction
13886 (goto-char pos)
13887 (setq cnt (1+ cnt))
13888 (org-toggle-tag tag (if off 'off 'on))
13889 (setq newhead (org-get-heading)))))
13890 (and agendap (org-agenda-change-all-lines newhead m))))
13891 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13893 (defun org-tags-completion-function (string predicate &optional flag)
13894 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13895 (confirm (lambda (x) (stringp (car x)))))
13896 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13897 (setq s1 (match-string 1 string)
13898 s2 (match-string 2 string))
13899 (setq s1 "" s2 string))
13900 (cond
13901 ((eq flag nil)
13902 ;; try completion
13903 (setq rtn (try-completion s2 ctable confirm))
13904 (if (stringp rtn)
13905 (setq rtn
13906 (concat s1 s2 (substring rtn (length s2))
13907 (if (and org-add-colon-after-tag-completion
13908 (assoc rtn ctable))
13909 ":" ""))))
13910 rtn)
13911 ((eq flag t)
13912 ;; all-completions
13913 (all-completions s2 ctable confirm)
13915 ((eq flag 'lambda)
13916 ;; exact match?
13917 (assoc s2 ctable)))
13920 (defun org-fast-tag-insert (kwd tags face &optional end)
13921 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13922 (insert (format "%-12s" (concat kwd ":"))
13923 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13924 (or end "")))
13926 (defun org-fast-tag-show-exit (flag)
13927 (save-excursion
13928 (org-goto-line 3)
13929 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13930 (replace-match ""))
13931 (when flag
13932 (end-of-line 1)
13933 (org-move-to-column (- (window-width) 19) t)
13934 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13936 (defun org-set-current-tags-overlay (current prefix)
13937 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13938 (if (featurep 'xemacs)
13939 (org-overlay-display org-tags-overlay (concat prefix s)
13940 'secondary-selection)
13941 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13942 (org-overlay-display org-tags-overlay (concat prefix s)))))
13944 (defvar org-last-tag-selection-key nil)
13945 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13946 "Fast tag selection with single keys.
13947 CURRENT is the current list of tags in the headline, INHERITED is the
13948 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13949 possibly with grouping information. TODO-TABLE is a similar table with
13950 TODO keywords, should these have keys assigned to them.
13951 If the keys are nil, a-z are automatically assigned.
13952 Returns the new tags string, or nil to not change the current settings."
13953 (let* ((fulltable (append table todo-table))
13954 (maxlen (apply 'max (mapcar
13955 (lambda (x)
13956 (if (stringp (car x)) (string-width (car x)) 0))
13957 fulltable)))
13958 (buf (current-buffer))
13959 (expert (eq org-fast-tag-selection-single-key 'expert))
13960 (buffer-tags nil)
13961 (fwidth (+ maxlen 3 1 3))
13962 (ncol (/ (- (window-width) 4) fwidth))
13963 (i-face 'org-done)
13964 (c-face 'org-todo)
13965 tg cnt e c char c1 c2 ntable tbl rtn
13966 ov-start ov-end ov-prefix
13967 (exit-after-next org-fast-tag-selection-single-key)
13968 (done-keywords org-done-keywords)
13969 groups ingroup)
13970 (save-excursion
13971 (beginning-of-line 1)
13972 (if (looking-at
13973 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13974 (setq ov-start (match-beginning 1)
13975 ov-end (match-end 1)
13976 ov-prefix "")
13977 (setq ov-start (1- (point-at-eol))
13978 ov-end (1+ ov-start))
13979 (skip-chars-forward "^\n\r")
13980 (setq ov-prefix
13981 (concat
13982 (buffer-substring (1- (point)) (point))
13983 (if (> (current-column) org-tags-column)
13985 (make-string (- org-tags-column (current-column)) ?\ ))))))
13986 (move-overlay org-tags-overlay ov-start ov-end)
13987 (save-window-excursion
13988 (if expert
13989 (set-buffer (get-buffer-create " *Org tags*"))
13990 (delete-other-windows)
13991 (split-window-vertically)
13992 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13993 (erase-buffer)
13994 (org-set-local 'org-done-keywords done-keywords)
13995 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13996 (org-fast-tag-insert "Current" current c-face "\n\n")
13997 (org-fast-tag-show-exit exit-after-next)
13998 (org-set-current-tags-overlay current ov-prefix)
13999 (setq tbl fulltable char ?a cnt 0)
14000 (while (setq e (pop tbl))
14001 (cond
14002 ((equal (car e) :startgroup)
14003 (push '() groups) (setq ingroup t)
14004 (when (not (= cnt 0))
14005 (setq cnt 0)
14006 (insert "\n"))
14007 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14008 ((equal (car e) :endgroup)
14009 (setq ingroup nil cnt 0)
14010 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14011 ((equal e '(:newline))
14012 (when (not (= cnt 0))
14013 (setq cnt 0)
14014 (insert "\n")
14015 (setq e (car tbl))
14016 (while (equal (car tbl) '(:newline))
14017 (insert "\n")
14018 (setq tbl (cdr tbl)))))
14020 (setq tg (copy-sequence (car e)) c2 nil)
14021 (if (cdr e)
14022 (setq c (cdr e))
14023 ;; automatically assign a character.
14024 (setq c1 (string-to-char
14025 (downcase (substring
14026 tg (if (= (string-to-char tg) ?@) 1 0)))))
14027 (if (or (rassoc c1 ntable) (rassoc c1 table))
14028 (while (or (rassoc char ntable) (rassoc char table))
14029 (setq char (1+ char)))
14030 (setq c2 c1))
14031 (setq c (or c2 char)))
14032 (if ingroup (push tg (car groups)))
14033 (setq tg (org-add-props tg nil 'face
14034 (cond
14035 ((not (assoc tg table))
14036 (org-get-todo-face tg))
14037 ((member tg current) c-face)
14038 ((member tg inherited) i-face))))
14039 (if (and (= cnt 0) (not ingroup)) (insert " "))
14040 (insert "[" c "] " tg (make-string
14041 (- fwidth 4 (length tg)) ?\ ))
14042 (push (cons tg c) ntable)
14043 (when (= (setq cnt (1+ cnt)) ncol)
14044 (insert "\n")
14045 (if ingroup (insert " "))
14046 (setq cnt 0)))))
14047 (setq ntable (nreverse ntable))
14048 (insert "\n")
14049 (goto-char (point-min))
14050 (if (not expert) (org-fit-window-to-buffer))
14051 (setq rtn
14052 (catch 'exit
14053 (while t
14054 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14055 (if (not groups) "no " "")
14056 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14057 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14058 (setq org-last-tag-selection-key c)
14059 (cond
14060 ((= c ?\r) (throw 'exit t))
14061 ((= c ?!)
14062 (setq groups (not groups))
14063 (goto-char (point-min))
14064 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14065 ((= c ?\C-c)
14066 (if (not expert)
14067 (org-fast-tag-show-exit
14068 (setq exit-after-next (not exit-after-next)))
14069 (setq expert nil)
14070 (delete-other-windows)
14071 (set-window-buffer (split-window-vertically) " *Org tags*")
14072 (org-switch-to-buffer-other-window " *Org tags*")
14073 (org-fit-window-to-buffer)))
14074 ((or (= c ?\C-g)
14075 (and (= c ?q) (not (rassoc c ntable))))
14076 (org-detach-overlay org-tags-overlay)
14077 (setq quit-flag t))
14078 ((= c ?\ )
14079 (setq current nil)
14080 (if exit-after-next (setq exit-after-next 'now)))
14081 ((= c ?\t)
14082 (condition-case nil
14083 (setq tg (org-icompleting-read
14084 "Tag: "
14085 (or buffer-tags
14086 (with-current-buffer buf
14087 (org-get-buffer-tags)))))
14088 (quit (setq tg "")))
14089 (when (string-match "\\S-" tg)
14090 (add-to-list 'buffer-tags (list tg))
14091 (if (member tg current)
14092 (setq current (delete tg current))
14093 (push tg current)))
14094 (if exit-after-next (setq exit-after-next 'now)))
14095 ((setq e (rassoc c todo-table) tg (car e))
14096 (with-current-buffer buf
14097 (save-excursion (org-todo tg)))
14098 (if exit-after-next (setq exit-after-next 'now)))
14099 ((setq e (rassoc c ntable) tg (car e))
14100 (if (member tg current)
14101 (setq current (delete tg current))
14102 (loop for g in groups do
14103 (if (member tg g)
14104 (mapc (lambda (x)
14105 (setq current (delete x current)))
14106 g)))
14107 (push tg current))
14108 (if exit-after-next (setq exit-after-next 'now))))
14110 ;; Create a sorted list
14111 (setq current
14112 (sort current
14113 (lambda (a b)
14114 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14115 (if (eq exit-after-next 'now) (throw 'exit t))
14116 (goto-char (point-min))
14117 (beginning-of-line 2)
14118 (delete-region (point) (point-at-eol))
14119 (org-fast-tag-insert "Current" current c-face)
14120 (org-set-current-tags-overlay current ov-prefix)
14121 (while (re-search-forward
14122 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14123 (setq tg (match-string 1))
14124 (add-text-properties
14125 (match-beginning 1) (match-end 1)
14126 (list 'face
14127 (cond
14128 ((member tg current) c-face)
14129 ((member tg inherited) i-face)
14130 (t (get-text-property (match-beginning 1) 'face))))))
14131 (goto-char (point-min)))))
14132 (org-detach-overlay org-tags-overlay)
14133 (if rtn
14134 (mapconcat 'identity current ":")
14135 nil))))
14137 (defun org-get-tags-string ()
14138 "Get the TAGS string in the current headline."
14139 (unless (org-at-heading-p t)
14140 (error "Not on a heading"))
14141 (save-excursion
14142 (beginning-of-line 1)
14143 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14144 (org-match-string-no-properties 1)
14145 "")))
14147 (defun org-get-tags ()
14148 "Get the list of tags specified in the current headline."
14149 (org-split-string (org-get-tags-string) ":"))
14151 (defun org-get-buffer-tags ()
14152 "Get a table of all tags used in the buffer, for completion."
14153 (let (tags)
14154 (save-excursion
14155 (goto-char (point-min))
14156 (while (re-search-forward
14157 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14158 (when (equal (char-after (point-at-bol 0)) ?*)
14159 (mapc (lambda (x) (add-to-list 'tags x))
14160 (org-split-string (org-match-string-no-properties 1) ":")))))
14161 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14162 (mapcar 'list tags)))
14164 ;;;; The mapping API
14166 ;;;###autoload
14167 (defun org-map-entries (func &optional match scope &rest skip)
14168 "Call FUNC at each headline selected by MATCH in SCOPE.
14170 FUNC is a function or a lisp form. The function will be called without
14171 arguments, with the cursor positioned at the beginning of the headline.
14172 The return values of all calls to the function will be collected and
14173 returned as a list.
14175 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14176 does not need to preserve point. After evaluation, the cursor will be
14177 moved to the end of the line (presumably of the headline of the
14178 processed entry) and search continues from there. Under some
14179 circumstances, this may not produce the wanted results. For example,
14180 if you have removed (e.g. archived) the current (sub)tree it could
14181 mean that the next entry will be skipped entirely. In such cases, you
14182 can specify the position from where search should continue by making
14183 FUNC set the variable `org-map-continue-from' to the desired buffer
14184 position.
14186 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14187 Only headlines that are matched by this query will be considered during
14188 the iteration. When MATCH is nil or t, all headlines will be
14189 visited by the iteration.
14191 SCOPE determines the scope of this command. It can be any of:
14193 nil The current buffer, respecting the restriction if any
14194 tree The subtree started with the entry at point
14195 region The entries within the active region, if any
14196 region-start-level
14197 The entries within the active region, but only those at
14198 the same level than the first one.
14199 file The current buffer, without restriction
14200 file-with-archives
14201 The current buffer, and any archives associated with it
14202 agenda All agenda files
14203 agenda-with-archives
14204 All agenda files with any archive files associated with them
14205 \(file1 file2 ...)
14206 If this is a list, all files in the list will be scanned
14208 The remaining args are treated as settings for the skipping facilities of
14209 the scanner. The following items can be given here:
14211 archive skip trees with the archive tag.
14212 comment skip trees with the COMMENT keyword
14213 function or Emacs Lisp form:
14214 will be used as value for `org-agenda-skip-function', so whenever
14215 the function returns t, FUNC will not be called for that
14216 entry and search will continue from the point where the
14217 function leaves it.
14219 If your function needs to retrieve the tags including inherited tags
14220 at the *current* entry, you can use the value of the variable
14221 `org-scanner-tags' which will be much faster than getting the value
14222 with `org-get-tags-at'. If your function gets properties with
14223 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14224 to t around the call to `org-entry-properties' to get the same speedup.
14225 Note that if your function moves around to retrieve tags and properties at
14226 a *different* entry, you cannot use these techniques."
14227 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14228 (not (org-region-active-p)))
14229 (let* ((org-agenda-archives-mode nil) ; just to make sure
14230 (org-agenda-skip-archived-trees (memq 'archive skip))
14231 (org-agenda-skip-comment-trees (memq 'comment skip))
14232 (org-agenda-skip-function
14233 (car (org-delete-all '(comment archive) skip)))
14234 (org-tags-match-list-sublevels t)
14235 (start-level (eq scope 'region-start-level))
14236 matcher file res
14237 org-todo-keywords-for-agenda
14238 org-done-keywords-for-agenda
14239 org-todo-keyword-alist-for-agenda
14240 org-drawers-for-agenda
14241 org-tag-alist-for-agenda
14242 todo-only)
14244 (cond
14245 ((eq match t) (setq matcher t))
14246 ((eq match nil) (setq matcher t))
14247 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14249 (save-excursion
14250 (save-restriction
14251 (cond ((eq scope 'tree)
14252 (org-back-to-heading t)
14253 (org-narrow-to-subtree)
14254 (setq scope nil))
14255 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14256 (org-region-active-p))
14257 ;; If needed, set start-level to a string like "2"
14258 (when start-level
14259 (save-excursion
14260 (goto-char (region-beginning))
14261 (unless (org-at-heading-p) (outline-next-heading))
14262 (setq start-level (org-current-level))))
14263 (narrow-to-region (region-beginning)
14264 (save-excursion
14265 (goto-char (region-end))
14266 (unless (and (bolp) (org-at-heading-p))
14267 (outline-next-heading))
14268 (point)))
14269 (setq scope nil)))
14271 (if (not scope)
14272 (progn
14273 (org-agenda-prepare-buffers
14274 (list (buffer-file-name (current-buffer))))
14275 (setq res (org-scan-tags func matcher todo-only start-level)))
14276 ;; Get the right scope
14277 (cond
14278 ((and scope (listp scope) (symbolp (car scope)))
14279 (setq scope (eval scope)))
14280 ((eq scope 'agenda)
14281 (setq scope (org-agenda-files t)))
14282 ((eq scope 'agenda-with-archives)
14283 (setq scope (org-agenda-files t))
14284 (setq scope (org-add-archive-files scope)))
14285 ((eq scope 'file)
14286 (setq scope (list (buffer-file-name))))
14287 ((eq scope 'file-with-archives)
14288 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14289 (org-agenda-prepare-buffers scope)
14290 (while (setq file (pop scope))
14291 (with-current-buffer (org-find-base-buffer-visiting file)
14292 (save-excursion
14293 (save-restriction
14294 (widen)
14295 (goto-char (point-min))
14296 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14297 res)))
14299 ;;;; Properties
14301 ;;; Setting and retrieving properties
14303 (defconst org-special-properties
14304 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14305 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14306 "The special properties valid in Org-mode.
14308 These are properties that are not defined in the property drawer,
14309 but in some other way.")
14311 (defconst org-default-properties
14312 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14313 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14314 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14315 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14316 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14317 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14318 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14319 "Some properties that are used by Org-mode for various purposes.
14320 Being in this list makes sure that they are offered for completion.")
14322 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14323 "Regular expression matching the first line of a property drawer.")
14325 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14326 "Regular expression matching the last line of a property drawer.")
14328 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14329 "Regular expression matching the first line of a property drawer.")
14331 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14332 "Regular expression matching the first line of a property drawer.")
14334 (defconst org-property-drawer-re
14335 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14336 org-property-end-re "\\)\n?")
14337 "Matches an entire property drawer.")
14339 (defconst org-clock-drawer-re
14340 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14341 org-property-end-re "\\)\n?")
14342 "Matches an entire clock drawer.")
14344 (defsubst org-re-property (property)
14345 "Return a regexp matching a PROPERTY line.
14346 Match group 1 will be set to the value."
14347 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14349 (defsubst org-re-property-keyword (property)
14350 "Return a regexp matching a PROPERTY line, possibly with no
14351 value for the property."
14352 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14354 (defun org-property-action ()
14355 "Do an action on properties."
14356 (interactive)
14357 (let (c)
14358 (org-at-property-p)
14359 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14360 (setq c (read-char-exclusive))
14361 (cond
14362 ((equal c ?s)
14363 (call-interactively 'org-set-property))
14364 ((equal c ?d)
14365 (call-interactively 'org-delete-property))
14366 ((equal c ?D)
14367 (call-interactively 'org-delete-property-globally))
14368 ((equal c ?c)
14369 (call-interactively 'org-compute-property-at-point))
14370 (t (error "No such property action %c" c)))))
14372 (defun org-inc-effort ()
14373 "Increment the value of the effort property in the current entry."
14374 (interactive)
14375 (org-set-effort nil t))
14377 (defun org-set-effort (&optional value increment)
14378 "Set the effort property of the current entry.
14379 With numerical prefix arg, use the nth allowed value, 0 stands for the
14380 10th allowed value.
14382 When INCREMENT is non-nil, set the property to the next allowed value."
14383 (interactive "P")
14384 (if (equal value 0) (setq value 10))
14385 (let* ((completion-ignore-case t)
14386 (prop org-effort-property)
14387 (cur (org-entry-get nil prop))
14388 (allowed (org-property-get-allowed-values nil prop 'table))
14389 (existing (mapcar 'list (org-property-values prop)))
14391 (val (cond
14392 ((stringp value) value)
14393 ((and allowed (integerp value))
14394 (or (car (nth (1- value) allowed))
14395 (car (org-last allowed))))
14396 ((and allowed increment)
14397 (or (caadr (member (list cur) allowed))
14398 (error "Allowed effort values are not set")))
14399 (allowed
14400 (message "Select 1-9,0, [RET%s]: %s"
14401 (if cur (concat "=" cur) "")
14402 (mapconcat 'car allowed " "))
14403 (setq rpl (read-char-exclusive))
14404 (if (equal rpl ?\r)
14406 (setq rpl (- rpl ?0))
14407 (if (equal rpl 0) (setq rpl 10))
14408 (if (and (> rpl 0) (<= rpl (length allowed)))
14409 (car (nth (1- rpl) allowed))
14410 (org-completing-read "Effort: " allowed nil))))
14412 (let (org-completion-use-ido org-completion-use-iswitchb)
14413 (org-completing-read
14414 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14415 (concat "[" cur "]") "")
14416 ": ")
14417 existing nil nil "" nil cur))))))
14418 (unless (equal (org-entry-get nil prop) val)
14419 (org-entry-put nil prop val))
14420 (message "%s is now %s" prop val)))
14422 (defun org-at-property-p ()
14423 "Is cursor inside a property drawer?"
14424 (save-excursion
14425 (beginning-of-line 1)
14426 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14427 (save-match-data ;; Used by calling procedures
14428 (let ((p (point))
14429 (range (unless (org-before-first-heading-p)
14430 (org-get-property-block))))
14431 (and range (<= (car range) p) (< p (cdr range))))))))
14433 (defun org-get-property-block (&optional beg end force)
14434 "Return the (beg . end) range of the body of the property drawer.
14435 BEG and END are the beginning and end of the current subtree, or of
14436 the part before the first headline. If they are not given, they will
14437 be found. If the drawer does not exist and FORCE is non-nil, create
14438 the drawer."
14439 (catch 'exit
14440 (save-excursion
14441 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14442 (progn (org-back-to-heading t) (point))))
14443 (end (or end (and (not (outline-next-heading)) (point-max))
14444 (point))))
14445 (goto-char beg)
14446 (if (re-search-forward org-property-start-re end t)
14447 (setq beg (1+ (match-end 0)))
14448 (if force
14449 (save-excursion
14450 (org-insert-property-drawer)
14451 (setq end (progn (outline-next-heading) (point))))
14452 (throw 'exit nil))
14453 (goto-char beg)
14454 (if (re-search-forward org-property-start-re end t)
14455 (setq beg (1+ (match-end 0)))))
14456 (if (re-search-forward org-property-end-re end t)
14457 (setq end (match-beginning 0))
14458 (or force (throw 'exit nil))
14459 (goto-char beg)
14460 (setq end beg)
14461 (org-indent-line)
14462 (insert ":END:\n"))
14463 (cons beg end)))))
14465 (defun org-entry-properties (&optional pom which specific)
14466 "Get all properties of the entry at point-or-marker POM.
14467 This includes the TODO keyword, the tags, time strings for deadline,
14468 scheduled, and clocking, and any additional properties defined in the
14469 entry. The return value is an alist, keys may occur multiple times
14470 if the property key was used several times.
14471 POM may also be nil, in which case the current entry is used.
14472 If WHICH is nil or `all', get all properties. If WHICH is
14473 `special' or `standard', only get that subclass. If WHICH
14474 is a string only get exactly this property. SPECIFIC can be a string, the
14475 specific property we are interested in. Specifying it can speed
14476 things up because then unnecessary parsing is avoided."
14477 (setq which (or which 'all))
14478 (org-with-point-at pom
14479 (let ((clockstr (substring org-clock-string 0 -1))
14480 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14481 (case-fold-search nil)
14482 beg end range props sum-props key key1 value string clocksum clocksumt)
14483 (save-excursion
14484 (when (condition-case nil
14485 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14486 (error nil))
14487 (setq beg (point))
14488 (setq sum-props (get-text-property (point) 'org-summaries))
14489 (setq clocksum (get-text-property (point) :org-clock-minutes)
14490 clocksumt (get-text-property (point) :org-clock-minutes-today))
14491 (outline-next-heading)
14492 (setq end (point))
14493 (when (memq which '(all special))
14494 ;; Get the special properties, like TODO and tags
14495 (goto-char beg)
14496 (when (and (or (not specific) (string= specific "TODO"))
14497 (looking-at org-todo-line-regexp) (match-end 2))
14498 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14499 (when (and (or (not specific) (string= specific "PRIORITY"))
14500 (looking-at org-priority-regexp))
14501 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14502 (when (or (not specific) (string= specific "FILE"))
14503 (push (cons "FILE" buffer-file-name) props))
14504 (when (and (or (not specific) (string= specific "TAGS"))
14505 (setq value (org-get-tags-string))
14506 (string-match "\\S-" value))
14507 (push (cons "TAGS" value) props))
14508 (when (and (or (not specific) (string= specific "ALLTAGS"))
14509 (setq value (org-get-tags-at)))
14510 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14511 ":"))
14512 props))
14513 (when (or (not specific) (string= specific "BLOCKED"))
14514 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14515 (when (or (not specific)
14516 (member specific
14517 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14518 "TIMESTAMP" "TIMESTAMP_IA")))
14519 (catch 'match
14520 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14521 (setq key (if (match-end 1)
14522 (substring (org-match-string-no-properties 1)
14523 0 -1))
14524 string (if (equal key clockstr)
14525 (org-trim
14526 (buffer-substring-no-properties
14527 (match-beginning 3) (goto-char
14528 (point-at-eol))))
14529 (substring (org-match-string-no-properties 3)
14530 1 -1)))
14531 ;; Get the correct property name from the key. This is
14532 ;; necessary if the user has configured time keywords.
14533 (setq key1 (concat key ":"))
14534 (cond
14535 ((not key)
14536 (setq key
14537 (if (= (char-after (match-beginning 3)) ?\[)
14538 "TIMESTAMP_IA" "TIMESTAMP")))
14539 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14540 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14541 ((equal key1 org-closed-string) (setq key "CLOSED"))
14542 ((equal key1 org-clock-string) (setq key "CLOCK")))
14543 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14544 (progn
14545 (push (cons key string) props)
14546 ;; no need to search further if match is found
14547 (throw 'match t))
14548 (when (or (equal key "CLOCK") (not (assoc key props)))
14549 (push (cons key string) props)))))))
14551 (when (memq which '(all standard))
14552 ;; Get the standard properties, like :PROP: ...
14553 (setq range (org-get-property-block beg end))
14554 (when range
14555 (goto-char (car range))
14556 (while (re-search-forward
14557 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14558 (cdr range) t)
14559 (setq key (org-match-string-no-properties 1)
14560 value (org-trim (or (org-match-string-no-properties 2) "")))
14561 (unless (member key excluded)
14562 (push (cons key (or value "")) props)))))
14563 (if clocksum
14564 (push (cons "CLOCKSUM"
14565 (org-columns-number-to-string (/ (float clocksum) 60.)
14566 'add_times))
14567 props))
14568 (if clocksumt
14569 (push (cons "CLOCKSUM_T"
14570 (org-columns-number-to-string (/ (float clocksumt) 60.)
14571 'add_times))
14572 props))
14573 (unless (assoc "CATEGORY" props)
14574 (push (cons "CATEGORY" (org-get-category)) props))
14575 (append sum-props (nreverse props)))))))
14577 (defun org-entry-get (pom property &optional inherit literal-nil)
14578 "Get value of PROPERTY for entry or content at point-or-marker POM.
14579 If INHERIT is non-nil and the entry does not have the property,
14580 then also check higher levels of the hierarchy.
14581 If INHERIT is the symbol `selective', use inheritance only if the setting
14582 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14583 If the property is present but empty, the return value is the empty string.
14584 If the property is not present at all, nil is returned.
14586 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14587 do not interpret it as the list atom nil. This is used for inheritance
14588 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14589 (org-with-point-at pom
14590 (if (and inherit (if (eq inherit 'selective)
14591 (org-property-inherit-p property)
14593 (org-entry-get-with-inheritance property literal-nil)
14594 (if (member property org-special-properties)
14595 ;; We need a special property. Use `org-entry-properties' to
14596 ;; retrieve it, but specify the wanted property
14597 (cdr (assoc property (org-entry-properties nil 'special property)))
14598 (let* ((range (org-get-property-block))
14599 (props (list (or (assoc property org-file-properties)
14600 (assoc property org-global-properties)
14601 (assoc property org-global-properties-fixed))))
14602 (ap (lambda (key)
14603 (when (re-search-forward
14604 (org-re-property key) (cdr range) t)
14605 (setq props
14606 (org-update-property-plist
14608 (if (match-end 1)
14609 (org-match-string-no-properties 1) "")
14610 props)))))
14611 val)
14612 (when (and range (goto-char (car range)))
14613 (funcall ap property)
14614 (goto-char (car range))
14615 (while (funcall ap (concat property "+")))
14616 (setq val (cdr (assoc property props)))
14617 (when val (if literal-nil val (org-not-nil val)))))))))
14619 (defun org-property-or-variable-value (var &optional inherit)
14620 "Check if there is a property fixing the value of VAR.
14621 If yes, return this value. If not, return the current value of the variable."
14622 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14623 (if (and prop (stringp prop) (string-match "\\S-" prop))
14624 (read prop)
14625 (symbol-value var))))
14627 (defun org-entry-delete (pom property)
14628 "Delete the property PROPERTY from entry at point-or-marker POM."
14629 (org-with-point-at pom
14630 (if (member property org-special-properties)
14631 nil ; cannot delete these properties.
14632 (let ((range (org-get-property-block)))
14633 (if (and range
14634 (goto-char (car range))
14635 (re-search-forward
14636 (org-re-property property)
14637 (cdr range) t))
14638 (progn
14639 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14641 nil)))))
14643 ;; Multi-values properties are properties that contain multiple values
14644 ;; These values are assumed to be single words, separated by whitespace.
14645 (defun org-entry-add-to-multivalued-property (pom property value)
14646 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14647 (let* ((old (org-entry-get pom property))
14648 (values (and old (org-split-string old "[ \t]"))))
14649 (setq value (org-entry-protect-space value))
14650 (unless (member value values)
14651 (setq values (cons value values))
14652 (org-entry-put pom property
14653 (mapconcat 'identity values " ")))))
14655 (defun org-entry-remove-from-multivalued-property (pom property value)
14656 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14657 (let* ((old (org-entry-get pom property))
14658 (values (and old (org-split-string old "[ \t]"))))
14659 (setq value (org-entry-protect-space value))
14660 (when (member value values)
14661 (setq values (delete value values))
14662 (org-entry-put pom property
14663 (mapconcat 'identity values " ")))))
14665 (defun org-entry-member-in-multivalued-property (pom property value)
14666 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14667 (let* ((old (org-entry-get pom property))
14668 (values (and old (org-split-string old "[ \t]"))))
14669 (setq value (org-entry-protect-space value))
14670 (member value values)))
14672 (defun org-entry-get-multivalued-property (pom property)
14673 "Return a list of values in a multivalued property."
14674 (let* ((value (org-entry-get pom property))
14675 (values (and value (org-split-string value "[ \t]"))))
14676 (mapcar 'org-entry-restore-space values)))
14678 (defun org-entry-put-multivalued-property (pom property &rest values)
14679 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14680 VALUES should be a list of strings. Spaces will be protected."
14681 (org-entry-put pom property
14682 (mapconcat 'org-entry-protect-space values " "))
14683 (let* ((value (org-entry-get pom property))
14684 (values (and value (org-split-string value "[ \t]"))))
14685 (mapcar 'org-entry-restore-space values)))
14687 (defun org-entry-protect-space (s)
14688 "Protect spaces and newline in string S."
14689 (while (string-match " " s)
14690 (setq s (replace-match "%20" t t s)))
14691 (while (string-match "\n" s)
14692 (setq s (replace-match "%0A" t t s)))
14695 (defun org-entry-restore-space (s)
14696 "Restore spaces and newline in string S."
14697 (while (string-match "%20" s)
14698 (setq s (replace-match " " t t s)))
14699 (while (string-match "%0A" s)
14700 (setq s (replace-match "\n" t t s)))
14703 (defvar org-entry-property-inherited-from (make-marker)
14704 "Marker pointing to the entry from where a property was inherited.
14705 Each call to `org-entry-get-with-inheritance' will set this marker to the
14706 location of the entry where the inheritance search matched. If there was
14707 no match, the marker will point nowhere.
14708 Note that also `org-entry-get' calls this function, if the INHERIT flag
14709 is set.")
14711 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14712 "Get PROPERTY of entry or content at point, search higher levels if needed.
14713 The search will stop at the first ancestor which has the property defined.
14714 If the value found is \"nil\", return nil to show that the property
14715 should be considered as undefined (this is the meaning of nil here).
14716 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14717 (move-marker org-entry-property-inherited-from nil)
14718 (let (tmp)
14719 (save-excursion
14720 (save-restriction
14721 (widen)
14722 (catch 'ex
14723 (while t
14724 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14725 (or (ignore-errors (org-back-to-heading t))
14726 (goto-char (point-min)))
14727 (move-marker org-entry-property-inherited-from (point))
14728 (throw 'ex tmp))
14729 (or (ignore-errors (org-up-heading-safe))
14730 (throw 'ex nil))))))
14731 (setq tmp (or tmp
14732 (cdr (assoc property org-file-properties))
14733 (cdr (assoc property org-global-properties))
14734 (cdr (assoc property org-global-properties-fixed))))
14735 (if literal-nil tmp (org-not-nil tmp))))
14737 (defvar org-property-changed-functions nil
14738 "Hook called when the value of a property has changed.
14739 Each hook function should accept two arguments, the name of the property
14740 and the new value.")
14742 (defun org-entry-put (pom property value)
14743 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14744 (org-with-point-at pom
14745 (org-back-to-heading t)
14746 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14747 range)
14748 (cond
14749 ((equal property "TODO")
14750 (when (and (stringp value) (string-match "\\S-" value)
14751 (not (member value org-todo-keywords-1)))
14752 (error "\"%s\" is not a valid TODO state" value))
14753 (if (or (not value)
14754 (not (string-match "\\S-" value)))
14755 (setq value 'none))
14756 (org-todo value)
14757 (org-set-tags nil 'align))
14758 ((equal property "PRIORITY")
14759 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14760 (string-to-char value) ?\ ))
14761 (org-set-tags nil 'align))
14762 ((equal property "CLOCKSUM")
14763 (if (not (re-search-forward
14764 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14765 (error "Cannot find a clock log")
14766 (goto-char (- (match-end 1) 2))
14767 (cond
14768 ((eq value 'earlier) (org-timestamp-down))
14769 ((eq value 'later) (org-timestamp-up)))
14770 (org-clock-sum-current-item)))
14771 ((equal property "SCHEDULED")
14772 (if (re-search-forward org-scheduled-time-regexp end t)
14773 (cond
14774 ((eq value 'earlier) (org-timestamp-change -1 'day))
14775 ((eq value 'later) (org-timestamp-change 1 'day))
14776 (t (call-interactively 'org-schedule)))
14777 (call-interactively 'org-schedule)))
14778 ((equal property "DEADLINE")
14779 (if (re-search-forward org-deadline-time-regexp end t)
14780 (cond
14781 ((eq value 'earlier) (org-timestamp-change -1 'day))
14782 ((eq value 'later) (org-timestamp-change 1 'day))
14783 (t (call-interactively 'org-deadline)))
14784 (call-interactively 'org-deadline)))
14785 ((member property org-special-properties)
14786 (error "The %s property can not yet be set with `org-entry-put'"
14787 property))
14788 (t ; a non-special property
14789 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14790 (setq range (org-get-property-block beg end 'force))
14791 (goto-char (car range))
14792 (if (re-search-forward
14793 (org-re-property-keyword property) (cdr range) t)
14794 (progn
14795 (delete-region (match-beginning 0) (match-end 0))
14796 (goto-char (match-beginning 0)))
14797 (goto-char (cdr range))
14798 (insert "\n")
14799 (backward-char 1)
14800 (org-indent-line))
14801 (insert ":" property ":")
14802 (and value (insert " " value))
14803 (org-indent-line)))))
14804 (run-hook-with-args 'org-property-changed-functions property value)))
14806 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14807 "Get all property keys in the current buffer.
14808 With INCLUDE-SPECIALS, also list the special properties that reflect things
14809 like tags and TODO state.
14810 With INCLUDE-DEFAULTS, also include properties that has special meaning
14811 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14812 and others.
14813 With INCLUDE-COLUMNS, also include property names given in COLUMN
14814 formats in the current buffer."
14815 (let (rtn range cfmt s p)
14816 (save-excursion
14817 (save-restriction
14818 (widen)
14819 (goto-char (point-min))
14820 (while (re-search-forward org-property-start-re nil t)
14821 (setq range (org-get-property-block))
14822 (goto-char (car range))
14823 (while (re-search-forward
14824 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14825 (cdr range) t)
14826 (add-to-list 'rtn (org-match-string-no-properties 1)))
14827 (outline-next-heading))))
14829 (when include-specials
14830 (setq rtn (append org-special-properties rtn)))
14832 (when include-defaults
14833 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14834 (add-to-list 'rtn org-effort-property))
14836 (when include-columns
14837 (save-excursion
14838 (save-restriction
14839 (widen)
14840 (goto-char (point-min))
14841 (while (re-search-forward
14842 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14843 nil t)
14844 (setq cfmt (match-string 2) s 0)
14845 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14846 cfmt s)
14847 (setq s (match-end 0)
14848 p (match-string 1 cfmt))
14849 (unless (or (equal p "ITEM")
14850 (member p org-special-properties))
14851 (add-to-list 'rtn (match-string 1 cfmt))))))))
14853 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14855 (defun org-property-values (key)
14856 "Return a list of all values of property KEY in the current buffer."
14857 (save-excursion
14858 (save-restriction
14859 (widen)
14860 (goto-char (point-min))
14861 (let ((re (org-re-property key))
14862 values)
14863 (while (re-search-forward re nil t)
14864 (add-to-list 'values (org-trim (match-string 1))))
14865 (delete "" values)))))
14867 (defun org-insert-property-drawer ()
14868 "Insert a property drawer into the current entry."
14869 (org-back-to-heading t)
14870 (looking-at org-outline-regexp)
14871 (let ((indent (if org-adapt-indentation
14872 (- (match-end 0) (match-beginning 0))
14874 (beg (point))
14875 (re (concat "^[ \t]*" org-keyword-time-regexp))
14876 end hiddenp)
14877 (outline-next-heading)
14878 (setq end (point))
14879 (goto-char beg)
14880 (while (re-search-forward re end t))
14881 (setq hiddenp (outline-invisible-p))
14882 (end-of-line 1)
14883 (and (equal (char-after) ?\n) (forward-char 1))
14884 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14885 (if (member (match-string 1) '("CLOCK:" ":END:"))
14886 ;; just skip this line
14887 (beginning-of-line 2)
14888 ;; Drawer start, find the end
14889 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14890 (beginning-of-line 1)))
14891 (org-skip-over-state-notes)
14892 (skip-chars-backward " \t\n\r")
14893 (if (eq (char-before) ?*) (forward-char 1))
14894 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14895 (beginning-of-line 0)
14896 (org-indent-to-column indent)
14897 (beginning-of-line 2)
14898 (org-indent-to-column indent)
14899 (beginning-of-line 0)
14900 (if hiddenp
14901 (save-excursion
14902 (org-back-to-heading t)
14903 (hide-entry))
14904 (org-flag-drawer t))))
14906 (defun org-insert-drawer (&optional arg drawer)
14907 "Insert a drawer at point.
14909 Optional argument DRAWER, when non-nil, is a string representing
14910 drawer's name. Otherwise, the user is prompted for a name.
14912 If a region is active, insert the drawer around that region
14913 instead.
14915 Point is left between drawer's boundaries."
14916 (interactive "P")
14917 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14918 "LOGBOOK"))
14919 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14920 ;; internally by Org. They are meant to be inserted
14921 ;; automatically.
14922 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14923 ;; Remove system drawers from list. Note: For some reason,
14924 ;; `org-completing-read' ignores the predicate while
14925 ;; `completing-read' handles it fine.
14926 (drawer (if arg "PROPERTIES"
14927 (or drawer
14928 (completing-read
14929 "Drawer: " org-drawers
14930 (lambda (d) (not (member d system-drawers))))))))
14931 (cond
14932 ;; With C-u, fall back on `org-insert-property-drawer'
14933 (arg (org-insert-property-drawer))
14934 ;; With an active region, insert a drawer at point.
14935 ((not (org-region-active-p))
14936 (progn
14937 (unless (bolp) (insert "\n"))
14938 (insert (format ":%s:\n\n:END:\n" drawer))
14939 (forward-line -2)))
14940 ;; Otherwise, insert the drawer at point
14942 (let ((rbeg (region-beginning))
14943 (rend (copy-marker (region-end))))
14944 (unwind-protect
14945 (progn
14946 (goto-char rbeg)
14947 (beginning-of-line)
14948 (when (save-excursion
14949 (re-search-forward org-outline-regexp-bol rend t))
14950 (error "Drawers cannot contain headlines"))
14951 ;; Position point at the beginning of the first
14952 ;; non-blank line in region. Insert drawer's opening
14953 ;; there, then indent it.
14954 (org-skip-whitespace)
14955 (beginning-of-line)
14956 (insert ":" drawer ":\n")
14957 (forward-line -1)
14958 (indent-for-tab-command)
14959 ;; Move point to the beginning of the first blank line
14960 ;; after the last non-blank line in region. Insert
14961 ;; drawer's closing, then indent it.
14962 (goto-char rend)
14963 (skip-chars-backward " \r\t\n")
14964 (insert "\n:END:")
14965 (deactivate-mark t)
14966 (indent-for-tab-command)
14967 (unless (eolp) (insert "\n")))
14968 ;; Clear marker, whatever the outcome of insertion is.
14969 (set-marker rend nil)))))))
14971 (defvar org-property-set-functions-alist nil
14972 "Property set function alist.
14973 Each entry should have the following format:
14975 (PROPERTY . READ-FUNCTION)
14977 The read function will be called with the same argument as
14978 `org-completing-read'.")
14980 (defun org-set-property-function (property)
14981 "Get the function that should be used to set PROPERTY.
14982 This is computed according to `org-property-set-functions-alist'."
14983 (or (cdr (assoc property org-property-set-functions-alist))
14984 'org-completing-read))
14986 (defun org-read-property-value (property)
14987 "Read PROPERTY value from user."
14988 (let* ((completion-ignore-case t)
14989 (allowed (org-property-get-allowed-values nil property 'table))
14990 (cur (org-entry-get nil property))
14991 (prompt (concat property " value"
14992 (if (and cur (string-match "\\S-" cur))
14993 (concat " [" cur "]") "") ": "))
14994 (set-function (org-set-property-function property))
14995 (val (if allowed
14996 (funcall set-function prompt allowed nil
14997 (not (get-text-property 0 'org-unrestricted
14998 (caar allowed))))
14999 (let (org-completion-use-ido org-completion-use-iswitchb)
15000 (funcall set-function prompt
15001 (mapcar 'list (org-property-values property))
15002 nil nil "" nil cur)))))
15003 (if (equal val "")
15005 val)))
15007 (defvar org-last-set-property nil)
15008 (defun org-read-property-name ()
15009 "Read a property name."
15010 (let* ((completion-ignore-case t)
15011 (keys (org-buffer-property-keys nil t t))
15012 (default-prop (or (save-excursion
15013 (save-match-data
15014 (beginning-of-line)
15015 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15016 (null (string= (match-string 1) "END"))
15017 (match-string 1))))
15018 org-last-set-property))
15019 (property (org-icompleting-read
15020 (concat "Property"
15021 (if default-prop (concat " [" default-prop "]") "")
15022 ": ")
15023 (mapcar 'list keys)
15024 nil nil nil nil
15025 default-prop
15027 (if (member property keys)
15028 property
15029 (or (cdr (assoc (downcase property)
15030 (mapcar (lambda (x) (cons (downcase x) x))
15031 keys)))
15032 property))))
15034 (defun org-set-property (property value)
15035 "In the current entry, set PROPERTY to VALUE.
15036 When called interactively, this will prompt for a property name, offering
15037 completion on existing and default properties. And then it will prompt
15038 for a value, offering completion either on allowed values (via an inherited
15039 xxx_ALL property) or on existing values in other instances of this property
15040 in the current file."
15041 (interactive (list nil nil))
15042 (let* ((property (or property (org-read-property-name)))
15043 (value (or value (org-read-property-value property)))
15044 (fn (cdr (assoc property org-properties-postprocess-alist))))
15045 (setq org-last-set-property property)
15046 ;; Possibly postprocess the inserted value:
15047 (when fn (setq value (funcall fn value)))
15048 (unless (equal (org-entry-get nil property) value)
15049 (org-entry-put nil property value))))
15051 (defun org-delete-property (property)
15052 "In the current entry, delete PROPERTY."
15053 (interactive
15054 (let* ((completion-ignore-case t)
15055 (prop (org-icompleting-read "Property: "
15056 (org-entry-properties nil 'standard))))
15057 (list prop)))
15058 (message "Property %s %s" property
15059 (if (org-entry-delete nil property)
15060 "deleted"
15061 "was not present in the entry")))
15063 (defun org-delete-property-globally (property)
15064 "Remove PROPERTY globally, from all entries."
15065 (interactive
15066 (let* ((completion-ignore-case t)
15067 (prop (org-icompleting-read
15068 "Globally remove property: "
15069 (mapcar 'list (org-buffer-property-keys)))))
15070 (list prop)))
15071 (save-excursion
15072 (save-restriction
15073 (widen)
15074 (goto-char (point-min))
15075 (let ((cnt 0))
15076 (while (re-search-forward
15077 (org-re-property property)
15078 nil t)
15079 (setq cnt (1+ cnt))
15080 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15081 (message "Property \"%s\" removed from %d entries" property cnt)))))
15083 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15085 (defun org-compute-property-at-point ()
15086 "Compute the property at point.
15087 This looks for an enclosing column format, extracts the operator and
15088 then applies it to the property in the column format's scope."
15089 (interactive)
15090 (unless (org-at-property-p)
15091 (error "Not at a property"))
15092 (let ((prop (org-match-string-no-properties 2)))
15093 (org-columns-get-format-and-top-level)
15094 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15095 (error "No operator defined for property %s" prop))
15096 (org-columns-compute prop)))
15098 (defvar org-property-allowed-value-functions nil
15099 "Hook for functions supplying allowed values for a specific property.
15100 The functions must take a single argument, the name of the property, and
15101 return a flat list of allowed values. If \":ETC\" is one of
15102 the values, this means that these values are intended as defaults for
15103 completion, but that other values should be allowed too.
15104 The functions must return nil if they are not responsible for this
15105 property.")
15107 (defun org-property-get-allowed-values (pom property &optional table)
15108 "Get allowed values for the property PROPERTY.
15109 When TABLE is non-nil, return an alist that can directly be used for
15110 completion."
15111 (let (vals)
15112 (cond
15113 ((equal property "TODO")
15114 (setq vals (org-with-point-at pom
15115 (append org-todo-keywords-1 '("")))))
15116 ((equal property "PRIORITY")
15117 (let ((n org-lowest-priority))
15118 (while (>= n org-highest-priority)
15119 (push (char-to-string n) vals)
15120 (setq n (1- n)))))
15121 ((member property org-special-properties))
15122 ((setq vals (run-hook-with-args-until-success
15123 'org-property-allowed-value-functions property)))
15125 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15126 (when (and vals (string-match "\\S-" vals))
15127 (setq vals (car (read-from-string (concat "(" vals ")"))))
15128 (setq vals (mapcar (lambda (x)
15129 (cond ((stringp x) x)
15130 ((numberp x) (number-to-string x))
15131 ((symbolp x) (symbol-name x))
15132 (t "???")))
15133 vals)))))
15134 (when (member ":ETC" vals)
15135 (setq vals (remove ":ETC" vals))
15136 (org-add-props (car vals) '(org-unrestricted t)))
15137 (if table (mapcar 'list vals) vals)))
15139 (defun org-property-previous-allowed-value (&optional previous)
15140 "Switch to the next allowed value for this property."
15141 (interactive)
15142 (org-property-next-allowed-value t))
15144 (defun org-property-next-allowed-value (&optional previous)
15145 "Switch to the next allowed value for this property."
15146 (interactive)
15147 (unless (org-at-property-p)
15148 (error "Not at a property"))
15149 (let* ((key (match-string 2))
15150 (value (match-string 3))
15151 (allowed (or (org-property-get-allowed-values (point) key)
15152 (and (member value '("[ ]" "[-]" "[X]"))
15153 '("[ ]" "[X]"))))
15154 nval)
15155 (unless allowed
15156 (error "Allowed values for this property have not been defined"))
15157 (if previous (setq allowed (reverse allowed)))
15158 (if (member value allowed)
15159 (setq nval (car (cdr (member value allowed)))))
15160 (setq nval (or nval (car allowed)))
15161 (if (equal nval value)
15162 (error "Only one allowed value for this property"))
15163 (org-at-property-p)
15164 (replace-match (concat " :" key ": " nval) t t)
15165 (org-indent-line)
15166 (beginning-of-line 1)
15167 (skip-chars-forward " \t")
15168 (run-hook-with-args 'org-property-changed-functions key nval)))
15170 (defun org-find-olp (path &optional this-buffer)
15171 "Return a marker pointing to the entry at outline path OLP.
15172 If anything goes wrong, throw an error.
15173 You can wrap this call to catch the error like this:
15175 (condition-case msg
15176 (org-mobile-locate-entry (match-string 4))
15177 (error (nth 1 msg)))
15179 The return value will then be either a string with the error message,
15180 or a marker if everything is OK.
15182 If THIS-BUFFER is set, the outline path does not contain a file,
15183 only headings."
15184 (let* ((file (if this-buffer buffer-file-name (pop path)))
15185 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15186 (level 1)
15187 (lmin 1)
15188 (lmax 1)
15189 limit re end found pos heading cnt flevel)
15190 (unless buffer (error "File not found :%s" file))
15191 (with-current-buffer buffer
15192 (save-excursion
15193 (save-restriction
15194 (widen)
15195 (setq limit (point-max))
15196 (goto-char (point-min))
15197 (while (setq heading (pop path))
15198 (setq re (format org-complex-heading-regexp-format
15199 (regexp-quote heading)))
15200 (setq cnt 0 pos (point))
15201 (while (re-search-forward re end t)
15202 (setq level (- (match-end 1) (match-beginning 1)))
15203 (if (and (>= level lmin) (<= level lmax))
15204 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15205 (when (= cnt 0) (error "Heading not found on level %d: %s"
15206 lmax heading))
15207 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15208 lmax heading))
15209 (goto-char found)
15210 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15211 (setq end (save-excursion (org-end-of-subtree t t))))
15212 (when (org-at-heading-p)
15213 (move-marker (make-marker) (point))))))))
15215 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15216 "Find node HEADING in BUFFER.
15217 Return a marker to the heading if it was found, or nil if not.
15218 If POS-ONLY is set, return just the position instead of a marker.
15220 The heading text must match exact, but it may have a TODO keyword,
15221 a priority cookie and tags in the standard locations."
15222 (with-current-buffer (or buffer (current-buffer))
15223 (save-excursion
15224 (save-restriction
15225 (widen)
15226 (goto-char (point-min))
15227 (let (case-fold-search)
15228 (if (re-search-forward
15229 (format org-complex-heading-regexp-format
15230 (regexp-quote heading)) nil t)
15231 (if pos-only
15232 (match-beginning 0)
15233 (move-marker (make-marker) (match-beginning 0)))))))))
15235 (defun org-find-exact-heading-in-directory (heading &optional dir)
15236 "Find Org node headline HEADING in all .org files in directory DIR.
15237 When the target headline is found, return a marker to this location."
15238 (let ((files (directory-files (or dir default-directory)
15239 nil "\\`[^.#].*\\.org\\'"))
15240 file visiting m buffer)
15241 (catch 'found
15242 (while (setq file (pop files))
15243 (message "trying %s" file)
15244 (setq visiting (org-find-base-buffer-visiting file))
15245 (setq buffer (or visiting (find-file-noselect file)))
15246 (setq m (org-find-exact-headline-in-buffer
15247 heading buffer))
15248 (when (and (not m) (not visiting)) (kill-buffer buffer))
15249 (and m (throw 'found m))))))
15251 (defun org-find-entry-with-id (ident)
15252 "Locate the entry that contains the ID property with exact value IDENT.
15253 IDENT can be a string, a symbol or a number, this function will search for
15254 the string representation of it.
15255 Return the position where this entry starts, or nil if there is no such entry."
15256 (interactive "sID: ")
15257 (let ((id (cond
15258 ((stringp ident) ident)
15259 ((symbol-name ident) (symbol-name ident))
15260 ((numberp ident) (number-to-string ident))
15261 (t (error "IDENT %s must be a string, symbol or number" ident))))
15262 (case-fold-search nil))
15263 (save-excursion
15264 (save-restriction
15265 (widen)
15266 (goto-char (point-min))
15267 (when (re-search-forward
15268 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15269 nil t)
15270 (org-back-to-heading t)
15271 (point))))))
15273 ;;;; Timestamps
15275 (defvar org-last-changed-timestamp nil)
15276 (defvar org-last-inserted-timestamp nil
15277 "The last time stamp inserted with `org-insert-time-stamp'.")
15278 (defvar org-time-was-given) ; dynamically scoped parameter
15279 (defvar org-end-time-was-given) ; dynamically scoped parameter
15280 (defvar org-ts-what) ; dynamically scoped parameter
15282 (defun org-time-stamp (arg &optional inactive)
15283 "Prompt for a date/time and insert a time stamp.
15284 If the user specifies a time like HH:MM or if this command is
15285 called with at least one prefix argument, the time stamp contains
15286 the date and the time. Otherwise, only the date is be included.
15288 All parts of a date not specified by the user is filled in from
15289 the current date/time. So if you just press return without
15290 typing anything, the time stamp will represent the current
15291 date/time.
15293 If there is already a timestamp at the cursor, it will be
15294 modified.
15296 With two universal prefix arguments, insert an active timestamp
15297 with the current time without prompting the user."
15298 (interactive "P")
15299 (let* ((ts nil)
15300 (default-time
15301 ;; Default time is either today, or, when entering a range,
15302 ;; the range start.
15303 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15304 (save-excursion
15305 (re-search-backward
15306 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15307 (- (point) 20) t)))
15308 (apply 'encode-time (org-parse-time-string (match-string 1)))
15309 (current-time)))
15310 (default-input (and ts (org-get-compact-tod ts)))
15311 (repeater (save-excursion
15312 (save-match-data
15313 (beginning-of-line)
15314 (when (re-search-forward
15315 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15316 (save-excursion (progn (end-of-line) (point))) t)
15317 (match-string 0)))))
15318 org-time-was-given org-end-time-was-given time)
15319 (cond
15320 ((and (org-at-timestamp-p t)
15321 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15322 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15323 (insert "--")
15324 (setq time (let ((this-command this-command))
15325 (org-read-date arg 'totime nil nil
15326 default-time default-input inactive)))
15327 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15328 ((org-at-timestamp-p t)
15329 (setq time (let ((this-command this-command))
15330 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15331 (when (org-at-timestamp-p t) ; just to get the match data
15332 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15333 (replace-match "")
15334 (setq org-last-changed-timestamp
15335 (org-insert-time-stamp
15336 time (or org-time-was-given arg)
15337 inactive nil nil (list org-end-time-was-given)))
15338 (when repeater (goto-char (1- (point))) (insert " " repeater)
15339 (setq org-last-changed-timestamp
15340 (concat (substring org-last-inserted-timestamp 0 -1)
15341 " " repeater ">"))))
15342 (message "Timestamp updated"))
15343 ((equal arg '(16))
15344 (org-insert-time-stamp (current-time) t))
15346 (setq time (let ((this-command this-command))
15347 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15348 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15349 nil nil (list org-end-time-was-given))))))
15351 ;; FIXME: can we use this for something else, like computing time differences?
15352 (defun org-get-compact-tod (s)
15353 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15354 (let* ((t1 (match-string 1 s))
15355 (h1 (string-to-number (match-string 2 s)))
15356 (m1 (string-to-number (match-string 3 s)))
15357 (t2 (and (match-end 4) (match-string 5 s)))
15358 (h2 (and t2 (string-to-number (match-string 6 s))))
15359 (m2 (and t2 (string-to-number (match-string 7 s))))
15360 dh dm)
15361 (if (not t2)
15363 (setq dh (- h2 h1) dm (- m2 m1))
15364 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15365 (concat t1 "+" (number-to-string dh)
15366 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15368 (defun org-time-stamp-inactive (&optional arg)
15369 "Insert an inactive time stamp.
15370 An inactive time stamp is enclosed in square brackets instead of angle
15371 brackets. It is inactive in the sense that it does not trigger agenda entries,
15372 does not link to the calendar and cannot be changed with the S-cursor keys.
15373 So these are more for recording a certain time/date."
15374 (interactive "P")
15375 (org-time-stamp arg 'inactive))
15377 (defvar org-date-ovl (make-overlay 1 1))
15378 (overlay-put org-date-ovl 'face 'org-date-selected)
15379 (org-detach-overlay org-date-ovl)
15381 (defvar org-ans1) ; dynamically scoped parameter
15382 (defvar org-ans2) ; dynamically scoped parameter
15384 (defvar org-plain-time-of-day-regexp) ; defined below
15386 (defvar org-overriding-default-time nil) ; dynamically scoped
15387 (defvar org-read-date-overlay nil)
15388 (defvar org-dcst nil) ; dynamically scoped
15389 (defvar org-read-date-history nil)
15390 (defvar org-read-date-final-answer nil)
15391 (defvar org-read-date-analyze-futurep nil)
15392 (defvar org-read-date-analyze-forced-year nil)
15393 (defvar org-read-date-inactive)
15395 (defun org-read-date (&optional org-with-time to-time from-string prompt
15396 default-time default-input inactive)
15397 "Read a date, possibly a time, and make things smooth for the user.
15398 The prompt will suggest to enter an ISO date, but you can also enter anything
15399 which will at least partially be understood by `parse-time-string'.
15400 Unrecognized parts of the date will default to the current day, month, year,
15401 hour and minute. If this command is called to replace a timestamp at point,
15402 or to enter the second timestamp of a range, the default time is taken
15403 from the existing stamp. Furthermore, the command prefers the future,
15404 so if you are giving a date where the year is not given, and the day-month
15405 combination is already past in the current year, it will assume you
15406 mean next year. For details, see the manual. A few examples:
15408 3-2-5 --> 2003-02-05
15409 feb 15 --> currentyear-02-15
15410 2/15 --> currentyear-02-15
15411 sep 12 9 --> 2009-09-12
15412 12:45 --> today 12:45
15413 22 sept 0:34 --> currentyear-09-22 0:34
15414 12 --> currentyear-currentmonth-12
15415 Fri --> nearest Friday (today or later)
15416 etc.
15418 Furthermore you can specify a relative date by giving, as the *first* thing
15419 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15420 change in days weeks, months, years.
15421 With a single plus or minus, the date is relative to today. With a double
15422 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15423 +4d --> four days from today
15424 +4 --> same as above
15425 +2w --> two weeks from today
15426 ++5 --> five days from default date
15428 The function understands only English month and weekday abbreviations.
15430 While prompting, a calendar is popped up - you can also select the
15431 date with the mouse (button 1). The calendar shows a period of three
15432 months. To scroll it to other months, use the keys `>' and `<'.
15433 If you don't like the calendar, turn it off with
15434 \(setq org-read-date-popup-calendar nil)
15436 With optional argument TO-TIME, the date will immediately be converted
15437 to an internal time.
15438 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15439 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15440 still enter a time, and this function will inform the calling routine
15441 about this change. The calling routine may then choose to change the
15442 format used to insert the time stamp into the buffer to include the time.
15443 With optional argument FROM-STRING, read from this string instead from
15444 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15445 the time/date that is used for everything that is not specified by the
15446 user."
15447 (require 'parse-time)
15448 (let* ((org-time-stamp-rounding-minutes
15449 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15450 (org-dcst org-display-custom-times)
15451 (ct (org-current-time))
15452 (org-def (or org-overriding-default-time default-time ct))
15453 (org-defdecode (decode-time org-def))
15454 (dummy (progn
15455 (when (< (nth 2 org-defdecode) org-extend-today-until)
15456 (setcar (nthcdr 2 org-defdecode) -1)
15457 (setcar (nthcdr 1 org-defdecode) 59)
15458 (setq org-def (apply 'encode-time org-defdecode)
15459 org-defdecode (decode-time org-def)))))
15460 (calendar-frame-setup nil)
15461 (calendar-setup nil)
15462 (calendar-move-hook nil)
15463 (calendar-view-diary-initially-flag nil)
15464 (calendar-view-holidays-initially-flag nil)
15465 (timestr (format-time-string
15466 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15467 (prompt (concat (if prompt (concat prompt " ") "")
15468 (format "Date+time [%s]: " timestr)))
15469 ans (org-ans0 "") org-ans1 org-ans2 final)
15471 (cond
15472 (from-string (setq ans from-string))
15473 (org-read-date-popup-calendar
15474 (save-excursion
15475 (save-window-excursion
15476 (calendar)
15477 (org-eval-in-calendar '(setq cursor-type nil) t)
15478 (unwind-protect
15479 (progn
15480 (calendar-forward-day (- (time-to-days org-def)
15481 (calendar-absolute-from-gregorian
15482 (calendar-current-date))))
15483 (org-eval-in-calendar nil t)
15484 (let* ((old-map (current-local-map))
15485 (map (copy-keymap calendar-mode-map))
15486 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15487 (org-defkey map (kbd "RET") 'org-calendar-select)
15488 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15489 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15490 (org-defkey minibuffer-local-map [(meta shift left)]
15491 (lambda () (interactive)
15492 (org-eval-in-calendar '(calendar-backward-month 1))))
15493 (org-defkey minibuffer-local-map [(meta shift right)]
15494 (lambda () (interactive)
15495 (org-eval-in-calendar '(calendar-forward-month 1))))
15496 (org-defkey minibuffer-local-map [(meta shift up)]
15497 (lambda () (interactive)
15498 (org-eval-in-calendar '(calendar-backward-year 1))))
15499 (org-defkey minibuffer-local-map [(meta shift down)]
15500 (lambda () (interactive)
15501 (org-eval-in-calendar '(calendar-forward-year 1))))
15502 (org-defkey minibuffer-local-map [?\e (shift left)]
15503 (lambda () (interactive)
15504 (org-eval-in-calendar '(calendar-backward-month 1))))
15505 (org-defkey minibuffer-local-map [?\e (shift right)]
15506 (lambda () (interactive)
15507 (org-eval-in-calendar '(calendar-forward-month 1))))
15508 (org-defkey minibuffer-local-map [?\e (shift up)]
15509 (lambda () (interactive)
15510 (org-eval-in-calendar '(calendar-backward-year 1))))
15511 (org-defkey minibuffer-local-map [?\e (shift down)]
15512 (lambda () (interactive)
15513 (org-eval-in-calendar '(calendar-forward-year 1))))
15514 (org-defkey minibuffer-local-map [(shift up)]
15515 (lambda () (interactive)
15516 (org-eval-in-calendar '(calendar-backward-week 1))))
15517 (org-defkey minibuffer-local-map [(shift down)]
15518 (lambda () (interactive)
15519 (org-eval-in-calendar '(calendar-forward-week 1))))
15520 (org-defkey minibuffer-local-map [(shift left)]
15521 (lambda () (interactive)
15522 (org-eval-in-calendar '(calendar-backward-day 1))))
15523 (org-defkey minibuffer-local-map [(shift right)]
15524 (lambda () (interactive)
15525 (org-eval-in-calendar '(calendar-forward-day 1))))
15526 (org-defkey minibuffer-local-map ">"
15527 (lambda () (interactive)
15528 (org-eval-in-calendar '(scroll-calendar-left 1))))
15529 (org-defkey minibuffer-local-map "<"
15530 (lambda () (interactive)
15531 (org-eval-in-calendar '(scroll-calendar-right 1))))
15532 (org-defkey minibuffer-local-map "\C-v"
15533 (lambda () (interactive)
15534 (org-eval-in-calendar
15535 '(calendar-scroll-left-three-months 1))))
15536 (org-defkey minibuffer-local-map "\M-v"
15537 (lambda () (interactive)
15538 (org-eval-in-calendar
15539 '(calendar-scroll-right-three-months 1))))
15540 (run-hooks 'org-read-date-minibuffer-setup-hook)
15541 (unwind-protect
15542 (progn
15543 (use-local-map map)
15544 (setq org-read-date-inactive inactive)
15545 (add-hook 'post-command-hook 'org-read-date-display)
15546 (setq org-ans0 (read-string prompt default-input
15547 'org-read-date-history nil))
15548 ;; org-ans0: from prompt
15549 ;; org-ans1: from mouse click
15550 ;; org-ans2: from calendar motion
15551 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15552 (remove-hook 'post-command-hook 'org-read-date-display)
15553 (use-local-map old-map)
15554 (when org-read-date-overlay
15555 (delete-overlay org-read-date-overlay)
15556 (setq org-read-date-overlay nil)))))
15557 (bury-buffer "*Calendar*")))))
15559 (t ; Naked prompt only
15560 (unwind-protect
15561 (setq ans (read-string prompt default-input
15562 'org-read-date-history timestr))
15563 (when org-read-date-overlay
15564 (delete-overlay org-read-date-overlay)
15565 (setq org-read-date-overlay nil)))))
15567 (setq final (org-read-date-analyze ans org-def org-defdecode))
15569 (when org-read-date-analyze-forced-year
15570 (message "Year was forced into %s"
15571 (if org-read-date-force-compatible-dates
15572 "compatible range (1970-2037)"
15573 "range representable on this machine"))
15574 (ding))
15576 ;; One round trip to get rid of 34th of August and stuff like that....
15577 (setq final (decode-time (apply 'encode-time final)))
15579 (setq org-read-date-final-answer ans)
15581 (if to-time
15582 (apply 'encode-time final)
15583 (if (and (boundp 'org-time-was-given) org-time-was-given)
15584 (format "%04d-%02d-%02d %02d:%02d"
15585 (nth 5 final) (nth 4 final) (nth 3 final)
15586 (nth 2 final) (nth 1 final))
15587 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15589 (defvar org-def)
15590 (defvar org-defdecode)
15591 (defvar org-with-time)
15592 (defun org-read-date-display ()
15593 "Display the current date prompt interpretation in the minibuffer."
15594 (when org-read-date-display-live
15595 (when org-read-date-overlay
15596 (delete-overlay org-read-date-overlay))
15597 (when (minibufferp (current-buffer))
15598 (save-excursion
15599 (end-of-line 1)
15600 (while (not (equal (buffer-substring
15601 (max (point-min) (- (point) 4)) (point))
15602 " "))
15603 (insert " ")))
15604 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15605 " " (or org-ans1 org-ans2)))
15606 (org-end-time-was-given nil)
15607 (f (org-read-date-analyze ans org-def org-defdecode))
15608 (fmts (if org-dcst
15609 org-time-stamp-custom-formats
15610 org-time-stamp-formats))
15611 (fmt (if (or org-with-time
15612 (and (boundp 'org-time-was-given) org-time-was-given))
15613 (cdr fmts)
15614 (car fmts)))
15615 (txt (format-time-string fmt (apply 'encode-time f)))
15616 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15617 (txt (concat "=> " txt)))
15618 (when (and org-end-time-was-given
15619 (string-match org-plain-time-of-day-regexp txt))
15620 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15621 org-end-time-was-given
15622 (substring txt (match-end 0)))))
15623 (when org-read-date-analyze-futurep
15624 (setq txt (concat txt " (=>F)")))
15625 (setq org-read-date-overlay
15626 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15627 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15629 (defun org-read-date-analyze (ans org-def org-defdecode)
15630 "Analyze the combined answer of the date prompt."
15631 ;; FIXME: cleanup and comment
15632 (let ((nowdecode (decode-time (current-time)))
15633 delta deltan deltaw deltadef year month day
15634 hour minute second wday pm h2 m2 tl wday1
15635 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15636 (setq org-read-date-analyze-futurep nil
15637 org-read-date-analyze-forced-year nil)
15638 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15639 (setq ans "+0"))
15641 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15642 (setq ans (replace-match "" t t ans)
15643 deltan (car delta)
15644 deltaw (nth 1 delta)
15645 deltadef (nth 2 delta)))
15647 ;; Check if there is an iso week date in there. If yes, store the
15648 ;; info and postpone interpreting it until the rest of the parsing
15649 ;; is done.
15650 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15651 (setq iso-year (if (match-end 1)
15652 (org-small-year-to-year
15653 (string-to-number (match-string 1 ans))))
15654 iso-weekday (if (match-end 3)
15655 (string-to-number (match-string 3 ans)))
15656 iso-week (string-to-number (match-string 2 ans)))
15657 (setq ans (replace-match "" t t ans)))
15659 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15660 (when (string-match
15661 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15662 (setq year (if (match-end 2)
15663 (string-to-number (match-string 2 ans))
15664 (progn (setq kill-year t)
15665 (string-to-number (format-time-string "%Y"))))
15666 month (string-to-number (match-string 3 ans))
15667 day (string-to-number (match-string 4 ans)))
15668 (if (< year 100) (setq year (+ 2000 year)))
15669 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15670 t nil ans)))
15672 ;; Help matching dotted european dates
15673 (when (string-match
15674 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15675 (setq year (if (match-end 3)
15676 (string-to-number (match-string 3 ans))
15677 (progn (setq kill-year t)
15678 (string-to-number (format-time-string "%Y"))))
15679 day (string-to-number (match-string 1 ans))
15680 month (string-to-number (match-string 2 ans))
15681 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15682 t nil ans)))
15684 ;; Help matching american dates, like 5/30 or 5/30/7
15685 (when (string-match
15686 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15687 (setq year (if (match-end 4)
15688 (string-to-number (match-string 4 ans))
15689 (progn (setq kill-year t)
15690 (string-to-number (format-time-string "%Y"))))
15691 month (string-to-number (match-string 1 ans))
15692 day (string-to-number (match-string 2 ans)))
15693 (if (< year 100) (setq year (+ 2000 year)))
15694 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15695 t nil ans)))
15696 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15697 ;; If there is a time with am/pm, and *no* time without it, we convert
15698 ;; so that matching will be successful.
15699 (loop for i from 1 to 2 do ; twice, for end time as well
15700 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15701 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15702 (setq hour (string-to-number (match-string 1 ans))
15703 minute (if (match-end 3)
15704 (string-to-number (match-string 3 ans))
15706 pm (equal ?p
15707 (string-to-char (downcase (match-string 4 ans)))))
15708 (if (and (= hour 12) (not pm))
15709 (setq hour 0)
15710 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15711 (setq ans (replace-match (format "%02d:%02d" hour minute)
15712 t t ans))))
15714 ;; Check if a time range is given as a duration
15715 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15716 (setq hour (string-to-number (match-string 1 ans))
15717 h2 (+ hour (string-to-number (match-string 3 ans)))
15718 minute (string-to-number (match-string 2 ans))
15719 m2 (+ minute (if (match-end 5) (string-to-number
15720 (match-string 5 ans))0)))
15721 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15722 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15723 t t ans)))
15725 ;; Check if there is a time range
15726 (when (boundp 'org-end-time-was-given)
15727 (setq org-time-was-given nil)
15728 (when (and (string-match org-plain-time-of-day-regexp ans)
15729 (match-end 8))
15730 (setq org-end-time-was-given (match-string 8 ans))
15731 (setq ans (concat (substring ans 0 (match-beginning 7))
15732 (substring ans (match-end 7))))))
15734 (setq tl (parse-time-string ans)
15735 day (or (nth 3 tl) (nth 3 org-defdecode))
15736 month (or (nth 4 tl)
15737 (if (and org-read-date-prefer-future
15738 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15739 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15740 (nth 4 org-defdecode)))
15741 year (or (and (not kill-year) (nth 5 tl))
15742 (if (and org-read-date-prefer-future
15743 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15744 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15745 (nth 5 org-defdecode)))
15746 hour (or (nth 2 tl) (nth 2 org-defdecode))
15747 minute (or (nth 1 tl) (nth 1 org-defdecode))
15748 second (or (nth 0 tl) 0)
15749 wday (nth 6 tl))
15751 (when (and (eq org-read-date-prefer-future 'time)
15752 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15753 (equal day (nth 3 nowdecode))
15754 (equal month (nth 4 nowdecode))
15755 (equal year (nth 5 nowdecode))
15756 (nth 2 tl)
15757 (or (< (nth 2 tl) (nth 2 nowdecode))
15758 (and (= (nth 2 tl) (nth 2 nowdecode))
15759 (nth 1 tl)
15760 (< (nth 1 tl) (nth 1 nowdecode)))))
15761 (setq day (1+ day)
15762 futurep t))
15764 ;; Special date definitions below
15765 (cond
15766 (iso-week
15767 ;; There was an iso week
15768 (require 'cal-iso)
15769 (setq futurep nil)
15770 (setq year (or iso-year year)
15771 day (or iso-weekday wday 1)
15772 wday nil ; to make sure that the trigger below does not match
15773 iso-date (calendar-gregorian-from-absolute
15774 (calendar-absolute-from-iso
15775 (list iso-week day year))))
15776 ; FIXME: Should we also push ISO weeks into the future?
15777 ; (when (and org-read-date-prefer-future
15778 ; (not iso-year)
15779 ; (< (calendar-absolute-from-gregorian iso-date)
15780 ; (time-to-days (current-time))))
15781 ; (setq year (1+ year)
15782 ; iso-date (calendar-gregorian-from-absolute
15783 ; (calendar-absolute-from-iso
15784 ; (list iso-week day year)))))
15785 (setq month (car iso-date)
15786 year (nth 2 iso-date)
15787 day (nth 1 iso-date)))
15788 (deltan
15789 (setq futurep nil)
15790 (unless deltadef
15791 (let ((now (decode-time (current-time))))
15792 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15793 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15794 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15795 ((equal deltaw "m") (setq month (+ month deltan)))
15796 ((equal deltaw "y") (setq year (+ year deltan)))))
15797 ((and wday (not (nth 3 tl)))
15798 ;; Weekday was given, but no day, so pick that day in the week
15799 ;; on or after the derived date.
15800 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15801 (unless (equal wday wday1)
15802 (setq day (+ day (% (- wday wday1 -7) 7))))))
15803 (if (and (boundp 'org-time-was-given)
15804 (nth 2 tl))
15805 (setq org-time-was-given t))
15806 (if (< year 100) (setq year (+ 2000 year)))
15807 ;; Check of the date is representable
15808 (if org-read-date-force-compatible-dates
15809 (progn
15810 (if (< year 1970)
15811 (setq year 1970 org-read-date-analyze-forced-year t))
15812 (if (> year 2037)
15813 (setq year 2037 org-read-date-analyze-forced-year t)))
15814 (condition-case nil
15815 (ignore (encode-time second minute hour day month year))
15816 (error
15817 (setq year (nth 5 org-defdecode))
15818 (setq org-read-date-analyze-forced-year t))))
15819 (setq org-read-date-analyze-futurep futurep)
15820 (list second minute hour day month year)))
15822 (defvar parse-time-weekdays)
15823 (defun org-read-date-get-relative (s today default)
15824 "Check string S for special relative date string.
15825 TODAY and DEFAULT are internal times, for today and for a default.
15826 Return shift list (N what def-flag)
15827 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15828 N is the number of WHATs to shift.
15829 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15830 the DEFAULT date rather than TODAY."
15831 (require 'parse-time)
15832 (when (and
15833 (string-match
15834 (concat
15835 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15836 "\\([0-9]+\\)?"
15837 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15838 "\\([ \t]\\|$\\)") s)
15839 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15840 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15841 (string-to-char (substring (match-string 1 s) -1))
15842 ?+))
15843 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15844 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15845 (what (if (match-end 3) (match-string 3 s) "d"))
15846 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15847 (date (if rel default today))
15848 (wday (nth 6 (decode-time date)))
15849 delta)
15850 (if wday1
15851 (progn
15852 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15853 (if (= dir ?-) (setq delta (- delta 7)))
15854 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15855 (list delta "d" rel))
15856 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15858 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15859 "Turn a user-specified date into the internal representation.
15860 The internal representation needed by the calendar is (month day year).
15861 This is a wrapper to handle the brain-dead convention in calendar that
15862 user function argument order change dependent on argument order."
15863 (if (boundp 'calendar-date-style)
15864 (cond
15865 ((eq calendar-date-style 'american)
15866 (list arg1 arg2 arg3))
15867 ((eq calendar-date-style 'european)
15868 (list arg2 arg1 arg3))
15869 ((eq calendar-date-style 'iso)
15870 (list arg2 arg3 arg1)))
15871 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15872 (if (org-bound-and-true-p european-calendar-style)
15873 (list arg2 arg1 arg3)
15874 (list arg1 arg2 arg3)))))
15876 (defun org-eval-in-calendar (form &optional keepdate)
15877 "Eval FORM in the calendar window and return to current window.
15878 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15879 otherwise stick to the current value of `org-ans2'."
15880 (let ((sf (selected-frame))
15881 (sw (selected-window)))
15882 (select-window (get-buffer-window "*Calendar*" t))
15883 (eval form)
15884 (when (and (not keepdate) (calendar-cursor-to-date))
15885 (let* ((date (calendar-cursor-to-date))
15886 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15887 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15888 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15889 (select-window sw)
15890 (org-select-frame-set-input-focus sf)))
15892 (defun org-calendar-select ()
15893 "Return to `org-read-date' with the date currently selected.
15894 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15895 (interactive)
15896 (when (calendar-cursor-to-date)
15897 (let* ((date (calendar-cursor-to-date))
15898 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15899 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15900 (if (active-minibuffer-window) (exit-minibuffer))))
15902 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15903 "Insert a date stamp for the date given by the internal TIME.
15904 WITH-HM means use the stamp format that includes the time of the day.
15905 INACTIVE means use square brackets instead of angular ones, so that the
15906 stamp will not contribute to the agenda.
15907 PRE and POST are optional strings to be inserted before and after the
15908 stamp.
15909 The command returns the inserted time stamp."
15910 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15911 stamp)
15912 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15913 (insert-before-markers (or pre ""))
15914 (when (listp extra)
15915 (setq extra (car extra))
15916 (if (and (stringp extra)
15917 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15918 (setq extra (format "-%02d:%02d"
15919 (string-to-number (match-string 1 extra))
15920 (string-to-number (match-string 2 extra))))
15921 (setq extra nil)))
15922 (when extra
15923 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15924 (insert-before-markers (setq stamp (format-time-string fmt time)))
15925 (insert-before-markers (or post ""))
15926 (setq org-last-inserted-timestamp stamp)))
15928 (defun org-toggle-time-stamp-overlays ()
15929 "Toggle the use of custom time stamp formats."
15930 (interactive)
15931 (setq org-display-custom-times (not org-display-custom-times))
15932 (unless org-display-custom-times
15933 (let ((p (point-min)) (bmp (buffer-modified-p)))
15934 (while (setq p (next-single-property-change p 'display))
15935 (if (and (get-text-property p 'display)
15936 (eq (get-text-property p 'face) 'org-date))
15937 (remove-text-properties
15938 p (setq p (next-single-property-change p 'display))
15939 '(display t))))
15940 (set-buffer-modified-p bmp)))
15941 (if (featurep 'xemacs)
15942 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15943 (org-restart-font-lock)
15944 (setq org-table-may-need-update t)
15945 (if org-display-custom-times
15946 (message "Time stamps are overlaid with custom format")
15947 (message "Time stamp overlays removed")))
15949 (defun org-display-custom-time (beg end)
15950 "Overlay modified time stamp format over timestamp between BEG and END."
15951 (let* ((ts (buffer-substring beg end))
15952 t1 w1 with-hm tf time str w2 (off 0))
15953 (save-match-data
15954 (setq t1 (org-parse-time-string ts t))
15955 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15956 (setq off (- (match-end 0) (match-beginning 0)))))
15957 (setq end (- end off))
15958 (setq w1 (- end beg)
15959 with-hm (and (nth 1 t1) (nth 2 t1))
15960 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15961 time (org-fix-decoded-time t1)
15962 str (org-add-props
15963 (format-time-string
15964 (substring tf 1 -1) (apply 'encode-time time))
15965 nil 'mouse-face 'highlight)
15966 w2 (length str))
15967 (if (not (= w2 w1))
15968 (add-text-properties (1+ beg) (+ 2 beg)
15969 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15970 (if (featurep 'xemacs)
15971 (progn
15972 (put-text-property beg end 'invisible t)
15973 (put-text-property beg end 'end-glyph (make-glyph str)))
15974 (put-text-property beg end 'display str))))
15976 (defun org-translate-time (string)
15977 "Translate all timestamps in STRING to custom format.
15978 But do this only if the variable `org-display-custom-times' is set."
15979 (when org-display-custom-times
15980 (save-match-data
15981 (let* ((start 0)
15982 (re org-ts-regexp-both)
15983 t1 with-hm inactive tf time str beg end)
15984 (while (setq start (string-match re string start))
15985 (setq beg (match-beginning 0)
15986 end (match-end 0)
15987 t1 (save-match-data
15988 (org-parse-time-string (substring string beg end) t))
15989 with-hm (and (nth 1 t1) (nth 2 t1))
15990 inactive (equal (substring string beg (1+ beg)) "[")
15991 tf (funcall (if with-hm 'cdr 'car)
15992 org-time-stamp-custom-formats)
15993 time (org-fix-decoded-time t1)
15994 str (format-time-string
15995 (concat
15996 (if inactive "[" "<") (substring tf 1 -1)
15997 (if inactive "]" ">"))
15998 (apply 'encode-time time))
15999 string (replace-match str t t string)
16000 start (+ start (length str)))))))
16001 string)
16003 (defun org-fix-decoded-time (time)
16004 "Set 0 instead of nil for the first 6 elements of time.
16005 Don't touch the rest."
16006 (let ((n 0))
16007 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16009 (defun org-days-to-time (timestamp-string)
16010 "Difference between TIMESTAMP-STRING and now in days."
16011 (- (time-to-days (org-time-string-to-time timestamp-string))
16012 (time-to-days (current-time))))
16014 (defun org-deadline-close (timestamp-string &optional ndays)
16015 "Is the time in TIMESTAMP-STRING close to the current date?"
16016 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16017 (and (< (org-days-to-time timestamp-string) ndays)
16018 (not (org-entry-is-done-p))))
16020 (defun org-get-wdays (ts)
16021 "Get the deadline lead time appropriate for timestring TS."
16022 (cond
16023 ((<= org-deadline-warning-days 0)
16024 ;; 0 or negative, enforce this value no matter what
16025 (- org-deadline-warning-days))
16026 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16027 ;; lead time is specified.
16028 (floor (* (string-to-number (match-string 1 ts))
16029 (cdr (assoc (match-string 2 ts)
16030 '(("d" . 1) ("w" . 7)
16031 ("m" . 30.4) ("y" . 365.25)))))))
16032 ;; go for the default.
16033 (t org-deadline-warning-days)))
16035 (defun org-calendar-select-mouse (ev)
16036 "Return to `org-read-date' with the date currently selected.
16037 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16038 (interactive "e")
16039 (mouse-set-point ev)
16040 (when (calendar-cursor-to-date)
16041 (let* ((date (calendar-cursor-to-date))
16042 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16043 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16044 (if (active-minibuffer-window) (exit-minibuffer))))
16046 (defun org-check-deadlines (ndays)
16047 "Check if there are any deadlines due or past due.
16048 A deadline is considered due if it happens within `org-deadline-warning-days'
16049 days from today's date. If the deadline appears in an entry marked DONE,
16050 it is not shown. The prefix arg NDAYS can be used to test that many
16051 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16052 (interactive "P")
16053 (let* ((org-warn-days
16054 (cond
16055 ((equal ndays '(4)) 100000)
16056 (ndays (prefix-numeric-value ndays))
16057 (t (abs org-deadline-warning-days))))
16058 (case-fold-search nil)
16059 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16060 (callback
16061 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16063 (message "%d deadlines past-due or due within %d days"
16064 (org-occur regexp nil callback)
16065 org-warn-days)))
16067 (defsubst org-re-timestamp (type)
16068 "Return a regexp for timestamp TYPE.
16069 Allowed values for TYPE are:
16071 all: all timestamps
16072 active: only active timestamps (<...>)
16073 inactive: only inactive timestamps ([...])
16074 scheduled: only scheduled timestamps
16075 deadline: only deadline timestamps
16077 When TYPE is nil, fall back on returning a regexp that matches
16078 both scheduled and deadline timestamps."
16079 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16080 ((eq type 'active) org-ts-regexp)
16081 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16082 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16083 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16084 ((eq type 'scheduled-or-deadline)
16085 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16087 (defun org-check-before-date (date)
16088 "Check if there are deadlines or scheduled entries before DATE."
16089 (interactive (list (org-read-date)))
16090 (let ((case-fold-search nil)
16091 (regexp (org-re-timestamp org-ts-type))
16092 (callback
16093 (lambda () (time-less-p
16094 (org-time-string-to-time (match-string 1))
16095 (org-time-string-to-time date)))))
16096 (message "%d entries before %s"
16097 (org-occur regexp nil callback) date)))
16099 (defun org-check-after-date (date)
16100 "Check if there are deadlines or scheduled entries after DATE."
16101 (interactive (list (org-read-date)))
16102 (let ((case-fold-search nil)
16103 (regexp (org-re-timestamp org-ts-type))
16104 (callback
16105 (lambda () (not
16106 (time-less-p
16107 (org-time-string-to-time (match-string 1))
16108 (org-time-string-to-time date))))))
16109 (message "%d entries after %s"
16110 (org-occur regexp nil callback) date)))
16112 (defun org-check-dates-range (start-date end-date)
16113 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16114 (interactive (list (org-read-date nil nil nil "Range starts")
16115 (org-read-date nil nil nil "Range end")))
16116 (let ((case-fold-search nil)
16117 (regexp (org-re-timestamp org-ts-type))
16118 (callback
16119 (lambda ()
16120 (let ((match (match-string 1)))
16121 (and
16122 (not (time-less-p
16123 (org-time-string-to-time match)
16124 (org-time-string-to-time start-date)))
16125 (time-less-p
16126 (org-time-string-to-time match)
16127 (org-time-string-to-time end-date)))))))
16128 (message "%d entries between %s and %s"
16129 (org-occur regexp nil callback) start-date end-date)))
16131 (defun org-evaluate-time-range (&optional to-buffer)
16132 "Evaluate a time range by computing the difference between start and end.
16133 Normally the result is just printed in the echo area, but with prefix arg
16134 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16135 If the time range is actually in a table, the result is inserted into the
16136 next column.
16137 For time difference computation, a year is assumed to be exactly 365
16138 days in order to avoid rounding problems."
16139 (interactive "P")
16141 (org-clock-update-time-maybe)
16142 (save-excursion
16143 (unless (org-at-date-range-p t)
16144 (goto-char (point-at-bol))
16145 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16146 (if (not (org-at-date-range-p t))
16147 (error "Not at a time-stamp range, and none found in current line")))
16148 (let* ((ts1 (match-string 1))
16149 (ts2 (match-string 2))
16150 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16151 (match-end (match-end 0))
16152 (time1 (org-time-string-to-time ts1))
16153 (time2 (org-time-string-to-time ts2))
16154 (t1 (org-float-time time1))
16155 (t2 (org-float-time time2))
16156 (diff (abs (- t2 t1)))
16157 (negative (< (- t2 t1) 0))
16158 ;; (ys (floor (* 365 24 60 60)))
16159 (ds (* 24 60 60))
16160 (hs (* 60 60))
16161 (fy "%dy %dd %02d:%02d")
16162 (fy1 "%dy %dd")
16163 (fd "%dd %02d:%02d")
16164 (fd1 "%dd")
16165 (fh "%02d:%02d")
16166 y d h m align)
16167 (if havetime
16168 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16170 d (floor (/ diff ds)) diff (mod diff ds)
16171 h (floor (/ diff hs)) diff (mod diff hs)
16172 m (floor (/ diff 60)))
16173 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16175 d (floor (+ (/ diff ds) 0.5))
16176 h 0 m 0))
16177 (if (not to-buffer)
16178 (message "%s" (org-make-tdiff-string y d h m))
16179 (if (org-at-table-p)
16180 (progn
16181 (goto-char match-end)
16182 (setq align t)
16183 (and (looking-at " *|") (goto-char (match-end 0))))
16184 (goto-char match-end))
16185 (if (looking-at
16186 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16187 (replace-match ""))
16188 (if negative (insert " -"))
16189 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16190 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16191 (insert " " (format fh h m))))
16192 (if align (org-table-align))
16193 (message "Time difference inserted")))))
16195 (defun org-make-tdiff-string (y d h m)
16196 (let ((fmt "")
16197 (l nil))
16198 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16199 l (push y l)))
16200 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16201 l (push d l)))
16202 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16203 l (push h l)))
16204 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16205 l (push m l)))
16206 (apply 'format fmt (nreverse l))))
16208 (defun org-time-string-to-time (s &optional buffer pos)
16209 "Convert a timestamp string into internal time."
16210 (condition-case errdata
16211 (apply 'encode-time (org-parse-time-string s))
16212 (error (error "Bad timestamp `%s'%s\nError was: %s"
16213 s (if (not (and buffer pos))
16215 (format " at %d in buffer `%s'" pos buffer))
16216 (cdr errdata)))))
16218 (defun org-time-string-to-seconds (s)
16219 "Convert a timestamp string to a number of seconds."
16220 (org-float-time (org-time-string-to-time s)))
16222 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16223 "Convert a time stamp to an absolute day number.
16224 If there is a specifier for a cyclic time stamp, get the closest date to
16225 DAYNR.
16226 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16227 The variable date is bound by the calendar when this is called."
16228 (cond
16229 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16230 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16231 daynr
16232 (+ daynr 1000)))
16233 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16234 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16235 (time-to-days (current-time))) (match-string 0 s)
16236 prefer show-all))
16237 (t (time-to-days
16238 (condition-case errdata
16239 (apply 'encode-time (org-parse-time-string s))
16240 (error (error "Bad timestamp `%s'%s\nError was: %s"
16241 s (if (not (and buffer pos))
16243 (format " at %d in buffer `%s'" pos buffer))
16244 (cdr errdata))))))))
16246 (defun org-days-to-iso-week (days)
16247 "Return the iso week number."
16248 (require 'cal-iso)
16249 (car (calendar-iso-from-absolute days)))
16251 (defun org-small-year-to-year (year)
16252 "Convert 2-digit years into 4-digit years.
16253 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16254 The year 2000 cannot be abbreviated. Any year larger than 99
16255 is returned unchanged."
16256 (if (< year 38)
16257 (setq year (+ 2000 year))
16258 (if (< year 100)
16259 (setq year (+ 1900 year))))
16260 year)
16262 (defun org-time-from-absolute (d)
16263 "Return the time corresponding to date D.
16264 D may be an absolute day number, or a calendar-type list (month day year)."
16265 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16266 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16268 (defun org-calendar-holiday ()
16269 "List of holidays, for Diary display in Org-mode."
16270 (require 'holidays)
16271 (let ((hl (funcall
16272 (if (fboundp 'calendar-check-holidays)
16273 'calendar-check-holidays 'check-calendar-holidays) date)))
16274 (if hl (mapconcat 'identity hl "; "))))
16276 (defun org-diary-sexp-entry (sexp entry date)
16277 "Process a SEXP diary ENTRY for DATE."
16278 (require 'diary-lib)
16279 (let ((result (if calendar-debug-sexp
16280 (let ((stack-trace-on-error t))
16281 (eval (car (read-from-string sexp))))
16282 (condition-case nil
16283 (eval (car (read-from-string sexp)))
16284 (error
16285 (beep)
16286 (message "Bad sexp at line %d in %s: %s"
16287 (org-current-line)
16288 (buffer-file-name) sexp)
16289 (sleep-for 2))))))
16290 (cond ((stringp result) (split-string result "; "))
16291 ((and (consp result)
16292 (not (consp (cdr result)))
16293 (stringp (cdr result))) (cdr result))
16294 ((and (consp result)
16295 (stringp (car result))) result)
16296 (result entry))))
16298 (defun org-diary-to-ical-string (frombuf)
16299 "Get iCalendar entries from diary entries in buffer FROMBUF.
16300 This uses the icalendar.el library."
16301 (let* ((tmpdir (if (featurep 'xemacs)
16302 (temp-directory)
16303 temporary-file-directory))
16304 (tmpfile (make-temp-name
16305 (expand-file-name "orgics" tmpdir)))
16306 buf rtn b e)
16307 (with-current-buffer frombuf
16308 (icalendar-export-region (point-min) (point-max) tmpfile)
16309 (setq buf (find-buffer-visiting tmpfile))
16310 (set-buffer buf)
16311 (goto-char (point-min))
16312 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16313 (setq b (match-beginning 0)))
16314 (goto-char (point-max))
16315 (if (re-search-backward "^END:VEVENT" nil t)
16316 (setq e (match-end 0)))
16317 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16318 (kill-buffer buf)
16319 (delete-file tmpfile)
16320 rtn))
16322 (defun org-closest-date (start current change prefer show-all)
16323 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16324 When PREFER is `past', return a date that is either CURRENT or past.
16325 When PREFER is `future', return a date that is either CURRENT or future.
16326 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16327 ;; Make the proper lists from the dates
16328 (catch 'exit
16329 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16330 dn dw sday cday n1 n2 n0
16331 d m y y1 y2 date1 date2 nmonths nm ny m2)
16333 (setq start (org-date-to-gregorian start)
16334 current (org-date-to-gregorian
16335 (if show-all
16336 current
16337 (time-to-days (current-time))))
16338 sday (calendar-absolute-from-gregorian start)
16339 cday (calendar-absolute-from-gregorian current))
16341 (if (<= cday sday) (throw 'exit sday))
16343 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16344 (setq dn (string-to-number (match-string 1 change))
16345 dw (cdr (assoc (match-string 2 change) a1)))
16346 (error "Invalid change specifier: %s" change))
16347 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16348 (cond
16349 ((eq dw 'day)
16350 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16351 n2 (+ n1 dn)))
16352 ((eq dw 'year)
16353 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16354 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16355 (setq date1 (list m d y1)
16356 n1 (calendar-absolute-from-gregorian date1)
16357 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16358 n2 (calendar-absolute-from-gregorian date2)))
16359 ((eq dw 'month)
16360 ;; approx number of month between the two dates
16361 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16362 ;; How often does dn fit in there?
16363 (setq d (nth 1 start) m (car start) y (nth 2 start)
16364 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16365 m (+ m nm)
16366 ny (floor (/ m 12))
16367 y (+ y ny)
16368 m (- m (* ny 12)))
16369 (while (> m 12) (setq m (- m 12) y (1+ y)))
16370 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16371 (setq m2 (+ m dn) y2 y)
16372 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16373 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16374 (while (<= n2 cday)
16375 (setq n1 n2 m m2 y y2)
16376 (setq m2 (+ m dn) y2 y)
16377 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16378 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16379 ;; Make sure n1 is the earlier date
16380 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16381 (if show-all
16382 (cond
16383 ((eq prefer 'past) (if (= cday n2) n2 n1))
16384 ((eq prefer 'future) (if (= cday n1) n1 n2))
16385 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16386 (cond
16387 ((eq prefer 'past) (if (= cday n2) n2 n1))
16388 ((eq prefer 'future) (if (= cday n1) n1 n2))
16389 (t (if (= cday n1) n1 n2)))))))
16391 (defun org-date-to-gregorian (date)
16392 "Turn any specification of DATE into a Gregorian date for the calendar."
16393 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16394 ((and (listp date) (= (length date) 3)) date)
16395 ((stringp date)
16396 (setq date (org-parse-time-string date))
16397 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16398 ((listp date)
16399 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16401 (defun org-parse-time-string (s &optional nodefault)
16402 "Parse the standard Org-mode time string.
16403 This should be a lot faster than the normal `parse-time-string'.
16404 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16405 hour and minute fields will be nil if not given."
16406 (if (string-match org-ts-regexp0 s)
16407 (list 0
16408 (if (or (match-beginning 8) (not nodefault))
16409 (string-to-number (or (match-string 8 s) "0")))
16410 (if (or (match-beginning 7) (not nodefault))
16411 (string-to-number (or (match-string 7 s) "0")))
16412 (string-to-number (match-string 4 s))
16413 (string-to-number (match-string 3 s))
16414 (string-to-number (match-string 2 s))
16415 nil nil nil)
16416 (error "Not a standard Org-mode time string: %s" s)))
16418 (defun org-timestamp-up (&optional arg)
16419 "Increase the date item at the cursor by one.
16420 If the cursor is on the year, change the year. If it is on the month,
16421 the day or the time, change that.
16422 With prefix ARG, change by that many units."
16423 (interactive "p")
16424 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16426 (defun org-timestamp-down (&optional arg)
16427 "Decrease the date item at the cursor by one.
16428 If the cursor is on the year, change the year. If it is on the month,
16429 the day or the time, change that.
16430 With prefix ARG, change by that many units."
16431 (interactive "p")
16432 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16434 (defun org-timestamp-up-day (&optional arg)
16435 "Increase the date in the time stamp by one day.
16436 With prefix ARG, change that many days."
16437 (interactive "p")
16438 (if (and (not (org-at-timestamp-p t))
16439 (org-at-heading-p))
16440 (org-todo 'up)
16441 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16443 (defun org-timestamp-down-day (&optional arg)
16444 "Decrease the date in the time stamp by one day.
16445 With prefix ARG, change that many days."
16446 (interactive "p")
16447 (if (and (not (org-at-timestamp-p t))
16448 (org-at-heading-p))
16449 (org-todo 'down)
16450 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16452 (defun org-at-timestamp-p (&optional inactive-ok)
16453 "Determine if the cursor is in or at a timestamp."
16454 (interactive)
16455 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16456 (pos (point))
16457 (ans (or (looking-at tsr)
16458 (save-excursion
16459 (skip-chars-backward "^[<\n\r\t")
16460 (if (> (point) (point-min)) (backward-char 1))
16461 (and (looking-at tsr)
16462 (> (- (match-end 0) pos) -1))))))
16463 (and ans
16464 (boundp 'org-ts-what)
16465 (setq org-ts-what
16466 (cond
16467 ((= pos (match-beginning 0)) 'bracket)
16468 ;; Point is considered to be "on the bracket" whether
16469 ;; it's really on it or right after it.
16470 ((= pos (1- (match-end 0))) 'bracket)
16471 ((= pos (match-end 0)) 'after)
16472 ((org-pos-in-match-range pos 2) 'year)
16473 ((org-pos-in-match-range pos 3) 'month)
16474 ((org-pos-in-match-range pos 7) 'hour)
16475 ((org-pos-in-match-range pos 8) 'minute)
16476 ((or (org-pos-in-match-range pos 4)
16477 (org-pos-in-match-range pos 5)) 'day)
16478 ((and (> pos (or (match-end 8) (match-end 5)))
16479 (< pos (match-end 0)))
16480 (- pos (or (match-end 8) (match-end 5))))
16481 (t 'day))))
16482 ans))
16484 (defun org-toggle-timestamp-type ()
16485 "Toggle the type (<active> or [inactive]) of a time stamp."
16486 (interactive)
16487 (when (org-at-timestamp-p t)
16488 (let ((beg (match-beginning 0)) (end (match-end 0))
16489 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16490 (save-excursion
16491 (goto-char beg)
16492 (while (re-search-forward "[][<>]" end t)
16493 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16494 t t)))
16495 (message "Timestamp is now %sactive"
16496 (if (equal (char-after beg) ?<) "" "in")))))
16498 (defvar org-clock-history) ; defined in org-clock.el
16499 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16500 (defun org-timestamp-change (n &optional what updown)
16501 "Change the date in the time stamp at point.
16502 The date will be changed by N times WHAT. WHAT can be `day', `month',
16503 `year', `minute', `second'. If WHAT is not given, the cursor position
16504 in the timestamp determines what will be changed."
16505 (let ((origin (point)) origin-cat
16506 with-hm inactive
16507 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16508 org-ts-what
16509 extra rem
16510 ts time time0 fixnext clrgx)
16511 (if (not (org-at-timestamp-p t))
16512 (error "Not at a timestamp"))
16513 (if (and (not what) (eq org-ts-what 'bracket))
16514 (org-toggle-timestamp-type)
16515 ;; Point isn't on brackets. Remember the part of the time-stamp
16516 ;; the point was in. Indeed, size of time-stamps may change,
16517 ;; but point must be kept in the same category nonetheless.
16518 (setq origin-cat org-ts-what)
16519 (if (and (not what) (not (eq org-ts-what 'day))
16520 org-display-custom-times
16521 (get-text-property (point) 'display)
16522 (not (get-text-property (1- (point)) 'display)))
16523 (setq org-ts-what 'day))
16524 (setq org-ts-what (or what org-ts-what)
16525 inactive (= (char-after (match-beginning 0)) ?\[)
16526 ts (match-string 0))
16527 (replace-match "")
16528 (if (string-match
16529 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16531 (setq extra (match-string 1 ts)))
16532 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16533 (setq with-hm t))
16534 (setq time0 (org-parse-time-string ts))
16535 (when (and updown
16536 (eq org-ts-what 'minute)
16537 (not current-prefix-arg))
16538 ;; This looks like s-up and s-down. Change by one rounding step.
16539 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16540 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16541 (setcar (cdr time0) (+ (nth 1 time0)
16542 (if (> n 0) (- rem) (- dm rem))))))
16543 (setq time
16544 (encode-time (or (car time0) 0)
16545 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16546 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16547 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16548 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16549 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16550 (nthcdr 6 time0)))
16551 (when (and (member org-ts-what '(hour minute))
16552 extra
16553 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16554 (setq extra (org-modify-ts-extra
16555 extra
16556 (if (eq org-ts-what 'hour) 2 5)
16557 n dm)))
16558 (when (integerp org-ts-what)
16559 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16560 (if (eq what 'calendar)
16561 (let ((cal-date (org-get-date-from-calendar)))
16562 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16563 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16564 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16565 (setcar time0 (or (car time0) 0))
16566 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16567 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16568 (setq time (apply 'encode-time time0))))
16569 ;; Insert the new time-stamp, and ensure point stays in the same
16570 ;; category as before (i.e. not after the last position in that
16571 ;; category).
16572 (let ((pos (point)))
16573 ;; Stay before inserted string. `save-excursion' is of no use.
16574 (setq org-last-changed-timestamp
16575 (org-insert-time-stamp time with-hm inactive nil nil extra))
16576 (goto-char pos))
16577 (save-match-data
16578 (looking-at org-ts-regexp3)
16579 (goto-char (cond
16580 ;; `day' category ends before `hour' if any, or at
16581 ;; the end of the day name.
16582 ((eq origin-cat 'day)
16583 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16584 ((eq origin-cat 'hour) (min (match-end 7) origin))
16585 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16586 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16587 ;; `year' and `month' have both fixed size: point
16588 ;; couldn't have moved into another part.
16589 (t origin))))
16590 ;; Update clock if on a CLOCK line.
16591 (org-clock-update-time-maybe)
16592 ;; Maybe adjust the closest clock in `org-clock-history'
16593 (when org-clock-adjust-closest
16594 (if (not (and (org-at-clock-log-p)
16595 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16596 org-clock-history))))))
16597 (message "No clock to adjust")
16598 (cond ((save-excursion ; fix previous clock?
16599 (re-search-backward org-ts-regexp0 nil t)
16600 (org-looking-back (concat org-clock-string " \\[")))
16601 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16602 ((save-excursion ; fix next clock?
16603 (re-search-backward org-ts-regexp0 nil t)
16604 (looking-at (concat org-ts-regexp0 "\\] =>")))
16605 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16606 (save-window-excursion
16607 ;; Find closest clock to point, adjust the previous/next one in history
16608 (let* ((p (save-excursion (org-back-to-heading t)))
16609 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16610 (clfixnth
16611 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16612 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16613 (if (not clfixpos)
16614 (message "No clock to adjust")
16615 (save-excursion
16616 (org-goto-marker-or-bmk clfixpos)
16617 (org-show-subtree)
16618 (when (re-search-forward clrgx nil t)
16619 (goto-char (match-beginning 1))
16620 (let (org-clock-adjust-closest)
16621 (org-timestamp-change n org-ts-what updown))
16622 (message "Clock adjusted in %s for heading: %s"
16623 (file-name-nondirectory (buffer-file-name))
16624 (org-get-heading t t)))))))))
16625 ;; Try to recenter the calendar window, if any.
16626 (if (and org-calendar-follow-timestamp-change
16627 (get-buffer-window "*Calendar*" t)
16628 (memq org-ts-what '(day month year)))
16629 (org-recenter-calendar (time-to-days time))))))
16631 (defun org-modify-ts-extra (s pos n dm)
16632 "Change the different parts of the lead-time and repeat fields in timestamp."
16633 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16634 ng h m new rem)
16635 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16636 (cond
16637 ((or (org-pos-in-match-range pos 2)
16638 (org-pos-in-match-range pos 3))
16639 (setq m (string-to-number (match-string 3 s))
16640 h (string-to-number (match-string 2 s)))
16641 (if (org-pos-in-match-range pos 2)
16642 (setq h (+ h n))
16643 (setq n (* dm (org-no-warnings (signum n))))
16644 (when (not (= 0 (setq rem (% m dm))))
16645 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16646 (setq m (+ m n)))
16647 (if (< m 0) (setq m (+ m 60) h (1- h)))
16648 (if (> m 59) (setq m (- m 60) h (1+ h)))
16649 (setq h (min 24 (max 0 h)))
16650 (setq ng 1 new (format "-%02d:%02d" h m)))
16651 ((org-pos-in-match-range pos 6)
16652 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16653 ((org-pos-in-match-range pos 5)
16654 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16656 ((org-pos-in-match-range pos 9)
16657 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16658 ((org-pos-in-match-range pos 8)
16659 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16661 (when ng
16662 (setq s (concat
16663 (substring s 0 (match-beginning ng))
16665 (substring s (match-end ng))))))
16668 (defun org-recenter-calendar (date)
16669 "If the calendar is visible, recenter it to DATE."
16670 (let ((cwin (get-buffer-window "*Calendar*" t)))
16671 (when cwin
16672 (let ((calendar-move-hook nil))
16673 (with-selected-window cwin
16674 (calendar-goto-date (if (listp date) date
16675 (calendar-gregorian-from-absolute date))))))))
16677 (defun org-goto-calendar (&optional arg)
16678 "Go to the Emacs calendar at the current date.
16679 If there is a time stamp in the current line, go to that date.
16680 A prefix ARG can be used to force the current date."
16681 (interactive "P")
16682 (let ((tsr org-ts-regexp) diff
16683 (calendar-move-hook nil)
16684 (calendar-view-holidays-initially-flag nil)
16685 (calendar-view-diary-initially-flag nil))
16686 (if (or (org-at-timestamp-p)
16687 (save-excursion
16688 (beginning-of-line 1)
16689 (looking-at (concat ".*" tsr))))
16690 (let ((d1 (time-to-days (current-time)))
16691 (d2 (time-to-days
16692 (org-time-string-to-time (match-string 1)))))
16693 (setq diff (- d2 d1))))
16694 (calendar)
16695 (calendar-goto-today)
16696 (if (and diff (not arg)) (calendar-forward-day diff))))
16698 (defun org-get-date-from-calendar ()
16699 "Return a list (month day year) of date at point in calendar."
16700 (with-current-buffer "*Calendar*"
16701 (save-match-data
16702 (calendar-cursor-to-date))))
16704 (defun org-date-from-calendar ()
16705 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16706 If there is already a time stamp at the cursor position, update it."
16707 (interactive)
16708 (if (org-at-timestamp-p t)
16709 (org-timestamp-change 0 'calendar)
16710 (let ((cal-date (org-get-date-from-calendar)))
16711 (org-insert-time-stamp
16712 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16714 (defun org-minutes-to-hh:mm-string (m)
16715 "Compute H:MM from a number of minutes."
16716 (let ((h (/ m 60)))
16717 (setq m (- m (* 60 h)))
16718 (format org-time-clocksum-format h m)))
16720 (defun org-hh:mm-string-to-minutes (s)
16721 "Convert a string H:MM to a number of minutes.
16722 If the string is just a number, interpret it as minutes.
16723 In fact, the first hh:mm or number in the string will be taken,
16724 there can be extra stuff in the string.
16725 If no number is found, the return value is 0."
16726 (cond
16727 ((integerp s) s)
16728 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16729 (+ (* (string-to-number (match-string 1 s)) 60)
16730 (string-to-number (match-string 2 s))))
16731 ((string-match "\\([0-9]+\\)" s)
16732 (string-to-number (match-string 1 s)))
16733 (t 0)))
16735 (defcustom org-effort-durations
16736 `(("h" . 60)
16737 ("d" . ,(* 60 8))
16738 ("w" . ,(* 60 8 5))
16739 ("m" . ,(* 60 8 5 4))
16740 ("y" . ,(* 60 8 5 40)))
16741 "Conversion factor to minutes for an effort modifier.
16743 Each entry has the form (MODIFIER . MINUTES).
16745 In an effort string, a number followed by MODIFIER is multiplied
16746 by the specified number of MINUTES to obtain an effort in
16747 minutes.
16749 For example, if the value of this variable is ((\"hours\" . 60)), then an
16750 effort string \"2hours\" is equivalent to 120 minutes."
16751 :group 'org-agenda
16752 :version "24.1"
16753 :type '(alist :key-type (string :tag "Modifier")
16754 :value-type (number :tag "Minutes")))
16756 (defcustom org-image-actual-width t
16757 "Should we use the actual width of images when inlining them?
16759 When set to `t', always use the image width.
16761 When set to a number, use imagemagick (when available) to set
16762 the image's width to this value.
16764 When set to a number in a list, try to get the width from the
16765 #+ATTR.* keyword if it matches a width specification like
16766 width=\"[0-9]+\", and fall back on that number if none is found.
16768 When set to nil, try to get the width from an #+ATTR.* keyword
16769 and fall back on the original width if none is found.
16771 This requires Emacs >= 24.1, build with imagemagick support."
16772 :group 'org-appearance
16773 :version "24.3"
16774 :type '(choice
16775 (const :tag "Use the image width" t)
16776 (integer :tag "Use a number of pixels")
16777 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16778 (const :tag "Use #+ATTR* or don't resize" nil)))
16780 (defun org-duration-string-to-minutes (s &optional output-to-string)
16781 "Convert a duration string S to minutes.
16783 A bare number is interpreted as minutes, modifiers can be set by
16784 customizing `org-effort-durations' (which see).
16786 Entries containing a colon are interpreted as H:MM by
16787 `org-hh:mm-string-to-minutes'."
16788 (let ((result 0)
16789 (re (concat "\\([0-9.]+\\) *\\("
16790 (regexp-opt (mapcar 'car org-effort-durations))
16791 "\\)")))
16792 (while (string-match re s)
16793 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16794 (string-to-number (match-string 1 s))))
16795 (setq s (replace-match "" nil t s)))
16796 (setq result (floor result))
16797 (incf result (org-hh:mm-string-to-minutes s))
16798 (if output-to-string (number-to-string result) result)))
16800 ;;;; Files
16802 (defun org-save-all-org-buffers ()
16803 "Save all Org-mode buffers without user confirmation."
16804 (interactive)
16805 (message "Saving all Org-mode buffers...")
16806 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16807 (when (featurep 'org-id) (org-id-locations-save))
16808 (message "Saving all Org-mode buffers... done"))
16810 (defun org-revert-all-org-buffers ()
16811 "Revert all Org-mode buffers.
16812 Prompt for confirmation when there are unsaved changes.
16813 Be sure you know what you are doing before letting this function
16814 overwrite your changes.
16816 This function is useful in a setup where one tracks org files
16817 with a version control system, to revert on one machine after pulling
16818 changes from another. I believe the procedure must be like this:
16820 1. M-x org-save-all-org-buffers
16821 2. Pull changes from the other machine, resolve conflicts
16822 3. M-x org-revert-all-org-buffers"
16823 (interactive)
16824 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16825 (error "Abort"))
16826 (save-excursion
16827 (save-window-excursion
16828 (mapc
16829 (lambda (b)
16830 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16831 (with-current-buffer b buffer-file-name))
16832 (org-pop-to-buffer-same-window b)
16833 (revert-buffer t 'no-confirm)))
16834 (buffer-list))
16835 (when (and (featurep 'org-id) org-id-track-globally)
16836 (org-id-locations-load)))))
16838 ;;;; Agenda files
16840 ;;;###autoload
16841 (defun org-switchb (&optional arg)
16842 "Switch between Org buffers.
16843 With one prefix argument, restrict available buffers to files.
16844 With two prefix arguments, restrict available buffers to agenda files.
16846 Defaults to `iswitchb' for buffer name completion.
16847 Set `org-completion-use-ido' to make it use ido instead."
16848 (interactive "P")
16849 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16850 ((equal arg '(16)) (org-buffer-list 'agenda))
16851 (t (org-buffer-list))))
16852 (org-completion-use-iswitchb org-completion-use-iswitchb)
16853 (org-completion-use-ido org-completion-use-ido))
16854 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16855 (setq org-completion-use-iswitchb t))
16856 (org-pop-to-buffer-same-window
16857 (org-icompleting-read "Org buffer: "
16858 (mapcar 'list (mapcar 'buffer-name blist))
16859 nil t))))
16861 ;;; Define some older names previously used for this functionality
16862 ;;;###autoload
16863 (defalias 'org-ido-switchb 'org-switchb)
16864 ;;;###autoload
16865 (defalias 'org-iswitchb 'org-switchb)
16867 (defun org-buffer-list (&optional predicate exclude-tmp)
16868 "Return a list of Org buffers.
16869 PREDICATE can be `export', `files' or `agenda'.
16871 export restrict the list to Export buffers.
16872 files restrict the list to buffers visiting Org files.
16873 agenda restrict the list to buffers visiting agenda files.
16875 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16876 (let* ((bfn nil)
16877 (agenda-files (and (eq predicate 'agenda)
16878 (mapcar 'file-truename (org-agenda-files t))))
16879 (filter
16880 (cond
16881 ((eq predicate 'files)
16882 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16883 ((eq predicate 'export)
16884 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16885 ((eq predicate 'agenda)
16886 (lambda (b)
16887 (with-current-buffer b
16888 (and (derived-mode-p 'org-mode)
16889 (setq bfn (buffer-file-name b))
16890 (member (file-truename bfn) agenda-files)))))
16891 (t (lambda (b) (with-current-buffer b
16892 (or (derived-mode-p 'org-mode)
16893 (string-match "\*Org .*Export"
16894 (buffer-name b)))))))))
16895 (delq nil
16896 (mapcar
16897 (lambda(b)
16898 (if (and (funcall filter b)
16899 (or (not exclude-tmp)
16900 (not (string-match "tmp" (buffer-name b)))))
16902 nil))
16903 (buffer-list)))))
16905 (defun org-agenda-files (&optional unrestricted archives)
16906 "Get the list of agenda files.
16907 Optional UNRESTRICTED means return the full list even if a restriction
16908 is currently in place.
16909 When ARCHIVES is t, include all archive files that are really being
16910 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16911 `org-agenda-archives-mode' is t."
16912 (let ((files
16913 (cond
16914 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16915 ((stringp org-agenda-files) (org-read-agenda-file-list))
16916 ((listp org-agenda-files) org-agenda-files)
16917 (t (error "Invalid value of `org-agenda-files'")))))
16918 (setq files (apply 'append
16919 (mapcar (lambda (f)
16920 (if (file-directory-p f)
16921 (directory-files
16922 f t org-agenda-file-regexp)
16923 (list f)))
16924 files)))
16925 (when org-agenda-skip-unavailable-files
16926 (setq files (delq nil
16927 (mapcar (function
16928 (lambda (file)
16929 (and (file-readable-p file) file)))
16930 files))))
16931 (when (or (eq archives t)
16932 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16933 (setq files (org-add-archive-files files)))
16934 files))
16936 (defun org-agenda-file-p (&optional file)
16937 "Return non-nil, if FILE is an agenda file.
16938 If FILE is omitted, use the file associated with the current
16939 buffer."
16940 (member (or file (buffer-file-name))
16941 (org-agenda-files t)))
16943 (defun org-edit-agenda-file-list ()
16944 "Edit the list of agenda files.
16945 Depending on setup, this either uses customize to edit the variable
16946 `org-agenda-files', or it visits the file that is holding the list. In the
16947 latter case, the buffer is set up in a way that saving it automatically kills
16948 the buffer and restores the previous window configuration."
16949 (interactive)
16950 (if (stringp org-agenda-files)
16951 (let ((cw (current-window-configuration)))
16952 (find-file org-agenda-files)
16953 (org-set-local 'org-window-configuration cw)
16954 (org-add-hook 'after-save-hook
16955 (lambda ()
16956 (set-window-configuration
16957 (prog1 org-window-configuration
16958 (kill-buffer (current-buffer))))
16959 (org-install-agenda-files-menu)
16960 (message "New agenda file list installed"))
16961 nil 'local)
16962 (message "%s" (substitute-command-keys
16963 "Edit list and finish with \\[save-buffer]")))
16964 (customize-variable 'org-agenda-files)))
16966 (defun org-store-new-agenda-file-list (list)
16967 "Set new value for the agenda file list and save it correctly."
16968 (if (stringp org-agenda-files)
16969 (let ((fe (org-read-agenda-file-list t)) b u)
16970 (while (setq b (find-buffer-visiting org-agenda-files))
16971 (kill-buffer b))
16972 (with-temp-file org-agenda-files
16973 (insert
16974 (mapconcat
16975 (lambda (f) ;; Keep un-expanded entries.
16976 (if (setq u (assoc f fe))
16977 (cdr u)
16979 list "\n")
16980 "\n")))
16981 (let ((org-mode-hook nil) (org-inhibit-startup t)
16982 (org-insert-mode-line-in-empty-file nil))
16983 (setq org-agenda-files list)
16984 (customize-save-variable 'org-agenda-files org-agenda-files))))
16986 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16987 "Read the list of agenda files from a file.
16988 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16989 filenames, used by `org-store-new-agenda-file-list' to write back
16990 un-expanded file names."
16991 (when (file-directory-p org-agenda-files)
16992 (error "`org-agenda-files' cannot be a single directory"))
16993 (when (stringp org-agenda-files)
16994 (with-temp-buffer
16995 (insert-file-contents org-agenda-files)
16996 (mapcar
16997 (lambda (f)
16998 (let ((e (expand-file-name (substitute-in-file-name f)
16999 org-directory)))
17000 (if pair-with-expansion
17001 (cons e f)
17002 e)))
17003 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17005 ;;;###autoload
17006 (defun org-cycle-agenda-files ()
17007 "Cycle through the files in `org-agenda-files'.
17008 If the current buffer visits an agenda file, find the next one in the list.
17009 If the current buffer does not, find the first agenda file."
17010 (interactive)
17011 (let* ((fs (org-agenda-files t))
17012 (files (append fs (list (car fs))))
17013 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17014 file)
17015 (unless files (error "No agenda files"))
17016 (catch 'exit
17017 (while (setq file (pop files))
17018 (if (equal (file-truename file) tcf)
17019 (when (car files)
17020 (find-file (car files))
17021 (throw 'exit t))))
17022 (find-file (car fs)))
17023 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17025 (defun org-agenda-file-to-front (&optional to-end)
17026 "Move/add the current file to the top of the agenda file list.
17027 If the file is not present in the list, it is added to the front. If it is
17028 present, it is moved there. With optional argument TO-END, add/move to the
17029 end of the list."
17030 (interactive "P")
17031 (let ((org-agenda-skip-unavailable-files nil)
17032 (file-alist (mapcar (lambda (x)
17033 (cons (file-truename x) x))
17034 (org-agenda-files t)))
17035 (ctf (file-truename buffer-file-name))
17036 x had)
17037 (setq x (assoc ctf file-alist) had x)
17039 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17040 (if to-end
17041 (setq file-alist (append (delq x file-alist) (list x)))
17042 (setq file-alist (cons x (delq x file-alist))))
17043 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17044 (org-install-agenda-files-menu)
17045 (message "File %s to %s of agenda file list"
17046 (if had "moved" "added") (if to-end "end" "front"))))
17048 (defun org-remove-file (&optional file)
17049 "Remove current file from the list of files in variable `org-agenda-files'.
17050 These are the files which are being checked for agenda entries.
17051 Optional argument FILE means use this file instead of the current."
17052 (interactive)
17053 (let* ((org-agenda-skip-unavailable-files nil)
17054 (file (or file buffer-file-name))
17055 (true-file (file-truename file))
17056 (afile (abbreviate-file-name file))
17057 (files (delq nil (mapcar
17058 (lambda (x)
17059 (if (equal true-file
17060 (file-truename x))
17061 nil x))
17062 (org-agenda-files t)))))
17063 (if (not (= (length files) (length (org-agenda-files t))))
17064 (progn
17065 (org-store-new-agenda-file-list files)
17066 (org-install-agenda-files-menu)
17067 (message "Removed file: %s" afile))
17068 (message "File was not in list: %s (not removed)" afile))))
17070 (defun org-file-menu-entry (file)
17071 (vector file (list 'find-file file) t))
17073 (defun org-check-agenda-file (file)
17074 "Make sure FILE exists. If not, ask user what to do."
17075 (when (not (file-exists-p file))
17076 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17077 (abbreviate-file-name file))
17078 (let ((r (downcase (read-char-exclusive))))
17079 (cond
17080 ((equal r ?r)
17081 (org-remove-file file)
17082 (throw 'nextfile t))
17083 (t (error "Abort"))))))
17085 (defun org-get-agenda-file-buffer (file)
17086 "Get a buffer visiting FILE. If the buffer needs to be created, add
17087 it to the list of buffers which might be released later."
17088 (let ((buf (org-find-base-buffer-visiting file)))
17089 (if buf
17090 buf ; just return it
17091 ;; Make a new buffer and remember it
17092 (setq buf (find-file-noselect file))
17093 (if buf (push buf org-agenda-new-buffers))
17094 buf)))
17096 (defun org-release-buffers (blist)
17097 "Release all buffers in list, asking the user for confirmation when needed.
17098 When a buffer is unmodified, it is just killed. When modified, it is saved
17099 \(if the user agrees) and then killed."
17100 (let (buf file)
17101 (while (setq buf (pop blist))
17102 (setq file (buffer-file-name buf))
17103 (when (and (buffer-modified-p buf)
17104 file
17105 (y-or-n-p (format "Save file %s? " file)))
17106 (with-current-buffer buf (save-buffer)))
17107 (kill-buffer buf))))
17109 (defun org-agenda-prepare-buffers (files)
17110 "Create buffers for all agenda files, protect archived trees and comments."
17111 (interactive)
17112 (let ((pa '(:org-archived t))
17113 (pc '(:org-comment t))
17114 (pall '(:org-archived t :org-comment t))
17115 (inhibit-read-only t)
17116 (rea (concat ":" org-archive-tag ":"))
17117 bmp file re)
17118 (save-excursion
17119 (save-restriction
17120 (while (setq file (pop files))
17121 (catch 'nextfile
17122 (if (bufferp file)
17123 (set-buffer file)
17124 (org-check-agenda-file file)
17125 (set-buffer (org-get-agenda-file-buffer file)))
17126 (widen)
17127 (setq bmp (buffer-modified-p))
17128 (org-refresh-category-properties)
17129 (setq org-todo-keywords-for-agenda
17130 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17131 (setq org-done-keywords-for-agenda
17132 (append org-done-keywords-for-agenda org-done-keywords))
17133 (setq org-todo-keyword-alist-for-agenda
17134 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17135 (setq org-drawers-for-agenda
17136 (append org-drawers-for-agenda org-drawers))
17137 (setq org-tag-alist-for-agenda
17138 (append org-tag-alist-for-agenda org-tag-alist))
17140 (save-excursion
17141 (remove-text-properties (point-min) (point-max) pall)
17142 (when org-agenda-skip-archived-trees
17143 (goto-char (point-min))
17144 (while (re-search-forward rea nil t)
17145 (if (org-at-heading-p t)
17146 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17147 (goto-char (point-min))
17148 (setq re (format org-heading-keyword-regexp-format
17149 org-comment-string))
17150 (while (re-search-forward re nil t)
17151 (add-text-properties
17152 (match-beginning 0) (org-end-of-subtree t) pc)))
17153 (set-buffer-modified-p bmp)))))
17154 (setq org-todo-keywords-for-agenda
17155 (org-uniquify org-todo-keywords-for-agenda))
17156 (setq org-todo-keyword-alist-for-agenda
17157 (org-uniquify org-todo-keyword-alist-for-agenda)
17158 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17160 ;;;; Embedded LaTeX
17162 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17163 "Keymap for the minor `org-cdlatex-mode'.")
17165 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17166 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17167 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17168 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17169 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17171 (defvar org-cdlatex-texmathp-advice-is-done nil
17172 "Flag remembering if we have applied the advice to texmathp already.")
17174 (define-minor-mode org-cdlatex-mode
17175 "Toggle the minor `org-cdlatex-mode'.
17176 This mode supports entering LaTeX environment and math in LaTeX fragments
17177 in Org-mode.
17178 \\{org-cdlatex-mode-map}"
17179 nil " OCDL" nil
17180 (when org-cdlatex-mode
17181 (require 'cdlatex)
17182 (run-hooks 'cdlatex-mode-hook)
17183 (cdlatex-compute-tables))
17184 (unless org-cdlatex-texmathp-advice-is-done
17185 (setq org-cdlatex-texmathp-advice-is-done t)
17186 (defadvice texmathp (around org-math-always-on activate)
17187 "Always return t in org-mode buffers.
17188 This is because we want to insert math symbols without dollars even outside
17189 the LaTeX math segments. If Orgmode thinks that point is actually inside
17190 an embedded LaTeX fragment, let texmathp do its job.
17191 \\[org-cdlatex-mode-map]"
17192 (interactive)
17193 (let (p)
17194 (cond
17195 ((not (derived-mode-p 'org-mode)) ad-do-it)
17196 ((eq this-command 'cdlatex-math-symbol)
17197 (setq ad-return-value t
17198 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17200 (let ((p (org-inside-LaTeX-fragment-p)))
17201 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17202 (setq ad-return-value t
17203 texmathp-why '("Org-mode embedded math" . 0))
17204 (if p ad-do-it)))))))))
17206 (defun turn-on-org-cdlatex ()
17207 "Unconditionally turn on `org-cdlatex-mode'."
17208 (org-cdlatex-mode 1))
17210 (defun org-inside-LaTeX-fragment-p ()
17211 "Test if point is inside a LaTeX fragment.
17212 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17213 sequence appearing also before point.
17214 Even though the matchers for math are configurable, this function assumes
17215 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17216 delimiters are skipped when they have been removed by customization.
17217 The return value is nil, or a cons cell with the delimiter and the
17218 position of this delimiter.
17220 This function does a reasonably good job, but can locally be fooled by
17221 for example currency specifications. For example it will assume being in
17222 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17223 fragments that are properly closed, but during editing, we have to live
17224 with the uncertainty caused by missing closing delimiters. This function
17225 looks only before point, not after."
17226 (catch 'exit
17227 (let ((pos (point))
17228 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17229 (lim (progn
17230 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17231 (point)))
17232 dd-on str (start 0) m re)
17233 (goto-char pos)
17234 (when dodollar
17235 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17236 re (nth 1 (assoc "$" org-latex-regexps)))
17237 (while (string-match re str start)
17238 (cond
17239 ((= (match-end 0) (length str))
17240 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17241 ((= (match-end 0) (- (length str) 5))
17242 (throw 'exit nil))
17243 (t (setq start (match-end 0))))))
17244 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17245 (goto-char pos)
17246 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17247 (and (match-beginning 2) (throw 'exit nil))
17248 ;; count $$
17249 (while (re-search-backward "\\$\\$" lim t)
17250 (setq dd-on (not dd-on)))
17251 (goto-char pos)
17252 (if dd-on (cons "$$" m))))))
17254 (defun org-inside-latex-macro-p ()
17255 "Is point inside a LaTeX macro or its arguments?"
17256 (save-match-data
17257 (org-in-regexp
17258 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17260 (defun org-try-cdlatex-tab ()
17261 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17262 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17263 - inside a LaTeX fragment, or
17264 - after the first word in a line, where an abbreviation expansion could
17265 insert a LaTeX environment."
17266 (when org-cdlatex-mode
17267 (cond
17268 ;; Before any word on the line: No expansion possible.
17269 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17270 ;; Just after first word on the line: Expand it. Make sure it
17271 ;; cannot happen on headlines, though.
17272 ((save-excursion
17273 (skip-chars-backward "a-zA-Z0-9*")
17274 (skip-chars-backward " \t")
17275 (and (bolp) (not (org-at-heading-p))))
17276 (cdlatex-tab) t)
17277 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17279 (defun org-cdlatex-underscore-caret (&optional arg)
17280 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17281 Revert to the normal definition outside of these fragments."
17282 (interactive "P")
17283 (if (org-inside-LaTeX-fragment-p)
17284 (call-interactively 'cdlatex-sub-superscript)
17285 (let (org-cdlatex-mode)
17286 (call-interactively (key-binding (vector last-input-event))))))
17288 (defun org-cdlatex-math-modify (&optional arg)
17289 "Execute `cdlatex-math-modify' in LaTeX fragments.
17290 Revert to the normal definition outside of these fragments."
17291 (interactive "P")
17292 (if (org-inside-LaTeX-fragment-p)
17293 (call-interactively 'cdlatex-math-modify)
17294 (let (org-cdlatex-mode)
17295 (call-interactively (key-binding (vector last-input-event))))))
17297 (defvar org-latex-fragment-image-overlays nil
17298 "List of overlays carrying the images of latex fragments.")
17299 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17301 (defun org-remove-latex-fragment-image-overlays ()
17302 "Remove all overlays with LaTeX fragment images in current buffer."
17303 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17304 (setq org-latex-fragment-image-overlays nil))
17306 (defun org-preview-latex-fragment (&optional subtree)
17307 "Preview the LaTeX fragment at point, or all locally or globally.
17308 If the cursor is in a LaTeX fragment, create the image and overlay
17309 it over the source code. If there is no fragment at point, display
17310 all fragments in the current text, from one headline to the next. With
17311 prefix SUBTREE, display all fragments in the current subtree. With a
17312 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17313 the cursor is before the first headline,
17314 display all fragments in the buffer.
17315 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17316 (interactive "P")
17317 (unless buffer-file-name
17318 (error "Can't preview LaTeX fragment in a non-file buffer"))
17319 (org-remove-latex-fragment-image-overlays)
17320 (save-excursion
17321 (save-restriction
17322 (let (beg end at msg)
17323 (cond
17324 ((or (equal subtree '(16))
17325 (not (save-excursion
17326 (re-search-backward org-outline-regexp-bol nil t))))
17327 (setq beg (point-min) end (point-max)
17328 msg "Creating images for buffer...%s"))
17329 ((equal subtree '(4))
17330 (org-back-to-heading)
17331 (setq beg (point) end (org-end-of-subtree t)
17332 msg "Creating images for subtree...%s"))
17334 (if (setq at (org-inside-LaTeX-fragment-p))
17335 (goto-char (max (point-min) (- (cdr at) 2)))
17336 (org-back-to-heading))
17337 (setq beg (point) end (progn (outline-next-heading) (point))
17338 msg (if at "Creating image...%s"
17339 "Creating images for entry...%s"))))
17340 (message msg "")
17341 (narrow-to-region beg end)
17342 (goto-char beg)
17343 (org-format-latex
17344 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17345 (file-name-nondirectory
17346 buffer-file-name)))
17347 default-directory 'overlays msg at 'forbuffer
17348 org-latex-create-formula-image-program)
17349 (message msg "done. Use `C-c C-c' to remove images.")))))
17351 (defvar org-latex-regexps
17352 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17353 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17354 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17355 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17356 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17357 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17358 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17359 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17360 "Regular expressions for matching embedded LaTeX.")
17362 (defvar org-export-have-math nil) ;; dynamic scoping
17363 (defun org-format-latex (prefix &optional dir overlays msg at
17364 forbuffer processing-type)
17365 "Replace LaTeX fragments with links to an image, and produce images.
17366 Some of the options can be changed using the variable
17367 `org-format-latex-options'."
17368 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17369 (let* ((prefixnodir (file-name-nondirectory prefix))
17370 (absprefix (expand-file-name prefix dir))
17371 (todir (file-name-directory absprefix))
17372 (opt org-format-latex-options)
17373 (optnew org-format-latex-options)
17374 (matchers (plist-get opt :matchers))
17375 (re-list org-latex-regexps)
17376 (org-format-latex-header-extra
17377 (plist-get (org-infile-export-plist) :latex-header-extra))
17378 (cnt 0) txt hash link beg end re e checkdir
17379 string
17380 m n block-type block linkfile movefile ov)
17381 ;; Check the different regular expressions
17382 (while (setq e (pop re-list))
17383 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17384 block (if block-type "\n\n" ""))
17385 (when (member m matchers)
17386 (goto-char (point-min))
17387 (while (re-search-forward re nil t)
17388 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17389 (not (get-text-property (match-beginning n)
17390 'org-protected))
17391 (or (not overlays)
17392 (not (eq (get-char-property (match-beginning n)
17393 'org-overlay-type)
17394 'org-latex-overlay))))
17395 (setq org-export-have-math t)
17396 (cond
17397 ((eq processing-type 'verbatim)
17398 ;; Leave the text verbatim, just protect it
17399 (add-text-properties (match-beginning n) (match-end n)
17400 '(org-protected t)))
17401 ((eq processing-type 'mathjax)
17402 ;; Prepare for MathJax processing
17403 (setq string (match-string n))
17404 (if (member m '("$" "$1"))
17405 (save-excursion
17406 (delete-region (match-beginning n) (match-end n))
17407 (goto-char (match-beginning n))
17408 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17409 "\\)")
17410 '(org-protected t))))
17411 (add-text-properties (match-beginning n) (match-end n)
17412 '(org-protected t))))
17413 ((or (eq processing-type 'dvipng)
17414 (eq processing-type 'imagemagick))
17415 ;; Process to an image
17416 (setq txt (match-string n)
17417 beg (match-beginning n) end (match-end n)
17418 cnt (1+ cnt))
17419 (let ((face (face-at-point))
17420 (fg (plist-get opt :foreground))
17421 (bg (plist-get opt :background))
17422 print-length print-level) ; make sure full list is printed
17423 (when forbuffer
17424 ; Get the colors from the face at point
17425 (goto-char beg)
17426 (when (eq fg 'auto)
17427 (setq fg (face-attribute face :foreground nil 'default)))
17428 (when (eq bg 'auto)
17429 (setq bg (face-attribute face :background nil 'default)))
17430 (setq optnew (copy-sequence opt))
17431 (plist-put optnew :foreground fg)
17432 (plist-put optnew :background bg))
17433 (setq hash (sha1 (prin1-to-string
17434 (list org-format-latex-header
17435 org-format-latex-header-extra
17436 org-export-latex-default-packages-alist
17437 org-export-latex-packages-alist
17438 org-format-latex-options
17439 forbuffer txt fg bg)))
17440 linkfile (format "%s_%s.png" prefix hash)
17441 movefile (format "%s_%s.png" absprefix hash)))
17442 (setq link (concat block "[[file:" linkfile "]]" block))
17443 (if msg (message msg cnt))
17444 (goto-char beg)
17445 (unless checkdir ; make sure the directory exists
17446 (setq checkdir t)
17447 (or (file-directory-p todir) (make-directory todir t)))
17448 (org-create-formula-image
17449 txt movefile optnew forbuffer processing-type)
17450 (if overlays
17451 (progn
17452 (mapc (lambda (o)
17453 (if (eq (overlay-get o 'org-overlay-type)
17454 'org-latex-overlay)
17455 (delete-overlay o)))
17456 (overlays-in beg end))
17457 (setq ov (make-overlay beg end))
17458 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17459 (if (featurep 'xemacs)
17460 (progn
17461 (overlay-put ov 'invisible t)
17462 (overlay-put
17463 ov 'end-glyph
17464 (make-glyph (vector 'png :file movefile))))
17465 (overlay-put
17466 ov 'display
17467 (list 'image :type 'png :file movefile :ascent 'center)))
17468 (push ov org-latex-fragment-image-overlays)
17469 (goto-char end))
17470 (delete-region beg end)
17471 (insert (org-add-props link
17472 (list 'org-latex-src
17473 (replace-regexp-in-string
17474 "\"" "" txt)
17475 'org-latex-src-embed-type
17476 (if block-type 'paragraph 'character))))))
17477 ((eq processing-type 'mathml)
17478 ;; Process to MathML
17479 (unless (save-match-data (org-format-latex-mathml-available-p))
17480 (error "LaTeX to MathML converter not configured"))
17481 (setq txt (match-string n)
17482 beg (match-beginning n) end (match-end n)
17483 cnt (1+ cnt))
17484 (if msg (message msg cnt))
17485 (goto-char beg)
17486 (delete-region beg end)
17487 (insert (org-format-latex-as-mathml
17488 txt block-type prefix dir)))
17490 (error "Unknown conversion type %s for latex fragments"
17491 processing-type)))))))))
17493 (defun org-create-math-formula (latex-frag &optional mathml-file)
17494 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17495 Use `org-latex-to-mathml-convert-command'. If the conversion is
17496 sucessful, return the portion between \"<math...> </math>\"
17497 elements otherwise return nil. When MATHML-FILE is specified,
17498 write the results in to that file. When invoked as an
17499 interactive command, prompt for LATEX-FRAG, with initial value
17500 set to the current active region and echo the results for user
17501 inspection."
17502 (interactive (list (let ((frag (when (org-region-active-p)
17503 (buffer-substring-no-properties
17504 (region-beginning) (region-end)))))
17505 (read-string "LaTeX Fragment: " frag nil frag))))
17506 (unless latex-frag (error "Invalid latex-frag"))
17507 (let* ((tmp-in-file (file-relative-name
17508 (make-temp-name (expand-file-name "ltxmathml-in"))))
17509 (ignore (write-region latex-frag nil tmp-in-file))
17510 (tmp-out-file (file-relative-name
17511 (make-temp-name (expand-file-name "ltxmathml-out"))))
17512 (cmd (format-spec
17513 org-latex-to-mathml-convert-command
17514 `((?j . ,(shell-quote-argument
17515 (expand-file-name org-latex-to-mathml-jar-file)))
17516 (?I . ,(shell-quote-argument tmp-in-file))
17517 (?o . ,(shell-quote-argument tmp-out-file)))))
17518 mathml shell-command-output)
17519 (when (org-called-interactively-p 'any)
17520 (unless (org-format-latex-mathml-available-p)
17521 (error "LaTeX to MathML converter not configured")))
17522 (message "Running %s" cmd)
17523 (setq shell-command-output (shell-command-to-string cmd))
17524 (setq mathml
17525 (when (file-readable-p tmp-out-file)
17526 (with-current-buffer (find-file-noselect tmp-out-file t)
17527 (goto-char (point-min))
17528 (when (re-search-forward
17529 (concat
17530 (regexp-quote
17531 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17532 "\\(.\\|\n\\)*"
17533 (regexp-quote "</math>")) nil t)
17534 (prog1 (match-string 0) (kill-buffer))))))
17535 (cond
17536 (mathml
17537 (setq mathml
17538 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17539 (when mathml-file
17540 (write-region mathml nil mathml-file))
17541 (when (org-called-interactively-p 'any)
17542 (message mathml)))
17543 ((message "LaTeX to MathML conversion failed")
17544 (message shell-command-output)))
17545 (delete-file tmp-in-file)
17546 (when (file-exists-p tmp-out-file)
17547 (delete-file tmp-out-file))
17548 mathml))
17550 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17551 prefix &optional dir)
17552 "Use `org-create-math-formula' but check local cache first."
17553 (let* ((absprefix (expand-file-name prefix dir))
17554 (print-length nil) (print-level nil)
17555 (formula-id (concat
17556 "formula-"
17557 (sha1
17558 (prin1-to-string
17559 (list latex-frag
17560 org-latex-to-mathml-convert-command)))))
17561 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17562 (formula-cache-dir (file-name-directory formula-cache)))
17564 (unless (file-directory-p formula-cache-dir)
17565 (make-directory formula-cache-dir t))
17567 (unless (file-exists-p formula-cache)
17568 (org-create-math-formula latex-frag formula-cache))
17570 (if (file-exists-p formula-cache)
17571 ;; Successful conversion. Return the link to MathML file.
17572 (org-add-props
17573 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17574 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17575 'org-latex-src-embed-type (if latex-frag-type
17576 'paragraph 'character)))
17577 ;; Failed conversion. Return the LaTeX fragment verbatim
17578 (add-text-properties
17579 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17580 latex-frag)))
17582 (defun org-create-formula-image (string tofile options buffer &optional type)
17583 "Create an image from LaTeX source using dvipng or convert.
17584 This function calls either `org-create-formula-image-with-dvipng'
17585 or `org-create-formula-image-with-imagemagick' depending on the
17586 value of `org-latex-create-formula-image-program' or on the value
17587 of the optional TYPE variable.
17589 Note: ultimately these two function should be combined as they
17590 share a good deal of logic."
17591 (org-check-external-command
17592 "latex" "needed to convert LaTeX fragments to images")
17593 (funcall
17594 (case (or type org-latex-create-formula-image-program)
17595 ('dvipng
17596 (org-check-external-command
17597 "dvipng" "needed to convert LaTeX fragments to images")
17598 #'org-create-formula-image-with-dvipng)
17599 ('imagemagick
17600 (org-check-external-command
17601 "convert" "you need to install imagemagick")
17602 #'org-create-formula-image-with-imagemagick)
17603 (t (error
17604 "invalid value of `org-latex-create-formula-image-program'")))
17605 string tofile options buffer))
17607 ;; This function borrows from Ganesh Swami's latex2png.el
17608 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17609 "This calls dvipng."
17610 (require 'org-latex)
17611 (let* ((tmpdir (if (featurep 'xemacs)
17612 (temp-directory)
17613 temporary-file-directory))
17614 (texfilebase (make-temp-name
17615 (expand-file-name "orgtex" tmpdir)))
17616 (texfile (concat texfilebase ".tex"))
17617 (dvifile (concat texfilebase ".dvi"))
17618 (pngfile (concat texfilebase ".png"))
17619 (fnh (if (featurep 'xemacs)
17620 (font-height (face-font 'default))
17621 (face-attribute 'default :height nil)))
17622 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17623 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17624 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17625 "Black"))
17626 (bg (or (plist-get options (if buffer :background :html-background))
17627 "Transparent")))
17628 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17629 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17630 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17631 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17632 (with-temp-file texfile
17633 (insert (org-splice-latex-header
17634 org-format-latex-header
17635 org-export-latex-default-packages-alist
17636 org-export-latex-packages-alist t
17637 org-format-latex-header-extra))
17638 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17639 (require 'org-latex)
17640 (org-export-latex-fix-inputenc))
17641 (let ((dir default-directory))
17642 (condition-case nil
17643 (progn
17644 (cd tmpdir)
17645 (call-process "latex" nil nil nil texfile))
17646 (error nil))
17647 (cd dir))
17648 (if (not (file-exists-p dvifile))
17649 (progn (message "Failed to create dvi file from %s" texfile) nil)
17650 (condition-case nil
17651 (if (featurep 'xemacs)
17652 (call-process "dvipng" nil nil nil
17653 "-fg" fg "-bg" bg
17654 "-T" "tight"
17655 "-o" pngfile
17656 dvifile)
17657 (call-process "dvipng" nil nil nil
17658 "-fg" fg "-bg" bg
17659 "-D" dpi
17660 ;;"-x" scale "-y" scale
17661 "-T" "tight"
17662 "-o" pngfile
17663 dvifile))
17664 (error nil))
17665 (if (not (file-exists-p pngfile))
17666 (if org-format-latex-signal-error
17667 (error "Failed to create png file from %s" texfile)
17668 (message "Failed to create png file from %s" texfile)
17669 nil)
17670 ;; Use the requested file name and clean up
17671 (copy-file pngfile tofile 'replace)
17672 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17673 (if (file-exists-p (concat texfilebase e))
17674 (delete-file (concat texfilebase e))))
17675 pngfile))))
17677 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17678 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17679 "This calls convert, which is included into imagemagick."
17680 (require 'org-latex)
17681 (let* ((tmpdir (if (featurep 'xemacs)
17682 (temp-directory)
17683 temporary-file-directory))
17684 (texfilebase (make-temp-name
17685 (expand-file-name "orgtex" tmpdir)))
17686 (texfile (concat texfilebase ".tex"))
17687 (pdffile (concat texfilebase ".pdf"))
17688 (pngfile (concat texfilebase ".png"))
17689 (fnh (if (featurep 'xemacs)
17690 (font-height (face-font 'default))
17691 (face-attribute 'default :height nil)))
17692 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17693 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17694 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17695 "black"))
17696 (bg (or (plist-get options (if buffer :background :html-background))
17697 "white")))
17698 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17699 (setq fg (org-latex-color-format fg)))
17700 (if (eq bg 'default) (setq bg (org-latex-color :background))
17701 (setq bg (org-latex-color-format
17702 (if (string= bg "Transparent") "white" bg))))
17703 (with-temp-file texfile
17704 (insert (org-splice-latex-header
17705 org-format-latex-header
17706 org-export-latex-default-packages-alist
17707 org-export-latex-packages-alist t
17708 org-format-latex-header-extra))
17709 (insert "\n\\begin{document}\n"
17710 "\\definecolor{fg}{rgb}{" fg "}\n"
17711 "\\definecolor{bg}{rgb}{" bg "}\n"
17712 "\n\\pagecolor{bg}\n"
17713 "\n{\\color{fg}\n"
17714 string
17715 "\n}\n"
17716 "\n\\end{document}\n" )
17717 (require 'org-latex)
17718 (org-export-latex-fix-inputenc))
17719 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17720 (condition-case nil
17721 (progn
17722 (cd tmpdir)
17723 (setq cmds org-latex-to-pdf-process)
17724 (while cmds
17725 (setq latex-frags-cmds (pop cmds))
17726 (if (listp latex-frags-cmds)
17727 (setq cmds nil)
17728 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17729 (while latex-frags-cmds
17730 (setq cmd (pop latex-frags-cmds))
17731 (while (string-match "%b" cmd)
17732 (setq cmd (replace-match
17733 (save-match-data
17734 (shell-quote-argument texfile))
17735 t t cmd)))
17736 (while (string-match "%f" cmd)
17737 (setq cmd (replace-match
17738 (save-match-data
17739 (shell-quote-argument (file-name-nondirectory texfile)))
17740 t t cmd)))
17741 (while (string-match "%o" cmd)
17742 (setq cmd (replace-match
17743 (save-match-data
17744 (shell-quote-argument (file-name-directory texfile)))
17745 t t cmd)))
17746 (setq cmd (split-string cmd))
17747 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17748 (error nil))
17749 (cd dir))
17750 (if (not (file-exists-p pdffile))
17751 (progn (message "Failed to create pdf file from %s" texfile) nil)
17752 (condition-case nil
17753 (if (featurep 'xemacs)
17754 (call-process "convert" nil nil nil
17755 "-density" "96"
17756 "-trim"
17757 "-antialias"
17758 pdffile
17759 "-quality" "100"
17760 ;; "-sharpen" "0x1.0"
17761 pngfile)
17762 (call-process "convert" nil nil nil
17763 "-density" dpi
17764 "-trim"
17765 "-antialias"
17766 pdffile
17767 "-quality" "100"
17768 ; "-sharpen" "0x1.0"
17769 pngfile))
17770 (error nil))
17771 (if (not (file-exists-p pngfile))
17772 (if org-format-latex-signal-error
17773 (error "Failed to create png file from %s" texfile)
17774 (message "Failed to create png file from %s" texfile)
17775 nil)
17776 ;; Use the requested file name and clean up
17777 (copy-file pngfile tofile 'replace)
17778 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17779 (if (file-exists-p (concat texfilebase e))
17780 (delete-file (concat texfilebase e))))
17781 pngfile))))
17783 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17784 "Fill a LaTeX header template TPL.
17785 In the template, the following place holders will be recognized:
17787 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17788 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17789 [PACKAGES] \\usepackage statements for PKG
17790 [NO-PACKAGES] do not include PKG
17791 [EXTRA] the string EXTRA
17792 [NO-EXTRA] do not include EXTRA
17794 For backward compatibility, if both the positive and the negative place
17795 holder is missing, the positive one (without the \"NO-\") will be
17796 assumed to be present at the end of the template.
17797 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17798 EXTRA is a string.
17799 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17800 (let (rpl (end ""))
17801 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17802 (setq rpl (if (or (match-end 1) (not def-pkg))
17803 "" (org-latex-packages-to-string def-pkg snippets-p t))
17804 tpl (replace-match rpl t t tpl))
17805 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17807 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17808 (setq rpl (if (or (match-end 1) (not pkg))
17809 "" (org-latex-packages-to-string pkg snippets-p t))
17810 tpl (replace-match rpl t t tpl))
17811 (if pkg (setq end
17812 (concat end "\n"
17813 (org-latex-packages-to-string pkg snippets-p)))))
17815 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17816 (setq rpl (if (or (match-end 1) (not extra))
17817 "" (concat extra "\n"))
17818 tpl (replace-match rpl t t tpl))
17819 (if (and extra (string-match "\\S-" extra))
17820 (setq end (concat end "\n" extra))))
17822 (if (string-match "\\S-" end)
17823 (concat tpl "\n" end)
17824 tpl)))
17826 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17827 "Turn an alist of packages into a string with the \\usepackage macros."
17828 (setq pkg (mapconcat (lambda(p)
17829 (cond
17830 ((stringp p) p)
17831 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17832 (format "%% Package %s omitted" (cadr p)))
17833 ((equal "" (car p))
17834 (format "\\usepackage{%s}" (cadr p)))
17836 (format "\\usepackage[%s]{%s}"
17837 (car p) (cadr p)))))
17839 "\n"))
17840 (if newline (concat pkg "\n") pkg))
17842 (defun org-dvipng-color (attr)
17843 "Return a RGB color specification for dvipng."
17844 (apply 'format "rgb %s %s %s"
17845 (mapcar 'org-normalize-color
17846 (if (featurep 'xemacs)
17847 (color-rgb-components
17848 (face-property 'default
17849 (cond ((eq attr :foreground) 'foreground)
17850 ((eq attr :background) 'background))))
17851 (color-values (face-attribute 'default attr nil))))))
17853 (defun org-dvipng-color-format (color-name)
17854 "Convert COLOR-NAME to a RGB color value for dvipng."
17855 (apply 'format "rgb %s %s %s"
17856 (mapcar 'org-normalize-color
17857 (color-values color-name))))
17859 (defun org-latex-color (attr)
17860 "Return a RGB color for the LaTeX color package."
17861 (apply 'format "%s,%s,%s"
17862 (mapcar 'org-normalize-color
17863 (if (featurep 'xemacs)
17864 (color-rgb-components
17865 (face-property 'default
17866 (cond ((eq attr :foreground) 'foreground)
17867 ((eq attr :background) 'background))))
17868 (color-values (face-attribute 'default attr nil))))))
17870 (defun org-latex-color-format (color-name)
17871 "Convert COLOR-NAME to a RGB color value."
17872 (apply 'format "%s,%s,%s"
17873 (mapcar 'org-normalize-color
17874 (color-values color-name))))
17876 (defun org-normalize-color (value)
17877 "Return string to be used as color value for an RGB component."
17878 (format "%g" (/ value 65535.0)))
17880 ;; Image display
17883 (defvar org-inline-image-overlays nil)
17884 (make-variable-buffer-local 'org-inline-image-overlays)
17886 (defun org-toggle-inline-images (&optional include-linked)
17887 "Toggle the display of inline images.
17888 INCLUDE-LINKED is passed to `org-display-inline-images'."
17889 (interactive "P")
17890 (if org-inline-image-overlays
17891 (progn
17892 (org-remove-inline-images)
17893 (message "Inline image display turned off"))
17894 (org-display-inline-images include-linked)
17895 (if (and (org-called-interactively-p)
17896 org-inline-image-overlays)
17897 (message "%d images displayed inline"
17898 (length org-inline-image-overlays))
17899 (message "No images to display inline"))))
17901 (defun org-redisplay-inline-images ()
17902 "Refresh the display of inline images."
17903 (interactive)
17904 (if (not org-inline-image-overlays)
17905 (org-toggle-inline-images)
17906 (org-toggle-inline-images)
17907 (org-toggle-inline-images)))
17909 (defun org-display-inline-images (&optional include-linked refresh beg end)
17910 "Display inline images.
17911 Normally only links without a description part are inlined, because this
17912 is how it will work for export. When INCLUDE-LINKED is set, also links
17913 with a description part will be inlined. This can be nice for a quick
17914 look at those images, but it does not reflect what exported files will look
17915 like.
17916 When REFRESH is set, refresh existing images between BEG and END.
17917 This will create new image displays only if necessary.
17918 BEG and END default to the buffer boundaries."
17919 (interactive "P")
17920 (unless refresh
17921 (org-remove-inline-images)
17922 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17923 (save-excursion
17924 (save-restriction
17925 (widen)
17926 (setq beg (or beg (point-min)) end (or end (point-max)))
17927 (goto-char beg)
17928 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17929 (substring (org-image-file-name-regexp) 0 -2)
17930 "\\)\\]" (if include-linked "" "\\]")))
17931 old file ov img type attrwidth width)
17932 (while (re-search-forward re end t)
17933 (setq old (get-char-property-and-overlay (match-beginning 1)
17934 'org-image-overlay)
17935 file (expand-file-name
17936 (concat (or (match-string 3) "") (match-string 4))))
17937 (when (image-type-available-p 'imagemagick)
17938 (setq attrwidth (if (or (listp org-image-actual-width)
17939 (null org-image-actual-width))
17940 (save-excursion
17941 (save-match-data
17942 (move-beginning-of-line 0)
17943 (if (looking-at "#\\+ATTR.*width=\"\\([^\"]+\\)\"")
17944 (string-to-number (match-string 1))))))
17945 width (cond ((eq org-image-actual-width t) nil)
17946 ((null org-image-actual-width) attrwidth)
17947 ((numberp org-image-actual-width)
17948 org-image-actual-width)
17949 ((listp org-image-actual-width)
17950 (or attrwidth (car org-image-actual-width))))
17951 type (if width 'imagemagick)))
17952 (when (file-exists-p file)
17953 (if (and (car-safe old) refresh)
17954 (image-refresh (overlay-get (cdr old) 'display))
17955 (setq img (save-match-data (create-image file type nil :width width)))
17956 (when img
17957 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17958 (overlay-put ov 'display img)
17959 (overlay-put ov 'face 'default)
17960 (overlay-put ov 'org-image-overlay t)
17961 (overlay-put ov 'modification-hooks
17962 (list 'org-display-inline-modification-hook))
17963 (push ov org-inline-image-overlays)))))))))
17965 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17966 "Remove inline-display overlay if a corresponding region is modified."
17967 (let ((inhibit-modification-hooks t))
17968 (when (and ov after)
17969 (delete ov org-inline-image-overlays)
17970 (delete-overlay ov))))
17972 (defun org-remove-inline-images ()
17973 "Remove inline display of images."
17974 (interactive)
17975 (mapc 'delete-overlay org-inline-image-overlays)
17976 (setq org-inline-image-overlays nil))
17978 ;;;; Key bindings
17980 ;; Outline functions from `outline-mode-prefix-map'
17981 ;; that can be remapped in Org:
17982 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17983 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17984 (define-key org-mode-map [remap outline-forward-same-level]
17985 'org-forward-heading-same-level)
17986 (define-key org-mode-map [remap outline-backward-same-level]
17987 'org-backward-heading-same-level)
17988 (define-key org-mode-map [remap show-branches]
17989 'org-kill-note-or-show-branches)
17990 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17991 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17992 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17994 ;; Outline functions from `outline-mode-prefix-map' that can not
17995 ;; be remapped in Org:
17997 ;; - the column "key binding" shows whether the Outline function is still
17998 ;; available in Org mode on the same key that it has been bound to in
17999 ;; Outline mode:
18000 ;; - "overridden": key used for a different functionality in Org mode
18001 ;; - else: key still bound to the same Outline function in Org mode
18003 ;; | Outline function | key binding | Org replacement |
18004 ;; |------------------------------------+-------------+-----------------------|
18005 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18006 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18007 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18008 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18009 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18010 ;; | `show-entry' | overridden | no replacement |
18011 ;; | `show-children' | `C-c C-i' | visibility cycling |
18012 ;; | `show-branches' | `C-c C-k' | still same function |
18013 ;; | `show-subtree' | overridden | visibility cycling |
18014 ;; | `show-all' | overridden | no replacement |
18015 ;; | `hide-subtree' | overridden | visibility cycling |
18016 ;; | `hide-body' | overridden | no replacement |
18017 ;; | `hide-entry' | overridden | visibility cycling |
18018 ;; | `hide-leaves' | overridden | no replacement |
18019 ;; | `hide-sublevels' | overridden | no replacement |
18020 ;; | `hide-other' | overridden | no replacement |
18022 ;; Make `C-c C-x' a prefix key
18023 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18025 ;; TAB key with modifiers
18026 (org-defkey org-mode-map "\C-i" 'org-cycle)
18027 (org-defkey org-mode-map [(tab)] 'org-cycle)
18028 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18029 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18030 ;; The following line is necessary under Suse GNU/Linux
18031 (unless (featurep 'xemacs)
18032 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18033 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18034 (define-key org-mode-map [backtab] 'org-shifttab)
18036 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18037 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18038 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18040 ;; Cursor keys with modifiers
18041 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18042 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18043 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18044 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18046 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18047 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18048 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18049 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18051 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18052 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18053 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18054 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18056 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18057 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18058 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18059 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18061 ;; Babel keys
18062 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18063 (mapc (lambda (pair)
18064 (define-key org-babel-map (car pair) (cdr pair)))
18065 org-babel-key-bindings)
18067 ;;; Extra keys for tty access.
18068 ;; We only set them when really needed because otherwise the
18069 ;; menus don't show the simple keys
18071 (when (or org-use-extra-keys
18072 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18073 (not window-system))
18074 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18075 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18076 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18077 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18078 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18079 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18080 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18081 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18082 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18083 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18084 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18085 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18086 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18087 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18088 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18089 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18090 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18091 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18092 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18093 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18094 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18095 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18096 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18097 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18098 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18099 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18100 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18101 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18103 ;; All the other keys
18105 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18106 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18107 (if (boundp 'narrow-map)
18108 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18109 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18110 (if (boundp 'narrow-map)
18111 (org-defkey narrow-map "b" 'org-narrow-to-block)
18112 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18113 (if (boundp 'narrow-map)
18114 (org-defkey narrow-map "e" 'org-narrow-to-element)
18115 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18116 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18117 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18118 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18119 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18120 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18121 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18122 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18123 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18124 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18125 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18126 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18127 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18128 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18129 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18130 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18131 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18132 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18133 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18134 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18135 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18136 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18137 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18138 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18139 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18140 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18141 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18142 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18143 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18144 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18145 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18146 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18147 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18148 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18149 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18150 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18151 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18152 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18153 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18154 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18155 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18156 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18157 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18158 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18159 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18160 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18161 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18162 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18163 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18164 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18165 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18166 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18167 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18168 (org-defkey org-mode-map "\C-c^" 'org-sort)
18169 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18170 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18171 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18172 (org-defkey org-mode-map "\C-m" 'org-return)
18173 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18174 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18175 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18176 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18177 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18178 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18179 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18180 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18181 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18182 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18183 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18184 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18185 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18186 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18187 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18188 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18189 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18190 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18191 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18192 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18193 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18194 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18195 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18197 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18198 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18199 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18200 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18202 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18203 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18204 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18205 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18206 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18207 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18208 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18209 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18210 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18211 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18212 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18213 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18214 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18215 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18216 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18217 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18218 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18219 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18220 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18221 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18222 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18223 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18225 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18226 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18227 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18228 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18229 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18231 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18233 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18235 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18236 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18238 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18241 (when (featurep 'xemacs)
18242 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18245 (defconst org-speed-commands-default
18247 ("Outline Navigation")
18248 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18249 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18250 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18251 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18252 ("u" . (org-speed-move-safe 'outline-up-heading))
18253 ("j" . org-goto)
18254 ("g" . (org-refile t))
18255 ("Outline Visibility")
18256 ("c" . org-cycle)
18257 ("C" . org-shifttab)
18258 (" " . org-display-outline-path)
18259 (":" . org-columns)
18260 ("Outline Structure Editing")
18261 ("U" . org-shiftmetaup)
18262 ("D" . org-shiftmetadown)
18263 ("r" . org-metaright)
18264 ("l" . org-metaleft)
18265 ("R" . org-shiftmetaright)
18266 ("L" . org-shiftmetaleft)
18267 ("i" . (progn (forward-char 1) (call-interactively
18268 'org-insert-heading-respect-content)))
18269 ("^" . org-sort)
18270 ("w" . org-refile)
18271 ("a" . org-archive-subtree-default-with-confirmation)
18272 ("." . org-mark-subtree)
18273 ("#" . org-toggle-comment)
18274 ("Clock Commands")
18275 ("I" . org-clock-in)
18276 ("O" . org-clock-out)
18277 ("Meta Data Editing")
18278 ("t" . org-todo)
18279 ("0" . (org-priority ?\ ))
18280 ("1" . (org-priority ?A))
18281 ("2" . (org-priority ?B))
18282 ("3" . (org-priority ?C))
18283 (";" . org-set-tags-command)
18284 ("e" . org-set-effort)
18285 ("E" . org-inc-effort)
18286 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18287 (org-entry-put (point) "APPT_WARNTIME" m)))
18288 ("Agenda Views etc")
18289 ("v" . org-agenda)
18290 ("/" . org-sparse-tree)
18291 ("Misc")
18292 ("o" . org-open-at-point)
18293 ("?" . org-speed-command-help)
18294 ("<" . (org-agenda-set-restriction-lock 'subtree))
18295 (">" . (org-agenda-remove-restriction-lock))
18297 "The default speed commands.")
18299 (defun org-print-speed-command (e)
18300 (if (> (length (car e)) 1)
18301 (progn
18302 (princ "\n")
18303 (princ (car e))
18304 (princ "\n")
18305 (princ (make-string (length (car e)) ?-))
18306 (princ "\n"))
18307 (princ (car e))
18308 (princ " ")
18309 (if (symbolp (cdr e))
18310 (princ (symbol-name (cdr e)))
18311 (prin1 (cdr e)))
18312 (princ "\n")))
18314 (defun org-speed-command-help ()
18315 "Show the available speed commands."
18316 (interactive)
18317 (if (not org-use-speed-commands)
18318 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18319 (with-output-to-temp-buffer "*Help*"
18320 (princ "User-defined Speed commands\n===========================\n")
18321 (mapc 'org-print-speed-command org-speed-commands-user)
18322 (princ "\n")
18323 (princ "Built-in Speed commands\n=======================\n")
18324 (mapc 'org-print-speed-command org-speed-commands-default))
18325 (with-current-buffer "*Help*"
18326 (setq truncate-lines t))))
18328 (defun org-speed-move-safe (cmd)
18329 "Execute CMD, but make sure that the cursor always ends up in a headline.
18330 If not, return to the original position and throw an error."
18331 (interactive)
18332 (let ((pos (point)))
18333 (call-interactively cmd)
18334 (unless (and (bolp) (org-at-heading-p))
18335 (goto-char pos)
18336 (error "Boundary reached while executing %s" cmd))))
18338 (defvar org-self-insert-command-undo-counter 0)
18340 (defvar org-table-auto-blank-field) ; defined in org-table.el
18341 (defvar org-speed-command nil)
18343 (defun org-speed-command-default-hook (keys)
18344 "Hook for activating single-letter speed commands.
18345 `org-speed-commands-default' specifies a minimal command set.
18346 Use `org-speed-commands-user' for further customization."
18347 (when (or (and (bolp) (looking-at org-outline-regexp))
18348 (and (functionp org-use-speed-commands)
18349 (funcall org-use-speed-commands)))
18350 (cdr (assoc keys (append org-speed-commands-user
18351 org-speed-commands-default)))))
18353 (defun org-babel-speed-command-hook (keys)
18354 "Hook for activating single-letter code block commands."
18355 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18356 (cdr (assoc keys org-babel-key-bindings))))
18358 (defcustom org-speed-command-hook
18359 '(org-speed-command-default-hook org-babel-speed-command-hook)
18360 "Hook for activating speed commands at strategic locations.
18361 Hook functions are called in sequence until a valid handler is
18362 found.
18364 Each hook takes a single argument, a user-pressed command key
18365 which is also a `self-insert-command' from the global map.
18367 Within the hook, examine the cursor position and the command key
18368 and return nil or a valid handler as appropriate. Handler could
18369 be one of an interactive command, a function, or a form.
18371 Set `org-use-speed-commands' to non-nil value to enable this
18372 hook. The default setting is `org-speed-command-default-hook'."
18373 :group 'org-structure
18374 :version "24.1"
18375 :type 'hook)
18377 (defun org-self-insert-command (N)
18378 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18379 If the cursor is in a table looking at whitespace, the whitespace is
18380 overwritten, and the table is not marked as requiring realignment."
18381 (interactive "p")
18382 (org-check-before-invisible-edit 'insert)
18383 (cond
18384 ((and org-use-speed-commands
18385 (setq org-speed-command
18386 (run-hook-with-args-until-success
18387 'org-speed-command-hook (this-command-keys))))
18388 (cond
18389 ((commandp org-speed-command)
18390 (setq this-command org-speed-command)
18391 (call-interactively org-speed-command))
18392 ((functionp org-speed-command)
18393 (funcall org-speed-command))
18394 ((and org-speed-command (listp org-speed-command))
18395 (eval org-speed-command))
18396 (t (let (org-use-speed-commands)
18397 (call-interactively 'org-self-insert-command)))))
18398 ((and
18399 (org-table-p)
18400 (progn
18401 ;; check if we blank the field, and if that triggers align
18402 (and (featurep 'org-table) org-table-auto-blank-field
18403 (member last-command
18404 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18405 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18406 ;; got extra space, this field does not determine column width
18407 (let (org-table-may-need-update) (org-table-blank-field))
18408 ;; no extra space, this field may determine column width
18409 (org-table-blank-field)))
18411 (eq N 1)
18412 (looking-at "[^|\n]* |"))
18413 (let (org-table-may-need-update)
18414 (goto-char (1- (match-end 0)))
18415 (backward-delete-char 1)
18416 (goto-char (match-beginning 0))
18417 (self-insert-command N)))
18419 (setq org-table-may-need-update t)
18420 (self-insert-command N)
18421 (org-fix-tags-on-the-fly)
18422 (if org-self-insert-cluster-for-undo
18423 (if (not (eq last-command 'org-self-insert-command))
18424 (setq org-self-insert-command-undo-counter 1)
18425 (if (>= org-self-insert-command-undo-counter 20)
18426 (setq org-self-insert-command-undo-counter 1)
18427 (and (> org-self-insert-command-undo-counter 0)
18428 buffer-undo-list (listp buffer-undo-list)
18429 (not (cadr buffer-undo-list)) ; remove nil entry
18430 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18431 (setq org-self-insert-command-undo-counter
18432 (1+ org-self-insert-command-undo-counter))))))))
18434 (defun org-check-before-invisible-edit (kind)
18435 "Check is editing if kind KIND would be dangerous with invisible text around.
18436 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18437 ;; First, try to get out of here as quickly as possible, to reduce overhead
18438 (if (and org-catch-invisible-edits
18439 (or (not (boundp 'visible-mode)) (not visible-mode))
18440 (or (get-char-property (point) 'invisible)
18441 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18442 ;; OK, we need to take a closer look
18443 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18444 (invisible-before-point (if (bobp) nil (get-char-property
18445 (1- (point)) 'invisible)))
18446 (border-and-ok-direction
18448 ;; Check if we are acting predictably before invisible text
18449 (and invisible-at-point (not invisible-before-point)
18450 (memq kind '(insert delete-backward)))
18451 ;; Check if we are acting predictably after invisible text
18452 ;; This works not well, and I have turned it off. It seems
18453 ;; better to always show and stop after invisible text.
18454 ;; (and (not invisible-at-point) invisible-before-point
18455 ;; (memq kind '(insert delete)))
18457 (when (or (memq invisible-at-point '(outline org-hide-block t))
18458 (memq invisible-before-point '(outline org-hide-block t)))
18459 (if (eq org-catch-invisible-edits 'error)
18460 (error "Editing in invisible areas is prohibited - make visible first"))
18461 (if (and org-custom-properties-overlays
18462 (y-or-n-p "Display invisible properties in this buffer? "))
18463 (org-toggle-custom-properties-visibility)
18464 ;; Make the area visible
18465 (save-excursion
18466 (if invisible-before-point
18467 (goto-char (previous-single-char-property-change
18468 (point) 'invisible)))
18469 (org-cycle))
18470 (cond
18471 ((eq org-catch-invisible-edits 'show)
18472 ;; That's it, we do the edit after showing
18473 (message
18474 "Unfolding invisible region around point before editing")
18475 (sit-for 1))
18476 ((and (eq org-catch-invisible-edits 'smart)
18477 border-and-ok-direction)
18478 (message "Unfolding invisible region around point before editing"))
18480 ;; Don't do the edit, make the user repeat it in full visibility
18481 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18483 (defun org-fix-tags-on-the-fly ()
18484 (when (and (equal (char-after (point-at-bol)) ?*)
18485 (org-at-heading-p))
18486 (org-align-tags-here org-tags-column)))
18488 (defun org-delete-backward-char (N)
18489 "Like `delete-backward-char', insert whitespace at field end in tables.
18490 When deleting backwards, in tables this function will insert whitespace in
18491 front of the next \"|\" separator, to keep the table aligned. The table will
18492 still be marked for re-alignment if the field did fill the entire column,
18493 because, in this case the deletion might narrow the column."
18494 (interactive "p")
18495 (org-check-before-invisible-edit 'delete-backward)
18496 (if (and (org-table-p)
18497 (eq N 1)
18498 (string-match "|" (buffer-substring (point-at-bol) (point)))
18499 (looking-at ".*?|"))
18500 (let ((pos (point))
18501 (noalign (looking-at "[^|\n\r]* |"))
18502 (c org-table-may-need-update))
18503 (backward-delete-char N)
18504 (if (not overwrite-mode)
18505 (progn
18506 (skip-chars-forward "^|")
18507 (insert " ")
18508 (goto-char (1- pos))))
18509 ;; noalign: if there were two spaces at the end, this field
18510 ;; does not determine the width of the column.
18511 (if noalign (setq org-table-may-need-update c)))
18512 (backward-delete-char N)
18513 (org-fix-tags-on-the-fly)))
18515 (defun org-delete-char (N)
18516 "Like `delete-char', but insert whitespace at field end in tables.
18517 When deleting characters, in tables this function will insert whitespace in
18518 front of the next \"|\" separator, to keep the table aligned. The table will
18519 still be marked for re-alignment if the field did fill the entire column,
18520 because, in this case the deletion might narrow the column."
18521 (interactive "p")
18522 (org-check-before-invisible-edit 'delete)
18523 (if (and (org-table-p)
18524 (not (bolp))
18525 (not (= (char-after) ?|))
18526 (eq N 1))
18527 (if (looking-at ".*?|")
18528 (let ((pos (point))
18529 (noalign (looking-at "[^|\n\r]* |"))
18530 (c org-table-may-need-update))
18531 (replace-match (concat
18532 (substring (match-string 0) 1 -1)
18533 " |"))
18534 (goto-char pos)
18535 ;; noalign: if there were two spaces at the end, this field
18536 ;; does not determine the width of the column.
18537 (if noalign (setq org-table-may-need-update c)))
18538 (delete-char N))
18539 (delete-char N)
18540 (org-fix-tags-on-the-fly)))
18542 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18543 (put 'org-self-insert-command 'delete-selection t)
18544 (put 'orgtbl-self-insert-command 'delete-selection t)
18545 (put 'org-delete-char 'delete-selection 'supersede)
18546 (put 'org-delete-backward-char 'delete-selection 'supersede)
18547 (put 'org-yank 'delete-selection 'yank)
18549 ;; Make `flyspell-mode' delay after some commands
18550 (put 'org-self-insert-command 'flyspell-delayed t)
18551 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18552 (put 'org-delete-char 'flyspell-delayed t)
18553 (put 'org-delete-backward-char 'flyspell-delayed t)
18555 ;; Make pabbrev-mode expand after org-mode commands
18556 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18557 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18559 ;; How to do this: Measure non-white length of current string
18560 ;; If equal to column width, we should realign.
18562 (defun org-remap (map &rest commands)
18563 "In MAP, remap the functions given in COMMANDS.
18564 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18565 (let (new old)
18566 (while commands
18567 (setq old (pop commands) new (pop commands))
18568 (if (fboundp 'command-remapping)
18569 (org-defkey map (vector 'remap old) new)
18570 (substitute-key-definition old new map global-map)))))
18572 (when (eq org-enable-table-editor 'optimized)
18573 ;; If the user wants maximum table support, we need to hijack
18574 ;; some standard editing functions
18575 (org-remap org-mode-map
18576 'self-insert-command 'org-self-insert-command
18577 'delete-char 'org-delete-char
18578 'delete-backward-char 'org-delete-backward-char)
18579 (org-defkey org-mode-map "|" 'org-force-self-insert))
18581 (defvar org-ctrl-c-ctrl-c-hook nil
18582 "Hook for functions attaching themselves to `C-c C-c'.
18584 This can be used to add additional functionality to the C-c C-c
18585 key which executes context-dependent commands. This hook is run
18586 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18587 run after the last test.
18589 Each function will be called with no arguments. The function
18590 must check if the context is appropriate for it to act. If yes,
18591 it should do its thing and then return a non-nil value. If the
18592 context is wrong, just do nothing and return nil.")
18594 (defvar org-ctrl-c-ctrl-c-final-hook nil
18595 "Hook for functions attaching themselves to `C-c C-c'.
18597 This can be used to add additional functionality to the C-c C-c
18598 key which executes context-dependent commands. This hook is run
18599 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18600 before the first test.
18602 Each function will be called with no arguments. The function
18603 must check if the context is appropriate for it to act. If yes,
18604 it should do its thing and then return a non-nil value. If the
18605 context is wrong, just do nothing and return nil.")
18607 (defvar org-tab-first-hook nil
18608 "Hook for functions to attach themselves to TAB.
18609 See `org-ctrl-c-ctrl-c-hook' for more information.
18610 This hook runs as the first action when TAB is pressed, even before
18611 `org-cycle' messes around with the `outline-regexp' to cater for
18612 inline tasks and plain list item folding.
18613 If any function in this hook returns t, any other actions that
18614 would have been caused by TAB (such as table field motion or visibility
18615 cycling) will not occur.")
18617 (defvar org-tab-after-check-for-table-hook nil
18618 "Hook for functions to attach themselves to TAB.
18619 See `org-ctrl-c-ctrl-c-hook' for more information.
18620 This hook runs after it has been established that the cursor is not in a
18621 table, but before checking if the cursor is in a headline or if global cycling
18622 should be done.
18623 If any function in this hook returns t, not other actions like visibility
18624 cycling will be done.")
18626 (defvar org-tab-after-check-for-cycling-hook nil
18627 "Hook for functions to attach themselves to TAB.
18628 See `org-ctrl-c-ctrl-c-hook' for more information.
18629 This hook runs after it has been established that not table field motion and
18630 not visibility should be done because of current context. This is probably
18631 the place where a package like yasnippets can hook in.")
18633 (defvar org-tab-before-tab-emulation-hook nil
18634 "Hook for functions to attach themselves to TAB.
18635 See `org-ctrl-c-ctrl-c-hook' for more information.
18636 This hook runs after every other options for TAB have been exhausted, but
18637 before indentation and \t insertion takes place.")
18639 (defvar org-metaleft-hook nil
18640 "Hook for functions attaching themselves to `M-left'.
18641 See `org-ctrl-c-ctrl-c-hook' for more information.")
18642 (defvar org-metaright-hook nil
18643 "Hook for functions attaching themselves to `M-right'.
18644 See `org-ctrl-c-ctrl-c-hook' for more information.")
18645 (defvar org-metaup-hook nil
18646 "Hook for functions attaching themselves to `M-up'.
18647 See `org-ctrl-c-ctrl-c-hook' for more information.")
18648 (defvar org-metadown-hook nil
18649 "Hook for functions attaching themselves to `M-down'.
18650 See `org-ctrl-c-ctrl-c-hook' for more information.")
18651 (defvar org-shiftmetaleft-hook nil
18652 "Hook for functions attaching themselves to `M-S-left'.
18653 See `org-ctrl-c-ctrl-c-hook' for more information.")
18654 (defvar org-shiftmetaright-hook nil
18655 "Hook for functions attaching themselves to `M-S-right'.
18656 See `org-ctrl-c-ctrl-c-hook' for more information.")
18657 (defvar org-shiftmetaup-hook nil
18658 "Hook for functions attaching themselves to `M-S-up'.
18659 See `org-ctrl-c-ctrl-c-hook' for more information.")
18660 (defvar org-shiftmetadown-hook nil
18661 "Hook for functions attaching themselves to `M-S-down'.
18662 See `org-ctrl-c-ctrl-c-hook' for more information.")
18663 (defvar org-metareturn-hook nil
18664 "Hook for functions attaching themselves to `M-RET'.
18665 See `org-ctrl-c-ctrl-c-hook' for more information.")
18666 (defvar org-shiftup-hook nil
18667 "Hook for functions attaching themselves to `S-up'.
18668 See `org-ctrl-c-ctrl-c-hook' for more information.")
18669 (defvar org-shiftup-final-hook nil
18670 "Hook for functions attaching themselves to `S-up'.
18671 This one runs after all other options except shift-select have been excluded.
18672 See `org-ctrl-c-ctrl-c-hook' for more information.")
18673 (defvar org-shiftdown-hook nil
18674 "Hook for functions attaching themselves to `S-down'.
18675 See `org-ctrl-c-ctrl-c-hook' for more information.")
18676 (defvar org-shiftdown-final-hook nil
18677 "Hook for functions attaching themselves to `S-down'.
18678 This one runs after all other options except shift-select have been excluded.
18679 See `org-ctrl-c-ctrl-c-hook' for more information.")
18680 (defvar org-shiftleft-hook nil
18681 "Hook for functions attaching themselves to `S-left'.
18682 See `org-ctrl-c-ctrl-c-hook' for more information.")
18683 (defvar org-shiftleft-final-hook nil
18684 "Hook for functions attaching themselves to `S-left'.
18685 This one runs after all other options except shift-select have been excluded.
18686 See `org-ctrl-c-ctrl-c-hook' for more information.")
18687 (defvar org-shiftright-hook nil
18688 "Hook for functions attaching themselves to `S-right'.
18689 See `org-ctrl-c-ctrl-c-hook' for more information.")
18690 (defvar org-shiftright-final-hook nil
18691 "Hook for functions attaching themselves to `S-right'.
18692 This one runs after all other options except shift-select have been excluded.
18693 See `org-ctrl-c-ctrl-c-hook' for more information.")
18695 (defun org-modifier-cursor-error ()
18696 "Throw an error, a modified cursor command was applied in wrong context."
18697 (error "This command is active in special context like tables, headlines or items"))
18699 (defun org-shiftselect-error ()
18700 "Throw an error because Shift-Cursor command was applied in wrong context."
18701 (if (and (boundp 'shift-select-mode) shift-select-mode)
18702 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18703 (error "This command works only in special context like headlines or timestamps")))
18705 (defun org-call-for-shift-select (cmd)
18706 (let ((this-command-keys-shift-translated t))
18707 (call-interactively cmd)))
18709 (defun org-shifttab (&optional arg)
18710 "Global visibility cycling or move to previous table field.
18711 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18712 on context.
18713 See the individual commands for more information."
18714 (interactive "P")
18715 (cond
18716 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18717 ((integerp arg)
18718 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18719 (message "Content view to level: %d" arg)
18720 (org-content (prefix-numeric-value arg2))
18721 (setq org-cycle-global-status 'overview)))
18722 (t (call-interactively 'org-global-cycle))))
18724 (defun org-shiftmetaleft ()
18725 "Promote subtree or delete table column.
18726 Calls `org-promote-subtree', `org-outdent-item-tree', or
18727 `org-table-delete-column', depending on context. See the
18728 individual commands for more information."
18729 (interactive)
18730 (cond
18731 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18732 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18733 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18734 ((if (not (org-region-active-p)) (org-at-item-p)
18735 (save-excursion (goto-char (region-beginning))
18736 (org-at-item-p)))
18737 (call-interactively 'org-outdent-item-tree))
18738 (t (org-modifier-cursor-error))))
18740 (defun org-shiftmetaright ()
18741 "Demote subtree or insert table column.
18742 Calls `org-demote-subtree', `org-indent-item-tree', or
18743 `org-table-insert-column', depending on context. See the
18744 individual commands for more information."
18745 (interactive)
18746 (cond
18747 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18748 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18749 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18750 ((if (not (org-region-active-p)) (org-at-item-p)
18751 (save-excursion (goto-char (region-beginning))
18752 (org-at-item-p)))
18753 (call-interactively 'org-indent-item-tree))
18754 (t (org-modifier-cursor-error))))
18756 (defun org-shiftmetaup (&optional arg)
18757 "Move subtree up or kill table row.
18758 Calls `org-move-subtree-up' or `org-table-kill-row' or
18759 `org-move-item-up' or `org-timestamp-up', depending on context.
18760 See the individual commands for more information."
18761 (interactive "P")
18762 (cond
18763 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18764 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18765 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18766 ((org-at-item-p) (call-interactively 'org-move-item-up))
18767 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18768 (call-interactively 'org-timestamp-up)))
18769 (t (org-modifier-cursor-error))))
18771 (defun org-shiftmetadown (&optional arg)
18772 "Move subtree down or insert table row.
18773 Calls `org-move-subtree-down' or `org-table-insert-row' or
18774 `org-move-item-down' or `org-timestamp-up', depending on context.
18775 See the individual commands for more information."
18776 (interactive "P")
18777 (cond
18778 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18779 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18780 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18781 ((org-at-item-p) (call-interactively 'org-move-item-down))
18782 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18783 (call-interactively 'org-timestamp-down)))
18784 (t (org-modifier-cursor-error))))
18786 (defsubst org-hidden-tree-error ()
18787 (error
18788 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18790 (defun org-metaleft (&optional arg)
18791 "Promote heading or move table column to left.
18792 Calls `org-do-promote' or `org-table-move-column', depending on context.
18793 With no specific context, calls the Emacs default `backward-word'.
18794 See the individual commands for more information."
18795 (interactive "P")
18796 (cond
18797 ((run-hook-with-args-until-success 'org-metaleft-hook))
18798 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18799 ((org-with-limited-levels
18800 (or (org-at-heading-p)
18801 (and (org-region-active-p)
18802 (save-excursion
18803 (goto-char (region-beginning))
18804 (org-at-heading-p)))))
18805 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18806 (call-interactively 'org-do-promote))
18807 ;; At an inline task.
18808 ((org-at-heading-p)
18809 (call-interactively 'org-inlinetask-promote))
18810 ((or (org-at-item-p)
18811 (and (org-region-active-p)
18812 (save-excursion
18813 (goto-char (region-beginning))
18814 (org-at-item-p))))
18815 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18816 (call-interactively 'org-outdent-item))
18817 (t (call-interactively 'backward-word))))
18819 (defun org-metaright (&optional arg)
18820 "Demote a subtree, a list item or move table column to right.
18821 In front of a drawer or a block keyword, indent it correctly.
18822 With no specific context, calls the Emacs default `forward-word'.
18823 See the individual commands for more information."
18824 (interactive "P")
18825 (cond
18826 ((run-hook-with-args-until-success 'org-metaright-hook))
18827 ((org-at-table-p) (call-interactively 'org-table-move-column))
18828 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18829 ((org-at-block-p) (call-interactively 'org-indent-block))
18830 ((org-with-limited-levels
18831 (or (org-at-heading-p)
18832 (and (org-region-active-p)
18833 (save-excursion
18834 (goto-char (region-beginning))
18835 (org-at-heading-p)))))
18836 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18837 (call-interactively 'org-do-demote))
18838 ;; At an inline task.
18839 ((org-at-heading-p)
18840 (call-interactively 'org-inlinetask-demote))
18841 ((or (org-at-item-p)
18842 (and (org-region-active-p)
18843 (save-excursion
18844 (goto-char (region-beginning))
18845 (org-at-item-p))))
18846 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18847 (call-interactively 'org-indent-item))
18848 (t (call-interactively 'forward-word))))
18850 (defun org-check-for-hidden (what)
18851 "Check if there are hidden headlines/items in the current visual line.
18852 WHAT can be either `headlines' or `items'. If the current line is
18853 an outline or item heading and it has a folded subtree below it,
18854 this function returns t, nil otherwise."
18855 (let ((re (cond
18856 ((eq what 'headlines) org-outline-regexp-bol)
18857 ((eq what 'items) (org-item-beginning-re))
18858 (t (error "This should not happen"))))
18859 beg end)
18860 (save-excursion
18861 (catch 'exit
18862 (unless (org-region-active-p)
18863 (setq beg (point-at-bol))
18864 (beginning-of-line 2)
18865 (while (and (not (eobp)) ;; this is like `next-line'
18866 (get-char-property (1- (point)) 'invisible))
18867 (beginning-of-line 2))
18868 (setq end (point))
18869 (goto-char beg)
18870 (goto-char (point-at-eol))
18871 (setq end (max end (point)))
18872 (while (re-search-forward re end t)
18873 (if (get-char-property (match-beginning 0) 'invisible)
18874 (throw 'exit t))))
18875 nil))))
18877 (autoload 'org-element-at-point "org-element")
18879 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18880 (declare-function org-element-type "org-element" (element))
18881 (declare-function org-element-context "org-element" ())
18882 (declare-function org-element-contents "org-element" (element))
18883 (declare-function org-element-property "org-element" (property element))
18884 (declare-function org-element-paragraph-parser "org-element" (limit))
18885 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18886 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18887 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18888 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18889 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18891 (defun org-metaup (&optional arg)
18892 "Move subtree up or move table row up.
18893 Calls `org-move-subtree-up' or `org-table-move-row' or
18894 `org-move-item-up', depending on context. See the individual commands
18895 for more information."
18896 (interactive "P")
18897 (cond
18898 ((run-hook-with-args-until-success 'org-metaup-hook))
18899 ((org-region-active-p)
18900 (let* ((a (min (region-beginning) (region-end)))
18901 (b (1- (max (region-beginning) (region-end))))
18902 (c (save-excursion (goto-char a)
18903 (move-beginning-of-line 0)))
18904 (d (save-excursion (goto-char a)
18905 (move-end-of-line 0) (point))))
18906 (transpose-regions a b c d)
18907 (goto-char c)))
18908 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18909 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18910 ((org-at-item-p) (call-interactively 'org-move-item-up))
18911 (t (org-drag-element-backward))))
18913 (defun org-metadown (&optional arg)
18914 "Move subtree down or move table row down.
18915 Calls `org-move-subtree-down' or `org-table-move-row' or
18916 `org-move-item-down', depending on context. See the individual
18917 commands for more information."
18918 (interactive "P")
18919 (cond
18920 ((run-hook-with-args-until-success 'org-metadown-hook))
18921 ((org-region-active-p)
18922 (let* ((a (min (region-beginning) (region-end)))
18923 (b (max (region-beginning) (region-end)))
18924 (c (save-excursion (goto-char b)
18925 (move-beginning-of-line 1)))
18926 (d (save-excursion (goto-char b)
18927 (move-end-of-line 1) (1+ (point)))))
18928 (transpose-regions a b c d)
18929 (goto-char d)))
18930 ((org-at-table-p) (call-interactively 'org-table-move-row))
18931 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18932 ((org-at-item-p) (call-interactively 'org-move-item-down))
18933 (t (org-drag-element-forward))))
18935 (defun org-shiftup (&optional arg)
18936 "Increase item in timestamp or increase priority of current headline.
18937 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18938 depending on context. See the individual commands for more information."
18939 (interactive "P")
18940 (cond
18941 ((run-hook-with-args-until-success 'org-shiftup-hook))
18942 ((and org-support-shift-select (org-region-active-p))
18943 (org-call-for-shift-select 'previous-line))
18944 ((org-at-timestamp-p t)
18945 (call-interactively (if org-edit-timestamp-down-means-later
18946 'org-timestamp-down 'org-timestamp-up)))
18947 ((and (not (eq org-support-shift-select 'always))
18948 org-enable-priority-commands
18949 (org-at-heading-p))
18950 (call-interactively 'org-priority-up))
18951 ((and (not org-support-shift-select) (org-at-item-p))
18952 (call-interactively 'org-previous-item))
18953 ((org-clocktable-try-shift 'up arg))
18954 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18955 (org-support-shift-select
18956 (org-call-for-shift-select 'previous-line))
18957 (t (org-shiftselect-error))))
18959 (defun org-shiftdown (&optional arg)
18960 "Decrease item in timestamp or decrease priority of current headline.
18961 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18962 depending on context. See the individual commands for more information."
18963 (interactive "P")
18964 (cond
18965 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18966 ((and org-support-shift-select (org-region-active-p))
18967 (org-call-for-shift-select 'next-line))
18968 ((org-at-timestamp-p t)
18969 (call-interactively (if org-edit-timestamp-down-means-later
18970 'org-timestamp-up 'org-timestamp-down)))
18971 ((and (not (eq org-support-shift-select 'always))
18972 org-enable-priority-commands
18973 (org-at-heading-p))
18974 (call-interactively 'org-priority-down))
18975 ((and (not org-support-shift-select) (org-at-item-p))
18976 (call-interactively 'org-next-item))
18977 ((org-clocktable-try-shift 'down arg))
18978 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18979 (org-support-shift-select
18980 (org-call-for-shift-select 'next-line))
18981 (t (org-shiftselect-error))))
18983 (defun org-shiftright (&optional arg)
18984 "Cycle the thing at point or in the current line, depending on context.
18985 Depending on context, this does one of the following:
18987 - switch a timestamp at point one day into the future
18988 - on a headline, switch to the next TODO keyword.
18989 - on an item, switch entire list to the next bullet type
18990 - on a property line, switch to the next allowed value
18991 - on a clocktable definition line, move time block into the future"
18992 (interactive "P")
18993 (cond
18994 ((run-hook-with-args-until-success 'org-shiftright-hook))
18995 ((and org-support-shift-select (org-region-active-p))
18996 (org-call-for-shift-select 'forward-char))
18997 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18998 ((and (not (eq org-support-shift-select 'always))
18999 (org-at-heading-p))
19000 (let ((org-inhibit-logging
19001 (not org-treat-S-cursor-todo-selection-as-state-change))
19002 (org-inhibit-blocking
19003 (not org-treat-S-cursor-todo-selection-as-state-change)))
19004 (org-call-with-arg 'org-todo 'right)))
19005 ((or (and org-support-shift-select
19006 (not (eq org-support-shift-select 'always))
19007 (org-at-item-bullet-p))
19008 (and (not org-support-shift-select) (org-at-item-p)))
19009 (org-call-with-arg 'org-cycle-list-bullet nil))
19010 ((and (not (eq org-support-shift-select 'always))
19011 (org-at-property-p))
19012 (call-interactively 'org-property-next-allowed-value))
19013 ((org-clocktable-try-shift 'right arg))
19014 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19015 (org-support-shift-select
19016 (org-call-for-shift-select 'forward-char))
19017 (t (org-shiftselect-error))))
19019 (defun org-shiftleft (&optional arg)
19020 "Cycle the thing at point or in the current line, depending on context.
19021 Depending on context, this does one of the following:
19023 - switch a timestamp at point one day into the past
19024 - on a headline, switch to the previous TODO keyword.
19025 - on an item, switch entire list to the previous bullet type
19026 - on a property line, switch to the previous allowed value
19027 - on a clocktable definition line, move time block into the past"
19028 (interactive "P")
19029 (cond
19030 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19031 ((and org-support-shift-select (org-region-active-p))
19032 (org-call-for-shift-select 'backward-char))
19033 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19034 ((and (not (eq org-support-shift-select 'always))
19035 (org-at-heading-p))
19036 (let ((org-inhibit-logging
19037 (not org-treat-S-cursor-todo-selection-as-state-change))
19038 (org-inhibit-blocking
19039 (not org-treat-S-cursor-todo-selection-as-state-change)))
19040 (org-call-with-arg 'org-todo 'left)))
19041 ((or (and org-support-shift-select
19042 (not (eq org-support-shift-select 'always))
19043 (org-at-item-bullet-p))
19044 (and (not org-support-shift-select) (org-at-item-p)))
19045 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19046 ((and (not (eq org-support-shift-select 'always))
19047 (org-at-property-p))
19048 (call-interactively 'org-property-previous-allowed-value))
19049 ((org-clocktable-try-shift 'left arg))
19050 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19051 (org-support-shift-select
19052 (org-call-for-shift-select 'backward-char))
19053 (t (org-shiftselect-error))))
19055 (defun org-shiftcontrolright ()
19056 "Switch to next TODO set."
19057 (interactive)
19058 (cond
19059 ((and org-support-shift-select (org-region-active-p))
19060 (org-call-for-shift-select 'forward-word))
19061 ((and (not (eq org-support-shift-select 'always))
19062 (org-at-heading-p))
19063 (org-call-with-arg 'org-todo 'nextset))
19064 (org-support-shift-select
19065 (org-call-for-shift-select 'forward-word))
19066 (t (org-shiftselect-error))))
19068 (defun org-shiftcontrolleft ()
19069 "Switch to previous TODO set."
19070 (interactive)
19071 (cond
19072 ((and org-support-shift-select (org-region-active-p))
19073 (org-call-for-shift-select 'backward-word))
19074 ((and (not (eq org-support-shift-select 'always))
19075 (org-at-heading-p))
19076 (org-call-with-arg 'org-todo 'previousset))
19077 (org-support-shift-select
19078 (org-call-for-shift-select 'backward-word))
19079 (t (org-shiftselect-error))))
19081 (defun org-shiftcontrolup ()
19082 "Change timestamps synchronously up in CLOCK log lines."
19083 (interactive)
19084 (cond ((and (not org-support-shift-select)
19085 (org-at-clock-log-p)
19086 (org-at-timestamp-p t))
19087 (org-clock-timestamps-up))
19088 (t (org-shiftselect-error))))
19090 (defun org-shiftcontroldown ()
19091 "Change timestamps synchronously down in CLOCK log lines."
19092 (interactive)
19093 (cond ((and (not org-support-shift-select)
19094 (org-at-clock-log-p)
19095 (org-at-timestamp-p t))
19096 (org-clock-timestamps-down))
19097 (t (org-shiftselect-error))))
19099 (defun org-ctrl-c-ret ()
19100 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19101 (interactive)
19102 (cond
19103 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19104 (t (call-interactively 'org-insert-heading))))
19106 (defun org-find-visible ()
19107 (let ((s (point)))
19108 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19109 (get-char-property s 'invisible)))
19111 (defun org-find-invisible ()
19112 (let ((s (point)))
19113 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19114 (not (get-char-property s 'invisible))))
19117 (defun org-copy-visible (beg end)
19118 "Copy the visible parts of the region."
19119 (interactive "r")
19120 (let (snippets s)
19121 (save-excursion
19122 (save-restriction
19123 (narrow-to-region beg end)
19124 (setq s (goto-char (point-min)))
19125 (while (not (= (point) (point-max)))
19126 (goto-char (org-find-invisible))
19127 (push (buffer-substring s (point)) snippets)
19128 (setq s (goto-char (org-find-visible))))))
19129 (kill-new (apply 'concat (nreverse snippets)))))
19131 (defun org-copy-special ()
19132 "Copy region in table or copy current subtree.
19133 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19134 See the individual commands for more information."
19135 (interactive)
19136 (call-interactively
19137 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19139 (defun org-cut-special ()
19140 "Cut region in table or cut current subtree.
19141 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19142 See the individual commands for more information."
19143 (interactive)
19144 (call-interactively
19145 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19147 (defun org-paste-special (arg)
19148 "Paste rectangular region into table, or past subtree relative to level.
19149 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19150 See the individual commands for more information."
19151 (interactive "P")
19152 (if (org-at-table-p)
19153 (org-table-paste-rectangle)
19154 (org-paste-subtree arg)))
19156 (defun org-edit-special (&optional arg)
19157 "Call a special editor for the stuff at point.
19158 When at a table, call the formula editor with `org-table-edit-formulas'.
19159 When at the first line of an src example, call `org-edit-src-code'.
19160 When in an #+include line, visit the include file. Otherwise call
19161 `ffap' to visit the file at point."
19162 (interactive)
19163 ;; possibly prep session before editing source
19164 (when arg
19165 (let* ((info (org-babel-get-src-block-info))
19166 (lang (nth 0 info))
19167 (params (nth 2 info))
19168 (session (cdr (assoc :session params))))
19169 (when (and info session) ;; we are in a source-code block with a session
19170 (funcall
19171 (intern (concat "org-babel-prep-session:" lang)) session params))))
19172 (cond ;; proceed with `org-edit-special'
19173 ((save-excursion
19174 (beginning-of-line 1)
19175 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19176 (find-file (org-trim (match-string 1))))
19177 ((org-edit-src-code))
19178 ((org-edit-fixed-width-region))
19179 ((org-at-table.el-p)
19180 (org-edit-src-code))
19181 ((or (org-at-table-p)
19182 (save-excursion
19183 (beginning-of-line 1)
19184 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19185 (call-interactively 'org-table-edit-formulas))
19186 (t (call-interactively 'ffap))))
19188 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19189 (defun org-ctrl-c-ctrl-c (&optional arg)
19190 "Set tags in headline, or update according to changed information at point.
19192 This command does many different things, depending on context:
19194 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19195 this is what we do.
19197 - If the cursor is on a statistics cookie, update it.
19199 - If the cursor is in a headline, prompt for tags and insert them
19200 into the current line, aligned to `org-tags-column'. When called
19201 with prefix arg, realign all tags in the current buffer.
19203 - If the cursor is in one of the special #+KEYWORD lines, this
19204 triggers scanning the buffer for these lines and updating the
19205 information.
19207 - If the cursor is inside a table, realign the table. This command
19208 works even if the automatic table editor has been turned off.
19210 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19211 the entire table.
19213 - If the cursor is at a footnote reference or definition, jump to
19214 the corresponding definition or references, respectively.
19216 - If the cursor is a the beginning of a dynamic block, update it.
19218 - If the current buffer is a capture buffer, close note and file it.
19220 - If the cursor is on a <<<target>>>, update radio targets and
19221 corresponding links in this buffer.
19223 - If the cursor is on a numbered item in a plain list, renumber the
19224 ordered list.
19226 - If the cursor is on a checkbox, toggle it.
19228 - If the cursor is on a code block, evaluate it. The variable
19229 `org-confirm-babel-evaluate' can be used to control prompting
19230 before code block evaluation, by default every code block
19231 evaluation requires confirmation. Code block evaluation can be
19232 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19233 (interactive "P")
19234 (let ((org-enable-table-editor t))
19235 (cond
19236 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19237 org-occur-highlights
19238 org-latex-fragment-image-overlays)
19239 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19240 (org-remove-occur-highlights)
19241 (org-remove-latex-fragment-image-overlays)
19242 (message "Temporary highlights/overlays removed from current buffer"))
19243 ((and (local-variable-p 'org-finish-function (current-buffer))
19244 (fboundp org-finish-function))
19245 (funcall org-finish-function))
19246 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19247 ((org-in-regexp org-ts-regexp-both)
19248 (org-timestamp-change 0 'day))
19249 ((or (looking-at org-property-start-re)
19250 (org-at-property-p))
19251 (call-interactively 'org-property-action))
19252 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19253 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19254 (or (org-at-heading-p) (org-at-item-p)))
19255 (call-interactively 'org-update-statistics-cookies))
19256 ((org-at-heading-p) (call-interactively 'org-set-tags))
19257 ((org-at-table.el-p)
19258 (message "Use C-c ' to edit table.el tables"))
19259 ((org-at-table-p)
19260 (org-table-maybe-eval-formula)
19261 (if arg
19262 (call-interactively 'org-table-recalculate)
19263 (org-table-maybe-recalculate-line))
19264 (call-interactively 'org-table-align)
19265 (orgtbl-send-table 'maybe))
19266 ((or (org-footnote-at-reference-p)
19267 (org-footnote-at-definition-p))
19268 (call-interactively 'org-footnote-action))
19269 ((org-at-item-checkbox-p)
19270 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19271 ;; list only if at top item.
19272 (let* ((cbox (match-string 1))
19273 (struct (org-list-struct))
19274 (old-struct (copy-tree struct))
19275 (parents (org-list-parents-alist struct))
19276 (orderedp (org-entry-get nil "ORDERED"))
19277 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19278 block-item)
19279 ;; Use a light version of `org-toggle-checkbox' to avoid
19280 ;; computing list structure twice.
19281 (let ((new-box (cond
19282 ((equal arg '(16)) "[-]")
19283 ((equal arg '(4)) nil)
19284 ((equal "[X]" cbox) "[ ]")
19285 (t "[X]"))))
19286 (if (and firstp arg)
19287 ;; If at first item of sub-list, remove check-box from
19288 ;; every item at the same level.
19289 (mapc
19290 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19291 (org-list-get-all-items
19292 (point-at-bol) struct (org-list-prevs-alist struct)))
19293 (org-list-set-checkbox (point-at-bol) struct new-box)))
19294 ;; Replicate `org-list-write-struct', while grabbing a return
19295 ;; value from `org-list-struct-fix-box'.
19296 (org-list-struct-fix-ind struct parents 2)
19297 (org-list-struct-fix-item-end struct)
19298 (let ((prevs (org-list-prevs-alist struct)))
19299 (org-list-struct-fix-bul struct prevs)
19300 (org-list-struct-fix-ind struct parents)
19301 (setq block-item
19302 (org-list-struct-fix-box struct parents prevs orderedp)))
19303 (org-list-struct-apply-struct struct old-struct)
19304 (org-update-checkbox-count-maybe)
19305 (when block-item
19306 (message
19307 "Checkboxes were removed due to unchecked box at line %d"
19308 (org-current-line block-item)))
19309 (when firstp (org-list-send-list 'maybe))))
19310 ((org-at-item-p)
19311 ;; Cursor at an item: repair list. Do checkbox related actions
19312 ;; only if function was called with an argument. Send list only
19313 ;; if at top item.
19314 (let* ((struct (org-list-struct))
19315 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19316 old-struct)
19317 (when arg
19318 (setq old-struct (copy-tree struct))
19319 (if firstp
19320 ;; If at first item of sub-list, add check-box to every
19321 ;; item at the same level.
19322 (mapc
19323 (lambda (pos)
19324 (unless (org-list-get-checkbox pos struct)
19325 (org-list-set-checkbox pos struct "[ ]")))
19326 (org-list-get-all-items
19327 (point-at-bol) struct (org-list-prevs-alist struct)))
19328 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19329 (org-list-write-struct
19330 struct (org-list-parents-alist struct) old-struct)
19331 (when arg (org-update-checkbox-count-maybe))
19332 (when firstp (org-list-send-list 'maybe))))
19333 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19334 ;; Dynamic block
19335 (beginning-of-line 1)
19336 (save-excursion (org-update-dblock)))
19337 ((save-excursion
19338 (let ((case-fold-search t))
19339 (beginning-of-line 1)
19340 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19341 (cond
19342 ((or (equal (match-string 1) "TBLFM")
19343 (equal (match-string 1) "tblfm"))
19344 ;; Recalculate the table before this line
19345 (save-excursion
19346 (beginning-of-line 1)
19347 (skip-chars-backward " \r\n\t")
19348 (if (org-at-table-p)
19349 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19351 (let ((org-inhibit-startup-visibility-stuff t)
19352 (org-startup-align-all-tables nil))
19353 (when (boundp 'org-table-coordinate-overlays)
19354 (mapc 'delete-overlay org-table-coordinate-overlays)
19355 (setq org-table-coordinate-overlays nil))
19356 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19357 (message "Local setup has been refreshed"))))
19358 ((org-clock-update-time-maybe))
19360 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19361 (error "C-c C-c can do nothing useful at this location"))))))
19363 (defun org-mode-restart ()
19364 "Restart Org-mode, to scan again for special lines.
19365 Also updates the keyword regular expressions."
19366 (interactive)
19367 (org-mode)
19368 (message "Org-mode restarted"))
19370 (defun org-kill-note-or-show-branches ()
19371 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19372 (interactive)
19373 (if (not org-finish-function)
19374 (progn
19375 (hide-subtree)
19376 (call-interactively 'show-branches))
19377 (let ((org-note-abort t))
19378 (funcall org-finish-function))))
19380 (defun org-return (&optional indent)
19381 "Goto next table row or insert a newline.
19382 Calls `org-table-next-row' or `newline', depending on context.
19383 See the individual commands for more information."
19384 (interactive)
19385 (let (org-ts-what)
19386 (cond
19387 ((or (bobp) (org-in-src-block-p))
19388 (if indent (newline-and-indent) (newline)))
19389 ((org-at-table-p)
19390 (org-table-justify-field-maybe)
19391 (call-interactively 'org-table-next-row))
19392 ;; when `newline-and-indent' is called within a list, make sure
19393 ;; text moved stays inside the item.
19394 ((and (org-in-item-p) indent)
19395 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19396 (progn
19397 (save-match-data (newline))
19398 (org-indent-line-to (length (match-string 0))))
19399 (let ((ind (org-get-indentation)))
19400 (newline)
19401 (if (org-looking-back org-list-end-re)
19402 (org-indent-line)
19403 (org-indent-line-to ind)))))
19404 ((and org-return-follows-link
19405 (org-at-timestamp-p t)
19406 (not (eq org-ts-what 'after)))
19407 (org-follow-timestamp-link))
19408 ((and org-return-follows-link
19409 (let ((tprop (get-text-property (point) 'face)))
19410 (or (eq tprop 'org-link)
19411 (and (listp tprop) (memq 'org-link tprop)))))
19412 (call-interactively 'org-open-at-point))
19413 ((and (org-at-heading-p)
19414 (looking-at
19415 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19416 (org-show-entry)
19417 (end-of-line 1)
19418 (newline))
19419 (t (if indent (newline-and-indent) (newline))))))
19421 (defun org-return-indent ()
19422 "Goto next table row or insert a newline and indent.
19423 Calls `org-table-next-row' or `newline-and-indent', depending on
19424 context. See the individual commands for more information."
19425 (interactive)
19426 (org-return t))
19428 (defun org-ctrl-c-star ()
19429 "Compute table, or change heading status of lines.
19430 Calls `org-table-recalculate' or `org-toggle-heading',
19431 depending on context."
19432 (interactive)
19433 (cond
19434 ((org-at-table-p)
19435 (call-interactively 'org-table-recalculate))
19437 ;; Convert all lines in region to list items
19438 (call-interactively 'org-toggle-heading))))
19440 (defun org-ctrl-c-minus ()
19441 "Insert separator line in table or modify bullet status of line.
19442 Also turns a plain line or a region of lines into list items.
19443 Calls `org-table-insert-hline', `org-toggle-item', or
19444 `org-cycle-list-bullet', depending on context."
19445 (interactive)
19446 (cond
19447 ((org-at-table-p)
19448 (call-interactively 'org-table-insert-hline))
19449 ((org-region-active-p)
19450 (call-interactively 'org-toggle-item))
19451 ((org-in-item-p)
19452 (call-interactively 'org-cycle-list-bullet))
19454 (call-interactively 'org-toggle-item))))
19456 (defun org-toggle-item (arg)
19457 "Convert headings or normal lines to items, items to normal lines.
19458 If there is no active region, only the current line is considered.
19460 If the first non blank line in the region is an headline, convert
19461 all headlines to items, shifting text accordingly.
19463 If it is an item, convert all items to normal lines.
19465 If it is normal text, change region into an item. With a prefix
19466 argument ARG, change each line in region into an item."
19467 (interactive "P")
19468 (let ((shift-text
19469 (function
19470 ;; Shift text in current section to IND, from point to END.
19471 ;; The function leaves point to END line.
19472 (lambda (ind end)
19473 (let ((min-i 1000) (end (copy-marker end)))
19474 ;; First determine the minimum indentation (MIN-I) of
19475 ;; the text.
19476 (save-excursion
19477 (catch 'exit
19478 (while (< (point) end)
19479 (let ((i (org-get-indentation)))
19480 (cond
19481 ;; Skip blank lines and inline tasks.
19482 ((looking-at "^[ \t]*$"))
19483 ((looking-at org-outline-regexp-bol))
19484 ;; We can't find less than 0 indentation.
19485 ((zerop i) (throw 'exit (setq min-i 0)))
19486 ((< i min-i) (setq min-i i))))
19487 (forward-line))))
19488 ;; Then indent each line so that a line indented to
19489 ;; MIN-I becomes indented to IND. Ignore blank lines
19490 ;; and inline tasks in the process.
19491 (let ((delta (- ind min-i)))
19492 (while (< (point) end)
19493 (unless (or (looking-at "^[ \t]*$")
19494 (looking-at org-outline-regexp-bol))
19495 (org-indent-line-to (+ (org-get-indentation) delta)))
19496 (forward-line)))))))
19497 (skip-blanks
19498 (function
19499 ;; Return beginning of first non-blank line, starting from
19500 ;; line at POS.
19501 (lambda (pos)
19502 (save-excursion
19503 (goto-char pos)
19504 (skip-chars-forward " \r\t\n")
19505 (point-at-bol)))))
19506 beg end)
19507 ;; Determine boundaries of changes.
19508 (if (org-region-active-p)
19509 (setq beg (funcall skip-blanks (region-beginning))
19510 end (copy-marker (region-end)))
19511 (setq beg (funcall skip-blanks (point-at-bol))
19512 end (copy-marker (point-at-eol))))
19513 ;; Depending on the starting line, choose an action on the text
19514 ;; between BEG and END.
19515 (org-with-limited-levels
19516 (save-excursion
19517 (goto-char beg)
19518 (cond
19519 ;; Case 1. Start at an item: de-itemize. Note that it only
19520 ;; happens when a region is active: `org-ctrl-c-minus'
19521 ;; would call `org-cycle-list-bullet' otherwise.
19522 ((org-at-item-p)
19523 (while (< (point) end)
19524 (when (org-at-item-p)
19525 (skip-chars-forward " \t")
19526 (delete-region (point) (match-end 0)))
19527 (forward-line)))
19528 ;; Case 2. Start at an heading: convert to items.
19529 ((org-at-heading-p)
19530 (let* ((bul (org-list-bullet-string "-"))
19531 (bul-len (length bul))
19532 ;; Indentation of the first heading. It should be
19533 ;; relative to the indentation of its parent, if any.
19534 (start-ind (save-excursion
19535 (cond
19536 ((not org-adapt-indentation) 0)
19537 ((not (outline-previous-heading)) 0)
19538 (t (length (match-string 0))))))
19539 ;; Level of first heading. Further headings will be
19540 ;; compared to it to determine hierarchy in the list.
19541 (ref-level (org-reduced-level (org-outline-level))))
19542 (while (< (point) end)
19543 (let* ((level (org-reduced-level (org-outline-level)))
19544 (delta (max 0 (- level ref-level))))
19545 ;; If current headline is less indented than the first
19546 ;; one, set it as reference, in order to preserve
19547 ;; subtrees.
19548 (when (< level ref-level) (setq ref-level level))
19549 (replace-match bul t t)
19550 (org-indent-line-to (+ start-ind (* delta bul-len)))
19551 ;; Ensure all text down to END (or SECTION-END) belongs
19552 ;; to the newly created item.
19553 (let ((section-end (save-excursion
19554 (or (outline-next-heading) (point)))))
19555 (forward-line)
19556 (funcall shift-text
19557 (+ start-ind (* (1+ delta) bul-len))
19558 (min end section-end)))))))
19559 ;; Case 3. Normal line with ARG: turn each non-item line into
19560 ;; an item.
19561 (arg
19562 (while (< (point) end)
19563 (unless (or (org-at-heading-p) (org-at-item-p))
19564 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19565 (replace-match
19566 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19567 (forward-line)))
19568 ;; Case 4. Normal line without ARG: make the first line of
19569 ;; region an item, and shift indentation of others
19570 ;; lines to set them as item's body.
19571 (t (let* ((bul (org-list-bullet-string "-"))
19572 (bul-len (length bul))
19573 (ref-ind (org-get-indentation)))
19574 (skip-chars-forward " \t")
19575 (insert bul)
19576 (forward-line)
19577 (while (< (point) end)
19578 ;; Ensure that lines less indented than first one
19579 ;; still get included in item body.
19580 (funcall shift-text
19581 (+ ref-ind bul-len)
19582 (min end (save-excursion (or (outline-next-heading)
19583 (point)))))
19584 (forward-line)))))))))
19586 (defun org-toggle-heading (&optional nstars)
19587 "Convert headings to normal text, or items or text to headings.
19588 If there is no active region, only the current line is considered.
19590 With a \\[universal-argument] prefix, convert the whole list at
19591 point into heading.
19593 In a region:
19595 - If the first non blank line is an headline, remove the stars
19596 from all headlines in the region.
19598 - If it is a normal line turn each and every normal line (i.e. not an
19599 heading or an item) in the region into a heading.
19601 - If it is a plain list item, turn all plain list items into headings.
19603 When converting a line into a heading, the number of stars is chosen
19604 such that the lines become children of the current entry. However,
19605 when a prefix argument is given, its value determines the number of
19606 stars to add."
19607 (interactive "P")
19608 (let ((skip-blanks
19609 (function
19610 ;; Return beginning of first non-blank line, starting from
19611 ;; line at POS.
19612 (lambda (pos)
19613 (save-excursion
19614 (goto-char pos)
19615 (while (org-at-comment-p) (forward-line))
19616 (skip-chars-forward " \r\t\n")
19617 (point-at-bol)))))
19618 beg end toggled)
19619 ;; Determine boundaries of changes. If a universal prefix has
19620 ;; been given, put the list in a region. If region ends at a bol,
19621 ;; do not consider the last line to be in the region.
19623 (when (and current-prefix-arg (org-at-item-p))
19624 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19625 (org-mark-element))
19627 (if (org-region-active-p)
19628 (setq beg (funcall skip-blanks (region-beginning))
19629 end (copy-marker (save-excursion
19630 (goto-char (region-end))
19631 (if (bolp) (point) (point-at-eol)))))
19632 (setq beg (funcall skip-blanks (point-at-bol))
19633 end (copy-marker (point-at-eol))))
19634 ;; Ensure inline tasks don't count as headings.
19635 (org-with-limited-levels
19636 (save-excursion
19637 (goto-char beg)
19638 (cond
19639 ;; Case 1. Started at an heading: de-star headings.
19640 ((org-at-heading-p)
19641 (while (< (point) end)
19642 (when (org-at-heading-p t)
19643 (looking-at org-outline-regexp) (replace-match "")
19644 (setq toggled t))
19645 (forward-line)))
19646 ;; Case 2. Started at an item: change items into headlines.
19647 ;; One star will be added by `org-list-to-subtree'.
19648 ((org-at-item-p)
19649 (let* ((stars (make-string
19650 (if nstars
19651 ;; subtract the star that will be added again by
19652 ;; `org-list-to-subtree'
19653 (1- (prefix-numeric-value current-prefix-arg))
19654 (or (org-current-level) 0))
19655 ?*))
19656 (add-stars
19657 (cond (nstars "") ; stars from prefix only
19658 ((equal stars "") "") ; before first heading
19659 (org-odd-levels-only "*") ; inside heading, odd
19660 (t "")))) ; inside heading, oddeven
19661 (while (< (point) end)
19662 (when (org-at-item-p)
19663 ;; Pay attention to cases when region ends before list.
19664 (let* ((struct (org-list-struct))
19665 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19666 (save-restriction
19667 (narrow-to-region (point) list-end)
19668 (insert
19669 (org-list-to-subtree
19670 (org-list-parse-list t)
19671 '(:istart (concat stars add-stars (funcall get-stars depth))
19672 :icount (concat stars add-stars (funcall get-stars depth)))))))
19673 (setq toggled t))
19674 (forward-line))))
19675 ;; Case 3. Started at normal text: make every line an heading,
19676 ;; skipping headlines and items.
19677 (t (let* ((stars (make-string
19678 (if nstars
19679 (prefix-numeric-value current-prefix-arg)
19680 (or (org-current-level) 0))
19681 ?*))
19682 (add-stars
19683 (cond (nstars "") ; stars from prefix only
19684 ((equal stars "") "*") ; before first heading
19685 (org-odd-levels-only "**") ; inside heading, odd
19686 (t "*"))) ; inside heading, oddeven
19687 (rpl (concat stars add-stars " ")))
19688 (while (< (point) end)
19689 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19690 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19691 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19692 (forward-line)))))))
19693 (unless toggled (message "Cannot toggle heading from here"))))
19695 (defun org-meta-return (&optional arg)
19696 "Insert a new heading or wrap a region in a table.
19697 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19698 See the individual commands for more information."
19699 (interactive "P")
19700 (cond
19701 ((run-hook-with-args-until-success 'org-metareturn-hook))
19702 ((or (org-at-drawer-p) (org-at-property-p))
19703 (newline-and-indent))
19704 ((org-at-table-p)
19705 (call-interactively 'org-table-wrap-region))
19706 (t (call-interactively 'org-insert-heading))))
19708 ;;; Menu entries
19710 ;; Define the Org-mode menus
19711 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19712 '("Tbl"
19713 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19714 ["Next Field" org-cycle (org-at-table-p)]
19715 ["Previous Field" org-shifttab (org-at-table-p)]
19716 ["Next Row" org-return (org-at-table-p)]
19717 "--"
19718 ["Blank Field" org-table-blank-field (org-at-table-p)]
19719 ["Edit Field" org-table-edit-field (org-at-table-p)]
19720 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19721 "--"
19722 ("Column"
19723 ["Move Column Left" org-metaleft (org-at-table-p)]
19724 ["Move Column Right" org-metaright (org-at-table-p)]
19725 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19726 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19727 ("Row"
19728 ["Move Row Up" org-metaup (org-at-table-p)]
19729 ["Move Row Down" org-metadown (org-at-table-p)]
19730 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19731 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19732 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19733 "--"
19734 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19735 ("Rectangle"
19736 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19737 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19738 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19739 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19740 "--"
19741 ("Calculate"
19742 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19743 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19744 ["Edit Formulas" org-edit-special (org-at-table-p)]
19745 "--"
19746 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19747 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19748 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19749 "--"
19750 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19751 "--"
19752 ["Sum Column/Rectangle" org-table-sum
19753 (or (org-at-table-p) (org-region-active-p))]
19754 ["Which Column?" org-table-current-column (org-at-table-p)])
19755 ["Debug Formulas"
19756 org-table-toggle-formula-debugger
19757 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19758 ["Show Col/Row Numbers"
19759 org-table-toggle-coordinate-overlays
19760 :style toggle
19761 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19762 "--"
19763 ["Create" org-table-create (and (not (org-at-table-p))
19764 org-enable-table-editor)]
19765 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19766 ["Import from File" org-table-import (not (org-at-table-p))]
19767 ["Export to File" org-table-export (org-at-table-p)]
19768 "--"
19769 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19771 (easy-menu-define org-org-menu org-mode-map "Org menu"
19772 '("Org"
19773 ("Show/Hide"
19774 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19775 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19776 ["Sparse Tree..." org-sparse-tree t]
19777 ["Reveal Context" org-reveal t]
19778 ["Show All" show-all t]
19779 "--"
19780 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19781 "--"
19782 ["New Heading" org-insert-heading t]
19783 ("Navigate Headings"
19784 ["Up" outline-up-heading t]
19785 ["Next" outline-next-visible-heading t]
19786 ["Previous" outline-previous-visible-heading t]
19787 ["Next Same Level" outline-forward-same-level t]
19788 ["Previous Same Level" outline-backward-same-level t]
19789 "--"
19790 ["Jump" org-goto t])
19791 ("Edit Structure"
19792 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19793 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19794 "--"
19795 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19796 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19797 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19798 "--"
19799 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19800 "--"
19801 ["Copy visible text" org-copy-visible t]
19802 "--"
19803 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19804 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19805 ["Demote Heading" org-metaright (not (org-at-table-p))]
19806 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19807 "--"
19808 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19809 "--"
19810 ["Convert to odd levels" org-convert-to-odd-levels t]
19811 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19812 ("Editing"
19813 ["Emphasis..." org-emphasize t]
19814 ["Edit Source Example" org-edit-special t]
19815 "--"
19816 ["Footnote new/jump" org-footnote-action t]
19817 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19818 ("Archive"
19819 ["Archive (default method)" org-archive-subtree-default t]
19820 "--"
19821 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19822 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19823 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19825 "--"
19826 ("Hyperlinks"
19827 ["Store Link (Global)" org-store-link t]
19828 ["Find existing link to here" org-occur-link-in-agenda-files t]
19829 ["Insert Link" org-insert-link t]
19830 ["Follow Link" org-open-at-point t]
19831 "--"
19832 ["Next link" org-next-link t]
19833 ["Previous link" org-previous-link t]
19834 "--"
19835 ["Descriptive Links"
19836 org-toggle-link-display
19837 :style radio
19838 :selected org-descriptive-links
19840 ["Literal Links"
19841 org-toggle-link-display
19842 :style radio
19843 :selected (not org-descriptive-links)])
19844 "--"
19845 ("TODO Lists"
19846 ["TODO/DONE/-" org-todo t]
19847 ("Select keyword"
19848 ["Next keyword" org-shiftright (org-at-heading-p)]
19849 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19850 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19851 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19852 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19853 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19854 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19855 "--"
19856 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19857 :selected org-enforce-todo-dependencies :style toggle :active t]
19858 "Settings for tree at point"
19859 ["Do Children sequentially" org-toggle-ordered-property :style radio
19860 :selected (org-entry-get nil "ORDERED")
19861 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19862 ["Do Children parallel" org-toggle-ordered-property :style radio
19863 :selected (not (org-entry-get nil "ORDERED"))
19864 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19865 "--"
19866 ["Set Priority" org-priority t]
19867 ["Priority Up" org-shiftup t]
19868 ["Priority Down" org-shiftdown t]
19869 "--"
19870 ["Get news from all feeds" org-feed-update-all t]
19871 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19872 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19873 ("TAGS and Properties"
19874 ["Set Tags" org-set-tags-command t]
19875 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19876 "--"
19877 ["Set property" org-set-property t]
19878 ["Column view of properties" org-columns t]
19879 ["Insert Column View DBlock" org-insert-columns-dblock t])
19880 ("Dates and Scheduling"
19881 ["Timestamp" org-time-stamp t]
19882 ["Timestamp (inactive)" org-time-stamp-inactive t]
19883 ("Change Date"
19884 ["1 Day Later" org-shiftright t]
19885 ["1 Day Earlier" org-shiftleft t]
19886 ["1 ... Later" org-shiftup t]
19887 ["1 ... Earlier" org-shiftdown t])
19888 ["Compute Time Range" org-evaluate-time-range t]
19889 ["Schedule Item" org-schedule t]
19890 ["Deadline" org-deadline t]
19891 "--"
19892 ["Custom time format" org-toggle-time-stamp-overlays
19893 :style radio :selected org-display-custom-times]
19894 "--"
19895 ["Goto Calendar" org-goto-calendar t]
19896 ["Date from Calendar" org-date-from-calendar t]
19897 "--"
19898 ["Start/Restart Timer" org-timer-start t]
19899 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19900 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19901 ["Insert Timer String" org-timer t]
19902 ["Insert Timer Item" org-timer-item t])
19903 ("Logging work"
19904 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19905 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19906 ["Clock out" org-clock-out t]
19907 ["Clock cancel" org-clock-cancel t]
19908 "--"
19909 ["Mark as default task" org-clock-mark-default-task t]
19910 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19911 ["Goto running clock" org-clock-goto t]
19912 "--"
19913 ["Display times" org-clock-display t]
19914 ["Create clock table" org-clock-report t]
19915 "--"
19916 ["Record DONE time"
19917 (progn (setq org-log-done (not org-log-done))
19918 (message "Switching to %s will %s record a timestamp"
19919 (car org-done-keywords)
19920 (if org-log-done "automatically" "not")))
19921 :style toggle :selected org-log-done])
19922 "--"
19923 ["Agenda Command..." org-agenda t]
19924 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19925 ("File List for Agenda")
19926 ("Special views current file"
19927 ["TODO Tree" org-show-todo-tree t]
19928 ["Check Deadlines" org-check-deadlines t]
19929 ["Timeline" org-timeline t]
19930 ["Tags/Property tree" org-match-sparse-tree t])
19931 "--"
19932 ["Export/Publish..." org-export t]
19933 ("LaTeX"
19934 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19935 :selected org-cdlatex-mode]
19936 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19937 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19938 ["Modify math symbol" org-cdlatex-math-modify
19939 (org-inside-LaTeX-fragment-p)]
19940 ["Insert citation" org-reftex-citation t]
19941 "--"
19942 ["Template for BEAMER" (progn (require 'org-beamer)
19943 (org-insert-beamer-options-template)) t])
19944 "--"
19945 ("MobileOrg"
19946 ["Push Files and Views" org-mobile-push t]
19947 ["Get Captured and Flagged" org-mobile-pull t]
19948 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19949 "--"
19950 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19951 "--"
19952 ("Documentation"
19953 ["Show Version" org-version t]
19954 ["Info Documentation" org-info t])
19955 ("Customize"
19956 ["Browse Org Group" org-customize t]
19957 "--"
19958 ["Expand This Menu" org-create-customize-menu
19959 (fboundp 'customize-menu-create)])
19960 ["Send bug report" org-submit-bug-report t]
19961 "--"
19962 ("Refresh/Reload"
19963 ["Refresh setup current buffer" org-mode-restart t]
19964 ["Reload Org (after update)" org-reload t]
19965 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19968 (defun org-info (&optional node)
19969 "Read documentation for Org-mode in the info system.
19970 With optional NODE, go directly to that node."
19971 (interactive)
19972 (info (format "(org)%s" (or node ""))))
19974 ;;;###autoload
19975 (defun org-submit-bug-report ()
19976 "Submit a bug report on Org-mode via mail.
19978 Don't hesitate to report any problems or inaccurate documentation.
19980 If you don't have setup sending mail from (X)Emacs, please copy the
19981 output buffer into your mail program, as it gives us important
19982 information about your Org-mode version and configuration."
19983 (interactive)
19984 (require 'reporter)
19985 (org-load-modules-maybe)
19986 (org-require-autoloaded-modules)
19987 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19988 (reporter-submit-bug-report
19989 "emacs-orgmode@gnu.org"
19990 (org-version nil 'full)
19991 (let (list)
19992 (save-window-excursion
19993 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19994 (delete-other-windows)
19995 (erase-buffer)
19996 (insert "You are about to submit a bug report to the Org-mode mailing list.
19998 We would like to add your full Org-mode and Outline configuration to the
19999 bug report. This greatly simplifies the work of the maintainer and
20000 other experts on the mailing list.
20002 HOWEVER, some variables you have customized may contain private
20003 information. The names of customers, colleagues, or friends, might
20004 appear in the form of file names, tags, todo states, or search strings.
20005 If you answer yes to the prompt, you might want to check and remove
20006 such private information before sending the email.")
20007 (add-text-properties (point-min) (point-max) '(face org-warning))
20008 (when (yes-or-no-p "Include your Org-mode configuration ")
20009 (mapatoms
20010 (lambda (v)
20011 (and (boundp v)
20012 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20013 (or (and (symbol-value v)
20014 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20015 (and
20016 (get v 'custom-type) (get v 'standard-value)
20017 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20018 (push v list)))))
20019 (kill-buffer (get-buffer "*Warn about privacy*"))
20020 list))
20021 nil nil
20022 "Remember to cover the basics, that is, what you expected to happen and
20023 what in fact did happen. You don't know how to make a good report? See
20025 http://orgmode.org/manual/Feedback.html#Feedback
20027 Your bug report will be posted to the Org-mode mailing list.
20028 ------------------------------------------------------------------------")
20029 (save-excursion
20030 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20031 (replace-match "\\1Bug: \\3 [\\2]")))))
20034 (defun org-install-agenda-files-menu ()
20035 (let ((bl (buffer-list)))
20036 (save-excursion
20037 (while bl
20038 (set-buffer (pop bl))
20039 (if (derived-mode-p 'org-mode) (setq bl nil)))
20040 (when (derived-mode-p 'org-mode)
20041 (easy-menu-change
20042 '("Org") "File List for Agenda"
20043 (append
20044 (list
20045 ["Edit File List" (org-edit-agenda-file-list) t]
20046 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20047 ["Remove Current File from List" org-remove-file t]
20048 ["Cycle through agenda files" org-cycle-agenda-files t]
20049 ["Occur in all agenda files" org-occur-in-agenda-files t]
20050 "--")
20051 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20053 ;;;; Documentation
20055 ;;;###autoload
20056 (defun org-require-autoloaded-modules ()
20057 (interactive)
20058 (mapc 'require
20059 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20060 org-docbook org-exp org-html org-icalendar
20061 org-id org-latex
20062 org-publish org-remember org-table
20063 org-timer org-xoxo)))
20065 ;;;###autoload
20066 (defun org-reload (&optional uncompiled)
20067 "Reload all org lisp files.
20068 With prefix arg UNCOMPILED, load the uncompiled versions."
20069 (interactive "P")
20070 (require 'find-func)
20071 (let* ((file-re "^org\\(-.*\\)?\\.el")
20072 (dir-org (file-name-directory (org-find-library-dir "org")))
20073 (dir-org-contrib (ignore-errors
20074 (file-name-directory
20075 (org-find-library-dir "org-contribdir"))))
20076 (babel-files
20077 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20078 (append (list nil "comint" "eval" "exp" "keys"
20079 "lob" "ref" "table" "tangle")
20080 (delq nil
20081 (mapcar
20082 (lambda (lang)
20083 (when (cdr lang) (symbol-name (car lang))))
20084 org-babel-load-languages)))))
20085 (files
20086 (append babel-files
20087 (and dir-org-contrib
20088 (directory-files dir-org-contrib t file-re))
20089 (directory-files dir-org t file-re)))
20090 (remove-re (concat (if (featurep 'xemacs)
20091 "org-colview" "org-colview-xemacs")
20092 "\\'")))
20093 (setq files (mapcar 'file-name-sans-extension files))
20094 (setq files (mapcar
20095 (lambda (x) (if (string-match remove-re x) nil x))
20096 files))
20097 (setq files (delq nil files))
20098 (mapc
20099 (lambda (f)
20100 (when (featurep (intern (file-name-nondirectory f)))
20101 (if (and (not uncompiled)
20102 (file-exists-p (concat f ".elc")))
20103 (load (concat f ".elc") nil nil 'nosuffix)
20104 (load (concat f ".el") nil nil 'nosuffix))))
20105 files)
20106 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20107 (org-version nil 'full 'message))
20109 ;;;###autoload
20110 (defun org-customize ()
20111 "Call the customize function with org as argument."
20112 (interactive)
20113 (org-load-modules-maybe)
20114 (org-require-autoloaded-modules)
20115 (customize-browse 'org))
20117 (defun org-create-customize-menu ()
20118 "Create a full customization menu for Org-mode, insert it into the menu."
20119 (interactive)
20120 (org-load-modules-maybe)
20121 (org-require-autoloaded-modules)
20122 (if (fboundp 'customize-menu-create)
20123 (progn
20124 (easy-menu-change
20125 '("Org") "Customize"
20126 `(["Browse Org group" org-customize t]
20127 "--"
20128 ,(customize-menu-create 'org)
20129 ["Set" Custom-set t]
20130 ["Save" Custom-save t]
20131 ["Reset to Current" Custom-reset-current t]
20132 ["Reset to Saved" Custom-reset-saved t]
20133 ["Reset to Standard Settings" Custom-reset-standard t]))
20134 (message "\"Org\"-menu now contains full customization menu"))
20135 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20137 ;;;; Miscellaneous stuff
20139 ;;; Generally useful functions
20141 (defun org-get-at-bol (property)
20142 "Get text property PROPERTY at beginning of line."
20143 (get-text-property (point-at-bol) property))
20145 (defun org-find-text-property-in-string (prop s)
20146 "Return the first non-nil value of property PROP in string S."
20147 (or (get-text-property 0 prop s)
20148 (get-text-property (or (next-single-property-change 0 prop s) 0)
20149 prop s)))
20151 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20152 "Display the given MESSAGE as a warning."
20153 (if (fboundp 'display-warning)
20154 (display-warning 'org message
20155 (if (featurep 'xemacs) 'warning :warning))
20156 (let ((buf (get-buffer-create "*Org warnings*")))
20157 (with-current-buffer buf
20158 (goto-char (point-max))
20159 (insert "Warning (Org): " message)
20160 (unless (bolp)
20161 (newline)))
20162 (display-buffer buf)
20163 (sit-for 0))))
20165 (defun org-eval (form)
20166 "Eval FORM and return result."
20167 (condition-case error
20168 (eval form)
20169 (error (format "%%![Error: %s]" error))))
20171 (defun org-in-clocktable-p ()
20172 "Check if the cursor is in a clocktable."
20173 (let ((pos (point)) start)
20174 (save-excursion
20175 (end-of-line 1)
20176 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20177 (setq start (match-beginning 0))
20178 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20179 (>= (match-end 0) pos)
20180 start))))
20182 (defun org-in-commented-line ()
20183 "Is point in a line starting with `#'?"
20184 (equal (char-after (point-at-bol)) ?#))
20186 (defun org-in-indented-comment-line ()
20187 "Is point in a line starting with `#' after some white space?"
20188 (save-excursion
20189 (save-match-data
20190 (goto-char (point-at-bol))
20191 (looking-at "[ \t]*#"))))
20193 (defun org-in-verbatim-emphasis ()
20194 (save-match-data
20195 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20197 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20198 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20199 (if (and marker (marker-buffer marker)
20200 (buffer-live-p (marker-buffer marker)))
20201 (progn
20202 (org-pop-to-buffer-same-window (marker-buffer marker))
20203 (if (or (> marker (point-max)) (< marker (point-min)))
20204 (widen))
20205 (goto-char marker)
20206 (org-show-context 'org-goto))
20207 (if bookmark
20208 (bookmark-jump bookmark)
20209 (error "Cannot find location"))))
20211 (defun org-quote-csv-field (s)
20212 "Quote field for inclusion in CSV material."
20213 (if (string-match "[\",]" s)
20214 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20217 (defun org-force-self-insert (N)
20218 "Needed to enforce self-insert under remapping."
20219 (interactive "p")
20220 (self-insert-command N))
20222 (defun org-string-width (s)
20223 "Compute width of string, ignoring invisible characters.
20224 This ignores character with invisibility property `org-link', and also
20225 characters with property `org-cwidth', because these will become invisible
20226 upon the next fontification round."
20227 (let (b l)
20228 (when (or (eq t buffer-invisibility-spec)
20229 (assq 'org-link buffer-invisibility-spec))
20230 (while (setq b (text-property-any 0 (length s)
20231 'invisible 'org-link s))
20232 (setq s (concat (substring s 0 b)
20233 (substring s (or (next-single-property-change
20234 b 'invisible s) (length s)))))))
20235 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20236 (setq s (concat (substring s 0 b)
20237 (substring s (or (next-single-property-change
20238 b 'org-cwidth s) (length s))))))
20239 (setq l (string-width s) b -1)
20240 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20241 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20244 (defun org-shorten-string (s maxlength)
20245 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20246 If the string is shorter or has length MAXLENGTH, just return the
20247 original string. If it is longer, the functions finds a space in the
20248 string, breaks this string off at that locations and adds three dots
20249 as ellipsis. Including the ellipsis, the string will not be longer
20250 than MAXLENGTH. If finding a good breaking point in the string does
20251 not work, the string is just chopped off in the middle of a word
20252 if necessary."
20253 (if (<= (length s) maxlength)
20255 (let* ((n (max (- maxlength 4) 1))
20256 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20257 (if (string-match re s)
20258 (concat (match-string 1 s) "...")
20259 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20261 (defun org-get-indentation (&optional line)
20262 "Get the indentation of the current line, interpreting tabs.
20263 When LINE is given, assume it represents a line and compute its indentation."
20264 (if line
20265 (if (string-match "^ *" (org-remove-tabs line))
20266 (match-end 0))
20267 (save-excursion
20268 (beginning-of-line 1)
20269 (skip-chars-forward " \t")
20270 (current-column))))
20272 (defun org-get-string-indentation (s)
20273 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20274 (let ((n -1) (i 0) (w tab-width) c)
20275 (catch 'exit
20276 (while (< (setq n (1+ n)) (length s))
20277 (setq c (aref s n))
20278 (cond ((= c ?\ ) (setq i (1+ i)))
20279 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20280 (t (throw 'exit t)))))
20283 (defun org-remove-tabs (s &optional width)
20284 "Replace tabulators in S with spaces.
20285 Assumes that s is a single line, starting in column 0."
20286 (setq width (or width tab-width))
20287 (while (string-match "\t" s)
20288 (setq s (replace-match
20289 (make-string
20290 (- (* width (/ (+ (match-beginning 0) width) width))
20291 (match-beginning 0)) ?\ )
20292 t t s)))
20295 (defun org-fix-indentation (line ind)
20296 "Fix indentation in LINE.
20297 IND is a cons cell with target and minimum indentation.
20298 If the current indentation in LINE is smaller than the minimum,
20299 leave it alone. If it is larger than ind, set it to the target."
20300 (let* ((l (org-remove-tabs line))
20301 (i (org-get-indentation l))
20302 (i1 (car ind)) (i2 (cdr ind)))
20303 (if (>= i i2) (setq l (substring line i2)))
20304 (if (> i1 0)
20305 (concat (make-string i1 ?\ ) l)
20306 l)))
20308 (defun org-remove-indentation (code &optional n)
20309 "Remove the maximum common indentation from the lines in CODE.
20310 N may optionally be the number of spaces to remove."
20311 (with-temp-buffer
20312 (insert code)
20313 (org-do-remove-indentation n)
20314 (buffer-string)))
20316 (defun org-do-remove-indentation (&optional n)
20317 "Remove the maximum common indentation from the buffer."
20318 (untabify (point-min) (point-max))
20319 (let ((min 10000) re)
20320 (if n
20321 (setq min n)
20322 (goto-char (point-min))
20323 (while (re-search-forward "^ *[^ \n]" nil t)
20324 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20325 (unless (or (= min 0) (= min 10000))
20326 (setq re (format "^ \\{%d\\}" min))
20327 (goto-char (point-min))
20328 (while (re-search-forward re nil t)
20329 (replace-match "")
20330 (end-of-line 1))
20331 min)))
20333 (defun org-fill-template (template alist)
20334 "Find each %key of ALIST in TEMPLATE and replace it."
20335 (let ((case-fold-search nil)
20336 entry key value)
20337 (setq alist (sort (copy-sequence alist)
20338 (lambda (a b) (< (length (car a)) (length (car b))))))
20339 (while (setq entry (pop alist))
20340 (setq template
20341 (replace-regexp-in-string
20342 (concat "%" (regexp-quote (car entry)))
20343 (or (cdr entry) "") template t t)))
20344 template))
20346 (defun org-base-buffer (buffer)
20347 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20348 (if (not buffer)
20349 buffer
20350 (or (buffer-base-buffer buffer)
20351 buffer)))
20353 (defun org-trim (s)
20354 "Remove whitespace at beginning and end of string."
20355 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20356 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20359 (defun org-wrap (string &optional width lines)
20360 "Wrap string to either a number of lines, or a width in characters.
20361 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20362 that costs. If there is a word longer than WIDTH, the text is actually
20363 wrapped to the length of that word.
20364 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20365 many lines, whatever width that takes.
20366 The return value is a list of lines, without newlines at the end."
20367 (let* ((words (org-split-string string "[ \t\n]+"))
20368 (maxword (apply 'max (mapcar 'org-string-width words)))
20369 w ll)
20370 (cond (width
20371 (org-do-wrap words (max maxword width)))
20372 (lines
20373 (setq w maxword)
20374 (setq ll (org-do-wrap words maxword))
20375 (if (<= (length ll) lines)
20377 (setq ll words)
20378 (while (> (length ll) lines)
20379 (setq w (1+ w))
20380 (setq ll (org-do-wrap words w)))
20381 ll))
20382 (t (error "Cannot wrap this")))))
20384 (defun org-do-wrap (words width)
20385 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20386 (let (lines line)
20387 (while words
20388 (setq line (pop words))
20389 (while (and words (< (+ (length line) (length (car words))) width))
20390 (setq line (concat line " " (pop words))))
20391 (setq lines (push line lines)))
20392 (nreverse lines)))
20394 (defun org-split-string (string &optional separators)
20395 "Splits STRING into substrings at SEPARATORS.
20396 No empty strings are returned if there are matches at the beginning
20397 and end of string."
20398 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20399 (start 0)
20400 notfirst
20401 (list nil))
20402 (while (and (string-match rexp string
20403 (if (and notfirst
20404 (= start (match-beginning 0))
20405 (< start (length string)))
20406 (1+ start) start))
20407 (< (match-beginning 0) (length string)))
20408 (setq notfirst t)
20409 (or (eq (match-beginning 0) 0)
20410 (and (eq (match-beginning 0) (match-end 0))
20411 (eq (match-beginning 0) start))
20412 (setq list
20413 (cons (substring string start (match-beginning 0))
20414 list)))
20415 (setq start (match-end 0)))
20416 (or (eq start (length string))
20417 (setq list
20418 (cons (substring string start)
20419 list)))
20420 (nreverse list)))
20422 (defun org-quote-vert (s)
20423 "Replace \"|\" with \"\\vert\"."
20424 (while (string-match "|" s)
20425 (setq s (replace-match "\\vert" t t s)))
20428 (defun org-uuidgen-p (s)
20429 "Is S an ID created by UUIDGEN?"
20430 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20432 (defun org-in-src-block-p nil
20433 "Whether point is in a code source block."
20434 (let (ov)
20435 (when (setq ov (overlays-at (point)))
20436 (memq 'org-block-background
20437 (overlay-properties
20438 (car ov))))))
20440 (defun org-context ()
20441 "Return a list of contexts of the current cursor position.
20442 If several contexts apply, all are returned.
20443 Each context entry is a list with a symbol naming the context, and
20444 two positions indicating start and end of the context. Possible
20445 contexts are:
20447 :headline anywhere in a headline
20448 :headline-stars on the leading stars in a headline
20449 :todo-keyword on a TODO keyword (including DONE) in a headline
20450 :tags on the TAGS in a headline
20451 :priority on the priority cookie in a headline
20452 :item on the first line of a plain list item
20453 :item-bullet on the bullet/number of a plain list item
20454 :checkbox on the checkbox in a plain list item
20455 :table in an org-mode table
20456 :table-special on a special filed in a table
20457 :table-table in a table.el table
20458 :clocktable in a clocktable
20459 :src-block in a source block
20460 :link on a hyperlink
20461 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20462 :target on a <<target>>
20463 :radio-target on a <<<radio-target>>>
20464 :latex-fragment on a LaTeX fragment
20465 :latex-preview on a LaTeX fragment with overlaid preview image
20467 This function expects the position to be visible because it uses font-lock
20468 faces as a help to recognize the following contexts: :table-special, :link,
20469 and :keyword."
20470 (let* ((f (get-text-property (point) 'face))
20471 (faces (if (listp f) f (list f)))
20472 (case-fold-search t)
20473 (p (point)) clist o)
20474 ;; First the large context
20475 (cond
20476 ((org-at-heading-p t)
20477 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20478 (when (progn
20479 (beginning-of-line 1)
20480 (looking-at org-todo-line-tags-regexp))
20481 (push (org-point-in-group p 1 :headline-stars) clist)
20482 (push (org-point-in-group p 2 :todo-keyword) clist)
20483 (push (org-point-in-group p 4 :tags) clist))
20484 (goto-char p)
20485 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20486 (if (looking-at "\\[#[A-Z0-9]\\]")
20487 (push (org-point-in-group p 0 :priority) clist)))
20489 ((org-at-item-p)
20490 (push (org-point-in-group p 2 :item-bullet) clist)
20491 (push (list :item (point-at-bol)
20492 (save-excursion (org-end-of-item) (point)))
20493 clist)
20494 (and (org-at-item-checkbox-p)
20495 (push (org-point-in-group p 0 :checkbox) clist)))
20497 ((org-at-table-p)
20498 (push (list :table (org-table-begin) (org-table-end)) clist)
20499 (if (memq 'org-formula faces)
20500 (push (list :table-special
20501 (previous-single-property-change p 'face)
20502 (next-single-property-change p 'face)) clist)))
20503 ((org-at-table-p 'any)
20504 (push (list :table-table) clist)))
20505 (goto-char p)
20507 (let ((case-fold-search t))
20508 ;; New the "medium" contexts: clocktables, source blocks
20509 (cond ((org-in-clocktable-p)
20510 (push (list :clocktable
20511 (and (or (looking-at "#\\+BEGIN: clocktable")
20512 (search-backward "#+BEGIN: clocktable" nil t))
20513 (match-beginning 0))
20514 (and (re-search-forward "#\\+END:?" nil t)
20515 (match-end 0))) clist))
20516 ((org-in-src-block-p)
20517 (push (list :src-block
20518 (and (or (looking-at "#\\+BEGIN_SRC")
20519 (search-backward "#+BEGIN_SRC" nil t))
20520 (match-beginning 0))
20521 (and (search-forward "#+END_SRC" nil t)
20522 (match-beginning 0))) clist))))
20523 (goto-char p)
20525 ;; Now the small context
20526 (cond
20527 ((org-at-timestamp-p)
20528 (push (org-point-in-group p 0 :timestamp) clist))
20529 ((memq 'org-link faces)
20530 (push (list :link
20531 (previous-single-property-change p 'face)
20532 (next-single-property-change p 'face)) clist))
20533 ((memq 'org-special-keyword faces)
20534 (push (list :keyword
20535 (previous-single-property-change p 'face)
20536 (next-single-property-change p 'face)) clist))
20537 ((org-at-target-p)
20538 (push (org-point-in-group p 0 :target) clist)
20539 (goto-char (1- (match-beginning 0)))
20540 (if (looking-at org-radio-target-regexp)
20541 (push (org-point-in-group p 0 :radio-target) clist))
20542 (goto-char p))
20543 ((setq o (car (delq nil
20544 (mapcar
20545 (lambda (x)
20546 (if (memq x org-latex-fragment-image-overlays) x))
20547 (overlays-at (point))))))
20548 (push (list :latex-fragment
20549 (overlay-start o) (overlay-end o)) clist)
20550 (push (list :latex-preview
20551 (overlay-start o) (overlay-end o)) clist))
20552 ((org-inside-LaTeX-fragment-p)
20553 ;; FIXME: positions wrong.
20554 (push (list :latex-fragment (point) (point)) clist)))
20556 (setq clist (nreverse (delq nil clist)))
20557 clist))
20559 ;; FIXME: Compare with at-regexp-p Do we need both?
20560 (defun org-in-regexp (re &optional nlines visually)
20561 "Check if point is inside a match of regexp.
20562 Normally only the current line is checked, but you can include NLINES extra
20563 lines both before and after point into the search.
20564 If VISUALLY is set, require that the cursor is not after the match but
20565 really on, so that the block visually is on the match."
20566 (catch 'exit
20567 (let ((pos (point))
20568 (eol (point-at-eol (+ 1 (or nlines 0))))
20569 (inc (if visually 1 0)))
20570 (save-excursion
20571 (beginning-of-line (- 1 (or nlines 0)))
20572 (while (re-search-forward re eol t)
20573 (if (and (<= (match-beginning 0) pos)
20574 (>= (+ inc (match-end 0)) pos))
20575 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20577 (defun org-at-regexp-p (regexp)
20578 "Is point inside a match of REGEXP in the current line?"
20579 (catch 'exit
20580 (save-excursion
20581 (let ((pos (point)) (end (point-at-eol)))
20582 (beginning-of-line 1)
20583 (while (re-search-forward regexp end t)
20584 (if (and (<= (match-beginning 0) pos)
20585 (>= (match-end 0) pos))
20586 (throw 'exit t)))
20587 nil))))
20589 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20590 "Non-nil when point is between matches of START-RE and END-RE.
20592 Also return a non-nil value when point is on one of the matches.
20594 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20595 buffer positions. Default values are the positions of headlines
20596 surrounding the point.
20598 The functions returns a cons cell whose car (resp. cdr) is the
20599 position before START-RE (resp. after END-RE)."
20600 (save-match-data
20601 (let ((pos (point))
20602 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20603 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20604 beg end)
20605 (save-excursion
20606 ;; Point is on a block when on START-RE or if START-RE can be
20607 ;; found before it...
20608 (and (or (org-at-regexp-p start-re)
20609 (re-search-backward start-re limit-up t))
20610 (setq beg (match-beginning 0))
20611 ;; ... and END-RE after it...
20612 (goto-char (match-end 0))
20613 (re-search-forward end-re limit-down t)
20614 (> (setq end (match-end 0)) pos)
20615 ;; ... without another START-RE in-between.
20616 (goto-char (match-beginning 0))
20617 (not (re-search-backward start-re (1+ beg) t))
20618 ;; Return value.
20619 (cons beg end))))))
20621 (defun org-in-block-p (names)
20622 "Non-nil when point belongs to a block whose name belongs to NAMES.
20624 NAMES is a list of strings containing names of blocks.
20626 Return first block name matched, or nil. Beware that in case of
20627 nested blocks, the returned name may not belong to the closest
20628 block from point."
20629 (save-match-data
20630 (catch 'exit
20631 (let ((case-fold-search t)
20632 (lim-up (save-excursion (outline-previous-heading)))
20633 (lim-down (save-excursion (outline-next-heading))))
20634 (mapc (lambda (name)
20635 (let ((n (regexp-quote name)))
20636 (when (org-between-regexps-p
20637 (concat "^[ \t]*#\\+begin_" n)
20638 (concat "^[ \t]*#\\+end_" n)
20639 lim-up lim-down)
20640 (throw 'exit n))))
20641 names))
20642 nil)))
20644 (defun org-occur-in-agenda-files (regexp &optional nlines)
20645 "Call `multi-occur' with buffers for all agenda files."
20646 (interactive "sOrg-files matching: \np")
20647 (let* ((files (org-agenda-files))
20648 (tnames (mapcar 'file-truename files))
20649 (extra org-agenda-text-search-extra-files)
20651 (when (eq (car extra) 'agenda-archives)
20652 (setq extra (cdr extra))
20653 (setq files (org-add-archive-files files)))
20654 (while (setq f (pop extra))
20655 (unless (member (file-truename f) tnames)
20656 (add-to-list 'files f 'append)
20657 (add-to-list 'tnames (file-truename f) 'append)))
20658 (multi-occur
20659 (mapcar (lambda (x)
20660 (with-current-buffer
20661 (or (get-file-buffer x) (find-file-noselect x))
20662 (widen)
20663 (current-buffer)))
20664 files)
20665 regexp)))
20667 (if (boundp 'occur-mode-find-occurrence-hook)
20668 ;; Emacs 23
20669 (add-hook 'occur-mode-find-occurrence-hook
20670 (lambda ()
20671 (when (derived-mode-p 'org-mode)
20672 (org-reveal))))
20673 ;; Emacs 22
20674 (defadvice occur-mode-goto-occurrence
20675 (after org-occur-reveal activate)
20676 (and (derived-mode-p 'org-mode) (org-reveal)))
20677 (defadvice occur-mode-goto-occurrence-other-window
20678 (after org-occur-reveal activate)
20679 (and (derived-mode-p 'org-mode) (org-reveal)))
20680 (defadvice occur-mode-display-occurrence
20681 (after org-occur-reveal activate)
20682 (when (derived-mode-p 'org-mode)
20683 (let ((pos (occur-mode-find-occurrence)))
20684 (with-current-buffer (marker-buffer pos)
20685 (save-excursion
20686 (goto-char pos)
20687 (org-reveal)))))))
20689 (defun org-occur-link-in-agenda-files ()
20690 "Create a link and search for it in the agendas.
20691 The link is not stored in `org-stored-links', it is just created
20692 for the search purpose."
20693 (interactive)
20694 (let ((link (condition-case nil
20695 (org-store-link nil)
20696 (error "Unable to create a link to here"))))
20697 (org-occur-in-agenda-files (regexp-quote link))))
20699 (defun org-uniquify (list)
20700 "Remove duplicate elements from LIST."
20701 (let (res)
20702 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20703 res))
20705 (defun org-delete-all (elts list)
20706 "Remove all elements in ELTS from LIST."
20707 (while elts
20708 (setq list (delete (pop elts) list)))
20709 list)
20711 (defun org-count (cl-item cl-seq)
20712 "Count the number of occurrences of ITEM in SEQ.
20713 Taken from `count' in cl-seq.el with all keyword arguments removed."
20714 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20715 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20716 (while (< cl-start cl-end)
20717 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20718 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20719 (setq cl-start (1+ cl-start)))
20720 cl-count))
20722 (defun org-remove-if (predicate seq)
20723 "Remove everything from SEQ that fulfills PREDICATE."
20724 (let (res e)
20725 (while seq
20726 (setq e (pop seq))
20727 (if (not (funcall predicate e)) (push e res)))
20728 (nreverse res)))
20730 (defun org-remove-if-not (predicate seq)
20731 "Remove everything from SEQ that does not fulfill PREDICATE."
20732 (let (res e)
20733 (while seq
20734 (setq e (pop seq))
20735 (if (funcall predicate e) (push e res)))
20736 (nreverse res)))
20738 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20739 "Reduce two-argument FUNCTION across SEQ.
20740 Taken from `reduce' in cl-seq.el with all keyword arguments but
20741 \":initial-value\" removed."
20742 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20743 (cadr (memq :initial-value cl-keys)))
20744 (cl-seq (pop cl-seq))
20745 (t (funcall cl-func)))))
20746 (while cl-seq
20747 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20748 cl-accum))
20750 (defun org-back-over-empty-lines ()
20751 "Move backwards over whitespace, to the beginning of the first empty line.
20752 Returns the number of empty lines passed."
20753 (let ((pos (point)))
20754 (if (cdr (assoc 'heading org-blank-before-new-entry))
20755 (skip-chars-backward " \t\n\r")
20756 (unless (eobp)
20757 (forward-line -1)))
20758 (beginning-of-line 2)
20759 (goto-char (min (point) pos))
20760 (count-lines (point) pos)))
20762 (defun org-skip-whitespace ()
20763 (skip-chars-forward " \t\n\r"))
20765 (defun org-point-in-group (point group &optional context)
20766 "Check if POINT is in match-group GROUP.
20767 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20768 match. If the match group does not exist or point is not inside it,
20769 return nil."
20770 (and (match-beginning group)
20771 (>= point (match-beginning group))
20772 (<= point (match-end group))
20773 (if context
20774 (list context (match-beginning group) (match-end group))
20775 t)))
20777 (defun org-switch-to-buffer-other-window (&rest args)
20778 "Switch to buffer in a second window on the current frame.
20779 In particular, do not allow pop-up frames.
20780 Returns the newly created buffer."
20781 (let (pop-up-frames special-display-buffer-names special-display-regexps
20782 special-display-function)
20783 (apply 'switch-to-buffer-other-window args)))
20785 (defun org-combine-plists (&rest plists)
20786 "Create a single property list from all plists in PLISTS.
20787 The process starts by copying the first list, and then setting properties
20788 from the other lists. Settings in the last list are the most significant
20789 ones and overrule settings in the other lists."
20790 (let ((rtn (copy-sequence (pop plists)))
20791 p v ls)
20792 (while plists
20793 (setq ls (pop plists))
20794 (while ls
20795 (setq p (pop ls) v (pop ls))
20796 (setq rtn (plist-put rtn p v))))
20797 rtn))
20799 (defun org-replace-escapes (string table)
20800 "Replace %-escapes in STRING with values in TABLE.
20801 TABLE is an association list with keys like \"%a\" and string values.
20802 The sequences in STRING may contain normal field width and padding information,
20803 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20804 so values can contain further %-escapes if they are define later in TABLE."
20805 (let ((tbl (copy-alist table))
20806 (case-fold-search nil)
20807 (pchg 0)
20808 e re rpl)
20809 (while (setq e (pop tbl))
20810 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20811 (when (and (cdr e) (string-match re (cdr e)))
20812 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20813 (safe "SREF"))
20814 (add-text-properties 0 3 (list 'sref sref) safe)
20815 (setcdr e (replace-match safe t t (cdr e)))))
20816 (while (string-match re string)
20817 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20818 (cdr e)))
20819 (setq string (replace-match rpl t t string))))
20820 (while (setq pchg (next-property-change pchg string))
20821 (let ((sref (get-text-property pchg 'sref string)))
20822 (when (and sref (string-match "SREF" string pchg))
20823 (setq string (replace-match sref t t string)))))
20824 string))
20826 (defun org-sublist (list start end)
20827 "Return a section of LIST, from START to END.
20828 Counting starts at 1."
20829 (let (rtn (c start))
20830 (setq list (nthcdr (1- start) list))
20831 (while (and list (<= c end))
20832 (push (pop list) rtn)
20833 (setq c (1+ c)))
20834 (nreverse rtn)))
20836 (defun org-find-base-buffer-visiting (file)
20837 "Like `find-buffer-visiting' but always return the base buffer and
20838 not an indirect buffer."
20839 (let ((buf (or (get-file-buffer file)
20840 (find-buffer-visiting file))))
20841 (if buf
20842 (or (buffer-base-buffer buf) buf)
20843 nil)))
20845 (defun org-image-file-name-regexp (&optional extensions)
20846 "Return regexp matching the file names of images.
20847 If EXTENSIONS is given, only match these."
20848 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20849 (image-file-name-regexp)
20850 (let ((image-file-name-extensions
20851 (or extensions
20852 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20853 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20854 (concat "\\."
20855 (regexp-opt (nconc (mapcar 'upcase
20856 image-file-name-extensions)
20857 image-file-name-extensions)
20859 "\\'"))))
20861 (defun org-file-image-p (file &optional extensions)
20862 "Return non-nil if FILE is an image."
20863 (save-match-data
20864 (string-match (org-image-file-name-regexp extensions) file)))
20866 (defun org-get-cursor-date ()
20867 "Return the date at cursor in as a time.
20868 This works in the calendar and in the agenda, anywhere else it just
20869 returns the current time."
20870 (let (date day defd)
20871 (cond
20872 ((eq major-mode 'calendar-mode)
20873 (setq date (calendar-cursor-to-date)
20874 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20875 ((eq major-mode 'org-agenda-mode)
20876 (setq day (get-text-property (point) 'day))
20877 (if day
20878 (setq date (calendar-gregorian-from-absolute day)
20879 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20880 (nth 2 date))))))
20881 (or defd (current-time))))
20883 (defvar org-agenda-action-marker (make-marker)
20884 "Marker pointing to the entry for the next agenda action.")
20886 (defun org-mark-entry-for-agenda-action ()
20887 "Mark the current entry as target of an agenda action.
20888 Agenda actions are actions executed from the agenda with the key `k',
20889 which make use of the date at the cursor."
20890 (interactive)
20891 (move-marker org-agenda-action-marker
20892 (save-excursion (org-back-to-heading t) (point))
20893 (current-buffer))
20894 (message
20895 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20897 (defun org-mark-subtree (&optional up)
20898 "Mark the current subtree.
20899 This puts point at the start of the current subtree, and mark at
20900 the end. If a numeric prefix UP is given, move up into the
20901 hierarchy of headlines by UP levels before marking the subtree."
20902 (interactive "P")
20903 (org-with-limited-levels
20904 (cond ((org-at-heading-p) (beginning-of-line))
20905 ((org-before-first-heading-p) (error "Not in a subtree"))
20906 (t (outline-previous-visible-heading 1))))
20907 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20908 (if (org-called-interactively-p 'any)
20909 (call-interactively 'org-mark-element)
20910 (org-mark-element)))
20913 ;;; Macros
20915 ;; Macros are expanded with `org-macro-replace-all', which relies
20916 ;; internally on `org-macro-expand'.
20918 ;; Templates for expansion are stored in the buffer-local variable
20919 ;; `org-macro-templates'. This variable is updated by
20920 ;; `org-macro-initialize-templates'.
20923 (defvar org-macro-templates nil
20924 "Alist containing all macro templates in current buffer.
20925 Associations are in the shape of (NAME . TEMPLATE) where NAME
20926 stands for macro's name and template for its replacement value,
20927 both as strings. This is an internal variable. Do not set it
20928 directly, use instead:
20930 #+MACRO: name template")
20931 (make-variable-buffer-local 'org-macro-templates)
20933 (defun org-macro-expand (macro)
20934 "Return expanded MACRO, as a string.
20935 MACRO is an object, obtained, for example, with
20936 `org-element-context'. Return nil if no template was found."
20937 (let ((template
20938 (cdr (assoc-string (org-element-property :key macro)
20939 org-macro-templates
20940 ;; Macro names are case-insensitive.
20941 t))))
20942 (when template
20943 (let ((value (replace-regexp-in-string
20944 "\\$[0-9]+"
20945 (lambda (arg)
20946 (or (nth (1- (string-to-number (substring arg 1)))
20947 (org-element-property :args macro))
20948 ;; No argument provided: remove
20949 ;; place-holder.
20950 ""))
20951 template)))
20952 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20953 (when (string-match "\\`(eval\\>" value)
20954 (setq value (eval (read value))))
20955 ;; Return string.
20956 (format "%s" (or value ""))))))
20958 (defun org-macro-replace-all ()
20959 "Replace all macros in current buffer by their expansion."
20960 (save-excursion
20961 (goto-char (point-min))
20962 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20963 (let ((object (org-element-context)))
20964 (when (eq (org-element-type object) 'macro)
20965 (let ((value (org-macro-expand object)))
20966 (when value
20967 (delete-region
20968 (org-element-property :begin object)
20969 ;; Preserve white spaces after the macro.
20970 (progn (goto-char (org-element-property :end object))
20971 (skip-chars-backward " \t")
20972 (point)))
20973 ;; Leave point before replacement in case of recursive
20974 ;; expansions.
20975 (save-excursion (insert value)))))))))
20977 (defun org-macro-initialize-templates ()
20978 "Collect macro templates defined in current buffer.
20979 Templates are stored in buffer-local variable
20980 `org-macro-templates'. In addition to buffer-defined macros, the
20981 function installs the following ones: \"property\", \"date\",
20982 \"time\". and, if appropriate, \"input-file\" and
20983 \"modification-time\"."
20984 (let ((case-fold-search t)
20985 (set-template
20986 (lambda (cell)
20987 ;; Add CELL to `org-macro-templates' if there's no
20988 ;; association matching its name already. Otherwise,
20989 ;; replace old association with the new one in that
20990 ;; variable.
20991 (let ((old-template (assoc (car cell) org-macro-templates)))
20992 (if old-template (setcdr old-template (cdr cell))
20993 (push cell org-macro-templates))))))
20994 ;; Install buffer-local macros.
20995 (org-with-wide-buffer
20996 (goto-char (point-min))
20997 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20998 (let ((element (org-element-at-point)))
20999 (when (eq (org-element-type element) 'keyword)
21000 (let ((value (org-element-property :value element)))
21001 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21002 (funcall set-template
21003 (cons (match-string 1 value)
21004 (or (match-string 2 value) "")))))))))
21005 ;; Install hard-coded macros.
21006 (mapc (lambda (cell) (funcall set-template cell))
21007 (list
21008 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21009 (cons "date" "(eval (format-time-string \"$1\"))")
21010 (cons "time" "(eval (format-time-string \"$1\"))")))
21011 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21012 (when (and visited-file (file-exists-p visited-file))
21013 (mapc (lambda (cell) (funcall set-template cell))
21014 (list
21015 (cons "input-file" (file-name-nondirectory visited-file))
21016 (cons "modification-time"
21017 (format "(eval (format-time-string \"$1\" '%s))"
21018 (prin1-to-string
21019 (nth 5 (file-attributes visited-file)))))))))))
21022 ;;; Indentation
21024 (defun org-indent-line ()
21025 "Indent line depending on context."
21026 (interactive)
21027 (let* ((pos (point))
21028 (itemp (org-at-item-p))
21029 (case-fold-search t)
21030 (org-drawer-regexp (or org-drawer-regexp "\000"))
21031 (inline-task-p (and (featurep 'org-inlinetask)
21032 (org-inlinetask-in-task-p)))
21033 (inline-re (and inline-task-p
21034 (org-inlinetask-outline-regexp)))
21035 column)
21036 (if (and orgstruct-is-++ (eq pos (point)))
21037 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21038 (indent-according-to-mode))
21039 (beginning-of-line 1)
21040 (cond
21041 ;; Headings
21042 ((looking-at org-outline-regexp) (setq column 0))
21043 ;; Included files
21044 ((looking-at "#\\+include:") (setq column 0))
21045 ;; Footnote definition
21046 ((looking-at org-footnote-definition-re) (setq column 0))
21047 ;; Literal examples
21048 ((looking-at "[ \t]*:\\( \\|$\\)")
21049 (setq column (org-get-indentation))) ; do nothing
21050 ;; Lists
21051 ((ignore-errors (goto-char (org-in-item-p)))
21052 (setq column (if itemp
21053 (org-get-indentation)
21054 (org-list-item-body-column (point))))
21055 (goto-char pos))
21056 ;; Drawers
21057 ((and (looking-at "[ \t]*:END:")
21058 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21059 (save-excursion
21060 (goto-char (1- (match-beginning 1)))
21061 (setq column (current-column))))
21062 ;; Special blocks
21063 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21064 (save-excursion
21065 (re-search-backward
21066 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21067 (setq column (org-get-indentation (match-string 0))))
21068 ((and (not (looking-at "[ \t]*#\\+begin_"))
21069 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21070 (save-excursion
21071 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21072 (setq column
21073 (cond ((equal (downcase (match-string 1)) "src")
21074 ;; src blocks: let `org-edit-src-exit' handle them
21075 (org-get-indentation))
21076 ((equal (downcase (match-string 1)) "example")
21077 (max (org-get-indentation)
21078 (org-get-indentation (match-string 0))))
21080 (org-get-indentation (match-string 0))))))
21081 ;; This line has nothing special, look at the previous relevant
21082 ;; line to compute indentation
21084 (beginning-of-line 0)
21085 (while (and (not (bobp))
21086 (not (looking-at org-drawer-regexp))
21087 ;; When point started in an inline task, do not move
21088 ;; above task starting line.
21089 (not (and inline-task-p (looking-at inline-re)))
21090 ;; Skip drawers, blocks, empty lines, verbatim,
21091 ;; comments, tables, footnotes definitions, lists,
21092 ;; inline tasks.
21093 (or (and (looking-at "[ \t]*:END:")
21094 (re-search-backward org-drawer-regexp nil t))
21095 (and (looking-at "[ \t]*#\\+end_")
21096 (re-search-backward "[ \t]*#\\+begin_"nil t))
21097 (looking-at "[ \t]*[\n:#|]")
21098 (looking-at org-footnote-definition-re)
21099 (and (ignore-errors (goto-char (org-in-item-p)))
21100 (goto-char
21101 (org-list-get-top-point (org-list-struct))))
21102 (and (not inline-task-p)
21103 (featurep 'org-inlinetask)
21104 (org-inlinetask-in-task-p)
21105 (or (org-inlinetask-goto-beginning) t))))
21106 (beginning-of-line 0))
21107 (cond
21108 ;; There was an heading above.
21109 ((looking-at "\\*+[ \t]+")
21110 (if (not org-adapt-indentation)
21111 (setq column 0)
21112 (goto-char (match-end 0))
21113 (setq column (current-column))))
21114 ;; A drawer had started and is unfinished
21115 ((looking-at org-drawer-regexp)
21116 (goto-char (1- (match-beginning 1)))
21117 (setq column (current-column)))
21118 ;; Else, nothing noticeable found: get indentation and go on.
21119 (t (setq column (org-get-indentation))))))
21120 ;; Now apply indentation and move cursor accordingly
21121 (goto-char pos)
21122 (if (<= (current-column) (current-indentation))
21123 (org-indent-line-to column)
21124 (save-excursion (org-indent-line-to column)))
21125 ;; Special polishing for properties, see `org-property-format'
21126 (setq column (current-column))
21127 (beginning-of-line 1)
21128 (if (looking-at
21129 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21130 (replace-match (concat (match-string 1)
21131 (format org-property-format
21132 (match-string 2) (match-string 3)))
21133 t t))
21134 (org-move-to-column column))))
21136 (defun org-indent-drawer ()
21137 "Indent the drawer at point."
21138 (interactive)
21139 (let ((p (point))
21140 (e (and (save-excursion (re-search-forward ":END:" nil t))
21141 (match-end 0)))
21142 (folded
21143 (save-excursion
21144 (end-of-line)
21145 (when (overlays-at (point))
21146 (member 'invisible (overlay-properties
21147 (car (overlays-at (point)))))))))
21148 (when folded (org-cycle))
21149 (indent-for-tab-command)
21150 (while (and (move-beginning-of-line 2) (< (point) e))
21151 (indent-for-tab-command))
21152 (goto-char p)
21153 (when folded (org-cycle)))
21154 (message "Drawer at point indented"))
21156 (defun org-indent-block ()
21157 "Indent the block at point."
21158 (interactive)
21159 (let ((p (point))
21160 (case-fold-search t)
21161 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21162 (match-end 0)))
21163 (folded
21164 (save-excursion
21165 (end-of-line)
21166 (when (overlays-at (point))
21167 (member 'invisible (overlay-properties
21168 (car (overlays-at (point)))))))))
21169 (when folded (org-cycle))
21170 (indent-for-tab-command)
21171 (while (and (move-beginning-of-line 2) (< (point) e))
21172 (indent-for-tab-command))
21173 (goto-char p)
21174 (when folded (org-cycle)))
21175 (message "Block at point indented"))
21177 (defun org-indent-region (start end)
21178 "Indent region."
21179 (interactive "r")
21180 (save-excursion
21181 (let ((line-end (org-current-line end)))
21182 (goto-char start)
21183 (while (< (org-current-line) line-end)
21184 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21185 (t (call-interactively 'org-indent-line)))
21186 (move-beginning-of-line 2)))))
21189 ;;; Filling
21191 ;; We use our own fill-paragraph and auto-fill functions.
21193 ;; `org-fill-paragraph' relies on adaptive filling and context
21194 ;; checking. Appropriate `fill-prefix' is computed with
21195 ;; `org-adaptive-fill-function'.
21197 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21198 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21199 ;; `org-adaptive-fill-function' value. Internally,
21200 ;; `org-comment-line-break-function' breaks the line.
21202 ;; `org-setup-filling' installs filling and auto-filling related
21203 ;; variables during `org-mode' initialization.
21205 (defun org-setup-filling ()
21206 (interactive)
21207 ;; Prevent auto-fill from inserting unwanted new items.
21208 (when (boundp 'fill-nobreak-predicate)
21209 (org-set-local
21210 'fill-nobreak-predicate
21211 (org-uniquify
21212 (append fill-nobreak-predicate
21213 '(org-fill-paragraph-separate-nobreak-p
21214 org-fill-line-break-nobreak-p)))))
21215 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21216 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21217 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21218 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21220 (defvar org-element-paragraph-separate) ; org-element.el
21221 (defun org-fill-paragraph-separate-nobreak-p ()
21222 "Non-nil when a line break at point would insert a new item."
21223 (looking-at (substring org-element-paragraph-separate 1)))
21225 (defun org-fill-line-break-nobreak-p ()
21226 "Non-nil when a line break at point would create an Org line break."
21227 (save-excursion
21228 (skip-chars-backward "[ \t]")
21229 (skip-chars-backward "\\\\")
21230 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21232 (declare-function message-in-body-p "message" ())
21233 (defvar org-element--affiliated-re) ; From org-element.el
21234 (defun org-adaptive-fill-function ()
21235 "Compute a fill prefix for the current line.
21236 Return fill prefix, as a string, or nil if current line isn't
21237 meant to be filled."
21238 (org-with-wide-buffer
21239 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21240 ;; FIXME: This is really the job of orgstruct++-mode
21241 (let* ((p (line-beginning-position))
21242 (element (save-excursion (beginning-of-line)
21243 (org-element-at-point)))
21244 (type (org-element-type element))
21245 (post-affiliated
21246 (save-excursion
21247 (goto-char (org-element-property :begin element))
21248 (while (looking-at org-element--affiliated-re) (forward-line))
21249 (point))))
21250 (unless (< p post-affiliated)
21251 (case type
21252 (comment (looking-at "[ \t]*# ?") (match-string 0))
21253 (footnote-definition "")
21254 ((item plain-list)
21255 (make-string (org-list-item-body-column post-affiliated) ? ))
21256 (paragraph
21257 ;; Fill prefix is usually the same as the current line,
21258 ;; except if the paragraph is at the beginning of an item.
21259 (let ((parent (org-element-property :parent element)))
21260 (cond ((eq (org-element-type parent) 'item)
21261 (make-string (org-list-item-body-column
21262 (org-element-property :begin parent))
21263 ? ))
21264 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21265 (match-string 0))
21266 (t ""))))
21267 (comment-block
21268 ;; Only fill contents if P is within block boundaries.
21269 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21270 (forward-line)
21271 (point)))
21272 (cend (save-excursion
21273 (goto-char (org-element-property :end element))
21274 (skip-chars-backward " \r\t\n")
21275 (line-beginning-position))))
21276 (when (and (>= p cbeg) (< p cend))
21277 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21278 (match-string 0)
21279 ""))))))))))
21281 (declare-function message-goto-body "message" ())
21282 (defvar message-cite-prefix-regexp) ; From message.el
21283 (defvar org-element-all-objects) ; From org-element.el
21284 (defun org-fill-paragraph (&optional justify)
21285 "Fill element at point, when applicable.
21287 This function only applies to comment blocks, comments, example
21288 blocks and paragraphs. Also, as a special case, re-align table
21289 when point is at one.
21291 If JUSTIFY is non-nil (interactively, with prefix argument),
21292 justify as well. If `sentence-end-double-space' is non-nil, then
21293 period followed by one space does not end a sentence, so don't
21294 break a line there. The variable `fill-column' controls the
21295 width for filling.
21297 For convenience, when point is at a plain list, an item or
21298 a footnote definition, try to fill the first paragraph within."
21299 ;; Falls back on message-fill-paragraph when necessary
21300 (interactive)
21301 (if (and (derived-mode-p 'message-mode)
21302 (or (not (message-in-body-p))
21303 (save-excursion (move-beginning-of-line 1)
21304 (looking-at message-cite-prefix-regexp))))
21305 (let ((fill-paragraph-function
21306 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21307 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21308 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21309 (paragraph-separate
21310 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21311 (fill-paragraph nil))
21312 (save-excursion
21313 ;; Move to end of line in order to get the first paragraph
21314 ;; within a plain list or a footnote definition.
21315 (end-of-line)
21316 (let ((element (org-element-at-point)))
21317 ;; First check if point is in a blank line at the beginning of
21318 ;; the buffer. In that case, ignore filling.
21319 (if (< (point) (org-element-property :begin element)) t
21320 (case (org-element-type element)
21321 ;; Align Org tables, leave table.el tables as-is.
21322 (table-row (org-table-align) t)
21323 (table
21324 (when (eq (org-element-property :type element) 'org)
21325 (org-table-align))
21327 (paragraph
21328 ;; Paragraphs may contain `line-break' type objects.
21329 (let ((beg (max (point-min)
21330 (org-element-property :contents-begin element)))
21331 (end (min (point-max)
21332 (org-element-property :contents-end element))))
21333 ;; Do nothing if point is at an affiliated keyword.
21334 (if (< (point) beg) t
21335 (when (derived-mode-p 'message-mode)
21336 ;; In `message-mode', do not fill following
21337 ;; citation in current paragraph nor text before
21338 ;; message body.
21339 (let ((body-start (save-excursion (message-goto-body))))
21340 (when body-start (setq beg (max body-start beg))))
21341 (when (save-excursion
21342 (re-search-forward
21343 (concat "^" message-cite-prefix-regexp) end t))
21344 (setq end (match-beginning 0))))
21345 ;; Fill paragraph, taking line breaks into
21346 ;; consideration. For that, slice the paragraph
21347 ;; using line breaks as separators, and fill the
21348 ;; parts in reverse order to avoid messing with
21349 ;; markers.
21350 (save-excursion
21351 (goto-char end)
21352 (mapc
21353 (lambda (pos)
21354 (fill-region-as-paragraph pos (point) justify)
21355 (goto-char pos))
21356 ;; Find the list of ending positions for line
21357 ;; breaks in the current paragraph. Add paragraph
21358 ;; beginning to include first slice.
21359 (nreverse
21360 (cons
21362 (org-element-map
21363 (org-element--parse-objects
21364 beg end nil org-element-all-objects)
21365 'line-break
21366 (lambda (lb) (org-element-property :end lb)))))))
21367 t)))
21368 ;; Contents of `comment-block' type elements should be
21369 ;; filled as plain text, but only if point is within block
21370 ;; markers.
21371 (comment-block
21372 (let* ((case-fold-search t)
21373 (beg (save-excursion
21374 (goto-char (org-element-property :begin element))
21375 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21376 (forward-line)
21377 (point)))
21378 (end (save-excursion
21379 (goto-char (org-element-property :end element))
21380 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21381 (line-beginning-position))))
21382 (when (and (>= (point) beg) (< (point) end))
21383 (fill-region-as-paragraph
21384 (save-excursion
21385 (end-of-line)
21386 (re-search-backward "^[ \t]*$" beg 'move)
21387 (line-beginning-position))
21388 (save-excursion
21389 (beginning-of-line)
21390 (re-search-forward "^[ \t]*$" end 'move)
21391 (line-beginning-position))
21392 justify)))
21394 ;; Fill comments.
21395 (comment (fill-comment-paragraph justify))
21396 ;; Ignore every other element.
21397 (otherwise t)))))))
21399 (defun org-auto-fill-function ()
21400 "Auto-fill function."
21401 ;; Check if auto-filling is meaningful.
21402 (let ((fc (current-fill-column)))
21403 (when (and fc (> (current-column) fc))
21404 (let ((fill-prefix (org-adaptive-fill-function)))
21405 (when fill-prefix (do-auto-fill))))))
21407 (defun org-comment-line-break-function (&optional soft)
21408 "Break line at point and indent, continuing comment if within one.
21409 The inserted newline is marked hard if variable
21410 `use-hard-newlines' is true, unless optional argument SOFT is
21411 non-nil."
21412 (if soft (insert-and-inherit ?\n) (newline 1))
21413 (save-excursion (forward-char -1) (delete-horizontal-space))
21414 (delete-horizontal-space)
21415 (indent-to-left-margin)
21416 (insert-before-markers-and-inherit fill-prefix))
21419 ;;; Comments
21421 ;; Org comments syntax is quite complex. It requires the entire line
21422 ;; to be just a comment. Also, even with the right syntax at the
21423 ;; beginning of line, some some elements (i.e. verse-block or
21424 ;; example-block) don't accept comments. Usual Emacs comment commands
21425 ;; cannot cope with those requirements. Therefore, Org replaces them.
21427 ;; Org still relies on `comment-dwim', but cannot trust
21428 ;; `comment-only-p'. So, `comment-region-function' and
21429 ;; `uncomment-region-function' both point
21430 ;; to`org-comment-or-uncomment-region'. Eventually,
21431 ;; `org-insert-comment' takes care of insertion of comments at the
21432 ;; beginning of line.
21434 ;; `org-setup-comments-handling' install comments related variables
21435 ;; during `org-mode' initialization.
21437 (defun org-setup-comments-handling ()
21438 (interactive)
21439 (org-set-local 'comment-use-syntax nil)
21440 (org-set-local 'comment-start "# ")
21441 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21442 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21443 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21444 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21446 (defun org-insert-comment ()
21447 "Insert an empty comment above current line.
21448 If the line is empty, insert comment at its beginning."
21449 (beginning-of-line)
21450 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21451 (org-indent-line)
21452 (insert "# "))
21454 (defvar comment-empty-lines) ; From newcomment.el.
21455 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21456 "Comment or uncomment each non-blank line in the region.
21457 Uncomment each non-blank line between BEG and END if it only
21458 contains commented lines. Otherwise, comment them."
21459 (save-restriction
21460 ;; Restrict region
21461 (narrow-to-region (save-excursion (goto-char beg)
21462 (skip-chars-forward " \r\t\n" end)
21463 (line-beginning-position))
21464 (save-excursion (goto-char end)
21465 (skip-chars-backward " \r\t\n" beg)
21466 (line-end-position)))
21467 (let ((uncommentp
21468 ;; UNCOMMENTP is non-nil when every non blank line between
21469 ;; BEG and END is a comment.
21470 (save-excursion
21471 (goto-char (point-min))
21472 (while (and (not (eobp))
21473 (let ((element (org-element-at-point)))
21474 (and (eq (org-element-type element) 'comment)
21475 (goto-char (min (point-max)
21476 (org-element-property
21477 :end element)))))))
21478 (eobp))))
21479 (if uncommentp
21480 ;; Only blank lines and comments in region: uncomment it.
21481 (save-excursion
21482 (goto-char (point-min))
21483 (while (not (eobp))
21484 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21485 (replace-match "" nil nil nil 1))
21486 (forward-line)))
21487 ;; Comment each line in region.
21488 (let ((min-indent (point-max)))
21489 ;; First find the minimum indentation across all lines.
21490 (save-excursion
21491 (goto-char (point-min))
21492 (while (and (not (eobp)) (not (zerop min-indent)))
21493 (unless (looking-at "[ \t]*$")
21494 (setq min-indent (min min-indent (current-indentation))))
21495 (forward-line)))
21496 ;; Then loop over all lines.
21497 (save-excursion
21498 (goto-char (point-min))
21499 (while (not (eobp))
21500 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21501 (org-move-to-column min-indent t)
21502 (insert comment-start))
21503 (forward-line))))))))
21506 ;;; Other stuff.
21508 (defun org-toggle-fixed-width-section (arg)
21509 "Toggle the fixed-width export.
21510 If there is no active region, the QUOTE keyword at the current headline is
21511 inserted or removed. When present, it causes the text between this headline
21512 and the next to be exported as fixed-width text, and unmodified.
21513 If there is an active region, this command adds or removes a colon as the
21514 first character of this line. If the first character of a line is a colon,
21515 this line is also exported in fixed-width font."
21516 (interactive "P")
21517 (let* ((cc 0)
21518 (regionp (org-region-active-p))
21519 (beg (if regionp (region-beginning) (point)))
21520 (end (if regionp (region-end)))
21521 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21522 (case-fold-search nil)
21523 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21524 off)
21525 (if regionp
21526 (save-excursion
21527 (goto-char beg)
21528 (setq cc (current-column))
21529 (beginning-of-line 1)
21530 (setq off (looking-at re))
21531 (while (> nlines 0)
21532 (setq nlines (1- nlines))
21533 (beginning-of-line 1)
21534 (cond
21535 (arg
21536 (org-move-to-column cc t)
21537 (insert ": \n")
21538 (forward-line -1))
21539 ((and off (looking-at re))
21540 (replace-match "" t t nil 1))
21541 ((not off) (org-move-to-column cc t) (insert ": ")))
21542 (forward-line 1)))
21543 (save-excursion
21544 (org-back-to-heading)
21545 (cond
21546 ((looking-at (format org-heading-keyword-regexp-format
21547 org-quote-string))
21548 (goto-char (match-end 1))
21549 (looking-at (concat " +" org-quote-string))
21550 (replace-match "" t t)
21551 (when (eolp) (insert " ")))
21552 ((looking-at org-outline-regexp)
21553 (goto-char (match-end 0))
21554 (insert org-quote-string " ")))))))
21556 (defun org-reftex-citation ()
21557 "Use reftex-citation to insert a citation into the buffer.
21558 This looks for a line like
21560 #+BIBLIOGRAPHY: foo plain option:-d
21562 and derives from it that foo.bib is the bibliography file relevant
21563 for this document. It then installs the necessary environment for RefTeX
21564 to work in this buffer and calls `reftex-citation' to insert a citation
21565 into the buffer.
21567 Export of such citations to both LaTeX and HTML is handled by the contributed
21568 package org-exp-bibtex by Taru Karttunen."
21569 (interactive)
21570 (let ((reftex-docstruct-symbol 'rds)
21571 (reftex-cite-format "\\cite{%l}")
21572 rds bib)
21573 (save-excursion
21574 (save-restriction
21575 (widen)
21576 (let ((case-fold-search t)
21577 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21578 (if (not (save-excursion
21579 (or (re-search-forward re nil t)
21580 (re-search-backward re nil t))))
21581 (error "No bibliography defined in file")
21582 (setq bib (concat (match-string 1) ".bib")
21583 rds (list (list 'bib bib)))))))
21584 (call-interactively 'reftex-citation)))
21586 ;;;; Functions extending outline functionality
21588 (defun org-beginning-of-line (&optional arg)
21589 "Go to the beginning of the current line. If that is invisible, continue
21590 to a visible line beginning. This makes the function of C-a more intuitive.
21591 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21592 first attempt, and only move to after the tags when the cursor is already
21593 beyond the end of the headline."
21594 (interactive "P")
21595 (let ((pos (point))
21596 (special (if (consp org-special-ctrl-a/e)
21597 (car org-special-ctrl-a/e)
21598 org-special-ctrl-a/e))
21599 refpos)
21600 (if (org-bound-and-true-p line-move-visual)
21601 (beginning-of-visual-line 1)
21602 (beginning-of-line 1))
21603 (if (and arg (fboundp 'move-beginning-of-line))
21604 (call-interactively 'move-beginning-of-line)
21605 (if (bobp)
21607 (backward-char 1)
21608 (if (org-truely-invisible-p)
21609 (while (and (not (bobp)) (org-truely-invisible-p))
21610 (backward-char 1)
21611 (beginning-of-line 1))
21612 (forward-char 1))))
21613 (when special
21614 (cond
21615 ((and (looking-at org-complex-heading-regexp)
21616 (= (char-after (match-end 1)) ?\ ))
21617 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21618 (point-at-eol)))
21619 (goto-char
21620 (if (eq special t)
21621 (cond ((> pos refpos) refpos)
21622 ((= pos (point)) refpos)
21623 (t (point)))
21624 (cond ((> pos (point)) (point))
21625 ((not (eq last-command this-command)) (point))
21626 (t refpos)))))
21627 ((org-at-item-p)
21628 ;; Being at an item and not looking at an the item means point
21629 ;; was previously moved to beginning of a visual line, which
21630 ;; doesn't contain the item. Therefore, do nothing special,
21631 ;; just stay here.
21632 (when (looking-at org-list-full-item-re)
21633 ;; Set special position at first white space character after
21634 ;; bullet, and check-box, if any.
21635 (let ((after-bullet
21636 (let ((box (match-end 3)))
21637 (if (not box) (match-end 1)
21638 (let ((after (char-after box)))
21639 (if (and after (= after ? )) (1+ box) box))))))
21640 ;; Special case: Move point to special position when
21641 ;; currently after it or at beginning of line.
21642 (if (eq special t)
21643 (when (or (> pos after-bullet) (= (point) pos))
21644 (goto-char after-bullet))
21645 ;; Reversed case: Move point to special position when
21646 ;; point was already at beginning of line and command is
21647 ;; repeated.
21648 (when (and (= (point) pos) (eq last-command this-command))
21649 (goto-char after-bullet))))))))
21650 (org-no-warnings
21651 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21653 (defun org-end-of-line (&optional arg)
21654 "Go to the end of the line.
21655 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21656 first attempt, and only move to after the tags when the cursor is already
21657 beyond the end of the headline."
21658 (interactive "P")
21659 (let ((special (if (consp org-special-ctrl-a/e)
21660 (cdr org-special-ctrl-a/e)
21661 org-special-ctrl-a/e)))
21662 (cond
21663 ((or (not special) arg
21664 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21665 (call-interactively
21666 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21667 ((fboundp 'move-end-of-line) 'move-end-of-line)
21668 (t 'end-of-line))))
21669 ((org-at-heading-p)
21670 (let ((pos (point)))
21671 (beginning-of-line 1)
21672 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21673 (if (eq special t)
21674 (if (or (< pos (match-beginning 1))
21675 (= pos (match-end 0)))
21676 (goto-char (match-beginning 1))
21677 (goto-char (match-end 0)))
21678 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21679 (goto-char (match-end 0))
21680 (goto-char (match-beginning 1))))
21681 (call-interactively (if (fboundp 'move-end-of-line)
21682 'move-end-of-line
21683 'end-of-line)))))
21684 ((org-at-drawer-p)
21685 (move-end-of-line 1)
21686 (when (overlays-at (1- (point))) (backward-char 1)))
21687 ;; At an item: Move before any hidden text.
21688 (t (call-interactively
21689 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21690 ((fboundp 'move-end-of-line) 'move-end-of-line)
21691 (t 'end-of-line)))))
21692 (org-no-warnings
21693 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21695 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21696 (define-key org-mode-map "\C-e" 'org-end-of-line)
21698 (defun org-backward-sentence (&optional arg)
21699 "Go to beginning of sentence, or beginning of table field.
21700 This will call `backward-sentence' or `org-table-beginning-of-field',
21701 depending on context."
21702 (interactive "P")
21703 (cond
21704 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21705 (t (call-interactively 'backward-sentence))))
21707 (defun org-forward-sentence (&optional arg)
21708 "Go to end of sentence, or end of table field.
21709 This will call `forward-sentence' or `org-table-end-of-field',
21710 depending on context."
21711 (interactive "P")
21712 (cond
21713 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21714 (t (call-interactively 'forward-sentence))))
21716 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21717 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21719 (defun org-kill-line (&optional arg)
21720 "Kill line, to tags or end of line."
21721 (interactive "P")
21722 (cond
21723 ((or (not org-special-ctrl-k)
21724 (bolp)
21725 (not (org-at-heading-p)))
21726 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21727 org-ctrl-k-protect-subtree)
21728 (if (or (eq org-ctrl-k-protect-subtree 'error)
21729 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21730 (error "C-k aborted - would kill hidden subtree")))
21731 (call-interactively
21732 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21733 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21734 (kill-region (point) (match-beginning 1))
21735 (org-set-tags nil t))
21736 (t (kill-region (point) (point-at-eol)))))
21738 (define-key org-mode-map "\C-k" 'org-kill-line)
21740 (defun org-yank (&optional arg)
21741 "Yank. If the kill is a subtree, treat it specially.
21742 This command will look at the current kill and check if is a single
21743 subtree, or a series of subtrees[1]. If it passes the test, and if the
21744 cursor is at the beginning of a line or after the stars of a currently
21745 empty headline, then the yank is handled specially. How exactly depends
21746 on the value of the following variables, both set by default.
21748 org-yank-folded-subtrees
21749 When set, the subtree(s) will be folded after insertion, but only
21750 if doing so would now swallow text after the yanked text.
21752 org-yank-adjusted-subtrees
21753 When set, the subtree will be promoted or demoted in order to
21754 fit into the local outline tree structure, which means that the level
21755 will be adjusted so that it becomes the smaller one of the two
21756 *visible* surrounding headings.
21758 Any prefix to this command will cause `yank' to be called directly with
21759 no special treatment. In particular, a simple \\[universal-argument] prefix \
21760 will just
21761 plainly yank the text as it is.
21763 \[1] The test checks if the first non-white line is a heading
21764 and if there are no other headings with fewer stars."
21765 (interactive "P")
21766 (org-yank-generic 'yank arg))
21768 (defun org-yank-generic (command arg)
21769 "Perform some yank-like command.
21771 This function implements the behavior described in the `org-yank'
21772 documentation. However, it has been generalized to work for any
21773 interactive command with similar behavior."
21775 ;; pretend to be command COMMAND
21776 (setq this-command command)
21778 (if arg
21779 (call-interactively command)
21781 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21782 (and (org-kill-is-subtree-p)
21783 (or (bolp)
21784 (and (looking-at "[ \t]*$")
21785 (string-match
21786 "\\`\\*+\\'"
21787 (buffer-substring (point-at-bol) (point)))))))
21788 swallowp)
21789 (cond
21790 ((and subtreep org-yank-folded-subtrees)
21791 (let ((beg (point))
21792 end)
21793 (if (and subtreep org-yank-adjusted-subtrees)
21794 (org-paste-subtree nil nil 'for-yank)
21795 (call-interactively command))
21797 (setq end (point))
21798 (goto-char beg)
21799 (when (and (bolp) subtreep
21800 (not (setq swallowp
21801 (org-yank-folding-would-swallow-text beg end))))
21802 (org-with-limited-levels
21803 (or (looking-at org-outline-regexp)
21804 (re-search-forward org-outline-regexp-bol end t))
21805 (while (and (< (point) end) (looking-at org-outline-regexp))
21806 (hide-subtree)
21807 (org-cycle-show-empty-lines 'folded)
21808 (condition-case nil
21809 (outline-forward-same-level 1)
21810 (error (goto-char end))))))
21811 (when swallowp
21812 (message
21813 "Inserted text not folded because that would swallow text"))
21815 (goto-char end)
21816 (skip-chars-forward " \t\n\r")
21817 (beginning-of-line 1)
21818 (push-mark beg 'nomsg)))
21819 ((and subtreep org-yank-adjusted-subtrees)
21820 (let ((beg (point-at-bol)))
21821 (org-paste-subtree nil nil 'for-yank)
21822 (push-mark beg 'nomsg)))
21824 (call-interactively command))))))
21826 (defun org-yank-folding-would-swallow-text (beg end)
21827 "Would hide-subtree at BEG swallow any text after END?"
21828 (let (level)
21829 (org-with-limited-levels
21830 (save-excursion
21831 (goto-char beg)
21832 (when (or (looking-at org-outline-regexp)
21833 (re-search-forward org-outline-regexp-bol end t))
21834 (setq level (org-outline-level)))
21835 (goto-char end)
21836 (skip-chars-forward " \t\r\n\v\f")
21837 (if (or (eobp)
21838 (and (bolp) (looking-at org-outline-regexp)
21839 (<= (org-outline-level) level)))
21840 nil ; Nothing would be swallowed
21841 t))))) ; something would swallow
21843 (define-key org-mode-map "\C-y" 'org-yank)
21845 (defun org-truely-invisible-p ()
21846 "Check if point is at a character currently not visible.
21847 This version does not only check the character property, but also
21848 `visible-mode'."
21849 ;; Early versions of noutline don't have `outline-invisible-p'.
21850 (if (org-bound-and-true-p visible-mode)
21852 (outline-invisible-p)))
21854 (defun org-invisible-p2 ()
21855 "Check if point is at a character currently not visible."
21856 (save-excursion
21857 (if (and (eolp) (not (bobp))) (backward-char 1))
21858 ;; Early versions of noutline don't have `outline-invisible-p'.
21859 (outline-invisible-p)))
21861 (defun org-back-to-heading (&optional invisible-ok)
21862 "Call `outline-back-to-heading', but provide a better error message."
21863 (condition-case nil
21864 (outline-back-to-heading invisible-ok)
21865 (error (error "Before first headline at position %d in buffer %s"
21866 (point) (current-buffer)))))
21868 (defun org-before-first-heading-p ()
21869 "Before first heading?"
21870 (save-excursion
21871 (end-of-line)
21872 (null (re-search-backward org-outline-regexp-bol nil t))))
21874 (defun org-at-heading-p (&optional ignored)
21875 (outline-on-heading-p t))
21876 ;; Compatibility alias with Org versions < 7.8.03
21877 (defalias 'org-on-heading-p 'org-at-heading-p)
21879 (defun org-at-comment-p nil
21880 "Is cursor in a line starting with a # character?"
21881 (save-excursion
21882 (beginning-of-line)
21883 (looking-at "^#")))
21885 (defun org-at-drawer-p nil
21886 "Is cursor at a drawer keyword?"
21887 (save-excursion
21888 (move-beginning-of-line 1)
21889 (looking-at org-drawer-regexp)))
21891 (defun org-at-block-p nil
21892 "Is cursor at a block keyword?"
21893 (save-excursion
21894 (move-beginning-of-line 1)
21895 (looking-at org-block-regexp)))
21897 (defun org-point-at-end-of-empty-headline ()
21898 "If point is at the end of an empty headline, return t, else nil.
21899 If the heading only contains a TODO keyword, it is still still considered
21900 empty."
21901 (and (looking-at "[ \t]*$")
21902 (when org-todo-line-regexp
21903 (save-excursion
21904 (beginning-of-line 1)
21905 (let ((case-fold-search nil))
21906 (looking-at org-todo-line-regexp)
21907 (string= (match-string 3) ""))))))
21909 (defun org-at-heading-or-item-p ()
21910 (or (org-at-heading-p) (org-at-item-p)))
21912 (defun org-at-target-p ()
21913 (or (org-in-regexp org-radio-target-regexp)
21914 (org-in-regexp org-target-regexp)))
21915 ;; Compatibility alias with Org versions < 7.8.03
21916 (defalias 'org-on-target-p 'org-at-target-p)
21918 (defun org-up-heading-all (arg)
21919 "Move to the heading line of which the present line is a subheading.
21920 This function considers both visible and invisible heading lines.
21921 With argument, move up ARG levels."
21922 (if (fboundp 'outline-up-heading-all)
21923 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21924 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21926 (defun org-up-heading-safe ()
21927 "Move to the heading line of which the present line is a subheading.
21928 This version will not throw an error. It will return the level of the
21929 headline found, or nil if no higher level is found.
21931 Also, this function will be a lot faster than `outline-up-heading',
21932 because it relies on stars being the outline starters. This can really
21933 make a significant difference in outlines with very many siblings."
21934 (let (start-level re)
21935 (org-back-to-heading t)
21936 (setq start-level (funcall outline-level))
21937 (if (equal start-level 1)
21939 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21940 (if (re-search-backward re nil t)
21941 (funcall outline-level)))))
21943 (defun org-first-sibling-p ()
21944 "Is this heading the first child of its parents?"
21945 (interactive)
21946 (let ((re org-outline-regexp-bol)
21947 level l)
21948 (unless (org-at-heading-p t)
21949 (error "Not at a heading"))
21950 (setq level (funcall outline-level))
21951 (save-excursion
21952 (if (not (re-search-backward re nil t))
21954 (setq l (funcall outline-level))
21955 (< l level)))))
21957 (defun org-goto-sibling (&optional previous)
21958 "Goto the next sibling, even if it is invisible.
21959 When PREVIOUS is set, go to the previous sibling instead. Returns t
21960 when a sibling was found. When none is found, return nil and don't
21961 move point."
21962 (let ((fun (if previous 're-search-backward 're-search-forward))
21963 (pos (point))
21964 (re org-outline-regexp-bol)
21965 level l)
21966 (when (condition-case nil (org-back-to-heading t) (error nil))
21967 (setq level (funcall outline-level))
21968 (catch 'exit
21969 (or previous (forward-char 1))
21970 (while (funcall fun re nil t)
21971 (setq l (funcall outline-level))
21972 (when (< l level) (goto-char pos) (throw 'exit nil))
21973 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21974 (goto-char pos)
21975 nil))))
21977 (defun org-show-siblings ()
21978 "Show all siblings of the current headline."
21979 (save-excursion
21980 (while (org-goto-sibling) (org-flag-heading nil)))
21981 (save-excursion
21982 (while (org-goto-sibling 'previous)
21983 (org-flag-heading nil))))
21985 (defun org-goto-first-child ()
21986 "Goto the first child, even if it is invisible.
21987 Return t when a child was found. Otherwise don't move point and
21988 return nil."
21989 (let (level (pos (point)) (re org-outline-regexp-bol))
21990 (when (condition-case nil (org-back-to-heading t) (error nil))
21991 (setq level (outline-level))
21992 (forward-char 1)
21993 (if (and (re-search-forward re nil t) (> (outline-level) level))
21994 (progn (goto-char (match-beginning 0)) t)
21995 (goto-char pos) nil))))
21997 (defun org-show-hidden-entry ()
21998 "Show an entry where even the heading is hidden."
21999 (save-excursion
22000 (org-show-entry)))
22002 (defun org-flag-heading (flag &optional entry)
22003 "Flag the current heading. FLAG non-nil means make invisible.
22004 When ENTRY is non-nil, show the entire entry."
22005 (save-excursion
22006 (org-back-to-heading t)
22007 ;; Check if we should show the entire entry
22008 (if entry
22009 (progn
22010 (org-show-entry)
22011 (save-excursion
22012 (and (outline-next-heading)
22013 (org-flag-heading nil))))
22014 (outline-flag-region (max (point-min) (1- (point)))
22015 (save-excursion (outline-end-of-heading) (point))
22016 flag))))
22018 (defun org-get-next-sibling ()
22019 "Move to next heading of the same level, and return point.
22020 If there is no such heading, return nil.
22021 This is like outline-next-sibling, but invisible headings are ok."
22022 (let ((level (funcall outline-level)))
22023 (outline-next-heading)
22024 (while (and (not (eobp)) (> (funcall outline-level) level))
22025 (outline-next-heading))
22026 (if (or (eobp) (< (funcall outline-level) level))
22028 (point))))
22030 (defun org-get-last-sibling ()
22031 "Move to previous heading of the same level, and return point.
22032 If there is no such heading, return nil."
22033 (let ((opoint (point))
22034 (level (funcall outline-level)))
22035 (outline-previous-heading)
22036 (when (and (/= (point) opoint) (outline-on-heading-p t))
22037 (while (and (> (funcall outline-level) level)
22038 (not (bobp)))
22039 (outline-previous-heading))
22040 (if (< (funcall outline-level) level)
22042 (point)))))
22044 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22045 "Goto to the end of a subtree."
22046 ;; This contains an exact copy of the original function, but it uses
22047 ;; `org-back-to-heading', to make it work also in invisible
22048 ;; trees. And is uses an invisible-ok argument.
22049 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22050 ;; Furthermore, when used inside Org, finding the end of a large subtree
22051 ;; with many children and grandchildren etc, this can be much faster
22052 ;; than the outline version.
22053 (org-back-to-heading invisible-ok)
22054 (let ((first t)
22055 (level (funcall outline-level)))
22056 (if (and (derived-mode-p 'org-mode) (< level 1000))
22057 ;; A true heading (not a plain list item), in Org-mode
22058 ;; This means we can easily find the end by looking
22059 ;; only for the right number of stars. Using a regexp to do
22060 ;; this is so much faster than using a Lisp loop.
22061 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22062 (forward-char 1)
22063 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22064 ;; something else, do it the slow way
22065 (while (and (not (eobp))
22066 (or first (> (funcall outline-level) level)))
22067 (setq first nil)
22068 (outline-next-heading)))
22069 (unless to-heading
22070 (if (memq (preceding-char) '(?\n ?\^M))
22071 (progn
22072 ;; Go to end of line before heading
22073 (forward-char -1)
22074 (if (memq (preceding-char) '(?\n ?\^M))
22075 ;; leave blank line before heading
22076 (forward-char -1))))))
22077 (point))
22079 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22080 "Use Org version in org-mode, for dramatic speed-up."
22081 (if (derived-mode-p 'org-mode)
22082 (progn
22083 (org-end-of-subtree nil t)
22084 (unless (eobp) (backward-char 1)))
22085 ad-do-it))
22087 (defun org-end-of-meta-data-and-drawers ()
22088 "Jump to the first text after meta data and drawers in the current entry.
22089 This will move over empty lines, lines with planning time stamps,
22090 clocking lines, and drawers."
22091 (org-back-to-heading t)
22092 (let ((end (save-excursion (outline-next-heading) (point)))
22093 (re (concat "\\(" org-drawer-regexp "\\)"
22094 "\\|" "[ \t]*" org-keyword-time-regexp)))
22095 (forward-line 1)
22096 (while (re-search-forward re end t)
22097 (if (not (match-end 1))
22098 ;; empty or planning line
22099 (forward-line 1)
22100 ;; a drawer, find the end
22101 (re-search-forward "^[ \t]*:END:" end 'move)
22102 (forward-line 1)))
22103 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22104 (point)))
22106 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22107 "Move forward to the arg'th subheading at same level as this one.
22108 Stop at the first and last subheadings of a superior heading.
22109 Normally this only looks at visible headings, but when INVISIBLE-OK is
22110 non-nil it will also look at invisible ones."
22111 (interactive "p")
22112 (org-back-to-heading invisible-ok)
22113 (org-at-heading-p)
22114 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22115 (re (format "^\\*\\{1,%d\\} " level))
22117 (forward-char 1)
22118 (while (> arg 0)
22119 (while (and (re-search-forward re nil 'move)
22120 (setq l (- (match-end 0) (match-beginning 0) 1))
22121 (= l level)
22122 (not invisible-ok)
22123 (progn (backward-char 1) (outline-invisible-p)))
22124 (if (< l level) (setq arg 1)))
22125 (setq arg (1- arg)))
22126 (beginning-of-line 1)))
22128 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22129 "Move backward to the arg'th subheading at same level as this one.
22130 Stop at the first and last subheadings of a superior heading."
22131 (interactive "p")
22132 (org-back-to-heading)
22133 (org-at-heading-p)
22134 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22135 (re (format "^\\*\\{1,%d\\} " level))
22137 (while (> arg 0)
22138 (while (and (re-search-backward re nil 'move)
22139 (setq l (- (match-end 0) (match-beginning 0) 1))
22140 (= l level)
22141 (not invisible-ok)
22142 (outline-invisible-p))
22143 (if (< l level) (setq arg 1)))
22144 (setq arg (1- arg)))))
22146 ;;;###autoload
22147 (defun org-forward-element ()
22148 "Move forward by one element.
22149 Move to the next element at the same level, when possible."
22150 (interactive)
22151 (cond ((eobp) (error "Cannot move further down"))
22152 ((org-with-limited-levels (org-at-heading-p))
22153 (let ((origin (point)))
22154 (org-forward-heading-same-level 1)
22155 (unless (org-with-limited-levels (org-at-heading-p))
22156 (goto-char origin)
22157 (error "Cannot move further down"))))
22159 (let* ((elem (org-element-at-point))
22160 (end (org-element-property :end elem))
22161 (parent (org-element-property :parent elem)))
22162 (if (and parent (= (org-element-property :contents-end parent) end))
22163 (goto-char (org-element-property :end parent))
22164 (goto-char end))))))
22166 ;;;###autoload
22167 (defun org-backward-element ()
22168 "Move backward by one element.
22169 Move to the previous element at the same level, when possible."
22170 (interactive)
22171 (cond ((bobp) (error "Cannot move further up"))
22172 ((org-with-limited-levels (org-at-heading-p))
22173 ;; At an headline, move to the previous one, if any, or stay
22174 ;; here.
22175 (let ((origin (point)))
22176 (org-backward-heading-same-level 1)
22177 (unless (org-with-limited-levels (org-at-heading-p))
22178 (goto-char origin)
22179 (error "Cannot move further up"))))
22181 (let* ((trail (org-element-at-point 'keep-trail))
22182 (elem (car trail))
22183 (prev-elem (nth 1 trail))
22184 (beg (org-element-property :begin elem)))
22185 (cond
22186 ;; Move to beginning of current element if point isn't
22187 ;; there already.
22188 ((/= (point) beg) (goto-char beg))
22189 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22190 ((org-before-first-heading-p) (goto-char (point-min)))
22191 (t (org-back-to-heading)))))))
22193 ;;;###autoload
22194 (defun org-up-element ()
22195 "Move to upper element."
22196 (interactive)
22197 (if (org-with-limited-levels (org-at-heading-p))
22198 (unless (org-up-heading-safe) (error "No surrounding element"))
22199 (let* ((elem (org-element-at-point))
22200 (parent (org-element-property :parent elem)))
22201 (if parent (goto-char (org-element-property :begin parent))
22202 (if (org-with-limited-levels (org-before-first-heading-p))
22203 (error "No surrounding element")
22204 (org-with-limited-levels (org-back-to-heading)))))))
22206 ;;;###autoload
22207 (defvar org-element-greater-elements)
22208 (defun org-down-element ()
22209 "Move to inner element."
22210 (interactive)
22211 (let ((element (org-element-at-point)))
22212 (cond
22213 ((memq (org-element-type element) '(plain-list table))
22214 (goto-char (org-element-property :contents-begin element))
22215 (forward-char))
22216 ((memq (org-element-type element) org-element-greater-elements)
22217 ;; If contents are hidden, first disclose them.
22218 (when (org-element-property :hiddenp element) (org-cycle))
22219 (goto-char (or (org-element-property :contents-begin element)
22220 (error "No content for this element"))))
22221 (t (error "No inner element")))))
22223 ;;;###autoload
22224 (defun org-drag-element-backward ()
22225 "Move backward element at point."
22226 (interactive)
22227 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22228 (let* ((trail (org-element-at-point 'keep-trail))
22229 (elem (car trail))
22230 (prev-elem (nth 1 trail)))
22231 ;; Error out if no previous element or previous element is
22232 ;; a parent of the current one.
22233 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22234 (error "Cannot drag element backward")
22235 (let ((pos (point)))
22236 (org-element-swap-A-B prev-elem elem)
22237 (goto-char (+ (org-element-property :begin prev-elem)
22238 (- pos (org-element-property :begin elem)))))))))
22240 ;;;###autoload
22241 (defun org-drag-element-forward ()
22242 "Move forward element at point."
22243 (interactive)
22244 (let* ((pos (point))
22245 (elem (org-element-at-point)))
22246 (when (= (point-max) (org-element-property :end elem))
22247 (error "Cannot drag element forward"))
22248 (goto-char (org-element-property :end elem))
22249 (let ((next-elem (org-element-at-point)))
22250 (when (or (org-element-nested-p elem next-elem)
22251 (and (eq (org-element-type next-elem) 'headline)
22252 (not (eq (org-element-type elem) 'headline))))
22253 (goto-char pos)
22254 (error "Cannot drag element forward"))
22255 ;; Compute new position of point: it's shifted by NEXT-ELEM
22256 ;; body's length (without final blanks) and by the length of
22257 ;; blanks between ELEM and NEXT-ELEM.
22258 (let ((size-next (- (save-excursion
22259 (goto-char (org-element-property :end next-elem))
22260 (skip-chars-backward " \r\t\n")
22261 (forward-line)
22262 ;; Small correction if buffer doesn't end
22263 ;; with a newline character.
22264 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22265 (org-element-property :begin next-elem)))
22266 (size-blank (- (org-element-property :end elem)
22267 (save-excursion
22268 (goto-char (org-element-property :end elem))
22269 (skip-chars-backward " \r\t\n")
22270 (forward-line)
22271 (point)))))
22272 (org-element-swap-A-B elem next-elem)
22273 (goto-char (+ pos size-next size-blank))))))
22275 ;;;###autoload
22276 (defun org-mark-element ()
22277 "Put point at beginning of this element, mark at end.
22279 Interactively, if this command is repeated or (in Transient Mark
22280 mode) if the mark is active, it marks the next element after the
22281 ones already marked."
22282 (interactive)
22283 (let (deactivate-mark)
22284 (if (and (org-called-interactively-p 'any)
22285 (or (and (eq last-command this-command) (mark t))
22286 (and transient-mark-mode mark-active)))
22287 (set-mark
22288 (save-excursion
22289 (goto-char (mark))
22290 (goto-char (org-element-property :end (org-element-at-point)))))
22291 (let ((element (org-element-at-point)))
22292 (end-of-line)
22293 (push-mark (org-element-property :end element) t t)
22294 (goto-char (org-element-property :begin element))))))
22296 ;;;###autoload
22297 (defun org-narrow-to-element ()
22298 "Narrow buffer to current element."
22299 (interactive)
22300 (let ((elem (org-element-at-point)))
22301 (cond
22302 ((eq (car elem) 'headline)
22303 (narrow-to-region
22304 (org-element-property :begin elem)
22305 (org-element-property :end elem)))
22306 ((memq (car elem) org-element-greater-elements)
22307 (narrow-to-region
22308 (org-element-property :contents-begin elem)
22309 (org-element-property :contents-end elem)))
22311 (narrow-to-region
22312 (org-element-property :begin elem)
22313 (org-element-property :end elem))))))
22315 ;;;###autoload
22316 (defun org-transpose-element ()
22317 "Transpose current and previous elements, keeping blank lines between.
22318 Point is moved after both elements."
22319 (interactive)
22320 (org-skip-whitespace)
22321 (let ((end (org-element-property :end (org-element-at-point))))
22322 (org-drag-element-backward)
22323 (goto-char end)))
22325 ;;;###autoload
22326 (defun org-unindent-buffer ()
22327 "Un-indent the visible part of the buffer.
22328 Relative indentation (between items, inside blocks, etc.) isn't
22329 modified."
22330 (interactive)
22331 (unless (eq major-mode 'org-mode)
22332 (error "Cannot un-indent a buffer not in Org mode"))
22333 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22334 unindent-tree ; For byte-compiler.
22335 (unindent-tree
22336 (function
22337 (lambda (contents)
22338 (mapc
22339 (lambda (element)
22340 (if (memq (org-element-type element) '(headline section))
22341 (funcall unindent-tree (org-element-contents element))
22342 (save-excursion
22343 (save-restriction
22344 (narrow-to-region
22345 (org-element-property :begin element)
22346 (org-element-property :end element))
22347 (org-do-remove-indentation)))))
22348 (reverse contents))))))
22349 (funcall unindent-tree (org-element-contents parse-tree))))
22351 (defun org-show-subtree ()
22352 "Show everything after this heading at deeper levels."
22353 (interactive)
22354 (outline-flag-region
22355 (point)
22356 (save-excursion
22357 (org-end-of-subtree t t))
22358 nil))
22360 (defun org-show-entry ()
22361 "Show the body directly following this heading.
22362 Show the heading too, if it is currently invisible."
22363 (interactive)
22364 (save-excursion
22365 (condition-case nil
22366 (progn
22367 (org-back-to-heading t)
22368 (outline-flag-region
22369 (max (point-min) (1- (point)))
22370 (save-excursion
22371 (if (re-search-forward
22372 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22373 (match-beginning 1)
22374 (point-max)))
22375 nil)
22376 (org-cycle-hide-drawers 'children))
22377 (error nil))))
22379 (defun org-make-options-regexp (kwds &optional extra)
22380 "Make a regular expression for keyword lines."
22381 (concat
22382 "^#\\+\\("
22383 (mapconcat 'regexp-quote kwds "\\|")
22384 (if extra (concat "\\|" extra))
22385 "\\):[ \t]*\\(.*\\)"))
22387 ;; Make isearch reveal the necessary context
22388 (defun org-isearch-end ()
22389 "Reveal context after isearch exits."
22390 (when isearch-success ; only if search was successful
22391 (if (featurep 'xemacs)
22392 ;; Under XEmacs, the hook is run in the correct place,
22393 ;; we directly show the context.
22394 (org-show-context 'isearch)
22395 ;; In Emacs the hook runs *before* restoring the overlays.
22396 ;; So we have to use a one-time post-command-hook to do this.
22397 ;; (Emacs 22 has a special variable, see function `org-mode')
22398 (unless (and (boundp 'isearch-mode-end-hook-quit)
22399 isearch-mode-end-hook-quit)
22400 ;; Only when the isearch was not quitted.
22401 (org-add-hook 'post-command-hook 'org-isearch-post-command
22402 'append 'local)))))
22404 (defun org-isearch-post-command ()
22405 "Remove self from hook, and show context."
22406 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22407 (org-show-context 'isearch))
22410 ;;;; Integration with and fixes for other packages
22412 ;;; Imenu support
22414 (defvar org-imenu-markers nil
22415 "All markers currently used by Imenu.")
22416 (make-variable-buffer-local 'org-imenu-markers)
22418 (defun org-imenu-new-marker (&optional pos)
22419 "Return a new marker for use by Imenu, and remember the marker."
22420 (let ((m (make-marker)))
22421 (move-marker m (or pos (point)))
22422 (push m org-imenu-markers)
22425 (defun org-imenu-get-tree ()
22426 "Produce the index for Imenu."
22427 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22428 (setq org-imenu-markers nil)
22429 (let* ((n org-imenu-depth)
22430 (re (concat "^" (org-get-limited-outline-regexp)))
22431 (subs (make-vector (1+ n) nil))
22432 (last-level 0)
22433 m level head)
22434 (save-excursion
22435 (save-restriction
22436 (widen)
22437 (goto-char (point-max))
22438 (while (re-search-backward re nil t)
22439 (setq level (org-reduced-level (funcall outline-level)))
22440 (when (and (<= level n)
22441 (looking-at org-complex-heading-regexp))
22442 (setq head (org-link-display-format
22443 (org-match-string-no-properties 4))
22444 m (org-imenu-new-marker))
22445 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22446 (if (>= level last-level)
22447 (push (cons head m) (aref subs level))
22448 (push (cons head (aref subs (1+ level))) (aref subs level))
22449 (loop for i from (1+ level) to n do (aset subs i nil)))
22450 (setq last-level level)))))
22451 (aref subs 1)))
22453 (eval-after-load "imenu"
22454 '(progn
22455 (add-hook 'imenu-after-jump-hook
22456 (lambda ()
22457 (if (derived-mode-p 'org-mode)
22458 (org-show-context 'org-goto))))))
22460 (defun org-link-display-format (link)
22461 "Replace a link with either the description, or the link target
22462 if no description is present"
22463 (save-match-data
22464 (if (string-match org-bracket-link-analytic-regexp link)
22465 (replace-match (if (match-end 5)
22466 (match-string 5 link)
22467 (concat (match-string 1 link)
22468 (match-string 3 link)))
22469 nil t link)
22470 link)))
22472 (defun org-toggle-link-display ()
22473 "Toggle the literal or descriptive display of links."
22474 (interactive)
22475 (if org-descriptive-links
22476 (progn (org-remove-from-invisibility-spec '(org-link))
22477 (org-restart-font-lock)
22478 (setq org-descriptive-links nil))
22479 (progn (add-to-invisibility-spec '(org-link))
22480 (org-restart-font-lock)
22481 (setq org-descriptive-links t))))
22483 ;; Speedbar support
22485 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22486 "Overlay marking the agenda restriction line in speedbar.")
22487 (overlay-put org-speedbar-restriction-lock-overlay
22488 'face 'org-agenda-restriction-lock)
22489 (overlay-put org-speedbar-restriction-lock-overlay
22490 'help-echo "Agendas are currently limited to this item.")
22491 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22493 (defun org-speedbar-set-agenda-restriction ()
22494 "Restrict future agenda commands to the location at point in speedbar.
22495 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22496 (interactive)
22497 (require 'org-agenda)
22498 (let (p m tp np dir txt)
22499 (cond
22500 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22501 'org-imenu t))
22502 (setq m (get-text-property p 'org-imenu-marker))
22503 (with-current-buffer (marker-buffer m)
22504 (goto-char m)
22505 (org-agenda-set-restriction-lock 'subtree)))
22506 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22507 'speedbar-function 'speedbar-find-file))
22508 (setq tp (previous-single-property-change
22509 (1+ p) 'speedbar-function)
22510 np (next-single-property-change
22511 tp 'speedbar-function)
22512 dir (speedbar-line-directory)
22513 txt (buffer-substring-no-properties (or tp (point-min))
22514 (or np (point-max))))
22515 (with-current-buffer (find-file-noselect
22516 (let ((default-directory dir))
22517 (expand-file-name txt)))
22518 (unless (derived-mode-p 'org-mode)
22519 (error "Cannot restrict to non-Org-mode file"))
22520 (org-agenda-set-restriction-lock 'file)))
22521 (t (error "Don't know how to restrict Org-mode's agenda")))
22522 (move-overlay org-speedbar-restriction-lock-overlay
22523 (point-at-bol) (point-at-eol))
22524 (setq current-prefix-arg nil)
22525 (org-agenda-maybe-redo)))
22527 (eval-after-load "speedbar"
22528 '(progn
22529 (speedbar-add-supported-extension ".org")
22530 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22531 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22532 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22533 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22534 (add-hook 'speedbar-visiting-tag-hook
22535 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22537 ;;; Fixes and Hacks for problems with other packages
22539 ;; Make flyspell not check words in links, to not mess up our keymap
22540 (defun org-mode-flyspell-verify ()
22541 "Don't let flyspell put overlays at active buttons, or on
22542 {todo,all-time,additional-option-like}-keywords."
22543 (let ((pos (max (1- (point)) (point-min)))
22544 (word (thing-at-point 'word)))
22545 (and (not (get-text-property pos 'keymap))
22546 (not (get-text-property pos 'org-no-flyspell))
22547 (not (member word org-todo-keywords-1))
22548 (not (member word org-all-time-keywords))
22549 (not (member word org-options-keywords))
22550 (not (member word (mapcar 'car org-startup-options)))
22551 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22553 (defun org-remove-flyspell-overlays-in (beg end)
22554 "Remove flyspell overlays in region."
22555 (and (org-bound-and-true-p flyspell-mode)
22556 (fboundp 'flyspell-delete-region-overlays)
22557 (flyspell-delete-region-overlays beg end))
22558 (add-text-properties beg end '(org-no-flyspell t)))
22560 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22561 (eval-after-load "bookmark"
22562 '(if (boundp 'bookmark-after-jump-hook)
22563 ;; We can use the hook
22564 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22565 ;; Hook not available, use advice
22566 (defadvice bookmark-jump (after org-make-visible activate)
22567 "Make the position visible."
22568 (org-bookmark-jump-unhide))))
22570 ;; Make sure saveplace shows the location if it was hidden
22571 (eval-after-load "saveplace"
22572 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22573 "Make the position visible."
22574 (org-bookmark-jump-unhide)))
22576 ;; Make sure ecb shows the location if it was hidden
22577 (eval-after-load "ecb"
22578 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22579 "Make hierarchy visible when jumping into location from ECB tree buffer."
22580 (if (derived-mode-p 'org-mode)
22581 (org-show-context))))
22583 (defun org-bookmark-jump-unhide ()
22584 "Unhide the current position, to show the bookmark location."
22585 (and (derived-mode-p 'org-mode)
22586 (or (outline-invisible-p)
22587 (save-excursion (goto-char (max (point-min) (1- (point))))
22588 (outline-invisible-p)))
22589 (org-show-context 'bookmark-jump)))
22591 ;; Make session.el ignore our circular variable
22592 (eval-after-load "session"
22593 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22595 ;;;; Experimental code
22597 (defun org-closed-in-range ()
22598 "Sparse tree of items closed in a certain time range.
22599 Still experimental, may disappear in the future."
22600 (interactive)
22601 ;; Get the time interval from the user.
22602 (let* ((time1 (org-float-time
22603 (org-read-date nil 'to-time nil "Starting date: ")))
22604 (time2 (org-float-time
22605 (org-read-date nil 'to-time nil "End date:")))
22606 ;; callback function
22607 (callback (lambda ()
22608 (let ((time
22609 (org-float-time
22610 (apply 'encode-time
22611 (org-parse-time-string
22612 (match-string 1))))))
22613 ;; check if time in interval
22614 (and (>= time time1) (<= time time2))))))
22615 ;; make tree, check each match with the callback
22616 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22618 ;;;; Finish up
22620 (provide 'org)
22622 (run-hooks 'org-load-hook)
22624 ;;; org.el ends here