org.el: Fix bug in ̀org-fontify-meta-lines-and-blocks-1'
[org-mode.git] / lisp / org.el
blob33dc8d756b6413e86fd853da2aa567269a77394c
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-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :version "24.1"
151 :type '(alist :tag "Babel Languages"
152 :key-type
153 (choice
154 (const :tag "Awk" awk)
155 (const :tag "C" C)
156 (const :tag "R" R)
157 (const :tag "Asymptote" asymptote)
158 (const :tag "Calc" calc)
159 (const :tag "Clojure" clojure)
160 (const :tag "CSS" css)
161 (const :tag "Ditaa" ditaa)
162 (const :tag "Dot" dot)
163 (const :tag "Emacs Lisp" emacs-lisp)
164 (const :tag "Fortran" fortran)
165 (const :tag "Gnuplot" gnuplot)
166 (const :tag "Haskell" haskell)
167 (const :tag "IO" io)
168 (const :tag "Java" java)
169 (const :tag "Javascript" js)
170 (const :tag "LaTeX" latex)
171 (const :tag "Ledger" ledger)
172 (const :tag "Lilypond" lilypond)
173 (const :tag "Lisp" lisp)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "Pico Lisp" picolisp)
182 (const :tag "PlantUML" plantuml)
183 (const :tag "Python" python)
184 (const :tag "Ruby" ruby)
185 (const :tag "Sass" sass)
186 (const :tag "Scala" scala)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :version "24.1"
203 :group 'org-id)
205 ;;; Version
206 (require 'org-compat)
207 (org-check-version)
208 ;;;###autoload
209 (defun org-version (&optional here full message)
210 "Show the org-mode version in the echo area.
211 With prefix argument HERE, insert it at point.
212 When FULL is non-nil, use a verbose version string.
213 When MESSAGE is non-nil, display a message with the version."
214 (interactive "P")
215 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
216 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
217 (org-trash (or
218 (and (fboundp 'org-release) (fboundp 'org-git-version))
219 (load (concat org-dir "org-version.el")
220 'noerror 'nomessage 'nosuffix)))
221 (org-version (org-release))
222 (git-version (org-git-version))
223 (version (format "Org-mode version %s (%s @ %s)"
224 org-version
225 git-version
226 (if org-install-dir
227 (if (string= org-dir org-install-dir)
228 org-install-dir
229 (concat "mixed installation! " org-install-dir " and " org-dir))
230 "org-install.el can not be found!")))
231 (_version (if full version org-version)))
232 (if (org-called-interactively-p 'interactive)
233 (if here
234 (insert version)
235 (message version))
236 (if message (message _version))
237 _version)))
239 ;;; Compatibility constants
241 ;;; The custom variables
243 (defgroup org nil
244 "Outline-based notes management and organizer."
245 :tag "Org"
246 :group 'outlines
247 :group 'calendar)
249 (defcustom org-mode-hook nil
250 "Mode hook for Org-mode, run after the mode was turned on."
251 :group 'org
252 :type 'hook)
254 (defcustom org-load-hook nil
255 "Hook that is run after org.el has been loaded."
256 :group 'org
257 :type 'hook)
259 (defcustom org-log-buffer-setup-hook nil
260 "Hook that is run after an Org log buffer is created."
261 :group 'org
262 :version "24.1"
263 :type 'hook)
265 (defvar org-modules) ; defined below
266 (defvar org-modules-loaded nil
267 "Have the modules been loaded already?")
269 (defun org-load-modules-maybe (&optional force)
270 "Load all extensions listed in `org-modules'."
271 (when (or force (not org-modules-loaded))
272 (mapc (lambda (ext)
273 (condition-case nil (require ext)
274 (error (message "Problems while trying to load feature `%s'" ext))))
275 org-modules)
276 (setq org-modules-loaded t)))
278 (defun org-set-modules (var value)
279 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
280 (set var value)
281 (when (featurep 'org)
282 (org-load-modules-maybe 'force)))
284 (when (org-bound-and-true-p org-modules)
285 (let ((a (member 'org-infojs org-modules)))
286 (and a (setcar a 'org-jsinfo))))
288 (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)
289 "Modules that should always be loaded together with org.el.
290 If a description starts with <C>, the file is not part of Emacs
291 and loading it will require that you have downloaded and properly installed
292 the org-mode distribution.
294 You can also use this system to load external packages (i.e. neither Org
295 core modules, nor modules from the CONTRIB directory). Just add symbols
296 to the end of the list. If the package is called org-xyz.el, then you need
297 to add the symbol `xyz', and the package must have a call to
299 (provide 'org-xyz)"
300 :group 'org
301 :set 'org-set-modules
302 :type
303 '(set :greedy t
304 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
305 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
306 (const :tag " crypt: Encryption of subtrees" org-crypt)
307 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
308 (const :tag " docview: Links to doc-view buffers" org-docview)
309 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
310 (const :tag " id: Global IDs for identifying entries" org-id)
311 (const :tag " info: Links to Info nodes" org-info)
312 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
313 (const :tag " habit: Track your consistency with habits" org-habit)
314 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
315 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
316 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
317 (const :tag " mew Links to Mew folders/messages" org-mew)
318 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
319 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
320 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
321 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
322 (const :tag " vm: Links to VM folders/messages" org-vm)
323 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
324 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
325 (const :tag " mouse: Additional mouse support" org-mouse)
326 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
328 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
329 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
330 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
331 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
332 (const :tag "C collector: Collect properties into tables" org-collector)
333 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
334 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
335 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
336 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
337 (const :tag "C eval: Include command output as text" org-eval)
338 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
339 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
340 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
341 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
342 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
344 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
346 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
347 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
348 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
349 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
350 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
351 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
352 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
353 (const :tag "C mtags: Support for muse-like tags" org-mtags)
354 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
355 (const :tag "C registry: A registry for Org-mode links" org-registry)
356 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
357 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
358 (const :tag "C secretary: Team management with org-mode" org-secretary)
359 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
360 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
361 (const :tag "C track: Keep up with Org-mode development" org-track)
362 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
363 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
364 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
366 (defcustom org-support-shift-select nil
367 "Non-nil means make shift-cursor commands select text when possible.
369 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
370 start selecting a region, or enlarge regions started in this way.
371 In Org-mode, in special contexts, these same keys are used for
372 other purposes, important enough to compete with shift selection.
373 Org tries to balance these needs by supporting `shift-select-mode'
374 outside these special contexts, under control of this variable.
376 The default of this variable is nil, to avoid confusing behavior. Shifted
377 cursor keys will then execute Org commands in the following contexts:
378 - on a headline, changing TODO state (left/right) and priority (up/down)
379 - on a time stamp, changing the time
380 - in a plain list item, changing the bullet type
381 - in a property definition line, switching between allowed values
382 - in the BEGIN line of a clock table (changing the time block).
383 Outside these contexts, the commands will throw an error.
385 When this variable is t and the cursor is not in a special
386 context, Org-mode will support shift-selection for making and
387 enlarging regions. To make this more effective, the bullet
388 cycling will no longer happen anywhere in an item line, but only
389 if the cursor is exactly on the bullet.
391 If you set this variable to the symbol `always', then the keys
392 will not be special in headlines, property lines, and item lines,
393 to make shift selection work there as well. If this is what you
394 want, you can use the following alternative commands: `C-c C-t'
395 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
396 can be used to switch TODO sets, `C-c -' to cycle item bullet
397 types, and properties can be edited by hand or in column view.
399 However, when the cursor is on a timestamp, shift-cursor commands
400 will still edit the time stamp - this is just too good to give up.
402 XEmacs user should have this variable set to nil, because
403 `shift-select-mode' is in Emacs 23 or later only."
404 :group 'org
405 :type '(choice
406 (const :tag "Never" nil)
407 (const :tag "When outside special context" t)
408 (const :tag "Everywhere except timestamps" always)))
410 (defcustom org-loop-over-headlines-in-active-region nil
411 "Shall some commands act upon headlines in the active region?
413 When set to `t', some commands will be performed in all headlines
414 within the active region.
416 When set to `start-level', some commands will be performed in all
417 headlines within the active region, provided that these headlines
418 are of the same level than the first one.
420 When set to a string, those commands will be performed on the
421 matching headlines within the active region. Such string must be
422 a tags/property/todo match as it is used in the agenda tags view.
424 The list of commands is: `org-schedule', `org-deadline',
425 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
426 `org-archive-to-archive-sibling'. The archiving commands skip
427 already archived entries."
428 :type '(choice (const :tag "Don't loop" nil)
429 (const :tag "All headlines in active region" t)
430 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
431 (string :tag "Tags/Property/Todo matcher"))
432 :version "24.1"
433 :group 'org-todo
434 :group 'org-archive)
436 (defgroup org-startup nil
437 "Options concerning startup of Org-mode."
438 :tag "Org Startup"
439 :group 'org)
441 (defcustom org-startup-folded t
442 "Non-nil means entering Org-mode will switch to OVERVIEW.
443 This can also be configured on a per-file basis by adding one of
444 the following lines anywhere in the buffer:
446 #+STARTUP: fold (or `overview', this is equivalent)
447 #+STARTUP: nofold (or `showall', this is equivalent)
448 #+STARTUP: content
449 #+STARTUP: showeverything"
450 :group 'org-startup
451 :type '(choice
452 (const :tag "nofold: show all" nil)
453 (const :tag "fold: overview" t)
454 (const :tag "content: all headlines" content)
455 (const :tag "show everything, even drawers" showeverything)))
457 (defcustom org-startup-truncated t
458 "Non-nil means entering Org-mode will set `truncate-lines'.
459 This is useful since some lines containing links can be very long and
460 uninteresting. Also tables look terrible when wrapped."
461 :group 'org-startup
462 :type 'boolean)
464 (defcustom org-startup-indented nil
465 "Non-nil means turn on `org-indent-mode' on startup.
466 This can also be configured on a per-file basis by adding one of
467 the following lines anywhere in the buffer:
469 #+STARTUP: indent
470 #+STARTUP: noindent"
471 :group 'org-structure
472 :type '(choice
473 (const :tag "Not" nil)
474 (const :tag "Globally (slow on startup in large files)" t)))
476 (defcustom org-use-sub-superscripts t
477 "Non-nil means interpret \"_\" and \"^\" for export.
478 When this option is turned on, you can use TeX-like syntax for sub- and
479 superscripts. Several characters after \"_\" or \"^\" will be
480 considered as a single item - so grouping with {} is normally not
481 needed. For example, the following things will be parsed as single
482 sub- or superscripts.
484 10^24 or 10^tau several digits will be considered 1 item.
485 10^-12 or 10^-tau a leading sign with digits or a word
486 x^2-y^3 will be read as x^2 - y^3, because items are
487 terminated by almost any nonword/nondigit char.
488 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
490 Still, ambiguity is possible - so when in doubt use {} to enclose the
491 sub/superscript. If you set this variable to the symbol `{}',
492 the braces are *required* in order to trigger interpretations as
493 sub/superscript. This can be helpful in documents that need \"_\"
494 frequently in plain text.
496 Not all export backends support this, but HTML does.
498 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
499 :group 'org-startup
500 :group 'org-export-translation
501 :version "24.1"
502 :type '(choice
503 (const :tag "Always interpret" t)
504 (const :tag "Only with braces" {})
505 (const :tag "Never interpret" nil)))
507 (if (fboundp 'defvaralias)
508 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
511 (defcustom org-startup-with-beamer-mode nil
512 "Non-nil means turn on `org-beamer-mode' on startup.
513 This can also be configured on a per-file basis by adding one of
514 the following lines anywhere in the buffer:
516 #+STARTUP: beamer"
517 :group 'org-startup
518 :version "24.1"
519 :type 'boolean)
521 (defcustom org-startup-align-all-tables nil
522 "Non-nil means align all tables when visiting a file.
523 This is useful when the column width in tables is forced with <N> cookies
524 in table fields. Such tables will look correct only after the first re-align.
525 This can also be configured on a per-file basis by adding one of
526 the following lines anywhere in the buffer:
527 #+STARTUP: align
528 #+STARTUP: noalign"
529 :group 'org-startup
530 :type 'boolean)
532 (defcustom org-startup-with-inline-images nil
533 "Non-nil means show inline images when loading a new Org file.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
536 #+STARTUP: inlineimages
537 #+STARTUP: noinlineimages"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-insert-mode-line-in-empty-file nil
543 "Non-nil means insert the first line setting Org-mode in empty files.
544 When the function `org-mode' is called interactively in an empty file, this
545 normally means that the file name does not automatically trigger Org-mode.
546 To ensure that the file will always be in Org-mode in the future, a
547 line enforcing Org-mode will be inserted into the buffer, if this option
548 has been set."
549 :group 'org-startup
550 :type 'boolean)
552 (defcustom org-replace-disputed-keys nil
553 "Non-nil means use alternative key bindings for some keys.
554 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
555 These keys are also used by other packages like shift-selection-mode'
556 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
557 If you want to use Org-mode together with one of these other modes,
558 or more generally if you would like to move some Org-mode commands to
559 other keys, set this variable and configure the keys with the variable
560 `org-disputed-keys'.
562 This option is only relevant at load-time of Org-mode, and must be set
563 *before* org.el is loaded. Changing it requires a restart of Emacs to
564 become effective."
565 :group 'org-startup
566 :type 'boolean)
568 (defcustom org-use-extra-keys nil
569 "Non-nil means use extra key sequence definitions for certain commands.
570 This happens automatically if you run XEmacs or if `window-system'
571 is nil. This variable lets you do the same manually. You must
572 set it before loading org.
574 Example: on Carbon Emacs 22 running graphically, with an external
575 keyboard on a Powerbook, the default way of setting M-left might
576 not work for either Alt or ESC. Setting this variable will make
577 it work for ESC."
578 :group 'org-startup
579 :type 'boolean)
581 (if (fboundp 'defvaralias)
582 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
584 (defcustom org-disputed-keys
585 '(([(shift up)] . [(meta p)])
586 ([(shift down)] . [(meta n)])
587 ([(shift left)] . [(meta -)])
588 ([(shift right)] . [(meta +)])
589 ([(control shift right)] . [(meta shift +)])
590 ([(control shift left)] . [(meta shift -)]))
591 "Keys for which Org-mode and other modes compete.
592 This is an alist, cars are the default keys, second element specifies
593 the alternative to use when `org-replace-disputed-keys' is t.
595 Keys can be specified in any syntax supported by `define-key'.
596 The value of this option takes effect only at Org-mode's startup,
597 therefore you'll have to restart Emacs to apply it after changing."
598 :group 'org-startup
599 :type 'alist)
601 (defun org-key (key)
602 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
603 Or return the original if not disputed.
604 Also apply the translations defined in `org-xemacs-key-equivalents'."
605 (when org-replace-disputed-keys
606 (let* ((nkey (key-description key))
607 (x (org-find-if (lambda (x)
608 (equal (key-description (car x)) nkey))
609 org-disputed-keys)))
610 (setq key (if x (cdr x) key))))
611 (when (featurep 'xemacs)
612 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
613 key)
615 (defun org-find-if (predicate seq)
616 (catch 'exit
617 (while seq
618 (if (funcall predicate (car seq))
619 (throw 'exit (car seq))
620 (pop seq)))))
622 (defun org-defkey (keymap key def)
623 "Define a key, possibly translated, as returned by `org-key'."
624 (define-key keymap (org-key key) def))
626 (defcustom org-ellipsis nil
627 "The ellipsis to use in the Org-mode outline.
628 When nil, just use the standard three dots. When a string, use that instead,
629 When a face, use the standard 3 dots, but with the specified face.
630 The change affects only Org-mode (which will then use its own display table).
631 Changing this requires executing `M-x org-mode' in a buffer to become
632 effective."
633 :group 'org-startup
634 :type '(choice (const :tag "Default" nil)
635 (face :tag "Face" :value org-warning)
636 (string :tag "String" :value "...#")))
638 (defvar org-display-table nil
639 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
641 (defgroup org-keywords nil
642 "Keywords in Org-mode."
643 :tag "Org Keywords"
644 :group 'org)
646 (defcustom org-deadline-string "DEADLINE:"
647 "String to mark deadline entries.
648 A deadline is this string, followed by a time stamp. Should be a word,
649 terminated by a colon. You can insert a schedule keyword and
650 a timestamp with \\[org-deadline].
651 Changes become only effective after restarting Emacs."
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-scheduled-string "SCHEDULED:"
656 "String to mark scheduled TODO entries.
657 A schedule is this string, followed by a time stamp. Should be a word,
658 terminated by a colon. You can insert a schedule keyword and
659 a timestamp with \\[org-schedule].
660 Changes become only effective after restarting Emacs."
661 :group 'org-keywords
662 :type 'string)
664 (defcustom org-closed-string "CLOSED:"
665 "String used as the prefix for timestamps logging closing a TODO entry."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-clock-string "CLOCK:"
670 "String used as prefix for timestamps clocking work hours on an item."
671 :group 'org-keywords
672 :type 'string)
674 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
675 org-scheduled-string "\\|"
676 org-deadline-string "\\|"
677 org-closed-string "\\|"
678 org-clock-string "\\)")
679 "Matches a line with planning or clock info.")
681 (defcustom org-comment-string "COMMENT"
682 "Entries starting with this keyword will never be exported.
683 An entry can be toggled between COMMENT and normal with
684 \\[org-toggle-comment].
685 Changes become only effective after restarting Emacs."
686 :group 'org-keywords
687 :type 'string)
689 (defcustom org-quote-string "QUOTE"
690 "Entries starting with this keyword will be exported in fixed-width font.
691 Quoting applies only to the text in the entry following the headline, and does
692 not extend beyond the next headline, even if that is lower level.
693 An entry can be toggled between QUOTE and normal with
694 \\[org-toggle-fixed-width-section]."
695 :group 'org-keywords
696 :type 'string)
698 (defconst org-repeat-re
699 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
700 "Regular expression for specifying repeated events.
701 After a match, group 1 contains the repeat expression.")
703 (defgroup org-structure nil
704 "Options concerning the general structure of Org-mode files."
705 :tag "Org Structure"
706 :group 'org)
708 (defgroup org-reveal-location nil
709 "Options about how to make context of a location visible."
710 :tag "Org Reveal Location"
711 :group 'org-structure)
713 (defconst org-context-choice
714 '(choice
715 (const :tag "Always" t)
716 (const :tag "Never" nil)
717 (repeat :greedy t :tag "Individual contexts"
718 (cons
719 (choice :tag "Context"
720 (const agenda)
721 (const org-goto)
722 (const occur-tree)
723 (const tags-tree)
724 (const link-search)
725 (const mark-goto)
726 (const bookmark-jump)
727 (const isearch)
728 (const default))
729 (boolean))))
730 "Contexts for the reveal options.")
732 (defcustom org-show-hierarchy-above '((default . t))
733 "Non-nil means show full hierarchy when revealing a location.
734 Org-mode often shows locations in an org-mode file which might have
735 been invisible before. When this is set, the hierarchy of headings
736 above the exposed location is shown.
737 Turning this off for example for sparse trees makes them very compact.
738 Instead of t, this can also be an alist specifying this option for different
739 contexts. Valid contexts are
740 agenda when exposing an entry from the agenda
741 org-goto when using the command `org-goto' on key C-c C-j
742 occur-tree when using the command `org-occur' on key C-c /
743 tags-tree when constructing a sparse tree based on tags matches
744 link-search when exposing search matches associated with a link
745 mark-goto when exposing the jump goal of a mark
746 bookmark-jump when exposing a bookmark location
747 isearch when exiting from an incremental search
748 default default for all contexts not set explicitly"
749 :group 'org-reveal-location
750 :type org-context-choice)
752 (defcustom org-show-following-heading '((default . nil))
753 "Non-nil means show following heading when revealing a location.
754 Org-mode often shows locations in an org-mode file which might have
755 been invisible before. When this is set, the heading following the
756 match is shown.
757 Turning this off for example for sparse trees makes them very compact,
758 but makes it harder to edit the location of the match. In such a case,
759 use the command \\[org-reveal] to show more context.
760 Instead of t, this can also be an alist specifying this option for different
761 contexts. See `org-show-hierarchy-above' for valid contexts."
762 :group 'org-reveal-location
763 :type org-context-choice)
765 (defcustom org-show-siblings '((default . nil) (isearch t))
766 "Non-nil means show all sibling heading when revealing a location.
767 Org-mode often shows locations in an org-mode file which might have
768 been invisible before. When this is set, the sibling of the current entry
769 heading are all made visible. If `org-show-hierarchy-above' is t,
770 the same happens on each level of the hierarchy above the current entry.
772 By default this is on for the isearch context, off for all other contexts.
773 Turning this off for example for sparse trees makes them very compact,
774 but makes it harder to edit the location of the match. In such a case,
775 use the command \\[org-reveal] to show more context.
776 Instead of t, this can also be an alist specifying this option for different
777 contexts. See `org-show-hierarchy-above' for valid contexts."
778 :group 'org-reveal-location
779 :type org-context-choice)
781 (defcustom org-show-entry-below '((default . nil))
782 "Non-nil means show the entry below a headline when revealing a location.
783 Org-mode often shows locations in an org-mode file which might have
784 been invisible before. When this is set, the text below the headline that is
785 exposed is also shown.
787 By default this is off for all contexts.
788 Instead of t, this can also be an alist specifying this option for different
789 contexts. See `org-show-hierarchy-above' for valid contexts."
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-indirect-buffer-display 'other-window
794 "How should indirect tree buffers be displayed?
795 This applies to indirect buffers created with the commands
796 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
797 Valid values are:
798 current-window Display in the current window
799 other-window Just display in another window.
800 dedicated-frame Create one new frame, and re-use it each time.
801 new-frame Make a new frame each time. Note that in this case
802 previously-made indirect buffers are kept, and you need to
803 kill these buffers yourself."
804 :group 'org-structure
805 :group 'org-agenda-windows
806 :type '(choice
807 (const :tag "In current window" current-window)
808 (const :tag "In current frame, other window" other-window)
809 (const :tag "Each time a new frame" new-frame)
810 (const :tag "One dedicated frame" dedicated-frame)))
812 (defcustom org-use-speed-commands nil
813 "Non-nil means activate single letter commands at beginning of a headline.
814 This may also be a function to test for appropriate locations where speed
815 commands should be active."
816 :group 'org-structure
817 :type '(choice
818 (const :tag "Never" nil)
819 (const :tag "At beginning of headline stars" t)
820 (function)))
822 (defcustom org-speed-commands-user nil
823 "Alist of additional speed commands.
824 This list will be checked before `org-speed-commands-default'
825 when the variable `org-use-speed-commands' is non-nil
826 and when the cursor is at the beginning of a headline.
827 The car if each entry is a string with a single letter, which must
828 be assigned to `self-insert-command' in the global map.
829 The cdr is either a command to be called interactively, a function
830 to be called, or a form to be evaluated.
831 An entry that is just a list with a single string will be interpreted
832 as a descriptive headline that will be added when listing the speed
833 commands in the Help buffer using the `?' speed command."
834 :group 'org-structure
835 :type '(repeat :value ("k" . ignore)
836 (choice :value ("k" . ignore)
837 (list :tag "Descriptive Headline" (string :tag "Headline"))
838 (cons :tag "Letter and Command"
839 (string :tag "Command letter")
840 (choice
841 (function)
842 (sexp))))))
844 (defgroup org-cycle nil
845 "Options concerning visibility cycling in Org-mode."
846 :tag "Org Cycle"
847 :group 'org-structure)
849 (defcustom org-cycle-skip-children-state-if-no-children t
850 "Non-nil means skip CHILDREN state in entries that don't have any."
851 :group 'org-cycle
852 :type 'boolean)
854 (defcustom org-cycle-max-level nil
855 "Maximum level which should still be subject to visibility cycling.
856 Levels higher than this will, for cycling, be treated as text, not a headline.
857 When `org-odd-levels-only' is set, a value of N in this variable actually
858 means 2N-1 stars as the limiting headline.
859 When nil, cycle all levels.
860 Note that the limiting level of cycling is also influenced by
861 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
862 `org-inlinetask-min-level' is, cycling will be limited to levels one less
863 than its value."
864 :group 'org-cycle
865 :type '(choice
866 (const :tag "No limit" nil)
867 (integer :tag "Maximum level")))
869 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
870 "Names of drawers. Drawers are not opened by cycling on the headline above.
871 Drawers only open with a TAB on the drawer line itself. A drawer looks like
872 this:
873 :DRAWERNAME:
874 .....
875 :END:
876 The drawer \"PROPERTIES\" is special for capturing properties through
877 the property API.
879 Drawers can be defined on the per-file basis with a line like:
881 #+DRAWERS: HIDDEN STATE PROPERTIES"
882 :group 'org-structure
883 :group 'org-cycle
884 :type '(repeat (string :tag "Drawer Name")))
886 (defcustom org-hide-block-startup nil
887 "Non-nil means entering Org-mode will fold all blocks.
888 This can also be set in on a per-file basis with
890 #+STARTUP: hideblocks
891 #+STARTUP: showblocks"
892 :group 'org-startup
893 :group 'org-cycle
894 :type 'boolean)
896 (defcustom org-cycle-global-at-bob nil
897 "Cycle globally if cursor is at beginning of buffer and not at a headline.
898 This makes it possible to do global cycling without having to use S-TAB or
899 \\[universal-argument] TAB. For this special case to work, the first line \
900 of the buffer
901 must not be a headline - it may be empty or some other text. When used in
902 this way, `org-cycle-hook' is disables temporarily, to make sure the
903 cursor stays at the beginning of the buffer.
904 When this option is nil, don't do anything special at the beginning
905 of the buffer."
906 :group 'org-cycle
907 :type 'boolean)
909 (defcustom org-cycle-level-after-item/entry-creation t
910 "Non-nil means cycle entry level or item indentation in new empty entries.
912 When the cursor is at the end of an empty headline, i.e with only stars
913 and maybe a TODO keyword, TAB will then switch the entry to become a child,
914 and then all possible ancestor states, before returning to the original state.
915 This makes data entry extremely fast: M-RET to create a new headline,
916 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
918 When the cursor is at the end of an empty plain list item, one TAB will
919 make it a subitem, two or more tabs will back up to make this an item
920 higher up in the item hierarchy."
921 :group 'org-cycle
922 :type 'boolean)
924 (defcustom org-cycle-emulate-tab t
925 "Where should `org-cycle' emulate TAB.
926 nil Never
927 white Only in completely white lines
928 whitestart Only at the beginning of lines, before the first non-white char
929 t Everywhere except in headlines
930 exc-hl-bol Everywhere except at the start of a headline
931 If TAB is used in a place where it does not emulate TAB, the current subtree
932 visibility is cycled."
933 :group 'org-cycle
934 :type '(choice (const :tag "Never" nil)
935 (const :tag "Only in completely white lines" white)
936 (const :tag "Before first char in a line" whitestart)
937 (const :tag "Everywhere except in headlines" t)
938 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
941 (defcustom org-cycle-separator-lines 2
942 "Number of empty lines needed to keep an empty line between collapsed trees.
943 If you leave an empty line between the end of a subtree and the following
944 headline, this empty line is hidden when the subtree is folded.
945 Org-mode will leave (exactly) one empty line visible if the number of
946 empty lines is equal or larger to the number given in this variable.
947 So the default 2 means at least 2 empty lines after the end of a subtree
948 are needed to produce free space between a collapsed subtree and the
949 following headline.
951 If the number is negative, and the number of empty lines is at least -N,
952 all empty lines are shown.
954 Special case: when 0, never leave empty lines in collapsed view."
955 :group 'org-cycle
956 :type 'integer)
957 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
959 (defcustom org-pre-cycle-hook nil
960 "Hook that is run before visibility cycling is happening.
961 The function(s) in this hook must accept a single argument which indicates
962 the new state that will be set right after running this hook. The
963 argument is a symbol. Before a global state change, it can have the values
964 `overview', `content', or `all'. Before a local state change, it can have
965 the values `folded', `children', or `subtree'."
966 :group 'org-cycle
967 :type 'hook)
969 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
970 org-cycle-hide-drawers
971 org-cycle-show-empty-lines
972 org-optimize-window-after-visibility-change)
973 "Hook that is run after `org-cycle' has changed the buffer visibility.
974 The function(s) in this hook must accept a single argument which indicates
975 the new state that was set by the most recent `org-cycle' command. The
976 argument is a symbol. After a global state change, it can have the values
977 `overview', `content', or `all'. After a local state change, it can have
978 the values `folded', `children', or `subtree'."
979 :group 'org-cycle
980 :type 'hook)
982 (defgroup org-edit-structure nil
983 "Options concerning structure editing in Org-mode."
984 :tag "Org Edit Structure"
985 :group 'org-structure)
987 (defcustom org-odd-levels-only nil
988 "Non-nil means skip even levels and only use odd levels for the outline.
989 This has the effect that two stars are being added/taken away in
990 promotion/demotion commands. It also influences how levels are
991 handled by the exporters.
992 Changing it requires restart of `font-lock-mode' to become effective
993 for fontification also in regions already fontified.
994 You may also set this on a per-file basis by adding one of the following
995 lines to the buffer:
997 #+STARTUP: odd
998 #+STARTUP: oddeven"
999 :group 'org-edit-structure
1000 :group 'org-appearance
1001 :type 'boolean)
1003 (defcustom org-adapt-indentation t
1004 "Non-nil means adapt indentation to outline node level.
1006 When this variable is set, Org assumes that you write outlines by
1007 indenting text in each node to align with the headline (after the stars).
1008 The following issues are influenced by this variable:
1010 - When this is set and the *entire* text in an entry is indented, the
1011 indentation is increased by one space in a demotion command, and
1012 decreased by one in a promotion command. If any line in the entry
1013 body starts with text at column 0, indentation is not changed at all.
1015 - Property drawers and planning information is inserted indented when
1016 this variable s set. When nil, they will not be indented.
1018 - TAB indents a line relative to context. The lines below a headline
1019 will be indented when this variable is set.
1021 Note that this is all about true indentation, by adding and removing
1022 space characters. See also `org-indent.el' which does level-dependent
1023 indentation in a virtual way, i.e. at display time in Emacs."
1024 :group 'org-edit-structure
1025 :type 'boolean)
1027 (defcustom org-special-ctrl-a/e nil
1028 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1030 When t, `C-a' will bring back the cursor to the beginning of the
1031 headline text, i.e. after the stars and after a possible TODO
1032 keyword. In an item, this will be the position after bullet and
1033 check-box, if any. When the cursor is already at that position,
1034 another `C-a' will bring it to the beginning of the line.
1036 `C-e' will jump to the end of the headline, ignoring the presence
1037 of tags in the headline. A second `C-e' will then jump to the
1038 true end of the line, after any tags. This also means that, when
1039 this variable is non-nil, `C-e' also will never jump beyond the
1040 end of the heading of a folded section, i.e. not after the
1041 ellipses.
1043 When set to the symbol `reversed', the first `C-a' or `C-e' works
1044 normally, going to the true line boundary first. Only a directly
1045 following, identical keypress will bring the cursor to the
1046 special positions.
1048 This may also be a cons cell where the behavior for `C-a' and
1049 `C-e' is set separately."
1050 :group 'org-edit-structure
1051 :type '(choice
1052 (const :tag "off" nil)
1053 (const :tag "on: after stars/bullet and before tags first" t)
1054 (const :tag "reversed: true line boundary first" reversed)
1055 (cons :tag "Set C-a and C-e separately"
1056 (choice :tag "Special C-a"
1057 (const :tag "off" nil)
1058 (const :tag "on: after stars/bullet first" t)
1059 (const :tag "reversed: before stars/bullet first" reversed))
1060 (choice :tag "Special C-e"
1061 (const :tag "off" nil)
1062 (const :tag "on: before tags first" t)
1063 (const :tag "reversed: after tags first" reversed)))))
1064 (if (fboundp 'defvaralias)
1065 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1067 (defcustom org-special-ctrl-k nil
1068 "Non-nil means `C-k' will behave specially in headlines.
1069 When nil, `C-k' will call the default `kill-line' command.
1070 When t, the following will happen while the cursor is in the headline:
1072 - When the cursor is at the beginning of a headline, kill the entire
1073 line and possible the folded subtree below the line.
1074 - When in the middle of the headline text, kill the headline up to the tags.
1075 - When after the headline text, kill the tags."
1076 :group 'org-edit-structure
1077 :type 'boolean)
1079 (defcustom org-ctrl-k-protect-subtree nil
1080 "Non-nil means, do not delete a hidden subtree with C-k.
1081 When set to the symbol `error', simply throw an error when C-k is
1082 used to kill (part-of) a headline that has hidden text behind it.
1083 Any other non-nil value will result in a query to the user, if it is
1084 OK to kill that hidden subtree. When nil, kill without remorse."
1085 :group 'org-edit-structure
1086 :version "24.1"
1087 :type '(choice
1088 (const :tag "Do not protect hidden subtrees" nil)
1089 (const :tag "Protect hidden subtrees with a security query" t)
1090 (const :tag "Never kill a hidden subtree with C-k" error)))
1092 (defcustom org-catch-invisible-edits nil
1093 "Check if in invisible region before inserting or deleting a character.
1094 Valid values are:
1096 nil Do not check, so just do invisible edits.
1097 error Throw an error and do nothing.
1098 show Make point visible, and do the requested edit.
1099 show-and-error Make point visible, then throw an error and abort the edit.
1100 smart Make point visible, and do insertion/deletion if it is
1101 adjacent to visible text and the change feels predictable.
1102 Never delete a previously invisible character or add in the
1103 middle or right after an invisible region. Basically, this
1104 allows insertion and backward-delete right before ellipses.
1105 FIXME: maybe in this case we should not even show?"
1106 :group 'org-edit-structure
1107 :version "24.1"
1108 :type '(choice
1109 (const :tag "Do not check" nil)
1110 (const :tag "Throw error when trying to edit" error)
1111 (const :tag "Unhide, but do not do the edit" show-and-error)
1112 (const :tag "Show invisible part and do the edit" show)
1113 (const :tag "Be smart and do the right thing" smart)))
1115 (defcustom org-yank-folded-subtrees t
1116 "Non-nil means when yanking subtrees, fold them.
1117 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1118 it starts with a heading and all other headings in it are either children
1119 or siblings, then fold all the subtrees. However, do this only if no
1120 text after the yank would be swallowed into a folded tree by this action."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-yank-adjusted-subtrees nil
1125 "Non-nil means when yanking subtrees, adjust the level.
1126 With this setting, `org-paste-subtree' is used to insert the subtree, see
1127 this function for details."
1128 :group 'org-edit-structure
1129 :type 'boolean)
1131 (defcustom org-M-RET-may-split-line '((default . t))
1132 "Non-nil means M-RET will split the line at the cursor position.
1133 When nil, it will go to the end of the line before making a
1134 new line.
1135 You may also set this option in a different way for different
1136 contexts. Valid contexts are:
1138 headline when creating a new headline
1139 item when creating a new item
1140 table in a table field
1141 default the value to be used for all contexts not explicitly
1142 customized"
1143 :group 'org-structure
1144 :group 'org-table
1145 :type '(choice
1146 (const :tag "Always" t)
1147 (const :tag "Never" nil)
1148 (repeat :greedy t :tag "Individual contexts"
1149 (cons
1150 (choice :tag "Context"
1151 (const headline)
1152 (const item)
1153 (const table)
1154 (const default))
1155 (boolean)))))
1158 (defcustom org-insert-heading-respect-content nil
1159 "Non-nil means insert new headings after the current subtree.
1160 When nil, the new heading is created directly after the current line.
1161 The commands \\[org-insert-heading-respect-content] and
1162 \\[org-insert-todo-heading-respect-content] turn this variable on
1163 for the duration of the command."
1164 :group 'org-structure
1165 :type 'boolean)
1167 (defcustom org-blank-before-new-entry '((heading . auto)
1168 (plain-list-item . auto))
1169 "Should `org-insert-heading' leave a blank line before new heading/item?
1170 The value is an alist, with `heading' and `plain-list-item' as CAR,
1171 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1172 which case Org will look at the surrounding headings/items and try to
1173 make an intelligent decision whether to insert a blank line or not.
1175 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1176 set, the setting here is ignored and no empty line is inserted, to avoid
1177 breaking the list structure."
1178 :group 'org-edit-structure
1179 :type '(list
1180 (cons (const heading)
1181 (choice (const :tag "Never" nil)
1182 (const :tag "Always" t)
1183 (const :tag "Auto" auto)))
1184 (cons (const plain-list-item)
1185 (choice (const :tag "Never" nil)
1186 (const :tag "Always" t)
1187 (const :tag "Auto" auto)))))
1189 (defcustom org-insert-heading-hook nil
1190 "Hook being run after inserting a new heading."
1191 :group 'org-edit-structure
1192 :type 'hook)
1194 (defcustom org-enable-fixed-width-editor t
1195 "Non-nil means lines starting with \":\" are treated as fixed-width.
1196 This currently only means they are never auto-wrapped.
1197 When nil, such lines will be treated like ordinary lines.
1198 See also the QUOTE keyword."
1199 :group 'org-edit-structure
1200 :type 'boolean)
1202 (defcustom org-goto-auto-isearch t
1203 "Non-nil means typing characters in `org-goto' starts incremental search."
1204 :group 'org-edit-structure
1205 :type 'boolean)
1207 (defgroup org-sparse-trees nil
1208 "Options concerning sparse trees in Org-mode."
1209 :tag "Org Sparse Trees"
1210 :group 'org-structure)
1212 (defcustom org-highlight-sparse-tree-matches t
1213 "Non-nil means highlight all matches that define a sparse tree.
1214 The highlights will automatically disappear the next time the buffer is
1215 changed by an edit command."
1216 :group 'org-sparse-trees
1217 :type 'boolean)
1219 (defcustom org-remove-highlights-with-change t
1220 "Non-nil means any change to the buffer will remove temporary highlights.
1221 Such highlights are created by `org-occur' and `org-clock-display'.
1222 When nil, `C-c C-c needs to be used to get rid of the highlights.
1223 The highlights created by `org-preview-latex-fragment' always need
1224 `C-c C-c' to be removed."
1225 :group 'org-sparse-trees
1226 :group 'org-time
1227 :type 'boolean)
1230 (defcustom org-occur-hook '(org-first-headline-recenter)
1231 "Hook that is run after `org-occur' has constructed a sparse tree.
1232 This can be used to recenter the window to show as much of the structure
1233 as possible."
1234 :group 'org-sparse-trees
1235 :type 'hook)
1237 (defgroup org-imenu-and-speedbar nil
1238 "Options concerning imenu and speedbar in Org-mode."
1239 :tag "Org Imenu and Speedbar"
1240 :group 'org-structure)
1242 (defcustom org-imenu-depth 2
1243 "The maximum level for Imenu access to Org-mode headlines.
1244 This also applied for speedbar access."
1245 :group 'org-imenu-and-speedbar
1246 :type 'integer)
1248 (defgroup org-table nil
1249 "Options concerning tables in Org-mode."
1250 :tag "Org Table"
1251 :group 'org)
1253 (defcustom org-enable-table-editor 'optimized
1254 "Non-nil means lines starting with \"|\" are handled by the table editor.
1255 When nil, such lines will be treated like ordinary lines.
1257 When equal to the symbol `optimized', the table editor will be optimized to
1258 do the following:
1259 - Automatic overwrite mode in front of whitespace in table fields.
1260 This makes the structure of the table stay in tact as long as the edited
1261 field does not exceed the column width.
1262 - Minimize the number of realigns. Normally, the table is aligned each time
1263 TAB or RET are pressed to move to another field. With optimization this
1264 happens only if changes to a field might have changed the column width.
1265 Optimization requires replacing the functions `self-insert-command',
1266 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1267 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1268 very good at guessing when a re-align will be necessary, but you can always
1269 force one with \\[org-ctrl-c-ctrl-c].
1271 If you would like to use the optimized version in Org-mode, but the
1272 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1274 This variable can be used to turn on and off the table editor during a session,
1275 but in order to toggle optimization, a restart is required.
1277 See also the variable `org-table-auto-blank-field'."
1278 :group 'org-table
1279 :type '(choice
1280 (const :tag "off" nil)
1281 (const :tag "on" t)
1282 (const :tag "on, optimized" optimized)))
1284 (defcustom org-self-insert-cluster-for-undo (version<= emacs-version "24.1")
1285 "Non-nil means cluster self-insert commands for undo when possible.
1286 If this is set, then, like in the Emacs command loop, 20 consecutive
1287 characters will be undone together.
1288 This is configurable, because there is some impact on typing performance."
1289 :group 'org-table
1290 :type 'boolean)
1292 (defcustom org-table-tab-recognizes-table.el t
1293 "Non-nil means TAB will automatically notice a table.el table.
1294 When it sees such a table, it moves point into it and - if necessary -
1295 calls `table-recognize-table'."
1296 :group 'org-table-editing
1297 :type 'boolean)
1299 (defgroup org-link nil
1300 "Options concerning links in Org-mode."
1301 :tag "Org Link"
1302 :group 'org)
1304 (defvar org-link-abbrev-alist-local nil
1305 "Buffer-local version of `org-link-abbrev-alist', which see.
1306 The value of this is taken from the #+LINK lines.")
1307 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1309 (defcustom org-link-abbrev-alist nil
1310 "Alist of link abbreviations.
1311 The car of each element is a string, to be replaced at the start of a link.
1312 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1313 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1315 [[linkkey:tag][description]]
1317 The 'linkkey' must be a word word, starting with a letter, followed
1318 by letters, numbers, '-' or '_'.
1320 If REPLACE is a string, the tag will simply be appended to create the link.
1321 If the string contains \"%s\", the tag will be inserted there. If the string
1322 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1323 at that point (see the function `url-hexify-string'). If the string contains
1324 the specifier \"%(my-function)\", then the custom function `my-function' will
1325 be invoked: this function takes the tag as its only argument and must return
1326 a string.
1328 REPLACE may also be a function that will be called with the tag as the
1329 only argument to create the link, which should be returned as a string.
1331 See the manual for examples."
1332 :group 'org-link
1333 :type '(repeat
1334 (cons
1335 (string :tag "Protocol")
1336 (choice
1337 (string :tag "Format")
1338 (function)))))
1340 (defcustom org-descriptive-links t
1341 "Non-nil means Org will display descriptive links.
1342 E.g. [[http://orgmode.org][Org website]] will be displayed as
1343 \"Org Website\", hiding the link itself and just displaying its
1344 description. When set to `nil', Org will display the full links
1345 literally.
1347 You can interactively set the value of this variable by calling
1348 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1349 :group 'org-link
1350 :type 'boolean)
1352 (defcustom org-link-file-path-type 'adaptive
1353 "How the path name in file links should be stored.
1354 Valid values are:
1356 relative Relative to the current directory, i.e. the directory of the file
1357 into which the link is being inserted.
1358 absolute Absolute path, if possible with ~ for home directory.
1359 noabbrev Absolute path, no abbreviation of home directory.
1360 adaptive Use relative path for files in the current directory and sub-
1361 directories of it. For other files, use an absolute path."
1362 :group 'org-link
1363 :type '(choice
1364 (const relative)
1365 (const absolute)
1366 (const noabbrev)
1367 (const adaptive)))
1369 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1370 "Types of links that should be activated in Org-mode files.
1371 This is a list of symbols, each leading to the activation of a certain link
1372 type. In principle, it does not hurt to turn on most link types - there may
1373 be a small gain when turning off unused link types. The types are:
1375 bracket The recommended [[link][description]] or [[link]] links with hiding.
1376 angle Links in angular brackets that may contain whitespace like
1377 <bbdb:Carsten Dominik>.
1378 plain Plain links in normal text, no whitespace, like http://google.com.
1379 radio Text that is matched by a radio target, see manual for details.
1380 tag Tag settings in a headline (link to tag search).
1381 date Time stamps (link to calendar).
1382 footnote Footnote labels.
1384 Changing this variable requires a restart of Emacs to become effective."
1385 :group 'org-link
1386 :type '(set :greedy t
1387 (const :tag "Double bracket links" bracket)
1388 (const :tag "Angular bracket links" angle)
1389 (const :tag "Plain text links" plain)
1390 (const :tag "Radio target matches" radio)
1391 (const :tag "Tags" tag)
1392 (const :tag "Timestamps" date)
1393 (const :tag "Footnotes" footnote)))
1395 (defcustom org-make-link-description-function nil
1396 "Function to use to generate link descriptions from links.
1397 If nil the link location will be used. This function must take
1398 two parameters; the first is the link and the second the
1399 description `org-insert-link' has generated, and should return the
1400 description to use."
1401 :group 'org-link
1402 :type 'function)
1404 (defgroup org-link-store nil
1405 "Options concerning storing links in Org-mode."
1406 :tag "Org Store Link"
1407 :group 'org-link)
1409 (defcustom org-url-hexify-p t
1410 "When non-nil, hexify URL when creating a link."
1411 :type 'boolean
1412 :version "24.3"
1413 :group 'org-link-store)
1415 (defcustom org-email-link-description-format "Email %c: %.30s"
1416 "Format of the description part of a link to an email or usenet message.
1417 The following %-escapes will be replaced by corresponding information:
1419 %F full \"From\" field
1420 %f name, taken from \"From\" field, address if no name
1421 %T full \"To\" field
1422 %t first name in \"To\" field, address if no name
1423 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1424 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1425 %s subject
1426 %d date
1427 %m message-id.
1429 You may use normal field width specification between the % and the letter.
1430 This is for example useful to limit the length of the subject.
1432 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1433 :group 'org-link-store
1434 :type 'string)
1436 (defcustom org-from-is-user-regexp
1437 (let (r1 r2)
1438 (when (and user-mail-address (not (string= user-mail-address "")))
1439 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1440 (when (and user-full-name (not (string= user-full-name "")))
1441 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1442 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1443 "Regexp matched against the \"From:\" header of an email or usenet message.
1444 It should match if the message is from the user him/herself."
1445 :group 'org-link-store
1446 :type 'regexp)
1448 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1449 "Non-nil means storing a link to an Org file will use entry IDs.
1451 Note that before this variable is even considered, org-id must be loaded,
1452 so please customize `org-modules' and turn it on.
1454 The variable can have the following values:
1456 t Create an ID if needed to make a link to the current entry.
1458 create-if-interactive
1459 If `org-store-link' is called directly (interactively, as a user
1460 command), do create an ID to support the link. But when doing the
1461 job for remember, only use the ID if it already exists. The
1462 purpose of this setting is to avoid proliferation of unwanted
1463 IDs, just because you happen to be in an Org file when you
1464 call `org-capture' that automatically and preemptively creates a
1465 link. If you do want to get an ID link in a remember template to
1466 an entry not having an ID, create it first by explicitly creating
1467 a link to it, using `C-c C-l' first.
1469 create-if-interactive-and-no-custom-id
1470 Like create-if-interactive, but do not create an ID if there is
1471 a CUSTOM_ID property defined in the entry. This is the default.
1473 use-existing
1474 Use existing ID, do not create one.
1476 nil Never use an ID to make a link, instead link using a text search for
1477 the headline text."
1478 :group 'org-link-store
1479 :type '(choice
1480 (const :tag "Create ID to make link" t)
1481 (const :tag "Create if storing link interactively"
1482 create-if-interactive)
1483 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1484 create-if-interactive-and-no-custom-id)
1485 (const :tag "Only use existing" use-existing)
1486 (const :tag "Do not use ID to create link" nil)))
1488 (defcustom org-context-in-file-links t
1489 "Non-nil means file links from `org-store-link' contain context.
1490 A search string will be added to the file name with :: as separator and
1491 used to find the context when the link is activated by the command
1492 `org-open-at-point'. When this option is t, the entire active region
1493 will be placed in the search string of the file link. If set to a
1494 positive integer, only the first n lines of context will be stored.
1496 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1497 negates this setting for the duration of the command."
1498 :group 'org-link-store
1499 :type '(choice boolean integer))
1501 (defcustom org-keep-stored-link-after-insertion nil
1502 "Non-nil means keep link in list for entire session.
1504 The command `org-store-link' adds a link pointing to the current
1505 location to an internal list. These links accumulate during a session.
1506 The command `org-insert-link' can be used to insert links into any
1507 Org-mode file (offering completion for all stored links). When this
1508 option is nil, every link which has been inserted once using \\[org-insert-link]
1509 will be removed from the list, to make completing the unused links
1510 more efficient."
1511 :group 'org-link-store
1512 :type 'boolean)
1514 (defgroup org-link-follow nil
1515 "Options concerning following links in Org-mode."
1516 :tag "Org Follow Link"
1517 :group 'org-link)
1519 (defcustom org-link-translation-function nil
1520 "Function to translate links with different syntax to Org syntax.
1521 This can be used to translate links created for example by the Planner
1522 or emacs-wiki packages to Org syntax.
1523 The function must accept two parameters, a TYPE containing the link
1524 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1525 which is everything after the link protocol. It should return a cons
1526 with possibly modified values of type and path.
1527 Org contains a function for this, so if you set this variable to
1528 `org-translate-link-from-planner', you should be able follow many
1529 links created by planner."
1530 :group 'org-link-follow
1531 :type 'function)
1533 (defcustom org-follow-link-hook nil
1534 "Hook that is run after a link has been followed."
1535 :group 'org-link-follow
1536 :type 'hook)
1538 (defcustom org-tab-follows-link nil
1539 "Non-nil means on links TAB will follow the link.
1540 Needs to be set before org.el is loaded.
1541 This really should not be used, it does not make sense, and the
1542 implementation is bad."
1543 :group 'org-link-follow
1544 :type 'boolean)
1546 (defcustom org-return-follows-link nil
1547 "Non-nil means on links RET will follow the link."
1548 :group 'org-link-follow
1549 :type 'boolean)
1551 (defcustom org-mouse-1-follows-link
1552 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1553 "Non-nil means mouse-1 on a link will follow the link.
1554 A longer mouse click will still set point. Does not work on XEmacs.
1555 Needs to be set before org.el is loaded."
1556 :group 'org-link-follow
1557 :type 'boolean)
1559 (defcustom org-mark-ring-length 4
1560 "Number of different positions to be recorded in the ring.
1561 Changing this requires a restart of Emacs to work correctly."
1562 :group 'org-link-follow
1563 :type 'integer)
1565 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1566 "Non-nil means internal links in Org files must exactly match a headline.
1567 When nil, the link search tries to match a phrase with all words
1568 in the search text."
1569 :group 'org-link-follow
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Use fuzzy text search" nil)
1573 (const :tag "Match only exact headline" t)
1574 (const :tag "Match exact headline or query to create it"
1575 query-to-create)))
1577 (defcustom org-link-frame-setup
1578 '((vm . vm-visit-folder-other-frame)
1579 (vm-imap . vm-visit-imap-folder-other-frame)
1580 (gnus . org-gnus-no-new-news)
1581 (file . find-file-other-window)
1582 (wl . wl-other-frame))
1583 "Setup the frame configuration for following links.
1584 When following a link with Emacs, it may often be useful to display
1585 this link in another window or frame. This variable can be used to
1586 set this up for the different types of links.
1587 For VM, use any of
1588 `vm-visit-folder'
1589 `vm-visit-folder-other-window'
1590 `vm-visit-folder-other-frame'
1591 For Gnus, use any of
1592 `gnus'
1593 `gnus-other-frame'
1594 `org-gnus-no-new-news'
1595 For FILE, use any of
1596 `find-file'
1597 `find-file-other-window'
1598 `find-file-other-frame'
1599 For Wanderlust use any of
1600 `wl'
1601 `wl-other-frame'
1602 For the calendar, use the variable `calendar-setup'.
1603 For BBDB, it is currently only possible to display the matches in
1604 another window."
1605 :group 'org-link-follow
1606 :type '(list
1607 (cons (const vm)
1608 (choice
1609 (const vm-visit-folder)
1610 (const vm-visit-folder-other-window)
1611 (const vm-visit-folder-other-frame)))
1612 (cons (const gnus)
1613 (choice
1614 (const gnus)
1615 (const gnus-other-frame)
1616 (const org-gnus-no-new-news)))
1617 (cons (const file)
1618 (choice
1619 (const find-file)
1620 (const find-file-other-window)
1621 (const find-file-other-frame)))
1622 (cons (const wl)
1623 (choice
1624 (const wl)
1625 (const wl-other-frame)))))
1627 (defcustom org-display-internal-link-with-indirect-buffer nil
1628 "Non-nil means use indirect buffer to display infile links.
1629 Activating internal links (from one location in a file to another location
1630 in the same file) normally just jumps to the location. When the link is
1631 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1632 is displayed in
1633 another window. When this option is set, the other window actually displays
1634 an indirect buffer clone of the current buffer, to avoid any visibility
1635 changes to the current buffer."
1636 :group 'org-link-follow
1637 :type 'boolean)
1639 (defcustom org-open-non-existing-files nil
1640 "Non-nil means `org-open-file' will open non-existing files.
1641 When nil, an error will be generated.
1642 This variable applies only to external applications because they
1643 might choke on non-existing files. If the link is to a file that
1644 will be opened in Emacs, the variable is ignored."
1645 :group 'org-link-follow
1646 :type 'boolean)
1648 (defcustom org-open-directory-means-index-dot-org nil
1649 "Non-nil means a link to a directory really means to index.org.
1650 When nil, following a directory link will run dired or open a finder/explorer
1651 window on that directory."
1652 :group 'org-link-follow
1653 :type 'boolean)
1655 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1656 "Function and arguments to call for following mailto links.
1657 This is a list with the first element being a Lisp function, and the
1658 remaining elements being arguments to the function. In string arguments,
1659 %a will be replaced by the address, and %s will be replaced by the subject
1660 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1661 :group 'org-link-follow
1662 :type '(choice
1663 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1664 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1665 (const :tag "message-mail" (message-mail "%a" "%s"))
1666 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1668 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1669 "Non-nil means ask for confirmation before executing shell links.
1670 Shell links can be dangerous: just think about a link
1672 [[shell:rm -rf ~/*][Google Search]]
1674 This link would show up in your Org-mode document as \"Google Search\",
1675 but really it would remove your entire home directory.
1676 Therefore we advise against setting this variable to nil.
1677 Just change it to `y-or-n-p' if you want to confirm with a
1678 single keystroke rather than having to type \"yes\"."
1679 :group 'org-link-follow
1680 :type '(choice
1681 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1682 (const :tag "with y-or-n (faster)" y-or-n-p)
1683 (const :tag "no confirmation (dangerous)" nil)))
1684 (put 'org-confirm-shell-link-function
1685 'safe-local-variable
1686 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1688 (defcustom org-confirm-shell-link-not-regexp ""
1689 "A regexp to skip confirmation for shell links."
1690 :group 'org-link-follow
1691 :version "24.1"
1692 :type 'regexp)
1694 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1695 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1696 Elisp links can be dangerous: just think about a link
1698 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1700 This link would show up in your Org-mode document as \"Google Search\",
1701 but really it would remove your entire home directory.
1702 Therefore we advise against setting this variable to nil.
1703 Just change it to `y-or-n-p' if you want to confirm with a
1704 single keystroke rather than having to type \"yes\"."
1705 :group 'org-link-follow
1706 :type '(choice
1707 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1708 (const :tag "with y-or-n (faster)" y-or-n-p)
1709 (const :tag "no confirmation (dangerous)" nil)))
1710 (put 'org-confirm-shell-link-function
1711 'safe-local-variable
1712 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1714 (defcustom org-confirm-elisp-link-not-regexp ""
1715 "A regexp to skip confirmation for Elisp links."
1716 :group 'org-link-follow
1717 :version "24.1"
1718 :type 'regexp)
1720 (defconst org-file-apps-defaults-gnu
1721 '((remote . emacs)
1722 (system . mailcap)
1723 (t . mailcap))
1724 "Default file applications on a UNIX or GNU/Linux system.
1725 See `org-file-apps'.")
1727 (defconst org-file-apps-defaults-macosx
1728 '((remote . emacs)
1729 (t . "open %s")
1730 (system . "open %s")
1731 ("ps.gz" . "gv %s")
1732 ("eps.gz" . "gv %s")
1733 ("dvi" . "xdvi %s")
1734 ("fig" . "xfig %s"))
1735 "Default file applications on a MacOS X system.
1736 The system \"open\" is known as a default, but we use X11 applications
1737 for some files for which the OS does not have a good default.
1738 See `org-file-apps'.")
1740 (defconst org-file-apps-defaults-windowsnt
1741 (list
1742 '(remote . emacs)
1743 (cons t
1744 (list (if (featurep 'xemacs)
1745 'mswindows-shell-execute
1746 'w32-shell-execute)
1747 "open" 'file))
1748 (cons 'system
1749 (list (if (featurep 'xemacs)
1750 'mswindows-shell-execute
1751 'w32-shell-execute)
1752 "open" 'file)))
1753 "Default file applications on a Windows NT system.
1754 The system \"open\" is used for most files.
1755 See `org-file-apps'.")
1757 (defcustom org-file-apps
1759 (auto-mode . emacs)
1760 ("\\.mm\\'" . default)
1761 ("\\.x?html?\\'" . default)
1762 ("\\.pdf\\'" . default)
1764 "External applications for opening `file:path' items in a document.
1765 Org-mode uses system defaults for different file types, but
1766 you can use this variable to set the application for a given file
1767 extension. The entries in this list are cons cells where the car identifies
1768 files and the cdr the corresponding command. Possible values for the
1769 file identifier are
1770 \"string\" A string as a file identifier can be interpreted in different
1771 ways, depending on its contents:
1773 - Alphanumeric characters only:
1774 Match links with this file extension.
1775 Example: (\"pdf\" . \"evince %s\")
1776 to open PDFs with evince.
1778 - Regular expression: Match links where the
1779 filename matches the regexp. If you want to
1780 use groups here, use shy groups.
1782 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1783 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1784 to open *.html and *.xhtml with firefox.
1786 - Regular expression which contains (non-shy) groups:
1787 Match links where the whole link, including \"::\", and
1788 anything after that, matches the regexp.
1789 In a custom command string, %1, %2, etc. are replaced with
1790 the parts of the link that were matched by the groups.
1791 For backwards compatibility, if a command string is given
1792 that does not use any of the group matches, this case is
1793 handled identically to the second one (i.e. match against
1794 file name only).
1795 In a custom lisp form, you can access the group matches with
1796 (match-string n link).
1798 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1799 to open [[file:document.pdf::5]] with evince at page 5.
1801 `directory' Matches a directory
1802 `remote' Matches a remote file, accessible through tramp or efs.
1803 Remote files most likely should be visited through Emacs
1804 because external applications cannot handle such paths.
1805 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1806 so all files Emacs knows how to handle. Using this with
1807 command `emacs' will open most files in Emacs. Beware that this
1808 will also open html files inside Emacs, unless you add
1809 (\"html\" . default) to the list as well.
1810 t Default for files not matched by any of the other options.
1811 `system' The system command to open files, like `open' on Windows
1812 and Mac OS X, and mailcap under GNU/Linux. This is the command
1813 that will be selected if you call `C-c C-o' with a double
1814 \\[universal-argument] \\[universal-argument] prefix.
1816 Possible values for the command are:
1817 `emacs' The file will be visited by the current Emacs process.
1818 `default' Use the default application for this file type, which is the
1819 association for t in the list, most likely in the system-specific
1820 part.
1821 This can be used to overrule an unwanted setting in the
1822 system-specific variable.
1823 `system' Use the system command for opening files, like \"open\".
1824 This command is specified by the entry whose car is `system'.
1825 Most likely, the system-specific version of this variable
1826 does define this command, but you can overrule/replace it
1827 here.
1828 string A command to be executed by a shell; %s will be replaced
1829 by the path to the file.
1830 sexp A Lisp form which will be evaluated. The file path will
1831 be available in the Lisp variable `file'.
1832 For more examples, see the system specific constants
1833 `org-file-apps-defaults-macosx'
1834 `org-file-apps-defaults-windowsnt'
1835 `org-file-apps-defaults-gnu'."
1836 :group 'org-link-follow
1837 :type '(repeat
1838 (cons (choice :value ""
1839 (string :tag "Extension")
1840 (const :tag "System command to open files" system)
1841 (const :tag "Default for unrecognized files" t)
1842 (const :tag "Remote file" remote)
1843 (const :tag "Links to a directory" directory)
1844 (const :tag "Any files that have Emacs modes"
1845 auto-mode))
1846 (choice :value ""
1847 (const :tag "Visit with Emacs" emacs)
1848 (const :tag "Use default" default)
1849 (const :tag "Use the system command" system)
1850 (string :tag "Command")
1851 (sexp :tag "Lisp form")))))
1853 (defcustom org-doi-server-url "http://dx.doi.org/"
1854 "The URL of the DOI server."
1855 :type 'string
1856 :version "24.3"
1857 :group 'org-link-follow)
1859 (defgroup org-refile nil
1860 "Options concerning refiling entries in Org-mode."
1861 :tag "Org Refile"
1862 :group 'org)
1864 (defcustom org-directory "~/org"
1865 "Directory with org files.
1866 This is just a default location to look for Org files. There is no need
1867 at all to put your files into this directory. It is only used in the
1868 following situations:
1870 1. When a remember template specifies a target file that is not an
1871 absolute path. The path will then be interpreted relative to
1872 `org-directory'
1873 2. When a remember note is filed away in an interactive way (when exiting the
1874 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1875 with `org-directory' as the default path."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :type 'directory)
1880 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1881 "Default target for storing notes.
1882 Used as a fall back file for org-remember.el and org-capture.el, for
1883 templates that do not specify a target file."
1884 :group 'org-refile
1885 :group 'org-remember
1886 :type '(choice
1887 (const :tag "Default from remember-data-file" nil)
1888 file))
1890 (defcustom org-goto-interface 'outline
1891 "The default interface to be used for `org-goto'.
1892 Allowed values are:
1893 outline The interface shows an outline of the relevant file
1894 and the correct heading is found by moving through
1895 the outline or by searching with incremental search.
1896 outline-path-completion Headlines in the current buffer are offered via
1897 completion. This is the interface also used by
1898 the refile command."
1899 :group 'org-refile
1900 :type '(choice
1901 (const :tag "Outline" outline)
1902 (const :tag "Outline-path-completion" outline-path-completion)))
1904 (defcustom org-goto-max-level 5
1905 "Maximum target level when running `org-goto' with refile interface."
1906 :group 'org-refile
1907 :type 'integer)
1909 (defcustom org-reverse-note-order nil
1910 "Non-nil means store new notes at the beginning of a file or entry.
1911 When nil, new notes will be filed to the end of a file or entry.
1912 This can also be a list with cons cells of regular expressions that
1913 are matched against file names, and values."
1914 :group 'org-remember
1915 :group 'org-refile
1916 :type '(choice
1917 (const :tag "Reverse always" t)
1918 (const :tag "Reverse never" nil)
1919 (repeat :tag "By file name regexp"
1920 (cons regexp boolean))))
1922 (defcustom org-log-refile nil
1923 "Information to record when a task is refiled.
1925 Possible values are:
1927 nil Don't add anything
1928 time Add a time stamp to the task
1929 note Prompt for a note and add it with template `org-log-note-headings'
1931 This option can also be set with on a per-file-basis with
1933 #+STARTUP: nologrefile
1934 #+STARTUP: logrefile
1935 #+STARTUP: lognoterefile
1937 You can have local logging settings for a subtree by setting the LOGGING
1938 property to one or more of these keywords.
1940 When bulk-refiling from the agenda, the value `note' is forbidden and
1941 will temporarily be changed to `time'."
1942 :group 'org-refile
1943 :group 'org-progress
1944 :version "24.1"
1945 :type '(choice
1946 (const :tag "No logging" nil)
1947 (const :tag "Record timestamp" time)
1948 (const :tag "Record timestamp with note." note)))
1950 (defcustom org-refile-targets nil
1951 "Targets for refiling entries with \\[org-refile].
1952 This is a list of cons cells. Each cell contains:
1953 - a specification of the files to be considered, either a list of files,
1954 or a symbol whose function or variable value will be used to retrieve
1955 a file name or a list of file names. If you use `org-agenda-files' for
1956 that, all agenda files will be scanned for targets. Nil means consider
1957 headings in the current buffer.
1958 - A specification of how to find candidate refile targets. This may be
1959 any of:
1960 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1961 This tag has to be present in all target headlines, inheritance will
1962 not be considered.
1963 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1964 todo keyword.
1965 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1966 headlines that are refiling targets.
1967 - a cons cell (:level . N). Any headline of level N is considered a target.
1968 Note that, when `org-odd-levels-only' is set, level corresponds to
1969 order in hierarchy, not to the number of stars.
1970 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1971 Note that, when `org-odd-levels-only' is set, level corresponds to
1972 order in hierarchy, not to the number of stars.
1974 Each element of this list generates a set of possible targets.
1975 The union of these sets is presented (with completion) to
1976 the user by `org-refile'.
1978 You can set the variable `org-refile-target-verify-function' to a function
1979 to verify each headline found by the simple criteria above.
1981 When this variable is nil, all top-level headlines in the current buffer
1982 are used, equivalent to the value `((nil . (:level . 1))'."
1983 :group 'org-refile
1984 :type '(repeat
1985 (cons
1986 (choice :value org-agenda-files
1987 (const :tag "All agenda files" org-agenda-files)
1988 (const :tag "Current buffer" nil)
1989 (function) (variable) (file))
1990 (choice :tag "Identify target headline by"
1991 (cons :tag "Specific tag" (const :value :tag) (string))
1992 (cons :tag "TODO keyword" (const :value :todo) (string))
1993 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1994 (cons :tag "Level number" (const :value :level) (integer))
1995 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1997 (defcustom org-refile-target-verify-function nil
1998 "Function to verify if the headline at point should be a refile target.
1999 The function will be called without arguments, with point at the
2000 beginning of the headline. It should return t and leave point
2001 where it is if the headline is a valid target for refiling.
2003 If the target should not be selected, the function must return nil.
2004 In addition to this, it may move point to a place from where the search
2005 should be continued. For example, the function may decide that the entire
2006 subtree of the current entry should be excluded and move point to the end
2007 of the subtree."
2008 :group 'org-refile
2009 :type 'function)
2011 (defcustom org-refile-use-cache nil
2012 "Non-nil means cache refile targets to speed up the process.
2013 The cache for a particular file will be updated automatically when
2014 the buffer has been killed, or when any of the marker used for flagging
2015 refile targets no longer points at a live buffer.
2016 If you have added new entries to a buffer that might themselves be targets,
2017 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2018 find that easier, `C-u C-u C-u C-c C-w'."
2019 :group 'org-refile
2020 :version "24.1"
2021 :type 'boolean)
2023 (defcustom org-refile-use-outline-path nil
2024 "Non-nil means provide refile targets as paths.
2025 So a level 3 headline will be available as level1/level2/level3.
2027 When the value is `file', also include the file name (without directory)
2028 into the path. In this case, you can also stop the completion after
2029 the file name, to get entries inserted as top level in the file.
2031 When `full-file-path', include the full file path."
2032 :group 'org-refile
2033 :type '(choice
2034 (const :tag "Not" nil)
2035 (const :tag "Yes" t)
2036 (const :tag "Start with file name" file)
2037 (const :tag "Start with full file path" full-file-path)))
2039 (defcustom org-outline-path-complete-in-steps t
2040 "Non-nil means complete the outline path in hierarchical steps.
2041 When Org-mode uses the refile interface to select an outline path
2042 \(see variable `org-refile-use-outline-path'), the completion of
2043 the path can be done is a single go, or if can be done in steps down
2044 the headline hierarchy. Going in steps is probably the best if you
2045 do not use a special completion package like `ido' or `icicles'.
2046 However, when using these packages, going in one step can be very
2047 fast, while still showing the whole path to the entry."
2048 :group 'org-refile
2049 :type 'boolean)
2051 (defcustom org-refile-allow-creating-parent-nodes nil
2052 "Non-nil means allow to create new nodes as refile targets.
2053 New nodes are then created by adding \"/new node name\" to the completion
2054 of an existing node. When the value of this variable is `confirm',
2055 new node creation must be confirmed by the user (recommended)
2056 When nil, the completion must match an existing entry.
2058 Note that, if the new heading is not seen by the criteria
2059 listed in `org-refile-targets', multiple instances of the same
2060 heading would be created by trying again to file under the new
2061 heading."
2062 :group 'org-refile
2063 :type '(choice
2064 (const :tag "Never" nil)
2065 (const :tag "Always" t)
2066 (const :tag "Prompt for confirmation" confirm)))
2068 (defcustom org-refile-active-region-within-subtree nil
2069 "Non-nil means also refile active region within a subtree.
2071 By default `org-refile' doesn't allow refiling regions if they
2072 don't contain a set of subtrees, but it might be convenient to
2073 do so sometimes: in that case, the first line of the region is
2074 converted to a headline before refiling."
2075 :group 'org-refile
2076 :version "24.1"
2077 :type 'boolean)
2079 (defgroup org-todo nil
2080 "Options concerning TODO items in Org-mode."
2081 :tag "Org TODO"
2082 :group 'org)
2084 (defgroup org-progress nil
2085 "Options concerning Progress logging in Org-mode."
2086 :tag "Org Progress"
2087 :group 'org-time)
2089 (defvar org-todo-interpretation-widgets
2090 '((:tag "Sequence (cycling hits every state)" sequence)
2091 (:tag "Type (cycling directly to DONE)" type))
2092 "The available interpretation symbols for customizing `org-todo-keywords'.
2093 Interested libraries should add to this list.")
2095 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2096 "List of TODO entry keyword sequences and their interpretation.
2097 \\<org-mode-map>This is a list of sequences.
2099 Each sequence starts with a symbol, either `sequence' or `type',
2100 indicating if the keywords should be interpreted as a sequence of
2101 action steps, or as different types of TODO items. The first
2102 keywords are states requiring action - these states will select a headline
2103 for inclusion into the global TODO list Org-mode produces. If one of
2104 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2105 signify that no further action is necessary. If \"|\" is not found,
2106 the last keyword is treated as the only DONE state of the sequence.
2108 The command \\[org-todo] cycles an entry through these states, and one
2109 additional state where no keyword is present. For details about this
2110 cycling, see the manual.
2112 TODO keywords and interpretation can also be set on a per-file basis with
2113 the special #+SEQ_TODO and #+TYP_TODO lines.
2115 Each keyword can optionally specify a character for fast state selection
2116 \(in combination with the variable `org-use-fast-todo-selection')
2117 and specifiers for state change logging, using the same syntax that
2118 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2119 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2120 indicates to record a time stamp each time this state is selected.
2122 Each keyword may also specify if a timestamp or a note should be
2123 recorded when entering or leaving the state, by adding additional
2124 characters in the parenthesis after the keyword. This looks like this:
2125 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2126 record only the time of the state change. With X and Y being either
2127 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2128 Y when leaving the state if and only if the *target* state does not
2129 define X. You may omit any of the fast-selection key or X or /Y,
2130 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2132 For backward compatibility, this variable may also be just a list
2133 of keywords. In this case the interpretation (sequence or type) will be
2134 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2135 :group 'org-todo
2136 :group 'org-keywords
2137 :type '(choice
2138 (repeat :tag "Old syntax, just keywords"
2139 (string :tag "Keyword"))
2140 (repeat :tag "New syntax"
2141 (cons
2142 (choice
2143 :tag "Interpretation"
2144 ;;Quick and dirty way to see
2145 ;;`org-todo-interpretations'. This takes the
2146 ;;place of item arguments
2147 :convert-widget
2148 (lambda (widget)
2149 (widget-put widget
2150 :args (mapcar
2151 #'(lambda (x)
2152 (widget-convert
2153 (cons 'const x)))
2154 org-todo-interpretation-widgets))
2155 widget))
2156 (repeat
2157 (string :tag "Keyword"))))))
2159 (defvar org-todo-keywords-1 nil
2160 "All TODO and DONE keywords active in a buffer.")
2161 (make-variable-buffer-local 'org-todo-keywords-1)
2162 (defvar org-todo-keywords-for-agenda nil)
2163 (defvar org-done-keywords-for-agenda nil)
2164 (defvar org-drawers-for-agenda nil)
2165 (defvar org-todo-keyword-alist-for-agenda nil)
2166 (defvar org-tag-alist-for-agenda nil)
2167 (defvar org-agenda-contributing-files nil)
2168 (defvar org-not-done-keywords nil)
2169 (make-variable-buffer-local 'org-not-done-keywords)
2170 (defvar org-done-keywords nil)
2171 (make-variable-buffer-local 'org-done-keywords)
2172 (defvar org-todo-heads nil)
2173 (make-variable-buffer-local 'org-todo-heads)
2174 (defvar org-todo-sets nil)
2175 (make-variable-buffer-local 'org-todo-sets)
2176 (defvar org-todo-log-states nil)
2177 (make-variable-buffer-local 'org-todo-log-states)
2178 (defvar org-todo-kwd-alist nil)
2179 (make-variable-buffer-local 'org-todo-kwd-alist)
2180 (defvar org-todo-key-alist nil)
2181 (make-variable-buffer-local 'org-todo-key-alist)
2182 (defvar org-todo-key-trigger nil)
2183 (make-variable-buffer-local 'org-todo-key-trigger)
2185 (defcustom org-todo-interpretation 'sequence
2186 "Controls how TODO keywords are interpreted.
2187 This variable is in principle obsolete and is only used for
2188 backward compatibility, if the interpretation of todo keywords is
2189 not given already in `org-todo-keywords'. See that variable for
2190 more information."
2191 :group 'org-todo
2192 :group 'org-keywords
2193 :type '(choice (const sequence)
2194 (const type)))
2196 (defcustom org-use-fast-todo-selection t
2197 "Non-nil means use the fast todo selection scheme with C-c C-t.
2198 This variable describes if and under what circumstances the cycling
2199 mechanism for TODO keywords will be replaced by a single-key, direct
2200 selection scheme.
2202 When nil, fast selection is never used.
2204 When the symbol `prefix', it will be used when `org-todo' is called
2205 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2206 `C-u t' in an agenda buffer.
2208 When t, fast selection is used by default. In this case, the prefix
2209 argument forces cycling instead.
2211 In all cases, the special interface is only used if access keys have
2212 actually been assigned by the user, i.e. if keywords in the configuration
2213 are followed by a letter in parenthesis, like TODO(t)."
2214 :group 'org-todo
2215 :type '(choice
2216 (const :tag "Never" nil)
2217 (const :tag "By default" t)
2218 (const :tag "Only with C-u C-c C-t" prefix)))
2220 (defcustom org-provide-todo-statistics t
2221 "Non-nil means update todo statistics after insert and toggle.
2222 ALL-HEADLINES means update todo statistics by including headlines
2223 with no TODO keyword as well, counting them as not done.
2224 A list of TODO keywords means the same, but skip keywords that are
2225 not in this list.
2227 When this is set, todo statistics is updated in the parent of the
2228 current entry each time a todo state is changed."
2229 :group 'org-todo
2230 :type '(choice
2231 (const :tag "Yes, only for TODO entries" t)
2232 (const :tag "Yes, including all entries" 'all-headlines)
2233 (repeat :tag "Yes, for TODOs in this list"
2234 (string :tag "TODO keyword"))
2235 (other :tag "No TODO statistics" nil)))
2237 (defcustom org-hierarchical-todo-statistics t
2238 "Non-nil means TODO statistics covers just direct children.
2239 When nil, all entries in the subtree are considered.
2240 This has only an effect if `org-provide-todo-statistics' is set.
2241 To set this to nil for only a single subtree, use a COOKIE_DATA
2242 property and include the word \"recursive\" into the value."
2243 :group 'org-todo
2244 :type 'boolean)
2246 (defcustom org-after-todo-state-change-hook nil
2247 "Hook which is run after the state of a TODO item was changed.
2248 The new state (a string with a TODO keyword, or nil) is available in the
2249 Lisp variable `org-state'."
2250 :group 'org-todo
2251 :type 'hook)
2253 (defvar org-blocker-hook nil
2254 "Hook for functions that are allowed to block a state change.
2256 Each function gets as its single argument a property list, see
2257 `org-trigger-hook' for more information about this list.
2259 If any of the functions in this hook returns nil, the state change
2260 is blocked.")
2262 (defvar org-trigger-hook nil
2263 "Hook for functions that are triggered by a state change.
2265 Each function gets as its single argument a property list with at least
2266 the following elements:
2268 (:type type-of-change :position pos-at-entry-start
2269 :from old-state :to new-state)
2271 Depending on the type, more properties may be present.
2273 This mechanism is currently implemented for:
2275 TODO state changes
2276 ------------------
2277 :type todo-state-change
2278 :from previous state (keyword as a string), or nil, or a symbol
2279 'todo' or 'done', to indicate the general type of state.
2280 :to new state, like in :from")
2282 (defcustom org-enforce-todo-dependencies nil
2283 "Non-nil means undone TODO entries will block switching the parent to DONE.
2284 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2285 be blocked if any prior sibling is not yet done.
2286 Finally, if the parent is blocked because of ordered siblings of its own,
2287 the child will also be blocked."
2288 :set (lambda (var val)
2289 (set var val)
2290 (if val
2291 (add-hook 'org-blocker-hook
2292 'org-block-todo-from-children-or-siblings-or-parent)
2293 (remove-hook 'org-blocker-hook
2294 'org-block-todo-from-children-or-siblings-or-parent)))
2295 :group 'org-todo
2296 :type 'boolean)
2298 (defcustom org-enforce-todo-checkbox-dependencies nil
2299 "Non-nil means unchecked boxes will block switching the parent to DONE.
2300 When this is nil, checkboxes have no influence on switching TODO states.
2301 When non-nil, you first need to check off all check boxes before the TODO
2302 entry can be switched to DONE.
2303 This variable needs to be set before org.el is loaded, and you need to
2304 restart Emacs after a change to make the change effective. The only way
2305 to change is while Emacs is running is through the customize interface."
2306 :set (lambda (var val)
2307 (set var val)
2308 (if val
2309 (add-hook 'org-blocker-hook
2310 'org-block-todo-from-checkboxes)
2311 (remove-hook 'org-blocker-hook
2312 'org-block-todo-from-checkboxes)))
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-insert-todo-heading-as-state-change nil
2317 "Non-nil means inserting a TODO heading is treated as state change.
2318 So when the command \\[org-insert-todo-heading] is used, state change
2319 logging will apply if appropriate. When nil, the new TODO item will
2320 be inserted directly, and no logging will take place."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2325 "Non-nil means switching TODO states with S-cursor counts as state change.
2326 This is the default behavior. However, setting this to nil allows a
2327 convenient way to select a TODO state and bypass any logging associated
2328 with that."
2329 :group 'org-todo
2330 :type 'boolean)
2332 (defcustom org-todo-state-tags-triggers nil
2333 "Tag changes that should be triggered by TODO state changes.
2334 This is a list. Each entry is
2336 (state-change (tag . flag) .......)
2338 State-change can be a string with a state, and empty string to indicate the
2339 state that has no TODO keyword, or it can be one of the symbols `todo'
2340 or `done', meaning any not-done or done state, respectively."
2341 :group 'org-todo
2342 :group 'org-tags
2343 :type '(repeat
2344 (cons (choice :tag "When changing to"
2345 (const :tag "Not-done state" todo)
2346 (const :tag "Done state" done)
2347 (string :tag "State"))
2348 (repeat
2349 (cons :tag "Tag action"
2350 (string :tag "Tag")
2351 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2353 (defcustom org-log-done nil
2354 "Information to record when a task moves to the DONE state.
2356 Possible values are:
2358 nil Don't add anything, just change the keyword
2359 time Add a time stamp to the task
2360 note Prompt for a note and add it with template `org-log-note-headings'
2362 This option can also be set with on a per-file-basis with
2364 #+STARTUP: nologdone
2365 #+STARTUP: logdone
2366 #+STARTUP: lognotedone
2368 You can have local logging settings for a subtree by setting the LOGGING
2369 property to one or more of these keywords."
2370 :group 'org-todo
2371 :group 'org-progress
2372 :type '(choice
2373 (const :tag "No logging" nil)
2374 (const :tag "Record CLOSED timestamp" time)
2375 (const :tag "Record CLOSED timestamp with note." note)))
2377 ;; Normalize old uses of org-log-done.
2378 (cond
2379 ((eq org-log-done t) (setq org-log-done 'time))
2380 ((and (listp org-log-done) (memq 'done org-log-done))
2381 (setq org-log-done 'note)))
2383 (defcustom org-log-reschedule nil
2384 "Information to record when the scheduling date of a tasks is modified.
2386 Possible values are:
2388 nil Don't add anything, just change the date
2389 time Add a time stamp to the task
2390 note Prompt for a note and add it with template `org-log-note-headings'
2392 This option can also be set with on a per-file-basis with
2394 #+STARTUP: nologreschedule
2395 #+STARTUP: logreschedule
2396 #+STARTUP: lognotereschedule"
2397 :group 'org-todo
2398 :group 'org-progress
2399 :type '(choice
2400 (const :tag "No logging" nil)
2401 (const :tag "Record timestamp" time)
2402 (const :tag "Record timestamp with note." note)))
2404 (defcustom org-log-redeadline nil
2405 "Information to record when the deadline date of a tasks is modified.
2407 Possible values are:
2409 nil Don't add anything, just change the date
2410 time Add a time stamp to the task
2411 note Prompt for a note and add it with template `org-log-note-headings'
2413 This option can also be set with on a per-file-basis with
2415 #+STARTUP: nologredeadline
2416 #+STARTUP: logredeadline
2417 #+STARTUP: lognoteredeadline
2419 You can have local logging settings for a subtree by setting the LOGGING
2420 property to one or more of these keywords."
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type '(choice
2424 (const :tag "No logging" nil)
2425 (const :tag "Record timestamp" time)
2426 (const :tag "Record timestamp with note." note)))
2428 (defcustom org-log-note-clock-out nil
2429 "Non-nil means record a note when clocking out of an item.
2430 This can also be configured on a per-file basis by adding one of
2431 the following lines anywhere in the buffer:
2433 #+STARTUP: lognoteclock-out
2434 #+STARTUP: nolognoteclock-out"
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type 'boolean)
2439 (defcustom org-log-done-with-time t
2440 "Non-nil means the CLOSED time stamp will contain date and time.
2441 When nil, only the date will be recorded."
2442 :group 'org-progress
2443 :type 'boolean)
2445 (defcustom org-log-note-headings
2446 '((done . "CLOSING NOTE %t")
2447 (state . "State %-12s from %-12S %t")
2448 (note . "Note taken on %t")
2449 (reschedule . "Rescheduled from %S on %t")
2450 (delschedule . "Not scheduled, was %S on %t")
2451 (redeadline . "New deadline from %S on %t")
2452 (deldeadline . "Removed deadline, was %S on %t")
2453 (refile . "Refiled on %t")
2454 (clock-out . ""))
2455 "Headings for notes added to entries.
2456 The value is an alist, with the car being a symbol indicating the note
2457 context, and the cdr is the heading to be used. The heading may also be the
2458 empty string.
2459 %t in the heading will be replaced by a time stamp.
2460 %T will be an active time stamp instead the default inactive one
2461 %d will be replaced by a short-format time stamp.
2462 %D will be replaced by an active short-format time stamp.
2463 %s will be replaced by the new TODO state, in double quotes.
2464 %S will be replaced by the old TODO state, in double quotes.
2465 %u will be replaced by the user name.
2466 %U will be replaced by the full user name.
2468 In fact, it is not a good idea to change the `state' entry, because
2469 agenda log mode depends on the format of these entries."
2470 :group 'org-todo
2471 :group 'org-progress
2472 :type '(list :greedy t
2473 (cons (const :tag "Heading when closing an item" done) string)
2474 (cons (const :tag
2475 "Heading when changing todo state (todo sequence only)"
2476 state) string)
2477 (cons (const :tag "Heading when just taking a note" note) string)
2478 (cons (const :tag "Heading when clocking out" clock-out) string)
2479 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2480 (cons (const :tag "Heading when rescheduling" reschedule) string)
2481 (cons (const :tag "Heading when changing deadline" redeadline) string)
2482 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2483 (cons (const :tag "Heading when refiling" refile) string)))
2485 (unless (assq 'note org-log-note-headings)
2486 (push '(note . "%t") org-log-note-headings))
2488 (defcustom org-log-into-drawer nil
2489 "Non-nil means insert state change notes and time stamps into a drawer.
2490 When nil, state changes notes will be inserted after the headline and
2491 any scheduling and clock lines, but not inside a drawer.
2493 The value of this variable should be the name of the drawer to use.
2494 LOGBOOK is proposed as the default drawer for this purpose, you can
2495 also set this to a string to define the drawer of your choice.
2497 A value of t is also allowed, representing \"LOGBOOK\".
2499 If this variable is set, `org-log-state-notes-insert-after-drawers'
2500 will be ignored.
2502 You can set the property LOG_INTO_DRAWER to overrule this setting for
2503 a subtree."
2504 :group 'org-todo
2505 :group 'org-progress
2506 :type '(choice
2507 (const :tag "Not into a drawer" nil)
2508 (const :tag "LOGBOOK" t)
2509 (string :tag "Other")))
2511 (if (fboundp 'defvaralias)
2512 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2514 (defun org-log-into-drawer ()
2515 "Return the value of `org-log-into-drawer', but let properties overrule.
2516 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2517 used instead of the default value."
2518 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2519 (cond
2520 ((or (not p) (equal p "nil")) org-log-into-drawer)
2521 ((equal p "t") "LOGBOOK")
2522 (t p))))
2524 (defcustom org-log-state-notes-insert-after-drawers nil
2525 "Non-nil means insert state change notes after any drawers in entry.
2526 Only the drawers that *immediately* follow the headline and the
2527 deadline/scheduled line are skipped.
2528 When nil, insert notes right after the heading and perhaps the line
2529 with deadline/scheduling if present.
2531 This variable will have no effect if `org-log-into-drawer' is
2532 set."
2533 :group 'org-todo
2534 :group 'org-progress
2535 :type 'boolean)
2537 (defcustom org-log-states-order-reversed t
2538 "Non-nil means the latest state note will be directly after heading.
2539 When nil, the state change notes will be ordered according to time."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type 'boolean)
2544 (defcustom org-todo-repeat-to-state nil
2545 "The TODO state to which a repeater should return the repeating task.
2546 By default this is the first task in a TODO sequence, or the previous state
2547 in a TODO_TYP set. But you can specify another task here.
2548 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2549 :group 'org-todo
2550 :version "24.1"
2551 :type '(choice (const :tag "Head of sequence" nil)
2552 (string :tag "Specific state")))
2554 (defcustom org-log-repeat 'time
2555 "Non-nil means record moving through the DONE state when triggering repeat.
2556 An auto-repeating task is immediately switched back to TODO when
2557 marked DONE. If you are not logging state changes (by adding \"@\"
2558 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2559 record a closing note, there will be no record of the task moving
2560 through DONE. This variable forces taking a note anyway.
2562 nil Don't force a record
2563 time Record a time stamp
2564 note Prompt for a note and add it with template `org-log-note-headings'
2566 This option can also be set with on a per-file-basis with
2568 #+STARTUP: nologrepeat
2569 #+STARTUP: logrepeat
2570 #+STARTUP: lognoterepeat
2572 You can have local logging settings for a subtree by setting the LOGGING
2573 property to one or more of these keywords."
2574 :group 'org-todo
2575 :group 'org-progress
2576 :type '(choice
2577 (const :tag "Don't force a record" nil)
2578 (const :tag "Force recording the DONE state" time)
2579 (const :tag "Force recording a note with the DONE state" note)))
2582 (defgroup org-priorities nil
2583 "Priorities in Org-mode."
2584 :tag "Org Priorities"
2585 :group 'org-todo)
2587 (defcustom org-enable-priority-commands t
2588 "Non-nil means priority commands are active.
2589 When nil, these commands will be disabled, so that you never accidentally
2590 set a priority."
2591 :group 'org-priorities
2592 :type 'boolean)
2594 (defcustom org-highest-priority ?A
2595 "The highest priority of TODO items. A character like ?A, ?B etc.
2596 Must have a smaller ASCII number than `org-lowest-priority'."
2597 :group 'org-priorities
2598 :type 'character)
2600 (defcustom org-lowest-priority ?C
2601 "The lowest priority of TODO items. A character like ?A, ?B etc.
2602 Must have a larger ASCII number than `org-highest-priority'."
2603 :group 'org-priorities
2604 :type 'character)
2606 (defcustom org-default-priority ?B
2607 "The default priority of TODO items.
2608 This is the priority an item gets if no explicit priority is given.
2609 When starting to cycle on an empty priority the first step in the cycle
2610 depends on `org-priority-start-cycle-with-default'. The resulting first
2611 step priority must not exceed the range from `org-highest-priority' to
2612 `org-lowest-priority' which means that `org-default-priority' has to be
2613 in this range exclusive or inclusive the range boundaries. Else the
2614 first step refuses to set the default and the second will fall back
2615 to (depending on the command used) the highest or lowest priority."
2616 :group 'org-priorities
2617 :type 'character)
2619 (defcustom org-priority-start-cycle-with-default t
2620 "Non-nil means start with default priority when starting to cycle.
2621 When this is nil, the first step in the cycle will be (depending on the
2622 command used) one higher or lower than the default priority.
2623 See also `org-default-priority'."
2624 :group 'org-priorities
2625 :type 'boolean)
2627 (defcustom org-get-priority-function nil
2628 "Function to extract the priority from a string.
2629 The string is normally the headline. If this is nil Org computes the
2630 priority from the priority cookie like [#A] in the headline. It returns
2631 an integer, increasing by 1000 for each priority level.
2632 The user can set a different function here, which should take a string
2633 as an argument and return the numeric priority."
2634 :group 'org-priorities
2635 :version "24.1"
2636 :type 'function)
2638 (defgroup org-time nil
2639 "Options concerning time stamps and deadlines in Org-mode."
2640 :tag "Org Time"
2641 :group 'org)
2643 (defcustom org-insert-labeled-timestamps-at-point nil
2644 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2645 When nil, these labeled time stamps are forces into the second line of an
2646 entry, just after the headline. When scheduling from the global TODO list,
2647 the time stamp will always be forced into the second line."
2648 :group 'org-time
2649 :type 'boolean)
2651 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2652 "Formats for `format-time-string' which are used for time stamps.
2653 It is not recommended to change this constant.")
2655 (defcustom org-time-stamp-rounding-minutes '(0 5)
2656 "Number of minutes to round time stamps to.
2657 These are two values, the first applies when first creating a time stamp.
2658 The second applies when changing it with the commands `S-up' and `S-down'.
2659 When changing the time stamp, this means that it will change in steps
2660 of N minutes, as given by the second value.
2662 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2663 numbers should be factors of 60, so for example 5, 10, 15.
2665 When this is larger than 1, you can still force an exact time stamp by using
2666 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2667 and by using a prefix arg to `S-up/down' to specify the exact number
2668 of minutes to shift."
2669 :group 'org-time
2670 :get #'(lambda (var) ; Make sure both elements are there
2671 (if (integerp (default-value var))
2672 (list (default-value var) 5)
2673 (default-value var)))
2674 :type '(list
2675 (integer :tag "when inserting times")
2676 (integer :tag "when modifying times")))
2678 ;; Normalize old customizations of this variable.
2679 (when (integerp org-time-stamp-rounding-minutes)
2680 (setq org-time-stamp-rounding-minutes
2681 (list org-time-stamp-rounding-minutes
2682 org-time-stamp-rounding-minutes)))
2684 (defcustom org-display-custom-times nil
2685 "Non-nil means overlay custom formats over all time stamps.
2686 The formats are defined through the variable `org-time-stamp-custom-formats'.
2687 To turn this on on a per-file basis, insert anywhere in the file:
2688 #+STARTUP: customtime"
2689 :group 'org-time
2690 :set 'set-default
2691 :type 'sexp)
2692 (make-variable-buffer-local 'org-display-custom-times)
2694 (defcustom org-time-stamp-custom-formats
2695 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2696 "Custom formats for time stamps. See `format-time-string' for the syntax.
2697 These are overlaid over the default ISO format if the variable
2698 `org-display-custom-times' is set. Time like %H:%M should be at the
2699 end of the second format. The custom formats are also honored by export
2700 commands, if custom time display is turned on at the time of export."
2701 :group 'org-time
2702 :type 'sexp)
2704 (defun org-time-stamp-format (&optional long inactive)
2705 "Get the right format for a time string."
2706 (let ((f (if long (cdr org-time-stamp-formats)
2707 (car org-time-stamp-formats))))
2708 (if inactive
2709 (concat "[" (substring f 1 -1) "]")
2710 f)))
2712 (defcustom org-time-clocksum-format "%d:%02d"
2713 "The format string used when creating CLOCKSUM lines.
2714 This is also used when org-mode generates a time duration."
2715 :group 'org-time
2716 :type 'string)
2718 (defcustom org-time-clocksum-use-fractional nil
2719 "If non-nil, \\[org-clock-display] uses fractional times.
2720 org-mode generates a time duration."
2721 :group 'org-time
2722 :type 'boolean)
2724 (defcustom org-time-clocksum-fractional-format "%.2f"
2725 "The format string used when creating CLOCKSUM lines, or when
2726 org-mode generates a time duration."
2727 :group 'org-time
2728 :type 'string)
2730 (defcustom org-deadline-warning-days 14
2731 "No. of days before expiration during which a deadline becomes active.
2732 This variable governs the display in sparse trees and in the agenda.
2733 When 0 or negative, it means use this number (the absolute value of it)
2734 even if a deadline has a different individual lead time specified.
2736 Custom commands can set this variable in the options section."
2737 :group 'org-time
2738 :group 'org-agenda-daily/weekly
2739 :type 'integer)
2741 (defcustom org-read-date-prefer-future t
2742 "Non-nil means assume future for incomplete date input from user.
2743 This affects the following situations:
2744 1. The user gives a month but not a year.
2745 For example, if it is April and you enter \"feb 2\", this will be read
2746 as Feb 2, *next* year. \"May 5\", however, will be this year.
2747 2. The user gives a day, but no month.
2748 For example, if today is the 15th, and you enter \"3\", Org-mode will
2749 read this as the third of *next* month. However, if you enter \"17\",
2750 it will be considered as *this* month.
2752 If you set this variable to the symbol `time', then also the following
2753 will work:
2755 3. If the user gives a time.
2756 If the time is before now, it will be interpreted as tomorrow.
2758 Currently none of this works for ISO week specifications.
2760 When this option is nil, the current day, month and year will always be
2761 used as defaults.
2763 See also `org-agenda-jump-prefer-future'."
2764 :group 'org-time
2765 :type '(choice
2766 (const :tag "Never" nil)
2767 (const :tag "Check month and day" t)
2768 (const :tag "Check month, day, and time" time)))
2770 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2771 "Should the agenda jump command prefer the future for incomplete dates?
2772 The default is to do the same as configured in `org-read-date-prefer-future'.
2773 But you can also set a deviating value here.
2774 This may t or nil, or the symbol `org-read-date-prefer-future'."
2775 :group 'org-agenda
2776 :group 'org-time
2777 :version "24.1"
2778 :type '(choice
2779 (const :tag "Use org-read-date-prefer-future"
2780 org-read-date-prefer-future)
2781 (const :tag "Never" nil)
2782 (const :tag "Always" t)))
2784 (defcustom org-read-date-force-compatible-dates t
2785 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2787 Depending on the system Emacs is running on, certain dates cannot
2788 be represented with the type used internally to represent time.
2789 Dates between 1970-1-1 and 2038-1-1 can always be represented
2790 correctly. Some systems allow for earlier dates, some for later,
2791 some for both. One way to find out it to insert any date into an
2792 Org buffer, putting the cursor on the year and hitting S-up and
2793 S-down to test the range.
2795 When this variable is set to t, the date/time prompt will not let
2796 you specify dates outside the 1970-2037 range, so it is certain that
2797 these dates will work in whatever version of Emacs you are
2798 running, and also that you can move a file from one Emacs implementation
2799 to another. WHenever Org is forcing the year for you, it will display
2800 a message and beep.
2802 When this variable is nil, Org will check if the date is
2803 representable in the specific Emacs implementation you are using.
2804 If not, it will force a year, usually the current year, and beep
2805 to remind you. Currently this setting is not recommended because
2806 the likelihood that you will open your Org files in an Emacs that
2807 has limited date range is not negligible.
2809 A workaround for this problem is to use diary sexp dates for time
2810 stamps outside of this range."
2811 :group 'org-time
2812 :version "24.1"
2813 :type 'boolean)
2815 (defcustom org-read-date-display-live t
2816 "Non-nil means display current interpretation of date prompt live.
2817 This display will be in an overlay, in the minibuffer."
2818 :group 'org-time
2819 :type 'boolean)
2821 (defcustom org-read-date-popup-calendar t
2822 "Non-nil means pop up a calendar when prompting for a date.
2823 In the calendar, the date can be selected with mouse-1. However, the
2824 minibuffer will also be active, and you can simply enter the date as well.
2825 When nil, only the minibuffer will be available."
2826 :group 'org-time
2827 :type 'boolean)
2828 (if (fboundp 'defvaralias)
2829 (defvaralias 'org-popup-calendar-for-date-prompt
2830 'org-read-date-popup-calendar))
2832 (defcustom org-read-date-minibuffer-setup-hook nil
2833 "Hook to be used to set up keys for the date/time interface.
2834 Add key definitions to `minibuffer-local-map', which will be a temporary
2835 copy."
2836 :group 'org-time
2837 :type 'hook)
2839 (defcustom org-extend-today-until 0
2840 "The hour when your day really ends. Must be an integer.
2841 This has influence for the following applications:
2842 - When switching the agenda to \"today\". It it is still earlier than
2843 the time given here, the day recognized as TODAY is actually yesterday.
2844 - When a date is read from the user and it is still before the time given
2845 here, the current date and time will be assumed to be yesterday, 23:59.
2846 Also, timestamps inserted in remember templates follow this rule.
2848 IMPORTANT: This is a feature whose implementation is and likely will
2849 remain incomplete. Really, it is only here because past midnight seems to
2850 be the favorite working time of John Wiegley :-)"
2851 :group 'org-time
2852 :type 'integer)
2854 (defcustom org-use-effective-time nil
2855 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2856 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2857 \"effective time\" of any timestamps between midnight and 8am will be
2858 23:59 of the previous day."
2859 :group 'org-time
2860 :version "24.1"
2861 :type 'boolean)
2863 (defcustom org-edit-timestamp-down-means-later nil
2864 "Non-nil means S-down will increase the time in a time stamp.
2865 When nil, S-up will increase."
2866 :group 'org-time
2867 :type 'boolean)
2869 (defcustom org-calendar-follow-timestamp-change t
2870 "Non-nil means make the calendar window follow timestamp changes.
2871 When a timestamp is modified and the calendar window is visible, it will be
2872 moved to the new date."
2873 :group 'org-time
2874 :type 'boolean)
2876 (defgroup org-tags nil
2877 "Options concerning tags in Org-mode."
2878 :tag "Org Tags"
2879 :group 'org)
2881 (defcustom org-tag-alist nil
2882 "List of tags allowed in Org-mode files.
2883 When this list is nil, Org-mode will base TAG input on what is already in the
2884 buffer.
2885 The value of this variable is an alist, the car of each entry must be a
2886 keyword as a string, the cdr may be a character that is used to select
2887 that tag through the fast-tag-selection interface.
2888 See the manual for details."
2889 :group 'org-tags
2890 :type '(repeat
2891 (choice
2892 (cons (string :tag "Tag name")
2893 (character :tag "Access char"))
2894 (list :tag "Start radio group"
2895 (const :startgroup)
2896 (option (string :tag "Group description")))
2897 (list :tag "End radio group"
2898 (const :endgroup)
2899 (option (string :tag "Group description")))
2900 (const :tag "New line" (:newline)))))
2902 (defcustom org-tag-persistent-alist nil
2903 "List of tags that will always appear in all Org-mode files.
2904 This is in addition to any in buffer settings or customizations
2905 of `org-tag-alist'.
2906 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2907 The value of this variable is an alist, the car of each entry must be a
2908 keyword as a string, the cdr may be a character that is used to select
2909 that tag through the fast-tag-selection interface.
2910 See the manual for details.
2911 To disable these tags on a per-file basis, insert anywhere in the file:
2912 #+STARTUP: noptag"
2913 :group 'org-tags
2914 :type '(repeat
2915 (choice
2916 (cons (string :tag "Tag name")
2917 (character :tag "Access char"))
2918 (const :tag "Start radio group" (:startgroup))
2919 (const :tag "End radio group" (:endgroup))
2920 (const :tag "New line" (:newline)))))
2922 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2923 "If non-nil, always offer completion for all tags of all agenda files.
2924 Instead of customizing this variable directly, you might want to
2925 set it locally for capture buffers, because there no list of
2926 tags in that file can be created dynamically (there are none).
2928 (add-hook 'org-capture-mode-hook
2929 (lambda ()
2930 (set (make-local-variable
2931 'org-complete-tags-always-offer-all-agenda-tags)
2932 t)))"
2933 :group 'org-tags
2934 :version "24.1"
2935 :type 'boolean)
2937 (defvar org-file-tags nil
2938 "List of tags that can be inherited by all entries in the file.
2939 The tags will be inherited if the variable `org-use-tag-inheritance'
2940 says they should be.
2941 This variable is populated from #+FILETAGS lines.")
2943 (defcustom org-use-fast-tag-selection 'auto
2944 "Non-nil means use fast tag selection scheme.
2945 This is a special interface to select and deselect tags with single keys.
2946 When nil, fast selection is never used.
2947 When the symbol `auto', fast selection is used if and only if selection
2948 characters for tags have been configured, either through the variable
2949 `org-tag-alist' or through a #+TAGS line in the buffer.
2950 When t, fast selection is always used and selection keys are assigned
2951 automatically if necessary."
2952 :group 'org-tags
2953 :type '(choice
2954 (const :tag "Always" t)
2955 (const :tag "Never" nil)
2956 (const :tag "When selection characters are configured" 'auto)))
2958 (defcustom org-fast-tag-selection-single-key nil
2959 "Non-nil means fast tag selection exits after first change.
2960 When nil, you have to press RET to exit it.
2961 During fast tag selection, you can toggle this flag with `C-c'.
2962 This variable can also have the value `expert'. In this case, the window
2963 displaying the tags menu is not even shown, until you press C-c again."
2964 :group 'org-tags
2965 :type '(choice
2966 (const :tag "No" nil)
2967 (const :tag "Yes" t)
2968 (const :tag "Expert" expert)))
2970 (defvar org-fast-tag-selection-include-todo nil
2971 "Non-nil means fast tags selection interface will also offer TODO states.
2972 This is an undocumented feature, you should not rely on it.")
2974 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2975 "The column to which tags should be indented in a headline.
2976 If this number is positive, it specifies the column. If it is negative,
2977 it means that the tags should be flushright to that column. For example,
2978 -80 works well for a normal 80 character screen.
2979 When 0, place tags directly after headline text, with only one space in
2980 between."
2981 :group 'org-tags
2982 :type 'integer)
2984 (defcustom org-auto-align-tags t
2985 "Non-nil keeps tags aligned when modifying headlines.
2986 Some operations (i.e. demoting) change the length of a headline and
2987 therefore shift the tags around. With this option turned on, after
2988 each such operation the tags are again aligned to `org-tags-column'."
2989 :group 'org-tags
2990 :type 'boolean)
2992 (defcustom org-use-tag-inheritance t
2993 "Non-nil means tags in levels apply also for sublevels.
2994 When nil, only the tags directly given in a specific line apply there.
2995 This may also be a list of tags that should be inherited, or a regexp that
2996 matches tags that should be inherited. Additional control is possible
2997 with the variable `org-tags-exclude-from-inheritance' which gives an
2998 explicit list of tags to be excluded from inheritance., even if the value of
2999 `org-use-tag-inheritance' would select it for inheritance.
3001 If this option is t, a match early-on in a tree can lead to a large
3002 number of matches in the subtree when constructing the agenda or creating
3003 a sparse tree. If you only want to see the first match in a tree during
3004 a search, check out the variable `org-tags-match-list-sublevels'."
3005 :group 'org-tags
3006 :type '(choice
3007 (const :tag "Not" nil)
3008 (const :tag "Always" t)
3009 (repeat :tag "Specific tags" (string :tag "Tag"))
3010 (regexp :tag "Tags matched by regexp")))
3012 (defcustom org-tags-exclude-from-inheritance nil
3013 "List of tags that should never be inherited.
3014 This is a way to exclude a few tags from inheritance. For way to do
3015 the opposite, to actively allow inheritance for selected tags,
3016 see the variable `org-use-tag-inheritance'."
3017 :group 'org-tags
3018 :type '(repeat (string :tag "Tag")))
3020 (defun org-tag-inherit-p (tag)
3021 "Check if TAG is one that should be inherited."
3022 (cond
3023 ((member tag org-tags-exclude-from-inheritance) nil)
3024 ((eq org-use-tag-inheritance t) t)
3025 ((not org-use-tag-inheritance) nil)
3026 ((stringp org-use-tag-inheritance)
3027 (string-match org-use-tag-inheritance tag))
3028 ((listp org-use-tag-inheritance)
3029 (member tag org-use-tag-inheritance))
3030 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3032 (defcustom org-tags-match-list-sublevels t
3033 "Non-nil means list also sublevels of headlines matching a search.
3034 This variable applies to tags/property searches, and also to stuck
3035 projects because this search is based on a tags match as well.
3037 When set to the symbol `indented', sublevels are indented with
3038 leading dots.
3040 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3041 the sublevels of a headline matching a tag search often also match
3042 the same search. Listing all of them can create very long lists.
3043 Setting this variable to nil causes subtrees of a match to be skipped.
3045 This variable is semi-obsolete and probably should always be true. It
3046 is better to limit inheritance to certain tags using the variables
3047 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3048 :group 'org-tags
3049 :type '(choice
3050 (const :tag "No, don't list them" nil)
3051 (const :tag "Yes, do list them" t)
3052 (const :tag "List them, indented with leading dots" indented)))
3054 (defcustom org-tags-sort-function nil
3055 "When set, tags are sorted using this function as a comparator."
3056 :group 'org-tags
3057 :type '(choice
3058 (const :tag "No sorting" nil)
3059 (const :tag "Alphabetical" string<)
3060 (const :tag "Reverse alphabetical" string>)
3061 (function :tag "Custom function" nil)))
3063 (defvar org-tags-history nil
3064 "History of minibuffer reads for tags.")
3065 (defvar org-last-tags-completion-table nil
3066 "The last used completion table for tags.")
3067 (defvar org-after-tags-change-hook nil
3068 "Hook that is run after the tags in a line have changed.")
3070 (defgroup org-properties nil
3071 "Options concerning properties in Org-mode."
3072 :tag "Org Properties"
3073 :group 'org)
3075 (defcustom org-property-format "%-10s %s"
3076 "How property key/value pairs should be formatted by `indent-line'.
3077 When `indent-line' hits a property definition, it will format the line
3078 according to this format, mainly to make sure that the values are
3079 lined-up with respect to each other."
3080 :group 'org-properties
3081 :type 'string)
3083 (defcustom org-properties-postprocess-alist nil
3084 "Alist of properties and functions to adjust inserted values.
3085 Elements of this alist must be of the form
3087 ([string] [function])
3089 where [string] must be a property name and [function] must be a
3090 lambda expression: this lambda expression must take one argument,
3091 the value to adjust, and return the new value as a string.
3093 For example, this element will allow the property \"Remaining\"
3094 to be updated wrt the relation between the \"Effort\" property
3095 and the clock summary:
3097 ((\"Remaining\" (lambda(value)
3098 (let ((clocksum (org-clock-sum-current-item))
3099 (effort (org-duration-string-to-minutes
3100 (org-entry-get (point) \"Effort\"))))
3101 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3102 :group 'org-properties
3103 :version "24.1"
3104 :type '(alist :key-type (string :tag "Property")
3105 :value-type (function :tag "Function")))
3107 (defcustom org-use-property-inheritance nil
3108 "Non-nil means properties apply also for sublevels.
3110 This setting is chiefly used during property searches. Turning it on can
3111 cause significant overhead when doing a search, which is why it is not
3112 on by default.
3114 When nil, only the properties directly given in the current entry count.
3115 When t, every property is inherited. The value may also be a list of
3116 properties that should have inheritance, or a regular expression matching
3117 properties that should be inherited.
3119 However, note that some special properties use inheritance under special
3120 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3121 and the properties ending in \"_ALL\" when they are used as descriptor
3122 for valid values of a property.
3124 Note for programmers:
3125 When querying an entry with `org-entry-get', you can control if inheritance
3126 should be used. By default, `org-entry-get' looks only at the local
3127 properties. You can request inheritance by setting the inherit argument
3128 to t (to force inheritance) or to `selective' (to respect the setting
3129 in this variable)."
3130 :group 'org-properties
3131 :type '(choice
3132 (const :tag "Not" nil)
3133 (const :tag "Always" t)
3134 (repeat :tag "Specific properties" (string :tag "Property"))
3135 (regexp :tag "Properties matched by regexp")))
3137 (defun org-property-inherit-p (property)
3138 "Check if PROPERTY is one that should be inherited."
3139 (cond
3140 ((eq org-use-property-inheritance t) t)
3141 ((not org-use-property-inheritance) nil)
3142 ((stringp org-use-property-inheritance)
3143 (string-match org-use-property-inheritance property))
3144 ((listp org-use-property-inheritance)
3145 (member property org-use-property-inheritance))
3146 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3148 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3149 "The default column format, if no other format has been defined.
3150 This variable can be set on the per-file basis by inserting a line
3152 #+COLUMNS: %25ITEM ....."
3153 :group 'org-properties
3154 :type 'string)
3156 (defcustom org-columns-ellipses ".."
3157 "The ellipses to be used when a field in column view is truncated.
3158 When this is the empty string, as many characters as possible are shown,
3159 but then there will be no visual indication that the field has been truncated.
3160 When this is a string of length N, the last N characters of a truncated
3161 field are replaced by this string. If the column is narrower than the
3162 ellipses string, only part of the ellipses string will be shown."
3163 :group 'org-properties
3164 :type 'string)
3166 (defcustom org-columns-modify-value-for-display-function nil
3167 "Function that modifies values for display in column view.
3168 For example, it can be used to cut out a certain part from a time stamp.
3169 The function must take 2 arguments:
3171 column-title The title of the column (*not* the property name)
3172 value The value that should be modified.
3174 The function should return the value that should be displayed,
3175 or nil if the normal value should be used."
3176 :group 'org-properties
3177 :type 'function)
3179 (defcustom org-effort-property "Effort"
3180 "The property that is being used to keep track of effort estimates.
3181 Effort estimates given in this property need to have the format H:MM."
3182 :group 'org-properties
3183 :group 'org-progress
3184 :type '(string :tag "Property"))
3186 (defconst org-global-properties-fixed
3187 '(("VISIBILITY_ALL" . "folded children content all")
3188 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3189 "List of property/value pairs that can be inherited by any entry.
3191 These are fixed values, for the preset properties. The user variable
3192 that can be used to add to this list is `org-global-properties'.
3194 The entries in this list are cons cells where the car is a property
3195 name and cdr is a string with the value. If the value represents
3196 multiple items like an \"_ALL\" property, separate the items by
3197 spaces.")
3199 (defcustom org-global-properties nil
3200 "List of property/value pairs that can be inherited by any entry.
3202 This list will be combined with the constant `org-global-properties-fixed'.
3204 The entries in this list are cons cells where the car is a property
3205 name and cdr is a string with the value.
3207 You can set buffer-local values for the same purpose in the variable
3208 `org-file-properties' this by adding lines like
3210 #+PROPERTY: NAME VALUE"
3211 :group 'org-properties
3212 :type '(repeat
3213 (cons (string :tag "Property")
3214 (string :tag "Value"))))
3216 (defvar org-file-properties nil
3217 "List of property/value pairs that can be inherited by any entry.
3218 Valid for the current buffer.
3219 This variable is populated from #+PROPERTY lines.")
3220 (make-variable-buffer-local 'org-file-properties)
3222 (defgroup org-agenda nil
3223 "Options concerning agenda views in Org-mode."
3224 :tag "Org Agenda"
3225 :group 'org)
3227 (defvar org-category nil
3228 "Variable used by org files to set a category for agenda display.
3229 Such files should use a file variable to set it, for example
3231 # -*- mode: org; org-category: \"ELisp\"
3233 or contain a special line
3235 #+CATEGORY: ELisp
3237 If the file does not specify a category, then file's base name
3238 is used instead.")
3239 (make-variable-buffer-local 'org-category)
3240 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3242 (defcustom org-agenda-files nil
3243 "The files to be used for agenda display.
3244 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3245 \\[org-remove-file]. You can also use customize to edit the list.
3247 If an entry is a directory, all files in that directory that are matched by
3248 `org-agenda-file-regexp' will be part of the file list.
3250 If the value of the variable is not a list but a single file name, then
3251 the list of agenda files is actually stored and maintained in that file, one
3252 agenda file per line. In this file paths can be given relative to
3253 `org-directory'. Tilde expansion and environment variable substitution
3254 are also made."
3255 :group 'org-agenda
3256 :type '(choice
3257 (repeat :tag "List of files and directories" file)
3258 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3260 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3261 "Regular expression to match files for `org-agenda-files'.
3262 If any element in the list in that variable contains a directory instead
3263 of a normal file, all files in that directory that are matched by this
3264 regular expression will be included."
3265 :group 'org-agenda
3266 :type 'regexp)
3268 (defcustom org-agenda-text-search-extra-files nil
3269 "List of extra files to be searched by text search commands.
3270 These files will be search in addition to the agenda files by the
3271 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3272 Note that these files will only be searched for text search commands,
3273 not for the other agenda views like todo lists, tag searches or the weekly
3274 agenda. This variable is intended to list notes and possibly archive files
3275 that should also be searched by these two commands.
3276 In fact, if the first element in the list is the symbol `agenda-archives',
3277 than all archive files of all agenda files will be added to the search
3278 scope."
3279 :group 'org-agenda
3280 :type '(set :greedy t
3281 (const :tag "Agenda Archives" agenda-archives)
3282 (repeat :inline t (file))))
3284 (if (fboundp 'defvaralias)
3285 (defvaralias 'org-agenda-multi-occur-extra-files
3286 'org-agenda-text-search-extra-files))
3288 (defcustom org-agenda-skip-unavailable-files nil
3289 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3290 A nil value means to remove them, after a query, from the list."
3291 :group 'org-agenda
3292 :type 'boolean)
3294 (defcustom org-calendar-to-agenda-key [?c]
3295 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3296 The command `org-calendar-goto-agenda' will be bound to this key. The
3297 default is the character `c' because then `c' can be used to switch back and
3298 forth between agenda and calendar."
3299 :group 'org-agenda
3300 :type 'sexp)
3302 (defcustom org-calendar-agenda-action-key [?k]
3303 "The key to be installed in `calendar-mode-map' for agenda-action.
3304 The command `org-agenda-action' will be bound to this key. The
3305 default is the character `k' because we use the same key in the agenda."
3306 :group 'org-agenda
3307 :type 'sexp)
3309 (defcustom org-calendar-insert-diary-entry-key [?i]
3310 "The key to be installed in `calendar-mode-map' for adding diary entries.
3311 This option is irrelevant until `org-agenda-diary-file' has been configured
3312 to point to an Org-mode file. When that is the case, the command
3313 `org-agenda-diary-entry' will be bound to the key given here, by default
3314 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3315 if you want to continue doing this, you need to change this to a different
3316 key."
3317 :group 'org-agenda
3318 :type 'sexp)
3320 (defcustom org-agenda-diary-file 'diary-file
3321 "File to which to add new entries with the `i' key in agenda and calendar.
3322 When this is the symbol `diary-file', the functionality in the Emacs
3323 calendar will be used to add entries to the `diary-file'. But when this
3324 points to a file, `org-agenda-diary-entry' will be used instead."
3325 :group 'org-agenda
3326 :type '(choice
3327 (const :tag "The standard Emacs diary file" diary-file)
3328 (file :tag "Special Org file diary entries")))
3330 (eval-after-load "calendar"
3331 '(progn
3332 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3333 'org-calendar-goto-agenda)
3334 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3335 'org-agenda-action)
3336 (add-hook 'calendar-mode-hook
3337 (lambda ()
3338 (unless (eq org-agenda-diary-file 'diary-file)
3339 (define-key calendar-mode-map
3340 org-calendar-insert-diary-entry-key
3341 'org-agenda-diary-entry))))))
3343 (defgroup org-latex nil
3344 "Options for embedding LaTeX code into Org-mode."
3345 :tag "Org LaTeX"
3346 :group 'org)
3348 (defcustom org-format-latex-options
3349 '(:foreground default :background default :scale 1.0
3350 :html-foreground "Black" :html-background "Transparent"
3351 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3352 "Options for creating images from LaTeX fragments.
3353 This is a property list with the following properties:
3354 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3355 `default' means use the foreground of the default face.
3356 :background the background color, or \"Transparent\".
3357 `default' means use the background of the default face.
3358 :scale a scaling factor for the size of the images, to get more pixels
3359 :html-foreground, :html-background, :html-scale
3360 the same numbers for HTML export.
3361 :matchers a list indicating which matchers should be used to
3362 find LaTeX fragments. Valid members of this list are:
3363 \"begin\" find environments
3364 \"$1\" find single characters surrounded by $.$
3365 \"$\" find math expressions surrounded by $...$
3366 \"$$\" find math expressions surrounded by $$....$$
3367 \"\\(\" find math expressions surrounded by \\(...\\)
3368 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3369 :group 'org-latex
3370 :type 'plist)
3372 (defcustom org-format-latex-signal-error t
3373 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3374 When nil, just push out a message."
3375 :group 'org-latex
3376 :version "24.1"
3377 :type 'boolean)
3379 (defcustom org-latex-to-mathml-jar-file nil
3380 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3381 Use this to specify additional executable file say a jar file.
3383 When using MathToWeb as the converter, specify the full-path to
3384 your mathtoweb.jar file."
3385 :group 'org-latex
3386 :version "24.1"
3387 :type '(choice
3388 (const :tag "None" nil)
3389 (file :tag "JAR file" :must-match t)))
3391 (defcustom org-latex-to-mathml-convert-command nil
3392 "Command to convert LaTeX fragments to MathML.
3393 Replace format-specifiers in the command as noted below and use
3394 `shell-command' to convert LaTeX to MathML.
3395 %j: Executable file in fully expanded form as specified by
3396 `org-latex-to-mathml-jar-file'.
3397 %I: Input LaTeX file in fully expanded form
3398 %o: Output MathML file
3399 This command is used by `org-create-math-formula'.
3401 When using MathToWeb as the converter, set this to
3402 \"java -jar %j -unicode -force -df %o %I\"."
3403 :group 'org-latex
3404 :version "24.1"
3405 :type '(choice
3406 (const :tag "None" nil)
3407 (string :tag "\nShell command")))
3409 (defcustom org-latex-create-formula-image-program 'dvipng
3410 "Program to convert LaTeX fragments with.
3412 dvipng Process the LaTeX fragments to dvi file, then convert
3413 dvi files to png files using dvipng.
3414 This will also include processing of non-math environments.
3415 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3416 to convert pdf files to png files"
3417 :group 'org-latex
3418 :version "24.1"
3419 :type '(choice
3420 (const :tag "dvipng" dvipng)
3421 (const :tag "imagemagick" imagemagick)))
3423 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3424 "Path to store latex preview images. A relative path here creates many
3425 directories relative to the processed org files paths. An absolute path
3426 puts all preview images at the same place."
3427 :group 'org-latex
3428 :version "24.3"
3429 :type 'string)
3431 (defun org-format-latex-mathml-available-p ()
3432 "Return t if `org-latex-to-mathml-convert-command' is usable."
3433 (save-match-data
3434 (when (and (boundp 'org-latex-to-mathml-convert-command)
3435 org-latex-to-mathml-convert-command)
3436 (let ((executable (car (split-string
3437 org-latex-to-mathml-convert-command))))
3438 (when (executable-find executable)
3439 (if (string-match
3440 "%j" org-latex-to-mathml-convert-command)
3441 (file-readable-p org-latex-to-mathml-jar-file)
3442 t))))))
3444 (defcustom org-format-latex-header "\\documentclass{article}
3445 \\usepackage[usenames]{color}
3446 \\usepackage{amsmath}
3447 \\usepackage[mathscr]{eucal}
3448 \\pagestyle{empty} % do not remove
3449 \[PACKAGES]
3450 \[DEFAULT-PACKAGES]
3451 % The settings below are copied from fullpage.sty
3452 \\setlength{\\textwidth}{\\paperwidth}
3453 \\addtolength{\\textwidth}{-3cm}
3454 \\setlength{\\oddsidemargin}{1.5cm}
3455 \\addtolength{\\oddsidemargin}{-2.54cm}
3456 \\setlength{\\evensidemargin}{\\oddsidemargin}
3457 \\setlength{\\textheight}{\\paperheight}
3458 \\addtolength{\\textheight}{-\\headheight}
3459 \\addtolength{\\textheight}{-\\headsep}
3460 \\addtolength{\\textheight}{-\\footskip}
3461 \\addtolength{\\textheight}{-3cm}
3462 \\setlength{\\topmargin}{1.5cm}
3463 \\addtolength{\\topmargin}{-2.54cm}"
3464 "The document header used for processing LaTeX fragments.
3465 It is imperative that this header make sure that no page number
3466 appears on the page. The package defined in the variables
3467 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3468 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3469 will be appended."
3470 :group 'org-latex
3471 :type 'string)
3473 (defvar org-format-latex-header-extra nil)
3475 (defun org-set-packages-alist (var val)
3476 "Set the packages alist and make sure it has 3 elements per entry."
3477 (set var (mapcar (lambda (x)
3478 (if (and (consp x) (= (length x) 2))
3479 (list (car x) (nth 1 x) t)
3481 val)))
3483 (defun org-get-packages-alist (var)
3485 "Get the packages alist and make sure it has 3 elements per entry."
3486 (mapcar (lambda (x)
3487 (if (and (consp x) (= (length x) 2))
3488 (list (car x) (nth 1 x) t)
3490 (default-value var)))
3492 ;; The following variables are defined here because is it also used
3493 ;; when formatting latex fragments. Originally it was part of the
3494 ;; LaTeX exporter, which is why the name includes "export".
3495 (defcustom org-export-latex-default-packages-alist
3496 '(("AUTO" "inputenc" t)
3497 ("T1" "fontenc" t)
3498 ("" "fixltx2e" nil)
3499 ("" "graphicx" t)
3500 ("" "longtable" nil)
3501 ("" "float" nil)
3502 ("" "wrapfig" nil)
3503 ("" "soul" t)
3504 ("" "textcomp" t)
3505 ("" "marvosym" t)
3506 ("" "wasysym" t)
3507 ("" "latexsym" t)
3508 ("" "amssymb" t)
3509 ("" "hyperref" nil)
3510 "\\tolerance=1000"
3512 "Alist of default packages to be inserted in the header.
3513 Change this only if one of the packages here causes an incompatibility
3514 with another package you are using.
3515 The packages in this list are needed by one part or another of Org-mode
3516 to function properly.
3518 - inputenc, fontenc: for basic font and character selection
3519 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3520 for interpreting the entities in `org-entities'. You can skip some of these
3521 packages if you don't use any of the symbols in it.
3522 - graphicx: for including images
3523 - float, wrapfig: for figure placement
3524 - longtable: for long tables
3525 - hyperref: for cross references
3527 Therefore you should not modify this variable unless you know what you
3528 are doing. The one reason to change it anyway is that you might be loading
3529 some other package that conflicts with one of the default packages.
3530 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3531 If SNIPPET-FLAG is t, the package also needs to be included when
3532 compiling LaTeX snippets into images for inclusion into HTML."
3533 :group 'org-export-latex
3534 :set 'org-set-packages-alist
3535 :get 'org-get-packages-alist
3536 :version "24.1"
3537 :type '(repeat
3538 (choice
3539 (list :tag "options/package pair"
3540 (string :tag "options")
3541 (string :tag "package")
3542 (boolean :tag "Snippet"))
3543 (string :tag "A line of LaTeX"))))
3545 (defcustom org-export-latex-packages-alist nil
3546 "Alist of packages to be inserted in every LaTeX header.
3547 These will be inserted after `org-export-latex-default-packages-alist'.
3548 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3549 SNIPPET-FLAG, when t, indicates that this package is also needed when
3550 turning LaTeX snippets into images for inclusion into HTML.
3551 Make sure that you only list packages here which:
3552 - you want in every file
3553 - do not conflict with the default packages in
3554 `org-export-latex-default-packages-alist'
3555 - do not conflict with the setup in `org-format-latex-header'."
3556 :group 'org-export-latex
3557 :set 'org-set-packages-alist
3558 :get 'org-get-packages-alist
3559 :type '(repeat
3560 (choice
3561 (list :tag "options/package pair"
3562 (string :tag "options")
3563 (string :tag "package")
3564 (boolean :tag "Snippet"))
3565 (string :tag "A line of LaTeX"))))
3568 (defgroup org-appearance nil
3569 "Settings for Org-mode appearance."
3570 :tag "Org Appearance"
3571 :group 'org)
3573 (defcustom org-level-color-stars-only nil
3574 "Non-nil means fontify only the stars in each headline.
3575 When nil, the entire headline is fontified.
3576 Changing it requires restart of `font-lock-mode' to become effective
3577 also in regions already fontified."
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hide-leading-stars nil
3582 "Non-nil means hide the first N-1 stars in a headline.
3583 This works by using the face `org-hide' for these stars. This
3584 face is white for a light background, and black for a dark
3585 background. You may have to customize the face `org-hide' to
3586 make this work.
3587 Changing it requires restart of `font-lock-mode' to become effective
3588 also in regions already fontified.
3589 You may also set this on a per-file basis by adding one of the following
3590 lines to the buffer:
3592 #+STARTUP: hidestars
3593 #+STARTUP: showstars"
3594 :group 'org-appearance
3595 :type 'boolean)
3597 (defcustom org-hidden-keywords nil
3598 "List of symbols corresponding to keywords to be hidden the org buffer.
3599 For example, a value '(title) for this list will make the document's title
3600 appear in the buffer without the initial #+TITLE: keyword."
3601 :group 'org-appearance
3602 :version "24.1"
3603 :type '(set (const :tag "#+AUTHOR" author)
3604 (const :tag "#+DATE" date)
3605 (const :tag "#+EMAIL" email)
3606 (const :tag "#+TITLE" title)))
3608 (defcustom org-custom-properties nil
3609 "List of properties (as strings) with a special meaning.
3610 The default use of these custom properties is to let the user
3611 hide them with `org-toggle-custom-properties-visibility'."
3612 :group 'org-properties
3613 :group 'org-appearance
3614 :version "24.3"
3615 :type '(repeat (string :tag "Property Name")))
3617 (defcustom org-fontify-done-headline nil
3618 "Non-nil means change the face of a headline if it is marked DONE.
3619 Normally, only the TODO/DONE keyword indicates the state of a headline.
3620 When this is non-nil, the headline after the keyword is set to the
3621 `org-headline-done' as an additional indication."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-fontify-emphasized-text t
3626 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3627 Changing this variable requires a restart of Emacs to take effect."
3628 :group 'org-appearance
3629 :type 'boolean)
3631 (defcustom org-fontify-whole-heading-line nil
3632 "Non-nil means fontify the whole line for headings.
3633 This is useful when setting a background color for the
3634 org-level-* faces."
3635 :group 'org-appearance
3636 :type 'boolean)
3638 (defcustom org-highlight-latex-fragments-and-specials nil
3639 "Non-nil means fontify what is treated specially by the exporters."
3640 :group 'org-appearance
3641 :type 'boolean)
3643 (defcustom org-hide-emphasis-markers nil
3644 "Non-nil mean font-lock should hide the emphasis marker characters."
3645 :group 'org-appearance
3646 :type 'boolean)
3648 (defcustom org-pretty-entities nil
3649 "Non-nil means show entities as UTF8 characters.
3650 When nil, the \\name form remains in the buffer."
3651 :group 'org-appearance
3652 :version "24.1"
3653 :type 'boolean)
3655 (defcustom org-pretty-entities-include-sub-superscripts t
3656 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3657 :group 'org-appearance
3658 :version "24.1"
3659 :type 'boolean)
3661 (defvar org-emph-re nil
3662 "Regular expression for matching emphasis.
3663 After a match, the match groups contain these elements:
3664 0 The match of the full regular expression, including the characters
3665 before and after the proper match
3666 1 The character before the proper match, or empty at beginning of line
3667 2 The proper match, including the leading and trailing markers
3668 3 The leading marker like * or /, indicating the type of highlighting
3669 4 The text between the emphasis markers, not including the markers
3670 5 The character after the match, empty at the end of a line")
3671 (defvar org-verbatim-re nil
3672 "Regular expression for matching verbatim text.")
3673 (defvar org-emphasis-regexp-components) ; defined just below
3674 (defvar org-emphasis-alist) ; defined just below
3675 (defun org-set-emph-re (var val)
3676 "Set variable and compute the emphasis regular expression."
3677 (set var val)
3678 (when (and (boundp 'org-emphasis-alist)
3679 (boundp 'org-emphasis-regexp-components)
3680 org-emphasis-alist org-emphasis-regexp-components)
3681 (let* ((e org-emphasis-regexp-components)
3682 (pre (car e))
3683 (post (nth 1 e))
3684 (border (nth 2 e))
3685 (body (nth 3 e))
3686 (nl (nth 4 e))
3687 (body1 (concat body "*?"))
3688 (markers (mapconcat 'car org-emphasis-alist ""))
3689 (vmarkers (mapconcat
3690 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3691 org-emphasis-alist "")))
3692 ;; make sure special characters appear at the right position in the class
3693 (if (string-match "\\^" markers)
3694 (setq markers (concat (replace-match "" t t markers) "^")))
3695 (if (string-match "-" markers)
3696 (setq markers (concat (replace-match "" t t markers) "-")))
3697 (if (string-match "\\^" vmarkers)
3698 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3699 (if (string-match "-" vmarkers)
3700 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3701 (if (> nl 0)
3702 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3703 (int-to-string nl) "\\}")))
3704 ;; Make the regexp
3705 (setq org-emph-re
3706 (concat "\\([" pre "]\\|^\\)"
3707 "\\("
3708 "\\([" markers "]\\)"
3709 "\\("
3710 "[^" border "]\\|"
3711 "[^" border "]"
3712 body1
3713 "[^" border "]"
3714 "\\)"
3715 "\\3\\)"
3716 "\\([" post "]\\|$\\)"))
3717 (setq org-verbatim-re
3718 (concat "\\([" pre "]\\|^\\)"
3719 "\\("
3720 "\\([" vmarkers "]\\)"
3721 "\\("
3722 "[^" border "]\\|"
3723 "[^" border "]"
3724 body1
3725 "[^" border "]"
3726 "\\)"
3727 "\\3\\)"
3728 "\\([" post "]\\|$\\)")))))
3730 (defcustom org-emphasis-regexp-components
3731 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3732 "Components used to build the regular expression for emphasis.
3733 This is a list with five entries. Terminology: In an emphasis string
3734 like \" *strong word* \", we call the initial space PREMATCH, the final
3735 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3736 and \"trong wor\" is the body. The different components in this variable
3737 specify what is allowed/forbidden in each part:
3739 pre Chars allowed as prematch. Beginning of line will be allowed too.
3740 post Chars allowed as postmatch. End of line will be allowed too.
3741 border The chars *forbidden* as border characters.
3742 body-regexp A regexp like \".\" to match a body character. Don't use
3743 non-shy groups here, and don't allow newline here.
3744 newline The maximum number of newlines allowed in an emphasis exp.
3746 Use customize to modify this, or restart Emacs after changing it."
3747 :group 'org-appearance
3748 :set 'org-set-emph-re
3749 :type '(list
3750 (sexp :tag "Allowed chars in pre ")
3751 (sexp :tag "Allowed chars in post ")
3752 (sexp :tag "Forbidden chars in border ")
3753 (sexp :tag "Regexp for body ")
3754 (integer :tag "number of newlines allowed")
3755 (option (boolean :tag "Please ignore this button"))))
3757 (defcustom org-emphasis-alist
3758 `(("*" bold "<b>" "</b>")
3759 ("/" italic "<i>" "</i>")
3760 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3761 ("=" org-code "<code>" "</code>" verbatim)
3762 ("~" org-verbatim "<code>" "</code>" verbatim)
3763 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3764 "<del>" "</del>")
3766 "Special syntax for emphasized text.
3767 Text starting and ending with a special character will be emphasized, for
3768 example *bold*, _underlined_ and /italic/. This variable sets the marker
3769 characters, the face to be used by font-lock for highlighting in Org-mode
3770 Emacs buffers, and the HTML tags to be used for this.
3771 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3772 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3773 Use customize to modify this, or restart Emacs after changing it."
3774 :group 'org-appearance
3775 :set 'org-set-emph-re
3776 :type '(repeat
3777 (list
3778 (string :tag "Marker character")
3779 (choice
3780 (face :tag "Font-lock-face")
3781 (plist :tag "Face property list"))
3782 (string :tag "HTML start tag")
3783 (string :tag "HTML end tag")
3784 (option (const verbatim)))))
3786 (defvar org-protecting-blocks
3787 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3788 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3789 This is needed for font-lock setup.")
3791 ;;; Miscellaneous options
3793 (defgroup org-completion nil
3794 "Completion in Org-mode."
3795 :tag "Org Completion"
3796 :group 'org)
3798 (defcustom org-completion-use-ido nil
3799 "Non-nil means use ido completion wherever possible.
3800 Note that `ido-mode' must be active for this variable to be relevant.
3801 If you decide to turn this variable on, you might well want to turn off
3802 `org-outline-path-complete-in-steps'.
3803 See also `org-completion-use-iswitchb'."
3804 :group 'org-completion
3805 :type 'boolean)
3807 (defcustom org-completion-use-iswitchb nil
3808 "Non-nil means use iswitchb completion wherever possible.
3809 Note that `iswitchb-mode' must be active for this variable to be relevant.
3810 If you decide to turn this variable on, you might well want to turn off
3811 `org-outline-path-complete-in-steps'.
3812 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3813 :group 'org-completion
3814 :type 'boolean)
3816 (defcustom org-completion-fallback-command 'hippie-expand
3817 "The expansion command called by \\[pcomplete] in normal context.
3818 Normal means, no org-mode-specific context."
3819 :group 'org-completion
3820 :type 'function)
3822 ;;; Functions and variables from their packages
3823 ;; Declared here to avoid compiler warnings
3825 ;; XEmacs only
3826 (defvar outline-mode-menu-heading)
3827 (defvar outline-mode-menu-show)
3828 (defvar outline-mode-menu-hide)
3829 (defvar zmacs-regions) ; XEmacs regions
3831 ;; Emacs only
3832 (defvar mark-active)
3834 ;; Various packages
3835 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3836 (declare-function calendar-forward-day "cal-move" (arg))
3837 (declare-function calendar-goto-date "cal-move" (date))
3838 (declare-function calendar-goto-today "cal-move" ())
3839 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3840 (defvar calc-embedded-close-formula)
3841 (defvar calc-embedded-open-formula)
3842 (declare-function cdlatex-tab "ext:cdlatex" ())
3843 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3844 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3845 (defvar font-lock-unfontify-region-function)
3846 (declare-function iswitchb-read-buffer "iswitchb"
3847 (prompt &optional default require-match start matches-set))
3848 (defvar iswitchb-temp-buflist)
3849 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3850 (defvar org-agenda-tags-todo-honor-ignore-options)
3851 (declare-function org-agenda-skip "org-agenda" ())
3852 (declare-function
3853 org-agenda-format-item "org-agenda"
3854 (extra txt &optional category tags dotime noprefix remove-re habitp))
3855 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3856 (declare-function org-agenda-change-all-lines "org-agenda"
3857 (newhead hdmarker &optional fixface just-this))
3858 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3859 (declare-function org-agenda-maybe-redo "org-agenda" ())
3860 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3861 (beg end))
3862 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3863 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3864 "org-agenda" (&optional end))
3865 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3866 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3867 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3868 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3869 (declare-function org-indent-mode "org-indent" (&optional arg))
3870 (declare-function parse-time-string "parse-time" (string))
3871 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3872 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3873 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3874 (defvar remember-data-file)
3875 (defvar texmathp-why)
3876 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3877 (declare-function table--at-cell-p "table" (position &optional object at-column))
3879 (defvar w3m-current-url)
3880 (defvar w3m-current-title)
3882 (defvar org-latex-regexps)
3884 ;;; Autoload and prepare some org modules
3886 ;; Some table stuff that needs to be defined here, because it is used
3887 ;; by the functions setting up org-mode or checking for table context.
3889 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3890 "Detect an org-type or table-type table.")
3891 (defconst org-table-line-regexp "^[ \t]*|"
3892 "Detect an org-type table line.")
3893 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3894 "Detect an org-type table line.")
3895 (defconst org-table-hline-regexp "^[ \t]*|-"
3896 "Detect an org-type table hline.")
3897 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3898 "Detect a table-type table hline.")
3899 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3900 "Detect the first line outside a table when searching from within it.
3901 This works for both table types.")
3903 ;; Autoload the functions in org-table.el that are needed by functions here.
3905 (eval-and-compile
3906 (org-autoload "org-table"
3907 '(org-table-align org-table-begin org-table-blank-field
3908 org-table-convert org-table-convert-region org-table-copy-down
3909 org-table-copy-region org-table-create
3910 org-table-create-or-convert-from-region
3911 org-table-create-with-table.el org-table-current-dline
3912 org-table-cut-region org-table-delete-column org-table-edit-field
3913 org-table-edit-formulas org-table-end org-table-eval-formula
3914 org-table-export org-table-field-info
3915 org-table-get-stored-formulas org-table-goto-column
3916 org-table-hline-and-move org-table-import org-table-insert-column
3917 org-table-insert-hline org-table-insert-row org-table-iterate
3918 org-table-justify-field-maybe org-table-kill-row
3919 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3920 org-table-move-column org-table-move-column-left
3921 org-table-move-column-right org-table-move-row
3922 org-table-move-row-down org-table-move-row-up
3923 org-table-next-field org-table-next-row org-table-paste-rectangle
3924 org-table-previous-field org-table-recalculate
3925 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3926 org-table-toggle-coordinate-overlays
3927 org-table-toggle-formula-debugger org-table-wrap-region
3928 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3929 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3930 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3932 (defun org-at-table-p (&optional table-type)
3933 "Return t if the cursor is inside an org-type table.
3934 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3935 (if org-enable-table-editor
3936 (save-excursion
3937 (beginning-of-line 1)
3938 (looking-at (if table-type org-table-any-line-regexp
3939 org-table-line-regexp)))
3940 nil))
3941 (defsubst org-table-p () (org-at-table-p))
3943 (defun org-at-table.el-p ()
3944 "Return t if and only if we are at a table.el table."
3945 (and (org-at-table-p 'any)
3946 (save-excursion
3947 (goto-char (org-table-begin 'any))
3948 (looking-at org-table1-hline-regexp))))
3949 (defun org-table-recognize-table.el ()
3950 "If there is a table.el table nearby, recognize it and move into it."
3951 (if org-table-tab-recognizes-table.el
3952 (if (org-at-table.el-p)
3953 (progn
3954 (beginning-of-line 1)
3955 (if (looking-at org-table-dataline-regexp)
3957 (if (looking-at org-table1-hline-regexp)
3958 (progn
3959 (beginning-of-line 2)
3960 (if (looking-at org-table-any-border-regexp)
3961 (beginning-of-line -1)))))
3962 (if (re-search-forward "|" (org-table-end t) t)
3963 (progn
3964 (require 'table)
3965 (if (table--at-cell-p (point))
3967 (message "recognizing table.el table...")
3968 (table-recognize-table)
3969 (message "recognizing table.el table...done")))
3970 (error "This should not happen"))
3972 nil)
3973 nil))
3975 (defun org-at-table-hline-p ()
3976 "Return t if the cursor is inside a hline in a table."
3977 (if org-enable-table-editor
3978 (save-excursion
3979 (beginning-of-line 1)
3980 (looking-at org-table-hline-regexp))
3981 nil))
3983 (defvar org-table-clean-did-remove-column nil)
3985 (defun org-table-map-tables (function &optional quietly)
3986 "Apply FUNCTION to the start of all tables in the buffer."
3987 (save-excursion
3988 (save-restriction
3989 (widen)
3990 (goto-char (point-min))
3991 (while (re-search-forward org-table-any-line-regexp nil t)
3992 (unless quietly
3993 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3994 (beginning-of-line 1)
3995 (when (and (looking-at org-table-line-regexp)
3996 ;; Exclude tables in src/example/verbatim/clocktable blocks
3997 (not (org-in-block-p '("src" "example"))))
3998 (save-excursion (funcall function))
3999 (or (looking-at org-table-line-regexp)
4000 (forward-char 1)))
4001 (re-search-forward org-table-any-border-regexp nil 1))))
4002 (unless quietly (message "Mapping tables: done")))
4004 ;; Declare and autoload functions from org-exp.el & Co
4006 (declare-function org-default-export-plist "org-exp")
4007 (declare-function org-infile-export-plist "org-exp")
4008 (declare-function org-get-current-options "org-exp")
4009 (eval-and-compile
4010 (org-autoload "org-exp"
4011 '(org-export org-export-visible
4012 org-insert-export-options-template
4013 org-table-clean-before-export))
4014 (org-autoload "org-ascii"
4015 '(org-export-as-ascii org-export-ascii-preprocess
4016 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4017 org-export-region-as-ascii))
4018 (org-autoload "org-latex"
4019 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4020 org-replace-region-by-latex org-export-region-as-latex
4021 org-export-as-latex org-export-as-pdf
4022 org-export-as-pdf-and-open))
4023 (org-autoload "org-html"
4024 '(org-export-as-html-and-open
4025 org-export-as-html-batch org-export-as-html-to-buffer
4026 org-replace-region-by-html org-export-region-as-html
4027 org-export-as-html))
4028 (org-autoload "org-docbook"
4029 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4030 org-replace-region-by-docbook org-export-region-as-docbook
4031 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4032 org-export-as-docbook))
4033 (org-autoload "org-icalendar"
4034 '(org-export-icalendar-this-file
4035 org-export-icalendar-all-agenda-files
4036 org-export-icalendar-combine-agenda-files))
4037 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4038 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4040 ;; Declare and autoload functions from org-agenda.el
4042 (eval-and-compile
4043 (org-autoload "org-agenda"
4044 '(org-agenda org-agenda-list org-search-view
4045 org-todo-list org-tags-view org-agenda-list-stuck-projects
4046 org-diary org-agenda-to-appt
4047 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4049 ;; Autoload org-remember
4051 (eval-and-compile
4052 (org-autoload "org-remember"
4053 '(org-remember-insinuate org-remember-annotation
4054 org-remember-apply-template org-remember org-remember-handler)))
4056 (eval-and-compile
4057 (org-autoload "org-capture"
4058 '(org-capture org-capture-insert-template-here
4059 org-capture-import-remember-templates)))
4061 ;; Autoload org-clock.el
4063 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4064 (beg end))
4065 (declare-function org-clock-update-mode-line "org-clock" ())
4066 (declare-function org-resolve-clocks "org-clock"
4067 (&optional also-non-dangling-p prompt last-valid))
4068 (defvar org-clock-start-time)
4069 (defvar org-clock-marker (make-marker)
4070 "Marker recording the last clock-in.")
4071 (defvar org-clock-hd-marker (make-marker)
4072 "Marker recording the last clock-in, but the headline position.")
4073 (defvar org-clock-heading ""
4074 "The heading of the current clock entry.")
4075 (defun org-clock-is-active ()
4076 "Return non-nil if clock is currently running.
4077 The return value is actually the clock marker."
4078 (marker-buffer org-clock-marker))
4080 (eval-and-compile
4081 (org-autoload
4082 "org-clock"
4083 '(org-clock-in org-clock-out org-clock-cancel
4084 org-clock-goto org-clock-sum org-clock-display
4085 org-clock-remove-overlays org-clock-report
4086 org-clocktable-shift org-dblock-write:clocktable
4087 org-get-clocktable org-resolve-clocks)))
4089 (defun org-clock-update-time-maybe ()
4090 "If this is a CLOCK line, update it and return t.
4091 Otherwise, return nil."
4092 (interactive)
4093 (save-excursion
4094 (beginning-of-line 1)
4095 (skip-chars-forward " \t")
4096 (when (looking-at org-clock-string)
4097 (let ((re (concat "[ \t]*" org-clock-string
4098 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4099 "\\([ \t]*=>.*\\)?\\)?"))
4100 ts te h m s neg)
4101 (cond
4102 ((not (looking-at re))
4103 nil)
4104 ((not (match-end 2))
4105 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4106 (> org-clock-marker (point))
4107 (<= org-clock-marker (point-at-eol)))
4108 ;; The clock is running here
4109 (setq org-clock-start-time
4110 (apply 'encode-time
4111 (org-parse-time-string (match-string 1))))
4112 (org-clock-update-mode-line)))
4114 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4115 (end-of-line 1)
4116 (setq ts (match-string 1)
4117 te (match-string 3))
4118 (setq s (- (org-float-time
4119 (apply 'encode-time (org-parse-time-string te)))
4120 (org-float-time
4121 (apply 'encode-time (org-parse-time-string ts))))
4122 neg (< s 0)
4123 s (abs s)
4124 h (floor (/ s 3600))
4125 s (- s (* 3600 h))
4126 m (floor (/ s 60))
4127 s (- s (* 60 s)))
4128 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4129 t))))))
4131 (defun org-check-running-clock ()
4132 "Check if the current buffer contains the running clock.
4133 If yes, offer to stop it and to save the buffer with the changes."
4134 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4135 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4136 (buffer-name))))
4137 (org-clock-out)
4138 (when (y-or-n-p "Save changed buffer?")
4139 (save-buffer))))
4141 (defun org-clocktable-try-shift (dir n)
4142 "Check if this line starts a clock table, if yes, shift the time block."
4143 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4144 (org-clocktable-shift dir n)))
4146 ;; Autoload org-timer.el
4148 (eval-and-compile
4149 (org-autoload
4150 "org-timer"
4151 '(org-timer-start org-timer org-timer-item
4152 org-timer-change-times-in-region
4153 org-timer-set-timer
4154 org-timer-reset-timers
4155 org-timer-show-remaining-time)))
4157 ;; Autoload org-feed.el
4159 (eval-and-compile
4160 (org-autoload
4161 "org-feed"
4162 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4165 ;; Autoload org-indent.el
4167 ;; Define the variable already here, to make sure we have it.
4168 (defvar org-indent-mode nil
4169 "Non-nil if Org-Indent mode is enabled.
4170 Use the command `org-indent-mode' to change this variable.")
4172 (eval-and-compile
4173 (org-autoload
4174 "org-indent"
4175 '(org-indent-mode)))
4177 ;; Autoload org-mobile.el
4179 (eval-and-compile
4180 (org-autoload
4181 "org-mobile"
4182 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4184 ;; Autoload archiving code
4185 ;; The stuff that is needed for cycling and tags has to be defined here.
4187 (defgroup org-archive nil
4188 "Options concerning archiving in Org-mode."
4189 :tag "Org Archive"
4190 :group 'org-structure)
4192 (defcustom org-archive-location "%s_archive::"
4193 "The location where subtrees should be archived.
4195 The value of this variable is a string, consisting of two parts,
4196 separated by a double-colon. The first part is a filename and
4197 the second part is a headline.
4199 When the filename is omitted, archiving happens in the same file.
4200 %s in the filename will be replaced by the current file
4201 name (without the directory part). Archiving to a different file
4202 is useful to keep archived entries from contributing to the
4203 Org-mode Agenda.
4205 The archived entries will be filed as subtrees of the specified
4206 headline. When the headline is omitted, the subtrees are simply
4207 filed away at the end of the file, as top-level entries. Also in
4208 the heading you can use %s to represent the file name, this can be
4209 useful when using the same archive for a number of different files.
4211 Here are a few examples:
4212 \"%s_archive::\"
4213 If the current file is Projects.org, archive in file
4214 Projects.org_archive, as top-level trees. This is the default.
4216 \"::* Archived Tasks\"
4217 Archive in the current file, under the top-level headline
4218 \"* Archived Tasks\".
4220 \"~/org/archive.org::\"
4221 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4223 \"~/org/archive.org::* From %s\"
4224 Archive in file ~/org/archive.org (absolute path), under headlines
4225 \"From FILENAME\" where file name is the current file name.
4227 \"~/org/datetree.org::datetree/* Finished Tasks\"
4228 The \"datetree/\" string is special, signifying to archive
4229 items to the datetree. Items are placed in either the CLOSED
4230 date of the item, or the current date if there is no CLOSED date.
4231 The heading will be a subentry to the current date. There doesn't
4232 need to be a heading, but there always needs to be a slash after
4233 datetree. For example, to store archived items directly in the
4234 datetree, use \"~/org/datetree.org::datetree/\".
4236 \"basement::** Finished Tasks\"
4237 Archive in file ./basement (relative path), as level 3 trees
4238 below the level 2 heading \"** Finished Tasks\".
4240 You may set this option on a per-file basis by adding to the buffer a
4241 line like
4243 #+ARCHIVE: basement::** Finished Tasks
4245 You may also define it locally for a subtree by setting an ARCHIVE property
4246 in the entry. If such a property is found in an entry, or anywhere up
4247 the hierarchy, it will be used."
4248 :group 'org-archive
4249 :type 'string)
4251 (defcustom org-archive-tag "ARCHIVE"
4252 "The tag that marks a subtree as archived.
4253 An archived subtree does not open during visibility cycling, and does
4254 not contribute to the agenda listings.
4255 After changing this, font-lock must be restarted in the relevant buffers to
4256 get the proper fontification."
4257 :group 'org-archive
4258 :group 'org-keywords
4259 :type 'string)
4261 (defcustom org-agenda-skip-archived-trees t
4262 "Non-nil means the agenda will skip any items located in archived trees.
4263 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4264 variable is no longer recommended, you should leave it at the value t.
4265 Instead, use the key `v' to cycle the archives-mode in the agenda."
4266 :group 'org-archive
4267 :group 'org-agenda-skip
4268 :type 'boolean)
4270 (defcustom org-columns-skip-archived-trees t
4271 "Non-nil means ignore archived trees when creating column view."
4272 :group 'org-archive
4273 :group 'org-properties
4274 :type 'boolean)
4276 (defcustom org-cycle-open-archived-trees nil
4277 "Non-nil means `org-cycle' will open archived trees.
4278 An archived tree is a tree marked with the tag ARCHIVE.
4279 When nil, archived trees will stay folded. You can still open them with
4280 normal outline commands like `show-all', but not with the cycling commands."
4281 :group 'org-archive
4282 :group 'org-cycle
4283 :type 'boolean)
4285 (defcustom org-sparse-tree-open-archived-trees nil
4286 "Non-nil means sparse tree construction shows matches in archived trees.
4287 When nil, matches in these trees are highlighted, but the trees are kept in
4288 collapsed state."
4289 :group 'org-archive
4290 :group 'org-sparse-trees
4291 :type 'boolean)
4293 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4294 "The default date type when building a sparse tree.
4295 When this is nil, a date is a scheduled or a deadline timestamp.
4296 Otherwise, these types are allowed:
4298 all: all timestamps
4299 active: only active timestamps (<...>)
4300 inactive: only inactive timestamps (<...)
4301 scheduled: only scheduled timestamps
4302 deadline: only deadline timestamps"
4303 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4304 (const :tag "All timestamps" all)
4305 (const :tag "Only active timestamps" active)
4306 (const :tag "Only inactive timestamps" inactive)
4307 (const :tag "Only scheduled timestamps" scheduled)
4308 (const :tag "Only deadline timestamps" deadline))
4309 :group 'org-sparse-trees
4310 :version "24.3")
4312 (defun org-cycle-hide-archived-subtrees (state)
4313 "Re-hide all archived subtrees after a visibility state change."
4314 (when (and (not org-cycle-open-archived-trees)
4315 (not (memq state '(overview folded))))
4316 (save-excursion
4317 (let* ((globalp (memq state '(contents all)))
4318 (beg (if globalp (point-min) (point)))
4319 (end (if globalp (point-max) (org-end-of-subtree t))))
4320 (org-hide-archived-subtrees beg end)
4321 (goto-char beg)
4322 (if (looking-at (concat ".*:" org-archive-tag ":"))
4323 (message "%s" (substitute-command-keys
4324 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4326 (defun org-force-cycle-archived ()
4327 "Cycle subtree even if it is archived."
4328 (interactive)
4329 (setq this-command 'org-cycle)
4330 (let ((org-cycle-open-archived-trees t))
4331 (call-interactively 'org-cycle)))
4333 (defun org-hide-archived-subtrees (beg end)
4334 "Re-hide all archived subtrees after a visibility state change."
4335 (save-excursion
4336 (let* ((re (concat ":" org-archive-tag ":")))
4337 (goto-char beg)
4338 (while (re-search-forward re end t)
4339 (when (org-at-heading-p)
4340 (org-flag-subtree t)
4341 (org-end-of-subtree t))))))
4343 (declare-function outline-end-of-heading "outline" ())
4344 (declare-function outline-flag-region "outline" (from to flag))
4345 (defun org-flag-subtree (flag)
4346 (save-excursion
4347 (org-back-to-heading t)
4348 (outline-end-of-heading)
4349 (outline-flag-region (point)
4350 (progn (org-end-of-subtree t) (point))
4351 flag)))
4353 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4355 (eval-and-compile
4356 (org-autoload "org-archive"
4357 '(org-add-archive-files org-archive-subtree
4358 org-archive-to-archive-sibling org-toggle-archive-tag
4359 org-archive-subtree-default
4360 org-archive-subtree-default-with-confirmation)))
4362 ;; Autoload Column View Code
4364 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4365 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4366 (declare-function org-columns-compute "org-colview" (property))
4368 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4369 '(org-columns-number-to-string org-columns-get-format-and-top-level
4370 org-columns-compute org-agenda-columns org-columns-remove-overlays
4371 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4373 ;; Autoload ID code
4375 (declare-function org-id-store-link "org-id")
4376 (declare-function org-id-locations-load "org-id")
4377 (declare-function org-id-locations-save "org-id")
4378 (defvar org-id-track-globally)
4379 (org-autoload "org-id"
4380 '(org-id-get-create org-id-new org-id-copy org-id-get
4381 org-id-get-with-outline-path-completion
4382 org-id-get-with-outline-drilling org-id-store-link
4383 org-id-goto org-id-find org-id-store-link))
4385 ;; Autoload Plotting Code
4387 (org-autoload "org-plot"
4388 '(org-plot/gnuplot))
4390 ;;; Variables for pre-computed regular expressions, all buffer local
4392 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4393 "Matches first line of a hidden block.")
4394 (make-variable-buffer-local 'org-drawer-regexp)
4395 (defvar org-todo-regexp nil
4396 "Matches any of the TODO state keywords.")
4397 (make-variable-buffer-local 'org-todo-regexp)
4398 (defvar org-not-done-regexp nil
4399 "Matches any of the TODO state keywords except the last one.")
4400 (make-variable-buffer-local 'org-not-done-regexp)
4401 (defvar org-not-done-heading-regexp nil
4402 "Matches a TODO headline that is not done.")
4403 (make-variable-buffer-local 'org-not-done-regexp)
4404 (defvar org-todo-line-regexp nil
4405 "Matches a headline and puts TODO state into group 2 if present.")
4406 (make-variable-buffer-local 'org-todo-line-regexp)
4407 (defvar org-complex-heading-regexp nil
4408 "Matches a headline and puts everything into groups:
4409 group 1: the stars
4410 group 2: The todo keyword, maybe
4411 group 3: Priority cookie
4412 group 4: True headline
4413 group 5: Tags")
4414 (make-variable-buffer-local 'org-complex-heading-regexp)
4415 (defvar org-complex-heading-regexp-format nil
4416 "Printf format to make regexp to match an exact headline.
4417 This regexp will match the headline of any node which has the
4418 exact headline text that is put into the format, but may have any
4419 TODO state, priority and tags.")
4420 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4421 (defvar org-todo-line-tags-regexp nil
4422 "Matches a headline and puts TODO state into group 2 if present.
4423 Also put tags into group 4 if tags are present.")
4424 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4425 (defvar org-ds-keyword-length 12
4426 "Maximum length of the Deadline and SCHEDULED keywords.")
4427 (make-variable-buffer-local 'org-ds-keyword-length)
4428 (defvar org-deadline-regexp nil
4429 "Matches the DEADLINE keyword.")
4430 (make-variable-buffer-local 'org-deadline-regexp)
4431 (defvar org-deadline-time-regexp nil
4432 "Matches the DEADLINE keyword together with a time stamp.")
4433 (make-variable-buffer-local 'org-deadline-time-regexp)
4434 (defvar org-deadline-line-regexp nil
4435 "Matches the DEADLINE keyword and the rest of the line.")
4436 (make-variable-buffer-local 'org-deadline-line-regexp)
4437 (defvar org-scheduled-regexp nil
4438 "Matches the SCHEDULED keyword.")
4439 (make-variable-buffer-local 'org-scheduled-regexp)
4440 (defvar org-scheduled-time-regexp nil
4441 "Matches the SCHEDULED keyword together with a time stamp.")
4442 (make-variable-buffer-local 'org-scheduled-time-regexp)
4443 (defvar org-closed-time-regexp nil
4444 "Matches the CLOSED keyword together with a time stamp.")
4445 (make-variable-buffer-local 'org-closed-time-regexp)
4447 (defvar org-keyword-time-regexp nil
4448 "Matches any of the 4 keywords, together with the time stamp.")
4449 (make-variable-buffer-local 'org-keyword-time-regexp)
4450 (defvar org-keyword-time-not-clock-regexp nil
4451 "Matches any of the 3 keywords, together with the time stamp.")
4452 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4453 (defvar org-maybe-keyword-time-regexp nil
4454 "Matches a timestamp, possibly preceded by a keyword.")
4455 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4456 (defvar org-all-time-keywords nil
4457 "List of time keywords.")
4458 (make-variable-buffer-local 'org-all-time-keywords)
4460 (defconst org-plain-time-of-day-regexp
4461 (concat
4462 "\\(\\<[012]?[0-9]"
4463 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4464 "\\(--?"
4465 "\\(\\<[012]?[0-9]"
4466 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4467 "\\)?")
4468 "Regular expression to match a plain time or time range.
4469 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4470 groups carry important information:
4471 0 the full match
4472 1 the first time, range or not
4473 8 the second time, if it is a range.")
4475 (defconst org-plain-time-extension-regexp
4476 (concat
4477 "\\(\\<[012]?[0-9]"
4478 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4479 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4480 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4481 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4482 groups carry important information:
4483 0 the full match
4484 7 hours of duration
4485 9 minutes of duration")
4487 (defconst org-stamp-time-of-day-regexp
4488 (concat
4489 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4490 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4491 "\\(--?"
4492 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4493 "Regular expression to match a timestamp time or time range.
4494 After a match, the following groups carry important information:
4495 0 the full match
4496 1 date plus weekday, for back referencing to make sure both times are on the same day
4497 2 the first time, range or not
4498 4 the second time, if it is a range.")
4500 (defconst org-startup-options
4501 '(("fold" org-startup-folded t)
4502 ("overview" org-startup-folded t)
4503 ("nofold" org-startup-folded nil)
4504 ("showall" org-startup-folded nil)
4505 ("showeverything" org-startup-folded showeverything)
4506 ("content" org-startup-folded content)
4507 ("indent" org-startup-indented t)
4508 ("noindent" org-startup-indented nil)
4509 ("hidestars" org-hide-leading-stars t)
4510 ("showstars" org-hide-leading-stars nil)
4511 ("odd" org-odd-levels-only t)
4512 ("oddeven" org-odd-levels-only nil)
4513 ("align" org-startup-align-all-tables t)
4514 ("noalign" org-startup-align-all-tables nil)
4515 ("inlineimages" org-startup-with-inline-images t)
4516 ("noinlineimages" org-startup-with-inline-images nil)
4517 ("customtime" org-display-custom-times t)
4518 ("logdone" org-log-done time)
4519 ("lognotedone" org-log-done note)
4520 ("nologdone" org-log-done nil)
4521 ("lognoteclock-out" org-log-note-clock-out t)
4522 ("nolognoteclock-out" org-log-note-clock-out nil)
4523 ("logrepeat" org-log-repeat state)
4524 ("lognoterepeat" org-log-repeat note)
4525 ("nologrepeat" org-log-repeat nil)
4526 ("logreschedule" org-log-reschedule time)
4527 ("lognotereschedule" org-log-reschedule note)
4528 ("nologreschedule" org-log-reschedule nil)
4529 ("logredeadline" org-log-redeadline time)
4530 ("lognoteredeadline" org-log-redeadline note)
4531 ("nologredeadline" org-log-redeadline nil)
4532 ("logrefile" org-log-refile time)
4533 ("lognoterefile" org-log-refile note)
4534 ("nologrefile" org-log-refile nil)
4535 ("fninline" org-footnote-define-inline t)
4536 ("nofninline" org-footnote-define-inline nil)
4537 ("fnlocal" org-footnote-section nil)
4538 ("fnauto" org-footnote-auto-label t)
4539 ("fnprompt" org-footnote-auto-label nil)
4540 ("fnconfirm" org-footnote-auto-label confirm)
4541 ("fnplain" org-footnote-auto-label plain)
4542 ("fnadjust" org-footnote-auto-adjust t)
4543 ("nofnadjust" org-footnote-auto-adjust nil)
4544 ("constcgs" constants-unit-system cgs)
4545 ("constSI" constants-unit-system SI)
4546 ("noptag" org-tag-persistent-alist nil)
4547 ("hideblocks" org-hide-block-startup t)
4548 ("nohideblocks" org-hide-block-startup nil)
4549 ("beamer" org-startup-with-beamer-mode t)
4550 ("entitiespretty" org-pretty-entities t)
4551 ("entitiesplain" org-pretty-entities nil))
4552 "Variable associated with STARTUP options for org-mode.
4553 Each element is a list of three items: the startup options (as written
4554 in the #+STARTUP line), the corresponding variable, and the value to set
4555 this variable to if the option is found. An optional forth element PUSH
4556 means to push this value onto the list in the variable.")
4558 (defun org-update-property-plist (key val props)
4559 "Update PROPS with KEY and VAL."
4560 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4561 (key (if appending (substring key 0 (- (length key) 1)) key))
4562 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4563 (previous (cdr (assoc key props))))
4564 (if appending
4565 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4566 (cons (cons key val) remainder))))
4568 (defconst org-block-regexp
4569 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4570 "Regular expression for hiding blocks.")
4571 (defconst org-heading-keyword-regexp-format
4572 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4573 "Printf format for a regexp matching an headline with some keyword.
4574 This regexp will match the headline of any node which has the
4575 exact keyword that is put into the format. The keyword isn't in
4576 any group by default, but the stars and the body are.")
4577 (defconst org-heading-keyword-maybe-regexp-format
4578 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4579 "Printf format for a regexp matching an headline, possibly with some keyword.
4580 This regexp can match any headline with the specified keyword, or
4581 without a keyword. The keyword isn't in any group by default,
4582 but the stars and the body are.")
4584 (defun org-set-regexps-and-options ()
4585 "Precompute regular expressions for current buffer."
4586 (when (derived-mode-p 'org-mode)
4587 (org-set-local 'org-todo-kwd-alist nil)
4588 (org-set-local 'org-todo-key-alist nil)
4589 (org-set-local 'org-todo-key-trigger nil)
4590 (org-set-local 'org-todo-keywords-1 nil)
4591 (org-set-local 'org-done-keywords nil)
4592 (org-set-local 'org-todo-heads nil)
4593 (org-set-local 'org-todo-sets nil)
4594 (org-set-local 'org-todo-log-states nil)
4595 (org-set-local 'org-file-properties nil)
4596 (org-set-local 'org-file-tags nil)
4597 (let ((re (org-make-options-regexp
4598 '("CATEGORY" "TODO" "COLUMNS"
4599 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4600 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4601 "OPTIONS")
4602 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4603 (splitre "[ \t]+")
4604 (scripts org-use-sub-superscripts)
4605 kwds kws0 kwsa key log value cat arch tags const links hw dws
4606 tail sep kws1 prio props ftags drawers beamer-p
4607 ext-setup-or-nil setup-contents (start 0))
4608 (save-excursion
4609 (save-restriction
4610 (widen)
4611 (goto-char (point-min))
4612 (while (or (and ext-setup-or-nil
4613 (string-match re ext-setup-or-nil start)
4614 (setq start (match-end 0)))
4615 (and (setq ext-setup-or-nil nil start 0)
4616 (re-search-forward re nil t)))
4617 (setq key (upcase (match-string 1 ext-setup-or-nil))
4618 value (org-match-string-no-properties 2 ext-setup-or-nil))
4619 (if (stringp value) (setq value (org-trim value)))
4620 (cond
4621 ((equal key "CATEGORY")
4622 (setq cat value))
4623 ((member key '("SEQ_TODO" "TODO"))
4624 (push (cons 'sequence (org-split-string value splitre)) kwds))
4625 ((equal key "TYP_TODO")
4626 (push (cons 'type (org-split-string value splitre)) kwds))
4627 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4628 ;; general TODO-like setup
4629 (push (cons (intern (downcase (match-string 1 key)))
4630 (org-split-string value splitre)) kwds))
4631 ((equal key "TAGS")
4632 (setq tags (append tags (if tags '("\\n") nil)
4633 (org-split-string value splitre))))
4634 ((equal key "COLUMNS")
4635 (org-set-local 'org-columns-default-format value))
4636 ((equal key "LINK")
4637 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4638 (push (cons (match-string 1 value)
4639 (org-trim (match-string 2 value)))
4640 links)))
4641 ((equal key "PRIORITIES")
4642 (setq prio (org-split-string value " +")))
4643 ((equal key "PROPERTY")
4644 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4645 (setq props (org-update-property-plist (match-string 1 value)
4646 (match-string 2 value)
4647 props))))
4648 ((equal key "FILETAGS")
4649 (when (string-match "\\S-" value)
4650 (setq ftags
4651 (append
4652 ftags
4653 (apply 'append
4654 (mapcar (lambda (x) (org-split-string x ":"))
4655 (org-split-string value)))))))
4656 ((equal key "DRAWERS")
4657 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4658 ((equal key "CONSTANTS")
4659 (setq const (append const (org-split-string value splitre))))
4660 ((equal key "STARTUP")
4661 (let ((opts (org-split-string value splitre))
4662 l var val)
4663 (while (setq l (pop opts))
4664 (when (setq l (assoc l org-startup-options))
4665 (setq var (nth 1 l) val (nth 2 l))
4666 (if (not (nth 3 l))
4667 (set (make-local-variable var) val)
4668 (if (not (listp (symbol-value var)))
4669 (set (make-local-variable var) nil))
4670 (set (make-local-variable var) (symbol-value var))
4671 (add-to-list var val))))))
4672 ((equal key "ARCHIVE")
4673 (setq arch value)
4674 (remove-text-properties 0 (length arch)
4675 '(face t fontified t) arch))
4676 ((equal key "LATEX_CLASS")
4677 (setq beamer-p (equal value "beamer")))
4678 ((equal key "OPTIONS")
4679 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4680 (setq scripts (read (match-string 2 value)))))
4681 ((equal key "SETUPFILE")
4682 (setq setup-contents (org-file-contents
4683 (expand-file-name
4684 (org-remove-double-quotes value))
4685 'noerror))
4686 (if (not ext-setup-or-nil)
4687 (setq ext-setup-or-nil setup-contents start 0)
4688 (setq ext-setup-or-nil
4689 (concat (substring ext-setup-or-nil 0 start)
4690 "\n" setup-contents "\n"
4691 (substring ext-setup-or-nil start)))))))
4692 ;; search for property blocks
4693 (goto-char (point-min))
4694 (while (re-search-forward org-block-regexp nil t)
4695 (when (equal "PROPERTY" (upcase (match-string 1)))
4696 (setq value (replace-regexp-in-string
4697 "[\n\r]" " " (match-string 4)))
4698 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4699 (setq props (org-update-property-plist (match-string 1 value)
4700 (match-string 2 value)
4701 props)))))))
4702 (org-set-local 'org-use-sub-superscripts scripts)
4703 (when cat
4704 (org-set-local 'org-category (intern cat))
4705 (push (cons "CATEGORY" cat) props))
4706 (when prio
4707 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4708 (setq prio (mapcar 'string-to-char prio))
4709 (org-set-local 'org-highest-priority (nth 0 prio))
4710 (org-set-local 'org-lowest-priority (nth 1 prio))
4711 (org-set-local 'org-default-priority (nth 2 prio)))
4712 (and props (org-set-local 'org-file-properties (nreverse props)))
4713 (and ftags (org-set-local 'org-file-tags
4714 (mapcar 'org-add-prop-inherited ftags)))
4715 (and drawers (org-set-local 'org-drawers drawers))
4716 (and arch (org-set-local 'org-archive-location arch))
4717 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4718 ;; Process the TODO keywords
4719 (unless kwds
4720 ;; Use the global values as if they had been given locally.
4721 (setq kwds (default-value 'org-todo-keywords))
4722 (if (stringp (car kwds))
4723 (setq kwds (list (cons org-todo-interpretation
4724 (default-value 'org-todo-keywords)))))
4725 (setq kwds (reverse kwds)))
4726 (setq kwds (nreverse kwds))
4727 (let (inter kws kw)
4728 (while (setq kws (pop kwds))
4729 (let ((kws (or
4730 (run-hook-with-args-until-success
4731 'org-todo-setup-filter-hook kws)
4732 kws)))
4733 (setq inter (pop kws) sep (member "|" kws)
4734 kws0 (delete "|" (copy-sequence kws))
4735 kwsa nil
4736 kws1 (mapcar
4737 (lambda (x)
4738 ;; 1 2
4739 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4740 (progn
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log (org-extract-log-state-settings x))
4744 (push (cons kw (and key (string-to-char key))) kwsa)
4745 (and log (push log org-todo-log-states))
4747 (error "Invalid TODO keyword %s" x)))
4748 kws0)
4749 kwsa (if kwsa (append '((:startgroup))
4750 (nreverse kwsa)
4751 '((:endgroup))))
4752 hw (car kws1)
4753 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4754 tail (list inter hw (car dws) (org-last dws))))
4755 (add-to-list 'org-todo-heads hw 'append)
4756 (push kws1 org-todo-sets)
4757 (setq org-done-keywords (append org-done-keywords dws nil))
4758 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4759 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4760 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4761 (setq org-todo-sets (nreverse org-todo-sets)
4762 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4763 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4764 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4765 ;; Process the constants
4766 (when const
4767 (let (e cst)
4768 (while (setq e (pop const))
4769 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4770 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4771 (setq org-table-formula-constants-local cst)))
4773 ;; Process the tags.
4774 (when tags
4775 (let (e tgs)
4776 (while (setq e (pop tags))
4777 (cond
4778 ((equal e "{") (push '(:startgroup) tgs))
4779 ((equal e "}") (push '(:endgroup) tgs))
4780 ((equal e "\\n") (push '(:newline) tgs))
4781 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4782 (push (cons (match-string 1 e)
4783 (string-to-char (match-string 2 e)))
4784 tgs))
4785 (t (push (list e) tgs))))
4786 (org-set-local 'org-tag-alist nil)
4787 (while (setq e (pop tgs))
4788 (or (and (stringp (car e))
4789 (assoc (car e) org-tag-alist))
4790 (push e org-tag-alist)))))
4792 ;; Compute the regular expressions and other local variables.
4793 ;; Using `org-outline-regexp-bol' would complicate them much,
4794 ;; because of the fixed white space at the end of that string.
4795 (if (not org-done-keywords)
4796 (setq org-done-keywords (and org-todo-keywords-1
4797 (list (org-last org-todo-keywords-1)))))
4798 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4799 (length org-scheduled-string)
4800 (length org-clock-string)
4801 (length org-closed-string)))
4802 org-drawer-regexp
4803 (concat "^[ \t]*:\\("
4804 (mapconcat 'regexp-quote org-drawers "\\|")
4805 "\\):[ \t]*$")
4806 org-not-done-keywords
4807 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4808 org-todo-regexp
4809 (concat "\\("
4810 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4811 "\\)")
4812 org-not-done-regexp
4813 (concat "\\("
4814 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4815 "\\)")
4816 org-not-done-heading-regexp
4817 (format org-heading-keyword-regexp-format org-not-done-regexp)
4818 org-todo-line-regexp
4819 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4820 org-complex-heading-regexp
4821 (concat "^\\(\\*+\\)"
4822 "\\(?: +" org-todo-regexp "\\)?"
4823 "\\(?: +\\(\\[#.\\]\\)\\)?"
4824 "\\(?: +\\(.*?\\)\\)?"
4825 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4826 "[ \t]*$")
4827 org-complex-heading-regexp-format
4828 (concat "^\\(\\*+\\)"
4829 "\\(?: +" org-todo-regexp "\\)?"
4830 "\\(?: +\\(\\[#.\\]\\)\\)?"
4831 "\\(?: +"
4832 ;; Stats cookies can be stuck to body.
4833 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4834 "\\(%s\\)"
4835 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4836 "\\)"
4837 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4838 "[ \t]*$")
4839 org-todo-line-tags-regexp
4840 (concat "^\\(\\*+\\)"
4841 "\\(?: +" org-todo-regexp "\\)?"
4842 "\\(?: +\\(.*?\\)\\)?"
4843 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4844 "[ \t]*$")
4845 org-deadline-regexp (concat "\\<" org-deadline-string)
4846 org-deadline-time-regexp
4847 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4848 org-deadline-line-regexp
4849 (concat "\\<\\(" org-deadline-string "\\).*")
4850 org-scheduled-regexp
4851 (concat "\\<" org-scheduled-string)
4852 org-scheduled-time-regexp
4853 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4854 org-closed-time-regexp
4855 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4856 org-keyword-time-regexp
4857 (concat "\\<\\(" org-scheduled-string
4858 "\\|" org-deadline-string
4859 "\\|" org-closed-string
4860 "\\|" org-clock-string "\\)"
4861 " *[[<]\\([^]>]+\\)[]>]")
4862 org-keyword-time-not-clock-regexp
4863 (concat "\\<\\(" org-scheduled-string
4864 "\\|" org-deadline-string
4865 "\\|" org-closed-string
4866 "\\)"
4867 " *[[<]\\([^]>]+\\)[]>]")
4868 org-maybe-keyword-time-regexp
4869 (concat "\\(\\<\\(" org-scheduled-string
4870 "\\|" org-deadline-string
4871 "\\|" org-closed-string
4872 "\\|" org-clock-string "\\)\\)?"
4873 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4874 org-all-time-keywords
4875 (mapcar (lambda (w) (substring w 0 -1))
4876 (list org-scheduled-string org-deadline-string
4877 org-clock-string org-closed-string))
4879 (org-compute-latex-and-specials-regexp)
4880 (org-set-font-lock-defaults))))
4882 (defun org-file-contents (file &optional noerror)
4883 "Return the contents of FILE, as a string."
4884 (if (or (not file)
4885 (not (file-readable-p file)))
4886 (if noerror
4887 (progn
4888 (message "Cannot read file \"%s\"" file)
4889 (ding) (sit-for 2)
4891 (error "Cannot read file \"%s\"" file))
4892 (with-temp-buffer
4893 (insert-file-contents file)
4894 (buffer-string))))
4896 (defun org-extract-log-state-settings (x)
4897 "Extract the log state setting from a TODO keyword string.
4898 This will extract info from a string like \"WAIT(w@/!)\"."
4899 (let (kw key log1 log2)
4900 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4901 (setq kw (match-string 1 x)
4902 key (and (match-end 2) (match-string 2 x))
4903 log1 (and (match-end 3) (match-string 3 x))
4904 log2 (and (match-end 4) (match-string 4 x)))
4905 (and (or log1 log2)
4906 (list kw
4907 (and log1 (if (equal log1 "!") 'time 'note))
4908 (and log2 (if (equal log2 "!") 'time 'note)))))))
4910 (defun org-remove-keyword-keys (list)
4911 "Remove a pair of parenthesis at the end of each string in LIST."
4912 (mapcar (lambda (x)
4913 (if (string-match "(.*)$" x)
4914 (substring x 0 (match-beginning 0))
4916 list))
4918 (defun org-assign-fast-keys (alist)
4919 "Assign fast keys to a keyword-key alist.
4920 Respect keys that are already there."
4921 (let (new e (alt ?0))
4922 (while (setq e (pop alist))
4923 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4924 (cdr e)) ;; Key already assigned.
4925 (push e new)
4926 (let ((clist (string-to-list (downcase (car e))))
4927 (used (append new alist)))
4928 (when (= (car clist) ?@)
4929 (pop clist))
4930 (while (and clist (rassoc (car clist) used))
4931 (pop clist))
4932 (unless clist
4933 (while (rassoc alt used)
4934 (incf alt)))
4935 (push (cons (car e) (or (car clist) alt)) new))))
4936 (nreverse new)))
4938 ;;; Some variables used in various places
4940 (defvar org-window-configuration nil
4941 "Used in various places to store a window configuration.")
4942 (defvar org-selected-window nil
4943 "Used in various places to store a window configuration.")
4944 (defvar org-finish-function nil
4945 "Function to be called when `C-c C-c' is used.
4946 This is for getting out of special buffers like remember.")
4949 ;; FIXME: Occasionally check by commenting these, to make sure
4950 ;; no other functions uses these, forgetting to let-bind them.
4951 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4952 (defvar org-last-state)
4953 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4955 ;; Defined somewhere in this file, but used before definition.
4956 (defvar org-entities) ;; defined in org-entities.el
4957 (defvar org-struct-menu)
4958 (defvar org-org-menu)
4959 (defvar org-tbl-menu)
4961 ;;;; Define the Org-mode
4963 ;; We use a before-change function to check if a table might need
4964 ;; an update.
4965 (defvar org-table-may-need-update t
4966 "Indicates that a table might need an update.
4967 This variable is set by `org-before-change-function'.
4968 `org-table-align' sets it back to nil.")
4969 (defun org-before-change-function (beg end)
4970 "Every change indicates that a table might need an update."
4971 (setq org-table-may-need-update t))
4972 (defvar org-mode-map)
4973 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4974 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4975 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4976 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4978 (defvar org-table-buffer-is-an nil)
4980 (defvar bidi-paragraph-direction)
4981 (defvar buffer-face-mode-face)
4983 (require 'outline)
4984 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4985 (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"))
4986 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4988 ;; Other stuff we need.
4989 (require 'time-date)
4990 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4991 (require 'easymenu)
4992 (require 'overlay)
4994 (require 'org-macs)
4995 (require 'org-entities)
4996 ;; (require 'org-compat) moved higher up in the file before it is first used
4997 (require 'org-faces)
4998 (require 'org-list)
4999 (require 'org-pcomplete)
5000 (require 'org-src)
5001 (require 'org-footnote)
5003 ;; babel
5004 (require 'ob)
5005 (require 'ob-table)
5006 (require 'ob-lob)
5007 (require 'ob-ref)
5008 (require 'ob-tangle)
5009 (require 'ob-comint)
5010 (require 'ob-keys)
5012 ;;;###autoload
5013 (define-derived-mode org-mode outline-mode "Org"
5014 "Outline-based notes management and organizer, alias
5015 \"Carsten's outline-mode for keeping track of everything.\"
5017 Org-mode develops organizational tasks around a NOTES file which
5018 contains information about projects as plain text. Org-mode is
5019 implemented on top of outline-mode, which is ideal to keep the content
5020 of large files well structured. It supports ToDo items, deadlines and
5021 time stamps, which magically appear in the diary listing of the Emacs
5022 calendar. Tables are easily created with a built-in table editor.
5023 Plain text URL-like links connect to websites, emails (VM), Usenet
5024 messages (Gnus), BBDB entries, and any files related to the project.
5025 For printing and sharing of notes, an Org-mode file (or a part of it)
5026 can be exported as a structured ASCII or HTML file.
5028 The following commands are available:
5030 \\{org-mode-map}"
5032 ;; Get rid of Outline menus, they are not needed
5033 ;; Need to do this here because define-derived-mode sets up
5034 ;; the keymap so late. Still, it is a waste to call this each time
5035 ;; we switch another buffer into org-mode.
5036 (if (featurep 'xemacs)
5037 (when (boundp 'outline-mode-menu-heading)
5038 ;; Assume this is Greg's port, it uses easymenu
5039 (easy-menu-remove outline-mode-menu-heading)
5040 (easy-menu-remove outline-mode-menu-show)
5041 (easy-menu-remove outline-mode-menu-hide))
5042 (define-key org-mode-map [menu-bar headings] 'undefined)
5043 (define-key org-mode-map [menu-bar hide] 'undefined)
5044 (define-key org-mode-map [menu-bar show] 'undefined))
5046 (org-load-modules-maybe)
5047 (easy-menu-add org-org-menu)
5048 (easy-menu-add org-tbl-menu)
5049 (org-install-agenda-files-menu)
5050 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5051 (add-to-invisibility-spec '(org-cwidth))
5052 (add-to-invisibility-spec '(org-hide-block . t))
5053 (when (featurep 'xemacs)
5054 (org-set-local 'line-move-ignore-invisible t))
5055 (org-set-local 'outline-regexp org-outline-regexp)
5056 (org-set-local 'outline-level 'org-outline-level)
5057 (setq bidi-paragraph-direction 'left-to-right)
5058 (when (and org-ellipsis
5059 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5060 (fboundp 'make-glyph-code))
5061 (unless org-display-table
5062 (setq org-display-table (make-display-table)))
5063 (set-display-table-slot
5064 org-display-table 4
5065 (vconcat (mapcar
5066 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5067 org-ellipsis)))
5068 (if (stringp org-ellipsis) org-ellipsis "..."))))
5069 (setq buffer-display-table org-display-table))
5070 (org-set-regexps-and-options)
5071 (when (and org-tag-faces (not org-tags-special-faces-re))
5072 ;; tag faces set outside customize.... force initialization.
5073 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5074 ;; Calc embedded
5075 (org-set-local 'calc-embedded-open-mode "# ")
5076 (modify-syntax-entry ?@ "w")
5077 (if org-startup-truncated (setq truncate-lines t))
5078 (org-set-local 'font-lock-unfontify-region-function
5079 'org-unfontify-region)
5080 ;; Activate before-change-function
5081 (org-set-local 'org-table-may-need-update t)
5082 (org-add-hook 'before-change-functions 'org-before-change-function nil
5083 'local)
5084 ;; Check for running clock before killing a buffer
5085 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5086 ;; Paragraphs and auto-filling
5087 (org-set-autofill-regexps)
5088 (org-set-local 'indent-line-function 'org-indent-line)
5089 (org-set-local 'indent-region-function 'org-indent-region)
5090 (org-update-radio-target-regexp)
5091 ;; Comments
5092 (org-set-local 'comment-use-syntax nil)
5093 (org-set-local 'comment-start "#")
5094 (org-set-local 'comment-start-skip "# ?")
5095 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
5096 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
5097 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region)
5098 ;; Beginning/end of defun
5099 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5100 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5101 ;; Next error for sparse trees
5102 (org-set-local 'next-error-function 'org-occur-next-match)
5103 ;; Make sure dependence stuff works reliably, even for users who set it
5104 ;; too late :-(
5105 (if org-enforce-todo-dependencies
5106 (add-hook 'org-blocker-hook
5107 'org-block-todo-from-children-or-siblings-or-parent)
5108 (remove-hook 'org-blocker-hook
5109 'org-block-todo-from-children-or-siblings-or-parent))
5110 (if org-enforce-todo-checkbox-dependencies
5111 (add-hook 'org-blocker-hook
5112 'org-block-todo-from-checkboxes)
5113 (remove-hook 'org-blocker-hook
5114 'org-block-todo-from-checkboxes))
5116 ;; Align options lines
5117 (org-set-local
5118 'align-mode-rules-list
5119 '((org-in-buffer-settings
5120 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5121 (modes . '(org-mode)))))
5123 ;; Imenu
5124 (org-set-local 'imenu-create-index-function
5125 'org-imenu-get-tree)
5127 ;; Make isearch reveal context
5128 (if (or (featurep 'xemacs)
5129 (not (boundp 'outline-isearch-open-invisible-function)))
5130 ;; Emacs 21 and XEmacs make use of the hook
5131 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5132 ;; Emacs 22 deals with this through a special variable
5133 (org-set-local 'outline-isearch-open-invisible-function
5134 (lambda (&rest ignore) (org-show-context 'isearch))))
5136 ;; Turn on org-beamer-mode?
5137 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5139 ;; Setup the pcomplete hooks
5140 (set (make-local-variable 'pcomplete-command-completion-function)
5141 'org-pcomplete-initial)
5142 (set (make-local-variable 'pcomplete-command-name-function)
5143 'org-command-at-point)
5144 (set (make-local-variable 'pcomplete-default-completion-function)
5145 'ignore)
5146 (set (make-local-variable 'pcomplete-parse-arguments-function)
5147 'org-parse-arguments)
5148 (set (make-local-variable 'pcomplete-termination-string) "")
5149 (when (>= emacs-major-version 23)
5150 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5152 ;; If empty file that did not turn on org-mode automatically, make it to.
5153 (if (and org-insert-mode-line-in-empty-file
5154 (org-called-interactively-p 'any)
5155 (= (point-min) (point-max)))
5156 (insert "# -*- mode: org -*-\n\n"))
5157 (unless org-inhibit-startup
5158 (when org-startup-align-all-tables
5159 (let ((bmp (buffer-modified-p)))
5160 (org-table-map-tables 'org-table-align 'quietly)
5161 (set-buffer-modified-p bmp)))
5162 (when org-startup-with-inline-images
5163 (org-display-inline-images))
5164 (when org-startup-indented
5165 (require 'org-indent)
5166 (org-indent-mode 1))
5167 (unless org-inhibit-startup-visibility-stuff
5168 (org-set-startup-visibility))))
5170 (when (fboundp 'abbrev-table-put)
5171 (abbrev-table-put org-mode-abbrev-table
5172 :parents (list text-mode-abbrev-table)))
5174 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5176 (defun org-current-time ()
5177 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5178 (if (> (car org-time-stamp-rounding-minutes) 1)
5179 (let ((r (car org-time-stamp-rounding-minutes))
5180 (time (decode-time)))
5181 (apply 'encode-time
5182 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5183 (nthcdr 2 time))))
5184 (current-time)))
5186 (defun org-today ()
5187 "Return today date, considering `org-extend-today-until'."
5188 (time-to-days
5189 (time-subtract (current-time)
5190 (list 0 (* 3600 org-extend-today-until) 0))))
5192 ;;;; Font-Lock stuff, including the activators
5194 (defvar org-mouse-map (make-sparse-keymap))
5195 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5196 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5197 (when org-mouse-1-follows-link
5198 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5199 (when org-tab-follows-link
5200 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5201 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5203 (require 'font-lock)
5205 (defconst org-non-link-chars "]\t\n\r<>")
5206 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5207 "shell" "elisp" "doi" "message"))
5208 (defvar org-link-types-re nil
5209 "Matches a link that has a url-like prefix like \"http:\"")
5210 (defvar org-link-re-with-space nil
5211 "Matches a link with spaces, optional angular brackets around it.")
5212 (defvar org-link-re-with-space2 nil
5213 "Matches a link with spaces, optional angular brackets around it.")
5214 (defvar org-link-re-with-space3 nil
5215 "Matches a link with spaces, only for internal part in bracket links.")
5216 (defvar org-angle-link-re nil
5217 "Matches link with angular brackets, spaces are allowed.")
5218 (defvar org-plain-link-re nil
5219 "Matches plain link, without spaces.")
5220 (defvar org-bracket-link-regexp nil
5221 "Matches a link in double brackets.")
5222 (defvar org-bracket-link-analytic-regexp nil
5223 "Regular expression used to analyze links.
5224 Here is what the match groups contain after a match:
5225 1: http:
5226 2: http
5227 3: path
5228 4: [desc]
5229 5: desc")
5230 (defvar org-bracket-link-analytic-regexp++ nil
5231 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5232 (defvar org-any-link-re nil
5233 "Regular expression matching any link.")
5235 (defcustom org-match-sexp-depth 3
5236 "Number of stacked braces for sub/superscript matching.
5237 This has to be set before loading org.el to be effective."
5238 :group 'org-export-translation ; ??????????????????????????/
5239 :type 'integer)
5241 (defun org-create-multibrace-regexp (left right n)
5242 "Create a regular expression which will match a balanced sexp.
5243 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5244 as single character strings.
5245 The regexp returned will match the entire expression including the
5246 delimiters. It will also define a single group which contains the
5247 match except for the outermost delimiters. The maximum depth of
5248 stacked delimiters is N. Escaping delimiters is not possible."
5249 (let* ((nothing (concat "[^" left right "]*?"))
5250 (or "\\|")
5251 (re nothing)
5252 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5253 (while (> n 1)
5254 (setq n (1- n)
5255 re (concat re or next)
5256 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5257 (concat left "\\(" re "\\)" right)))
5259 (defvar org-match-substring-regexp
5260 (concat
5261 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5262 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5263 "\\|"
5264 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5265 "\\|"
5266 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5267 "The regular expression matching a sub- or superscript.")
5269 (defvar org-match-substring-with-braces-regexp
5270 (concat
5271 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5272 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5273 "\\)")
5274 "The regular expression matching a sub- or superscript, forcing braces.")
5276 (defun org-make-link-regexps ()
5277 "Update the link regular expressions.
5278 This should be called after the variable `org-link-types' has changed."
5279 (setq org-link-types-re
5280 (concat
5281 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5282 org-link-re-with-space
5283 (concat
5284 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5285 "\\([^" org-non-link-chars " ]"
5286 "[^" org-non-link-chars "]*"
5287 "[^" org-non-link-chars " ]\\)>?")
5288 org-link-re-with-space2
5289 (concat
5290 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5291 "\\([^" org-non-link-chars " ]"
5292 "[^\t\n\r]*"
5293 "[^" org-non-link-chars " ]\\)>?")
5294 org-link-re-with-space3
5295 (concat
5296 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5297 "\\([^" org-non-link-chars " ]"
5298 "[^\t\n\r]*\\)")
5299 org-angle-link-re
5300 (concat
5301 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5302 "\\([^" org-non-link-chars " ]"
5303 "[^" org-non-link-chars "]*"
5304 "\\)>")
5305 org-plain-link-re
5306 (concat
5307 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5308 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5309 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5310 org-bracket-link-regexp
5311 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5312 org-bracket-link-analytic-regexp
5313 (concat
5314 "\\[\\["
5315 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5316 "\\([^]]+\\)"
5317 "\\]"
5318 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5319 "\\]")
5320 org-bracket-link-analytic-regexp++
5321 (concat
5322 "\\[\\["
5323 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5324 "\\([^]]+\\)"
5325 "\\]"
5326 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5327 "\\]")
5328 org-any-link-re
5329 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5330 org-angle-link-re "\\)\\|\\("
5331 org-plain-link-re "\\)")))
5333 (org-make-link-regexps)
5335 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5336 "Regular expression for fast time stamp matching.")
5337 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5338 "Regular expression for fast time stamp matching.")
5339 (defconst org-ts-regexp0
5340 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5341 "Regular expression matching time strings for analysis.
5342 This one does not require the space after the date, so it can be used
5343 on a string that terminates immediately after the date.")
5344 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5345 "Regular expression matching time strings for analysis.")
5346 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5347 "Regular expression matching time stamps, with groups.")
5348 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5349 "Regular expression matching time stamps (also [..]), with groups.")
5350 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5351 "Regular expression matching a time stamp range.")
5352 (defconst org-tr-regexp-both
5353 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5354 "Regular expression matching a time stamp range.")
5355 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5356 org-ts-regexp "\\)?")
5357 "Regular expression matching a time stamp or time stamp range.")
5358 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5359 org-ts-regexp-both "\\)?")
5360 "Regular expression matching a time stamp or time stamp range.
5361 The time stamps may be either active or inactive.")
5363 (defvar org-emph-face nil)
5365 (defun org-do-emphasis-faces (limit)
5366 "Run through the buffer and add overlays to emphasized strings."
5367 (let (rtn a)
5368 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5369 (if (not (= (char-after (match-beginning 3))
5370 (char-after (match-beginning 4))))
5371 (progn
5372 (setq rtn t)
5373 (setq a (assoc (match-string 3) org-emphasis-alist))
5374 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5375 'face
5376 (nth 1 a))
5377 (and (nth 4 a)
5378 (org-remove-flyspell-overlays-in
5379 (match-beginning 0) (match-end 0)))
5380 (add-text-properties (match-beginning 2) (match-end 2)
5381 '(font-lock-multiline t org-emphasis t))
5382 (when org-hide-emphasis-markers
5383 (add-text-properties (match-end 4) (match-beginning 5)
5384 '(invisible org-link))
5385 (add-text-properties (match-beginning 3) (match-end 3)
5386 '(invisible org-link)))))
5387 (backward-char 1))
5388 rtn))
5390 (defun org-emphasize (&optional char)
5391 "Insert or change an emphasis, i.e. a font like bold or italic.
5392 If there is an active region, change that region to a new emphasis.
5393 If there is no region, just insert the marker characters and position
5394 the cursor between them.
5395 CHAR should be either the marker character, or the first character of the
5396 HTML tag associated with that emphasis. If CHAR is a space, the means
5397 to remove the emphasis of the selected region.
5398 If char is not given (for example in an interactive call) it
5399 will be prompted for."
5400 (interactive)
5401 (let ((eal org-emphasis-alist) e det
5402 (erc org-emphasis-regexp-components)
5403 (prompt "")
5404 (string "") beg end move tag c s)
5405 (if (org-region-active-p)
5406 (setq beg (region-beginning) end (region-end)
5407 string (buffer-substring beg end))
5408 (setq move t))
5410 (while (setq e (pop eal))
5411 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5412 c (aref tag 0))
5413 (push (cons c (string-to-char (car e))) det)
5414 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5415 (substring tag 1)))))
5416 (setq det (nreverse det))
5417 (unless char
5418 (message "%s" (concat "Emphasis marker or tag:" prompt))
5419 (setq char (read-char-exclusive)))
5420 (setq char (or (cdr (assoc char det)) char))
5421 (if (equal char ?\ )
5422 (setq s "" move nil)
5423 (unless (assoc (char-to-string char) org-emphasis-alist)
5424 (error "No such emphasis marker: \"%c\"" char))
5425 (setq s (char-to-string char)))
5426 (while (and (> (length string) 1)
5427 (equal (substring string 0 1) (substring string -1))
5428 (assoc (substring string 0 1) org-emphasis-alist))
5429 (setq string (substring string 1 -1)))
5430 (setq string (concat s string s))
5431 (if beg (delete-region beg end))
5432 (unless (or (bolp)
5433 (string-match (concat "[" (nth 0 erc) "\n]")
5434 (char-to-string (char-before (point)))))
5435 (insert " "))
5436 (unless (or (eobp)
5437 (string-match (concat "[" (nth 1 erc) "\n]")
5438 (char-to-string (char-after (point)))))
5439 (insert " ") (backward-char 1))
5440 (insert string)
5441 (and move (backward-char 1))))
5443 (defconst org-nonsticky-props
5444 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5446 (defsubst org-rear-nonsticky-at (pos)
5447 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5449 (defun org-activate-plain-links (limit)
5450 "Run through the buffer and add overlays to links."
5451 (catch 'exit
5452 (let (f)
5453 (if (re-search-forward org-plain-link-re limit t)
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (setq f (get-text-property (match-beginning 0) 'face))
5457 (if (or (eq f 'org-tag)
5458 (and (listp f) (memq 'org-tag f)))
5460 (add-text-properties (match-beginning 0) (match-end 0)
5461 (list 'mouse-face 'highlight
5462 'face 'org-link
5463 'keymap org-mouse-map))
5464 (org-rear-nonsticky-at (match-end 0)))
5465 t)))))
5467 (defun org-activate-code (limit)
5468 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5469 (progn
5470 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5471 (remove-text-properties (match-beginning 0) (match-end 0)
5472 '(display t invisible t intangible t))
5473 t)))
5475 (defcustom org-src-fontify-natively nil
5476 "When non-nil, fontify code in code blocks."
5477 :type 'boolean
5478 :version "24.1"
5479 :group 'org-appearance
5480 :group 'org-babel)
5482 (defcustom org-src-prevent-auto-filling nil
5483 "When non-nil, prevent auto-filling in src blocks."
5484 :type 'boolean
5485 :version "24.1"
5486 :group 'org-appearance
5487 :group 'org-babel)
5489 (defcustom org-allow-promoting-top-level-subtree nil
5490 "When non-nil, allow promoting a top level subtree.
5491 The leading star of the top level headline will be replaced
5492 by a #."
5493 :type 'boolean
5494 :version "24.1"
5495 :group 'org-appearance)
5497 (defun org-fontify-meta-lines-and-blocks (limit)
5498 (condition-case nil
5499 (org-fontify-meta-lines-and-blocks-1 limit)
5500 (error (message "org-mode fontification error"))))
5502 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5503 "Fontify #+ lines and blocks, in the correct ways."
5504 (let ((case-fold-search t))
5505 (if (re-search-forward
5506 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5507 limit t)
5508 (let ((beg (match-beginning 0))
5509 (block-start (match-end 0))
5510 (block-end nil)
5511 (lang (match-string 7))
5512 (beg1 (line-beginning-position 2))
5513 (dc1 (downcase (match-string 2)))
5514 (dc3 (downcase (match-string 3)))
5515 end end1 quoting block-type ovl)
5516 (cond
5517 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5518 ;; a single line of backend-specific content
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (remove-text-properties (match-beginning 0) (match-end 0)
5521 '(display t invisible t intangible t))
5522 (add-text-properties (match-beginning 1) (match-end 3)
5523 '(font-lock-fontified t face org-meta-line))
5524 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5525 '(font-lock-fontified t face org-block))
5526 ; for backend-specific code
5528 ((and (match-end 4) (equal dc3 "+begin"))
5529 ;; Truly a block
5530 (setq block-type (downcase (match-string 5))
5531 quoting (member block-type org-protecting-blocks))
5532 (when (re-search-forward
5533 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5534 nil t) ;; on purpose, we look further than LIMIT
5535 (setq end (min (point-max) (match-end 0))
5536 end1 (min (point-max) (1- (match-beginning 0))))
5537 (setq block-end (match-beginning 0))
5538 (when quoting
5539 (remove-text-properties beg end
5540 '(display t invisible t intangible t)))
5541 (add-text-properties
5542 beg end
5543 '(font-lock-fontified t font-lock-multiline t))
5544 (add-text-properties beg beg1 '(face org-meta-line))
5545 (add-text-properties end1 (min (point-max) (1+ end))
5546 '(face org-meta-line)) ; for end_src
5547 (cond
5548 ((and lang (not (string= lang "")) org-src-fontify-natively)
5549 (org-src-font-lock-fontify-block lang block-start block-end)
5550 ;; remove old background overlays
5551 (mapc (lambda (ov)
5552 (if (eq (overlay-get ov 'face) 'org-block-background)
5553 (delete-overlay ov)))
5554 (overlays-at (/ (+ beg1 block-end) 2)))
5555 ;; add a background overlay
5556 (setq ovl (make-overlay beg1 block-end))
5557 (overlay-put ovl 'face 'org-block-background)
5558 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5559 (quoting
5560 (add-text-properties beg1 (min (point-max) (1+ end1))
5561 '(face org-block))) ; end of source block
5562 ((not org-fontify-quote-and-verse-blocks))
5563 ((string= block-type "quote")
5564 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5565 ((string= block-type "verse")
5566 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5567 (add-text-properties beg beg1 '(face org-block-begin-line))
5568 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5569 '(face org-block-end-line))
5571 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5572 (add-text-properties
5573 beg (match-end 3)
5574 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5575 '(font-lock-fontified t invisible t)
5576 '(font-lock-fontified t face org-document-info-keyword)))
5577 (add-text-properties
5578 (match-beginning 6) (match-end 6)
5579 (if (string-equal dc1 "+title:")
5580 '(font-lock-fontified t face org-document-title)
5581 '(font-lock-fontified t face org-document-info))))
5582 ((or (equal dc1 "+results")
5583 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5584 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5585 "+call:" "+header:" "+headers:" "+name:"))
5586 (and (match-end 4) (equal dc3 "+attr")))
5587 (add-text-properties
5588 beg (match-end 0)
5589 '(font-lock-fontified t face org-meta-line))
5591 ((member dc3 '(" " ""))
5592 (add-text-properties
5593 beg (match-end 0)
5594 '(font-lock-fontified t face font-lock-comment-face)))
5595 ((not (member (char-after beg) '(?\ ?\t)))
5596 ;; just any other in-buffer setting, but not indented
5597 (add-text-properties
5598 beg (match-end 0)
5599 '(font-lock-fontified t face org-meta-line))
5601 (t nil))))))
5603 (defun org-strip-protective-commas (beg end)
5604 "Strip protective commas between BEG and END in the current buffer."
5605 (interactive "r")
5606 (save-excursion
5607 (save-match-data
5608 (goto-char beg)
5609 (let ((front-line (save-excursion
5610 (re-search-forward
5611 "[^[:space:]]" end t)
5612 (goto-char (match-beginning 0))
5613 (current-column))))
5614 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5615 (goto-char (match-beginning 1))
5616 (when (= (current-column) front-line)
5617 (replace-match "" nil nil nil 1)))))))
5619 (defun org-activate-angle-links (limit)
5620 "Run through the buffer and add overlays to links."
5621 (if (re-search-forward org-angle-link-re limit t)
5622 (progn
5623 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5624 (add-text-properties (match-beginning 0) (match-end 0)
5625 (list 'mouse-face 'highlight
5626 'keymap org-mouse-map))
5627 (org-rear-nonsticky-at (match-end 0))
5628 t)))
5630 (defun org-activate-footnote-links (limit)
5631 "Run through the buffer and add overlays to footnotes."
5632 (let ((fn (org-footnote-next-reference-or-definition limit)))
5633 (when fn
5634 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5635 (org-remove-flyspell-overlays-in beg end)
5636 (add-text-properties beg end
5637 (list 'mouse-face 'highlight
5638 'keymap org-mouse-map
5639 'help-echo
5640 (if (= (point-at-bol) beg)
5641 "Footnote definition"
5642 "Footnote reference")
5643 'font-lock-fontified t
5644 'font-lock-multiline t
5645 'face 'org-footnote))))))
5647 (defun org-activate-bracket-links (limit)
5648 "Run through the buffer and add overlays to bracketed links."
5649 (if (re-search-forward org-bracket-link-regexp limit t)
5650 (let* ((help (concat "LINK: "
5651 (org-match-string-no-properties 1)))
5652 ;; FIXME: above we should remove the escapes.
5653 ;; but that requires another match, protecting match data,
5654 ;; a lot of overhead for font-lock.
5655 (ip (org-maybe-intangible
5656 (list 'invisible 'org-link
5657 'keymap org-mouse-map 'mouse-face 'highlight
5658 'font-lock-multiline t 'help-echo help)))
5659 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5660 'font-lock-multiline t 'help-echo help)))
5661 ;; We need to remove the invisible property here. Table narrowing
5662 ;; may have made some of this invisible.
5663 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5664 (remove-text-properties (match-beginning 0) (match-end 0)
5665 '(invisible nil))
5666 (if (match-end 3)
5667 (progn
5668 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5669 (org-rear-nonsticky-at (match-beginning 3))
5670 (add-text-properties (match-beginning 3) (match-end 3) vp)
5671 (org-rear-nonsticky-at (match-end 3))
5672 (add-text-properties (match-end 3) (match-end 0) ip)
5673 (org-rear-nonsticky-at (match-end 0)))
5674 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5675 (org-rear-nonsticky-at (match-beginning 1))
5676 (add-text-properties (match-beginning 1) (match-end 1) vp)
5677 (org-rear-nonsticky-at (match-end 1))
5678 (add-text-properties (match-end 1) (match-end 0) ip)
5679 (org-rear-nonsticky-at (match-end 0)))
5680 t)))
5682 (defun org-activate-dates (limit)
5683 "Run through the buffer and add overlays to dates."
5684 (if (re-search-forward org-tsr-regexp-both limit t)
5685 (progn
5686 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5687 (add-text-properties (match-beginning 0) (match-end 0)
5688 (list 'mouse-face 'highlight
5689 'keymap org-mouse-map))
5690 (org-rear-nonsticky-at (match-end 0))
5691 (when org-display-custom-times
5692 (if (match-end 3)
5693 (org-display-custom-time (match-beginning 3) (match-end 3)))
5694 (org-display-custom-time (match-beginning 1) (match-end 1)))
5695 t)))
5697 (defvar org-target-link-regexp nil
5698 "Regular expression matching radio targets in plain text.")
5699 (make-variable-buffer-local 'org-target-link-regexp)
5700 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5701 "Regular expression matching a link target.")
5702 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5703 "Regular expression matching a radio target.")
5704 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5705 "Regular expression matching any target.")
5707 (defun org-activate-target-links (limit)
5708 "Run through the buffer and add overlays to target matches."
5709 (when org-target-link-regexp
5710 (let ((case-fold-search t))
5711 (if (re-search-forward org-target-link-regexp limit t)
5712 (progn
5713 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5714 (add-text-properties (match-beginning 0) (match-end 0)
5715 (list 'mouse-face 'highlight
5716 'keymap org-mouse-map
5717 'help-echo "Radio target link"
5718 'org-linked-text t))
5719 (org-rear-nonsticky-at (match-end 0))
5720 t)))))
5722 (defun org-update-radio-target-regexp ()
5723 "Find all radio targets in this file and update the regular expression."
5724 (interactive)
5725 (when (memq 'radio org-activate-links)
5726 (setq org-target-link-regexp
5727 (org-make-target-link-regexp (org-all-targets 'radio)))
5728 (org-restart-font-lock)))
5730 (defun org-hide-wide-columns (limit)
5731 (let (s e)
5732 (setq s (text-property-any (point) (or limit (point-max))
5733 'org-cwidth t))
5734 (when s
5735 (setq e (next-single-property-change s 'org-cwidth))
5736 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5737 (goto-char e)
5738 t)))
5740 (defvar org-latex-and-specials-regexp nil
5741 "Regular expression for highlighting export special stuff.")
5742 (defvar org-match-substring-regexp)
5743 (defvar org-match-substring-with-braces-regexp)
5745 ;; This should be with the exporter code, but we also use if for font-locking
5746 (defconst org-export-html-special-string-regexps
5747 '(("\\\\-" . "&shy;")
5748 ("---\\([^-]\\)" . "&mdash;\\1")
5749 ("--\\([^-]\\)" . "&ndash;\\1")
5750 ("\\.\\.\\." . "&hellip;"))
5751 "Regular expressions for special string conversion.")
5754 (defun org-compute-latex-and-specials-regexp ()
5755 "Compute regular expression for stuff treated specially by exporters."
5756 (if (not org-highlight-latex-fragments-and-specials)
5757 (org-set-local 'org-latex-and-specials-regexp nil)
5758 (require 'org-exp)
5759 (let*
5760 ((matchers (plist-get org-format-latex-options :matchers))
5761 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5762 org-latex-regexps)))
5763 (org-export-allow-BIND nil)
5764 (options (org-combine-plists (org-default-export-plist)
5765 (org-infile-export-plist)))
5766 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5767 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5768 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5769 (org-export-html-expand (plist-get options :expand-quoted-html))
5770 (org-export-with-special-strings (plist-get options :special-strings))
5771 (re-sub
5772 (cond
5773 ((equal org-export-with-sub-superscripts '{})
5774 (list org-match-substring-with-braces-regexp))
5775 (org-export-with-sub-superscripts
5776 (list org-match-substring-regexp))
5777 (t nil)))
5778 (re-latex
5779 (if org-export-with-LaTeX-fragments
5780 (mapcar (lambda (x) (nth 1 x)) latexs)))
5781 (re-macros
5782 (if org-export-with-TeX-macros
5783 (list (concat "\\\\"
5784 (regexp-opt
5785 (append
5787 (delq nil
5788 (mapcar 'car-safe
5789 (append org-entities-user
5790 org-entities)))
5791 (if (boundp 'org-latex-entities)
5792 (mapcar (lambda (x)
5793 (or (car-safe x) x))
5794 org-latex-entities)
5795 nil))
5796 'words))) ; FIXME
5798 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5799 (re-special (if org-export-with-special-strings
5800 (mapcar (lambda (x) (car x))
5801 org-export-html-special-string-regexps)))
5802 (re-rest
5803 (delq nil
5804 (list
5805 (if org-export-html-expand "@<[^>\n]+>")
5806 ))))
5807 (org-set-local
5808 'org-latex-and-specials-regexp
5809 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5810 re-rest) "\\|")))))
5812 (defun org-do-latex-and-special-faces (limit)
5813 "Run through the buffer and add overlays to links."
5814 (when org-latex-and-specials-regexp
5815 (let (rtn d)
5816 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5817 limit t))
5818 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5819 'face))
5820 '(org-code org-verbatim underline)))
5821 (progn
5822 (setq rtn t
5823 d (cond ((member (char-after (1+ (match-beginning 0)))
5824 '(?_ ?^)) 1)
5825 (t 0)))
5826 (font-lock-prepend-text-property
5827 (+ d (match-beginning 0)) (match-end 0)
5828 'face 'org-latex-and-export-specials)
5829 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5830 '(font-lock-multiline t)))))
5831 rtn)))
5833 (defun org-restart-font-lock ()
5834 "Restart `font-lock-mode', to force refontification."
5835 (when (and (boundp 'font-lock-mode) font-lock-mode)
5836 (font-lock-mode -1)
5837 (font-lock-mode 1)))
5839 (defun org-all-targets (&optional radio)
5840 "Return a list of all targets in this file.
5841 With optional argument RADIO, only find radio targets."
5842 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5843 rtn)
5844 (save-excursion
5845 (goto-char (point-min))
5846 (while (re-search-forward re nil t)
5847 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5848 rtn)))
5850 (defun org-make-target-link-regexp (targets)
5851 "Make regular expression matching all strings in TARGETS.
5852 The regular expression finds the targets also if there is a line break
5853 between words."
5854 (and targets
5855 (concat
5856 "\\<\\("
5857 (mapconcat
5858 (lambda (x)
5859 (setq x (regexp-quote x))
5860 (while (string-match " +" x)
5861 (setq x (replace-match "\\s-+" t t x)))
5863 targets
5864 "\\|")
5865 "\\)\\>")))
5867 (defun org-activate-tags (limit)
5868 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5869 (progn
5870 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5871 (add-text-properties (match-beginning 1) (match-end 1)
5872 (list 'mouse-face 'highlight
5873 'keymap org-mouse-map))
5874 (org-rear-nonsticky-at (match-end 1))
5875 t)))
5877 (defun org-outline-level ()
5878 "Compute the outline level of the heading at point.
5879 This function assumes that the cursor is at the beginning of a line matched
5880 by `outline-regexp'. Otherwise it returns garbage.
5881 If this is called at a normal headline, the level is the number of stars.
5882 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5883 (save-excursion
5884 (looking-at org-outline-regexp)
5885 (1- (- (match-end 0) (match-beginning 0)))))
5887 (defvar org-font-lock-keywords nil)
5889 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5890 "Regular expression matching a property line.")
5892 (defvar org-font-lock-hook nil
5893 "Functions to be called for special font lock stuff.")
5895 (defvar org-font-lock-set-keywords-hook nil
5896 "Functions that can manipulate `org-font-lock-extra-keywords'.
5897 This is called after `org-font-lock-extra-keywords' is defined, but before
5898 it is installed to be used by font lock. This can be useful if something
5899 needs to be inserted at a specific position in the font-lock sequence.")
5901 (defun org-font-lock-hook (limit)
5902 (run-hook-with-args 'org-font-lock-hook limit))
5904 (defun org-set-font-lock-defaults ()
5905 (let* ((em org-fontify-emphasized-text)
5906 (lk org-activate-links)
5907 (org-font-lock-extra-keywords
5908 (list
5909 ;; Call the hook
5910 '(org-font-lock-hook)
5911 ;; Headlines
5912 `(,(if org-fontify-whole-heading-line
5913 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5914 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5915 (1 (org-get-level-face 1))
5916 (2 (org-get-level-face 2))
5917 (3 (org-get-level-face 3)))
5918 ;; Table lines
5919 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5920 (1 'org-table t))
5921 ;; Table internals
5922 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5923 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5924 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5925 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5926 ;; Drawers
5927 (list org-drawer-regexp '(0 'org-special-keyword t))
5928 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5929 ;; Properties
5930 (list org-property-re
5931 '(1 'org-special-keyword t)
5932 '(3 'org-property-value t))
5933 ;; Links
5934 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5935 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5936 (if (memq 'plain lk) '(org-activate-plain-links))
5937 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5938 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5939 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5940 (if (memq 'footnote lk) '(org-activate-footnote-links))
5941 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5942 '(org-hide-wide-columns (0 nil append))
5943 ;; TODO keyword
5944 (list (format org-heading-keyword-regexp-format
5945 org-todo-regexp)
5946 '(2 (org-get-todo-face 2) t))
5947 ;; DONE
5948 (if org-fontify-done-headline
5949 (list (format org-heading-keyword-regexp-format
5950 (concat
5951 "\\(?:"
5952 (mapconcat 'regexp-quote org-done-keywords "\\|")
5953 "\\)"))
5954 '(2 'org-headline-done t))
5955 nil)
5956 ;; Priorities
5957 '(org-font-lock-add-priority-faces)
5958 ;; Tags
5959 '(org-font-lock-add-tag-faces)
5960 ;; Special keywords
5961 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5962 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5963 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5964 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5965 ;; Emphasis
5966 (if em
5967 (if (featurep 'xemacs)
5968 '(org-do-emphasis-faces (0 nil append))
5969 '(org-do-emphasis-faces)))
5970 ;; Checkboxes
5971 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5972 1 'org-checkbox prepend)
5973 (if (cdr (assq 'checkbox org-list-automatic-rules))
5974 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5975 (0 (org-get-checkbox-statistics-face) t)))
5976 ;; Description list items
5977 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5978 1 'org-list-dt prepend)
5979 ;; ARCHIVEd headings
5980 (list (concat
5981 org-outline-regexp-bol
5982 "\\(.*:" org-archive-tag ":.*\\)")
5983 '(1 'org-archived prepend))
5984 ;; Specials
5985 '(org-do-latex-and-special-faces)
5986 '(org-fontify-entities)
5987 '(org-raise-scripts)
5988 ;; Code
5989 '(org-activate-code (1 'org-code t))
5990 ;; COMMENT
5991 (list (format org-heading-keyword-regexp-format
5992 (concat "\\("
5993 org-comment-string "\\|" org-quote-string
5994 "\\)"))
5995 '(2 'org-special-keyword t))
5996 '("^[ \t]*#.*" (0 'font-lock-comment-face t))
5997 ;; Blocks and meta lines
5998 '(org-fontify-meta-lines-and-blocks)
6000 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6001 (run-hooks 'org-font-lock-set-keywords-hook)
6002 ;; Now set the full font-lock-keywords
6003 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6004 (org-set-local 'font-lock-defaults
6005 '(org-font-lock-keywords t nil nil backward-paragraph))
6006 (kill-local-variable 'font-lock-keywords) nil))
6008 (defun org-toggle-pretty-entities ()
6009 "Toggle the composition display of entities as UTF8 characters."
6010 (interactive)
6011 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6012 (org-restart-font-lock)
6013 (if org-pretty-entities
6014 (message "Entities are displayed as UTF8 characters")
6015 (save-restriction
6016 (widen)
6017 (org-decompose-region (point-min) (point-max))
6018 (message "Entities are displayed plain"))))
6020 (defvar org-custom-properties-overlays nil
6021 "List of overlays used for custom properties.")
6022 (make-variable-buffer-local 'org-custom-properties-overlays)
6024 (defun org-toggle-custom-properties-visibility ()
6025 "Display or hide properties in `org-custom-properties'."
6026 (interactive)
6027 (if org-custom-properties-overlays
6028 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6029 (setq org-custom-properties-overlays nil))
6030 (unless (not org-custom-properties)
6031 (save-excursion
6032 (save-restriction
6033 (widen)
6034 (goto-char (point-min))
6035 (while (re-search-forward org-property-re nil t)
6036 (mapc (lambda(p)
6037 (when (equal p (substring (match-string 1) 1 -1))
6038 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6039 (overlay-put o 'invisible t)
6040 (overlay-put o 'org-custom-property t)
6041 (push o org-custom-properties-overlays))))
6042 org-custom-properties)))))))
6044 (defun org-fontify-entities (limit)
6045 "Find an entity to fontify."
6046 (let (ee)
6047 (when org-pretty-entities
6048 (catch 'match
6049 (while (re-search-forward
6050 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6051 limit t)
6052 (if (and (not (org-in-indented-comment-line))
6053 (setq ee (org-entity-get (match-string 1)))
6054 (= (length (nth 6 ee)) 1))
6055 (let*
6056 ((end (if (equal (match-string 2) "{}")
6057 (match-end 2)
6058 (match-end 1))))
6059 (add-text-properties
6060 (match-beginning 0) end
6061 (list 'font-lock-fontified t))
6062 (compose-region (match-beginning 0) end
6063 (nth 6 ee) nil)
6064 (backward-char 1)
6065 (throw 'match t))))
6066 nil))))
6068 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6069 "Fontify string S like in Org-mode."
6070 (with-temp-buffer
6071 (insert s)
6072 (let ((org-odd-levels-only odd-levels))
6073 (org-mode)
6074 (font-lock-fontify-buffer)
6075 (buffer-string))))
6077 (defvar org-m nil)
6078 (defvar org-l nil)
6079 (defvar org-f nil)
6080 (defun org-get-level-face (n)
6081 "Get the right face for match N in font-lock matching of headlines."
6082 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6083 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6084 (if org-cycle-level-faces
6085 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6086 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6087 (cond
6088 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6089 ((eq n 2) org-f)
6090 (t (if org-level-color-stars-only nil org-f))))
6093 (defun org-get-todo-face (kwd)
6094 "Get the right face for a TODO keyword KWD.
6095 If KWD is a number, get the corresponding match group."
6096 (if (numberp kwd) (setq kwd (match-string kwd)))
6097 (or (org-face-from-face-or-color
6098 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6099 (and (member kwd org-done-keywords) 'org-done)
6100 'org-todo))
6102 (defun org-face-from-face-or-color (context inherit face-or-color)
6103 "Create a face list that inherits INHERIT, but sets the foreground color.
6104 When FACE-OR-COLOR is not a string, just return it."
6105 (if (stringp face-or-color)
6106 (list :inherit inherit
6107 (cdr (assoc context org-faces-easy-properties))
6108 face-or-color)
6109 face-or-color))
6111 (defun org-font-lock-add-tag-faces (limit)
6112 "Add the special tag faces."
6113 (when (and org-tag-faces org-tags-special-faces-re)
6114 (while (re-search-forward org-tags-special-faces-re limit t)
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'face (org-get-tag-face 1)
6117 'font-lock-fontified t))
6118 (backward-char 1))))
6120 (defun org-font-lock-add-priority-faces (limit)
6121 "Add the special priority faces."
6122 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6123 (when (save-match-data (org-at-heading-p))
6124 (add-text-properties
6125 (match-beginning 0) (match-end 0)
6126 (list 'face (or (org-face-from-face-or-color
6127 'priority 'org-special-keyword
6128 (cdr (assoc (char-after (match-beginning 1))
6129 org-priority-faces)))
6130 'org-special-keyword)
6131 'font-lock-fontified t)))))
6133 (defun org-get-tag-face (kwd)
6134 "Get the right face for a TODO keyword KWD.
6135 If KWD is a number, get the corresponding match group."
6136 (if (numberp kwd) (setq kwd (match-string kwd)))
6137 (or (org-face-from-face-or-color
6138 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6139 'org-tag))
6141 (defun org-unfontify-region (beg end &optional maybe_loudly)
6142 "Remove fontification and activation overlays from links."
6143 (font-lock-default-unfontify-region beg end)
6144 (let* ((buffer-undo-list t)
6145 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6146 (inhibit-modification-hooks t)
6147 deactivate-mark buffer-file-name buffer-file-truename)
6148 (org-decompose-region beg end)
6149 (remove-text-properties beg end
6150 '(mouse-face t keymap t org-linked-text t
6151 invisible t intangible t
6152 org-no-flyspell t org-emphasis t))
6153 (org-remove-font-lock-display-properties beg end)))
6155 (defconst org-script-display '(((raise -0.3) (height 0.7))
6156 ((raise 0.3) (height 0.7))
6157 ((raise -0.5))
6158 ((raise 0.5)))
6159 "Display properties for showing superscripts and subscripts.")
6161 (defun org-remove-font-lock-display-properties (beg end)
6162 "Remove specific display properties that have been added by font lock.
6163 The will remove the raise properties that are used to show superscripts
6164 and subscripts."
6165 (let (next prop)
6166 (while (< beg end)
6167 (setq next (next-single-property-change beg 'display nil end)
6168 prop (get-text-property beg 'display))
6169 (if (member prop org-script-display)
6170 (put-text-property beg next 'display nil))
6171 (setq beg next))))
6173 (defun org-raise-scripts (limit)
6174 "Add raise properties to sub/superscripts."
6175 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6176 (if (re-search-forward
6177 (if (eq org-use-sub-superscripts t)
6178 org-match-substring-regexp
6179 org-match-substring-with-braces-regexp)
6180 limit t)
6181 (let* ((pos (point)) table-p comment-p
6182 (mpos (match-beginning 3))
6183 (emph-p (get-text-property mpos 'org-emphasis))
6184 (link-p (get-text-property mpos 'mouse-face))
6185 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6186 (goto-char (point-at-bol))
6187 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6188 comment-p (org-looking-at-p "[ \t]*#"))
6189 (goto-char pos)
6190 ;; FIXME: Should we go back one character here, for a_b^c
6191 ;; (goto-char (1- pos)) ;????????????????????
6192 (if (or comment-p emph-p link-p keyw-p)
6194 (put-text-property (match-beginning 3) (match-end 0)
6195 'display
6196 (if (equal (char-after (match-beginning 2)) ?^)
6197 (nth (if table-p 3 1) org-script-display)
6198 (nth (if table-p 2 0) org-script-display)))
6199 (add-text-properties (match-beginning 2) (match-end 2)
6200 (list 'invisible t
6201 'org-dwidth t 'org-dwidth-n 1))
6202 (if (and (eq (char-after (match-beginning 3)) ?{)
6203 (eq (char-before (match-end 3)) ?}))
6204 (progn
6205 (add-text-properties
6206 (match-beginning 3) (1+ (match-beginning 3))
6207 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6208 (add-text-properties
6209 (1- (match-end 3)) (match-end 3)
6210 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6211 t)))))
6213 ;;;; Visibility cycling, including org-goto and indirect buffer
6215 ;;; Cycling
6217 (defvar org-cycle-global-status nil)
6218 (make-variable-buffer-local 'org-cycle-global-status)
6219 (defvar org-cycle-subtree-status nil)
6220 (make-variable-buffer-local 'org-cycle-subtree-status)
6222 ;;;###autoload
6224 (defvar org-inlinetask-min-level)
6226 (defun org-cycle (&optional arg)
6227 "TAB-action and visibility cycling for Org-mode.
6229 This is the command invoked in Org-mode by the TAB key. Its main purpose
6230 is outline visibility cycling, but it also invokes other actions
6231 in special contexts.
6233 - When this function is called with a prefix argument, rotate the entire
6234 buffer through 3 states (global cycling)
6235 1. OVERVIEW: Show only top-level headlines.
6236 2. CONTENTS: Show all headlines of all levels, but no body text.
6237 3. SHOW ALL: Show everything.
6238 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6239 determined by the variable `org-startup-folded', and by any VISIBILITY
6240 properties in the buffer.
6241 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6242 including any drawers.
6244 - When inside a table, re-align the table and move to the next field.
6246 - When point is at the beginning of a headline, rotate the subtree started
6247 by this line through 3 different states (local cycling)
6248 1. FOLDED: Only the main headline is shown.
6249 2. CHILDREN: The main headline and the direct children are shown.
6250 From this state, you can move to one of the children
6251 and zoom in further.
6252 3. SUBTREE: Show the entire subtree, including body text.
6253 If there is no subtree, switch directly from CHILDREN to FOLDED.
6255 - When point is at the beginning of an empty headline and the variable
6256 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6257 of the headline by demoting and promoting it to likely levels. This
6258 speeds up creation document structure by pressing TAB once or several
6259 times right after creating a new headline.
6261 - When there is a numeric prefix, go up to a heading with level ARG, do
6262 a `show-subtree' and return to the previous cursor position. If ARG
6263 is negative, go up that many levels.
6265 - When point is not at the beginning of a headline, execute the global
6266 binding for TAB, which is re-indenting the line. See the option
6267 `org-cycle-emulate-tab' for details.
6269 - Special case: if point is at the beginning of the buffer and there is
6270 no headline in line 1, this function will act as if called with prefix arg
6271 (C-u TAB, same as S-TAB) also when called without prefix arg.
6272 But only if also the variable `org-cycle-global-at-bob' is t."
6273 (interactive "P")
6274 (org-load-modules-maybe)
6275 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6276 (and org-cycle-level-after-item/entry-creation
6277 (or (org-cycle-level)
6278 (org-cycle-item-indentation))))
6279 (let* ((limit-level
6280 (or org-cycle-max-level
6281 (and (boundp 'org-inlinetask-min-level)
6282 org-inlinetask-min-level
6283 (1- org-inlinetask-min-level))))
6284 (nstars (and limit-level
6285 (if org-odd-levels-only
6286 (and limit-level (1- (* limit-level 2)))
6287 limit-level)))
6288 (org-outline-regexp
6289 (if (not (derived-mode-p 'org-mode))
6290 outline-regexp
6291 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6292 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6293 (not (looking-at org-outline-regexp))))
6294 (org-cycle-hook
6295 (if bob-special
6296 (delq 'org-optimize-window-after-visibility-change
6297 (copy-sequence org-cycle-hook))
6298 org-cycle-hook))
6299 (pos (point)))
6301 (if (or bob-special (equal arg '(4)))
6302 ;; special case: use global cycling
6303 (setq arg t))
6305 (cond
6307 ((equal arg '(16))
6308 (setq last-command 'dummy)
6309 (org-set-startup-visibility)
6310 (message "Startup visibility, plus VISIBILITY properties"))
6312 ((equal arg '(64))
6313 (show-all)
6314 (message "Entire buffer visible, including drawers"))
6316 ;; Table: enter it or move to the next field.
6317 ((org-at-table-p 'any)
6318 (if (org-at-table.el-p)
6319 (message "Use C-c ' to edit table.el tables")
6320 (if arg (org-table-edit-field t)
6321 (org-table-justify-field-maybe)
6322 (call-interactively 'org-table-next-field))))
6324 ((run-hook-with-args-until-success
6325 'org-tab-after-check-for-table-hook))
6327 ;; Global cycling: delegate to `org-cycle-internal-global'.
6328 ((eq arg t) (org-cycle-internal-global))
6330 ;; Drawers: delegate to `org-flag-drawer'.
6331 ((and org-drawers org-drawer-regexp
6332 (save-excursion
6333 (beginning-of-line 1)
6334 (looking-at org-drawer-regexp)))
6335 (org-flag-drawer ; toggle block visibility
6336 (not (get-char-property (match-end 0) 'invisible))))
6338 ;; Show-subtree, ARG levels up from here.
6339 ((integerp arg)
6340 (save-excursion
6341 (org-back-to-heading)
6342 (outline-up-heading (if (< arg 0) (- arg)
6343 (- (funcall outline-level) arg)))
6344 (org-show-subtree)))
6346 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6347 ((and (featurep 'org-inlinetask)
6348 (org-inlinetask-at-task-p)
6349 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6350 (org-inlinetask-toggle-visibility))
6352 ((org-try-cdlatex-tab))
6354 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6355 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6356 (save-excursion (beginning-of-line 1)
6357 (looking-at org-outline-regexp)))
6358 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6359 (org-cycle-internal-local))
6361 ;; From there: TAB emulation and template completion.
6362 (buffer-read-only (org-back-to-heading))
6364 ((run-hook-with-args-until-success
6365 'org-tab-after-check-for-cycling-hook))
6367 ((org-try-structure-completion))
6369 ((run-hook-with-args-until-success
6370 'org-tab-before-tab-emulation-hook))
6372 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6373 (or (not (bolp))
6374 (not (looking-at org-outline-regexp))))
6375 (call-interactively (global-key-binding "\t")))
6377 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6378 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6379 (or (and (eq org-cycle-emulate-tab 'white)
6380 (= (match-end 0) (point-at-eol)))
6381 (and (eq org-cycle-emulate-tab 'whitestart)
6382 (>= (match-end 0) pos))))
6384 (eq org-cycle-emulate-tab t))
6385 (call-interactively (global-key-binding "\t")))
6387 (t (save-excursion
6388 (org-back-to-heading)
6389 (org-cycle)))))))
6391 (defun org-cycle-internal-global ()
6392 "Do the global cycling action."
6393 ;; Hack to avoid display of messages for .org attachments in Gnus
6394 (let ((ga (string-match "\\*fontification" (buffer-name))))
6395 (cond
6396 ((and (eq last-command this-command)
6397 (eq org-cycle-global-status 'overview))
6398 ;; We just created the overview - now do table of contents
6399 ;; This can be slow in very large buffers, so indicate action
6400 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6401 (unless ga (message "CONTENTS..."))
6402 (org-content)
6403 (unless ga (message "CONTENTS...done"))
6404 (setq org-cycle-global-status 'contents)
6405 (run-hook-with-args 'org-cycle-hook 'contents))
6407 ((and (eq last-command this-command)
6408 (eq org-cycle-global-status 'contents))
6409 ;; We just showed the table of contents - now show everything
6410 (run-hook-with-args 'org-pre-cycle-hook 'all)
6411 (show-all)
6412 (unless ga (message "SHOW ALL"))
6413 (setq org-cycle-global-status 'all)
6414 (run-hook-with-args 'org-cycle-hook 'all))
6417 ;; Default action: go to overview
6418 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6419 (org-overview)
6420 (unless ga (message "OVERVIEW"))
6421 (setq org-cycle-global-status 'overview)
6422 (run-hook-with-args 'org-cycle-hook 'overview)))))
6424 (defun org-cycle-internal-local ()
6425 "Do the local cycling action."
6426 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6427 ;; First, determine end of headline (EOH), end of subtree or item
6428 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6429 (save-excursion
6430 (if (org-at-item-p)
6431 (progn
6432 (beginning-of-line)
6433 (setq struct (org-list-struct))
6434 (setq eoh (point-at-eol))
6435 (setq eos (org-list-get-item-end-before-blank (point) struct))
6436 (setq has-children (org-list-has-child-p (point) struct)))
6437 (org-back-to-heading)
6438 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6439 (setq eos (save-excursion
6440 (org-end-of-subtree t)
6441 (unless (eobp)
6442 (skip-chars-forward " \t\n"))
6443 (if (eobp) (point) (1- (point)))))
6444 (setq has-children
6445 (or (save-excursion
6446 (let ((level (funcall outline-level)))
6447 (outline-next-heading)
6448 (and (org-at-heading-p t)
6449 (> (funcall outline-level) level))))
6450 (save-excursion
6451 (org-list-search-forward (org-item-beginning-re) eos t)))))
6452 ;; Determine end invisible part of buffer (EOL)
6453 (beginning-of-line 2)
6454 ;; XEmacs doesn't have `next-single-char-property-change'
6455 (if (featurep 'xemacs)
6456 (while (and (not (eobp)) ;; this is like `next-line'
6457 (get-char-property (1- (point)) 'invisible))
6458 (beginning-of-line 2))
6459 (while (and (not (eobp)) ;; this is like `next-line'
6460 (get-char-property (1- (point)) 'invisible))
6461 (goto-char (next-single-char-property-change (point) 'invisible))
6462 (and (eolp) (beginning-of-line 2))))
6463 (setq eol (point)))
6464 ;; Find out what to do next and set `this-command'
6465 (cond
6466 ((= eos eoh)
6467 ;; Nothing is hidden behind this heading
6468 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6469 (message "EMPTY ENTRY")
6470 (setq org-cycle-subtree-status nil)
6471 (save-excursion
6472 (goto-char eos)
6473 (outline-next-heading)
6474 (if (outline-invisible-p) (org-flag-heading nil))))
6475 ((and (or (>= eol eos)
6476 (not (string-match "\\S-" (buffer-substring eol eos))))
6477 (or has-children
6478 (not (setq children-skipped
6479 org-cycle-skip-children-state-if-no-children))))
6480 ;; Entire subtree is hidden in one line: children view
6481 (run-hook-with-args 'org-pre-cycle-hook 'children)
6482 (if (org-at-item-p)
6483 (org-list-set-item-visibility (point-at-bol) struct 'children)
6484 (org-show-entry)
6485 (org-with-limited-levels (show-children))
6486 ;; FIXME: This slows down the func way too much.
6487 ;; How keep drawers hidden in subtree anyway?
6488 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6489 ;; (org-cycle-hide-drawers 'subtree))
6491 ;; Fold every list in subtree to top-level items.
6492 (when (eq org-cycle-include-plain-lists 'integrate)
6493 (save-excursion
6494 (org-back-to-heading)
6495 (while (org-list-search-forward (org-item-beginning-re) eos t)
6496 (beginning-of-line 1)
6497 (let* ((struct (org-list-struct))
6498 (prevs (org-list-prevs-alist struct))
6499 (end (org-list-get-bottom-point struct)))
6500 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6501 (org-list-get-all-items (point) struct prevs))
6502 (goto-char end))))))
6503 (message "CHILDREN")
6504 (save-excursion
6505 (goto-char eos)
6506 (outline-next-heading)
6507 (if (outline-invisible-p) (org-flag-heading nil)))
6508 (setq org-cycle-subtree-status 'children)
6509 (run-hook-with-args 'org-cycle-hook 'children))
6510 ((or children-skipped
6511 (and (eq last-command this-command)
6512 (eq org-cycle-subtree-status 'children)))
6513 ;; We just showed the children, or no children are there,
6514 ;; now show everything.
6515 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6516 (outline-flag-region eoh eos nil)
6517 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6518 (setq org-cycle-subtree-status 'subtree)
6519 (run-hook-with-args 'org-cycle-hook 'subtree))
6521 ;; Default action: hide the subtree.
6522 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6523 (outline-flag-region eoh eos t)
6524 (message "FOLDED")
6525 (setq org-cycle-subtree-status 'folded)
6526 (run-hook-with-args 'org-cycle-hook 'folded)))))
6528 ;;;###autoload
6529 (defun org-global-cycle (&optional arg)
6530 "Cycle the global visibility. For details see `org-cycle'.
6531 With \\[universal-argument] prefix arg, switch to startup visibility.
6532 With a numeric prefix, show all headlines up to that level."
6533 (interactive "P")
6534 (let ((org-cycle-include-plain-lists
6535 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6536 (cond
6537 ((integerp arg)
6538 (show-all)
6539 (hide-sublevels arg)
6540 (setq org-cycle-global-status 'contents))
6541 ((equal arg '(4))
6542 (org-set-startup-visibility)
6543 (message "Startup visibility, plus VISIBILITY properties."))
6545 (org-cycle '(4))))))
6547 (defun org-set-startup-visibility ()
6548 "Set the visibility required by startup options and properties."
6549 (cond
6550 ((eq org-startup-folded t)
6551 (org-cycle '(4)))
6552 ((eq org-startup-folded 'content)
6553 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6554 (org-cycle '(4)) (org-cycle '(4)))))
6555 (unless (eq org-startup-folded 'showeverything)
6556 (if org-hide-block-startup (org-hide-block-all))
6557 (org-set-visibility-according-to-property 'no-cleanup)
6558 (org-cycle-hide-archived-subtrees 'all)
6559 (org-cycle-hide-drawers 'all)
6560 (org-cycle-show-empty-lines t)))
6562 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6563 "Switch subtree visibilities according to :VISIBILITY: property."
6564 (interactive)
6565 (let (org-show-entry-below state)
6566 (save-excursion
6567 (goto-char (point-min))
6568 (while (re-search-forward
6569 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6570 nil t)
6571 (setq state (match-string 1))
6572 (save-excursion
6573 (org-back-to-heading t)
6574 (hide-subtree)
6575 (org-reveal)
6576 (cond
6577 ((equal state '("fold" "folded"))
6578 (hide-subtree))
6579 ((equal state "children")
6580 (org-show-hidden-entry)
6581 (show-children))
6582 ((equal state "content")
6583 (save-excursion
6584 (save-restriction
6585 (org-narrow-to-subtree)
6586 (org-content))))
6587 ((member state '("all" "showall"))
6588 (show-subtree)))))
6589 (unless no-cleanup
6590 (org-cycle-hide-archived-subtrees 'all)
6591 (org-cycle-hide-drawers 'all)
6592 (org-cycle-show-empty-lines 'all)))))
6594 ;; This function uses outline-regexp instead of the more fundamental
6595 ;; org-outline-regexp so that org-cycle-global works outside of Org
6596 ;; buffers, where outline-regexp is needed.
6597 (defun org-overview ()
6598 "Switch to overview mode, showing only top-level headlines.
6599 Really, this shows all headlines with level equal or greater than the level
6600 of the first headline in the buffer. This is important, because if the
6601 first headline is not level one, then (hide-sublevels 1) gives confusing
6602 results."
6603 (interactive)
6604 (let ((level (save-excursion
6605 (goto-char (point-min))
6606 (if (re-search-forward (concat "^" outline-regexp) nil t)
6607 (progn
6608 (goto-char (match-beginning 0))
6609 (funcall outline-level))))))
6610 (and level (hide-sublevels level))))
6612 (defun org-content (&optional arg)
6613 "Show all headlines in the buffer, like a table of contents.
6614 With numerical argument N, show content up to level N."
6615 (interactive "P")
6616 (save-excursion
6617 ;; Visit all headings and show their offspring
6618 (and (integerp arg) (org-overview))
6619 (goto-char (point-max))
6620 (catch 'exit
6621 (while (and (progn (condition-case nil
6622 (outline-previous-visible-heading 1)
6623 (error (goto-char (point-min))))
6625 (looking-at org-outline-regexp))
6626 (if (integerp arg)
6627 (show-children (1- arg))
6628 (show-branches))
6629 (if (bobp) (throw 'exit nil))))))
6632 (defun org-optimize-window-after-visibility-change (state)
6633 "Adjust the window after a change in outline visibility.
6634 This function is the default value of the hook `org-cycle-hook'."
6635 (when (get-buffer-window (current-buffer))
6636 (cond
6637 ((eq state 'content) nil)
6638 ((eq state 'all) nil)
6639 ((eq state 'folded) nil)
6640 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6641 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6643 (defun org-remove-empty-overlays-at (pos)
6644 "Remove outline overlays that do not contain non-white stuff."
6645 (mapc
6646 (lambda (o)
6647 (and (eq 'outline (overlay-get o 'invisible))
6648 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6649 (overlay-end o))))
6650 (delete-overlay o)))
6651 (overlays-at pos)))
6653 (defun org-clean-visibility-after-subtree-move ()
6654 "Fix visibility issues after moving a subtree."
6655 ;; First, find a reasonable region to look at:
6656 ;; Start two siblings above, end three below
6657 (let* ((beg (save-excursion
6658 (and (org-get-last-sibling)
6659 (org-get-last-sibling))
6660 (point)))
6661 (end (save-excursion
6662 (and (org-get-next-sibling)
6663 (org-get-next-sibling)
6664 (org-get-next-sibling))
6665 (if (org-at-heading-p)
6666 (point-at-eol)
6667 (point))))
6668 (level (looking-at "\\*+"))
6669 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6670 (save-excursion
6671 (save-restriction
6672 (narrow-to-region beg end)
6673 (when re
6674 ;; Properly fold already folded siblings
6675 (goto-char (point-min))
6676 (while (re-search-forward re nil t)
6677 (if (and (not (outline-invisible-p))
6678 (save-excursion
6679 (goto-char (point-at-eol)) (outline-invisible-p)))
6680 (hide-entry))))
6681 (org-cycle-show-empty-lines 'overview)
6682 (org-cycle-hide-drawers 'overview)))))
6684 (defun org-cycle-show-empty-lines (state)
6685 "Show empty lines above all visible headlines.
6686 The region to be covered depends on STATE when called through
6687 `org-cycle-hook'. Lisp program can use t for STATE to get the
6688 entire buffer covered. Note that an empty line is only shown if there
6689 are at least `org-cycle-separator-lines' empty lines before the headline."
6690 (when (not (= org-cycle-separator-lines 0))
6691 (save-excursion
6692 (let* ((n (abs org-cycle-separator-lines))
6693 (re (cond
6694 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6695 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6696 (t (let ((ns (number-to-string (- n 2))))
6697 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6698 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6699 beg end b e)
6700 (cond
6701 ((memq state '(overview contents t))
6702 (setq beg (point-min) end (point-max)))
6703 ((memq state '(children folded))
6704 (setq beg (point) end (progn (org-end-of-subtree t t)
6705 (beginning-of-line 2)
6706 (point)))))
6707 (when beg
6708 (goto-char beg)
6709 (while (re-search-forward re end t)
6710 (unless (get-char-property (match-end 1) 'invisible)
6711 (setq e (match-end 1))
6712 (if (< org-cycle-separator-lines 0)
6713 (setq b (save-excursion
6714 (goto-char (match-beginning 0))
6715 (org-back-over-empty-lines)
6716 (if (save-excursion
6717 (goto-char (max (point-min) (1- (point))))
6718 (org-at-heading-p))
6719 (1- (point))
6720 (point))))
6721 (setq b (match-beginning 1)))
6722 (outline-flag-region b e nil)))))))
6723 ;; Never hide empty lines at the end of the file.
6724 (save-excursion
6725 (goto-char (point-max))
6726 (outline-previous-heading)
6727 (outline-end-of-heading)
6728 (if (and (looking-at "[ \t\n]+")
6729 (= (match-end 0) (point-max)))
6730 (outline-flag-region (point) (match-end 0) nil))))
6732 (defun org-show-empty-lines-in-parent ()
6733 "Move to the parent and re-show empty lines before visible headlines."
6734 (save-excursion
6735 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6736 (org-cycle-show-empty-lines context))))
6738 (defun org-files-list ()
6739 "Return `org-agenda-files' list, plus all open org-mode files.
6740 This is useful for operations that need to scan all of a user's
6741 open and agenda-wise Org files."
6742 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6743 (dolist (buf (buffer-list))
6744 (with-current-buffer buf
6745 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6746 (let ((file (expand-file-name (buffer-file-name))))
6747 (unless (member file files)
6748 (push file files))))))
6749 files))
6751 (defsubst org-entry-beginning-position ()
6752 "Return the beginning position of the current entry."
6753 (save-excursion (outline-back-to-heading t) (point)))
6755 (defsubst org-entry-end-position ()
6756 "Return the end position of the current entry."
6757 (save-excursion (outline-next-heading) (point)))
6759 (defun org-cycle-hide-drawers (state)
6760 "Re-hide all drawers after a visibility state change."
6761 (when (and (derived-mode-p 'org-mode)
6762 (not (memq state '(overview folded contents))))
6763 (save-excursion
6764 (let* ((globalp (memq state '(contents all)))
6765 (beg (if globalp (point-min) (point)))
6766 (end (if globalp (point-max)
6767 (if (eq state 'children)
6768 (save-excursion (outline-next-heading) (point))
6769 (org-end-of-subtree t)))))
6770 (goto-char beg)
6771 (while (re-search-forward org-drawer-regexp end t)
6772 (org-flag-drawer t))))))
6774 (defun org-flag-drawer (flag)
6775 "When FLAG is non-nil, hide the drawer we are within.
6776 Otherwise make it visible."
6777 (save-excursion
6778 (beginning-of-line 1)
6779 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6780 (let ((b (match-end 0)))
6781 (if (re-search-forward
6782 "^[ \t]*:END:"
6783 (save-excursion (outline-next-heading) (point)) t)
6784 (outline-flag-region b (point-at-eol) flag)
6785 (error ":END: line missing at position %s" b))))))
6787 (defun org-subtree-end-visible-p ()
6788 "Is the end of the current subtree visible?"
6789 (pos-visible-in-window-p
6790 (save-excursion (org-end-of-subtree t) (point))))
6792 (defun org-first-headline-recenter (&optional N)
6793 "Move cursor to the first headline and recenter the headline.
6794 Optional argument N means put the headline into the Nth line of the window."
6795 (goto-char (point-min))
6796 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6797 (beginning-of-line)
6798 (recenter (prefix-numeric-value N))))
6800 ;;; Saving and restoring visibility
6802 (defun org-outline-overlay-data (&optional use-markers)
6803 "Return a list of the locations of all outline overlays.
6804 These are overlays with the `invisible' property value `outline'.
6805 The return value is a list of cons cells, with start and stop
6806 positions for each overlay.
6807 If USE-MARKERS is set, return the positions as markers."
6808 (let (beg end)
6809 (save-excursion
6810 (save-restriction
6811 (widen)
6812 (delq nil
6813 (mapcar (lambda (o)
6814 (when (eq (overlay-get o 'invisible) 'outline)
6815 (setq beg (overlay-start o)
6816 end (overlay-end o))
6817 (and beg end (> end beg)
6818 (if use-markers
6819 (cons (move-marker (make-marker) beg)
6820 (move-marker (make-marker) end))
6821 (cons beg end)))))
6822 (overlays-in (point-min) (point-max))))))))
6824 (defun org-set-outline-overlay-data (data)
6825 "Create visibility overlays for all positions in DATA.
6826 DATA should have been made by `org-outline-overlay-data'."
6827 (let (o)
6828 (save-excursion
6829 (save-restriction
6830 (widen)
6831 (show-all)
6832 (mapc (lambda (c)
6833 (outline-flag-region (car c) (cdr c) t))
6834 data)))))
6836 ;;; Folding of blocks
6838 (defvar org-hide-block-overlays nil
6839 "Overlays hiding blocks.")
6840 (make-variable-buffer-local 'org-hide-block-overlays)
6842 (defun org-block-map (function &optional start end)
6843 "Call FUNCTION at the head of all source blocks in the current buffer.
6844 Optional arguments START and END can be used to limit the range."
6845 (let ((start (or start (point-min)))
6846 (end (or end (point-max))))
6847 (save-excursion
6848 (goto-char start)
6849 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6850 (save-excursion
6851 (save-match-data
6852 (goto-char (match-beginning 0))
6853 (funcall function)))))))
6855 (defun org-hide-block-toggle-all ()
6856 "Toggle the visibility of all blocks in the current buffer."
6857 (org-block-map #'org-hide-block-toggle))
6859 (defun org-hide-block-all ()
6860 "Fold all blocks in the current buffer."
6861 (interactive)
6862 (org-show-block-all)
6863 (org-block-map #'org-hide-block-toggle-maybe))
6865 (defun org-show-block-all ()
6866 "Unfold all blocks in the current buffer."
6867 (interactive)
6868 (mapc 'delete-overlay org-hide-block-overlays)
6869 (setq org-hide-block-overlays nil))
6871 (defun org-hide-block-toggle-maybe ()
6872 "Toggle visibility of block at point."
6873 (interactive)
6874 (let ((case-fold-search t))
6875 (if (save-excursion
6876 (beginning-of-line 1)
6877 (looking-at org-block-regexp))
6878 (progn (org-hide-block-toggle)
6879 t) ;; to signal that we took action
6880 nil))) ;; to signal that we did not
6882 (defun org-hide-block-toggle (&optional force)
6883 "Toggle the visibility of the current block."
6884 (interactive)
6885 (save-excursion
6886 (beginning-of-line)
6887 (if (re-search-forward org-block-regexp nil t)
6888 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6889 (end (match-end 0)) ;; end of entire body
6891 (if (memq t (mapcar (lambda (overlay)
6892 (eq (overlay-get overlay 'invisible)
6893 'org-hide-block))
6894 (overlays-at start)))
6895 (if (or (not force) (eq force 'off))
6896 (mapc (lambda (ov)
6897 (when (member ov org-hide-block-overlays)
6898 (setq org-hide-block-overlays
6899 (delq ov org-hide-block-overlays)))
6900 (when (eq (overlay-get ov 'invisible)
6901 'org-hide-block)
6902 (delete-overlay ov)))
6903 (overlays-at start)))
6904 (setq ov (make-overlay start end))
6905 (overlay-put ov 'invisible 'org-hide-block)
6906 ;; make the block accessible to isearch
6907 (overlay-put
6908 ov 'isearch-open-invisible
6909 (lambda (ov)
6910 (when (member ov org-hide-block-overlays)
6911 (setq org-hide-block-overlays
6912 (delq ov org-hide-block-overlays)))
6913 (when (eq (overlay-get ov 'invisible)
6914 'org-hide-block)
6915 (delete-overlay ov))))
6916 (push ov org-hide-block-overlays)))
6917 (error "Not looking at a source block"))))
6919 ;; org-tab-after-check-for-cycling-hook
6920 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6921 ;; Remove overlays when changing major mode
6922 (add-hook 'org-mode-hook
6923 (lambda () (org-add-hook 'change-major-mode-hook
6924 'org-show-block-all 'append 'local)))
6926 ;;; Org-goto
6928 (defvar org-goto-window-configuration nil)
6929 (defvar org-goto-marker nil)
6930 (defvar org-goto-map
6931 (let ((map (make-sparse-keymap)))
6932 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6933 (while (setq cmd (pop cmds))
6934 (substitute-key-definition cmd cmd map global-map)))
6935 (suppress-keymap map)
6936 (org-defkey map "\C-m" 'org-goto-ret)
6937 (org-defkey map [(return)] 'org-goto-ret)
6938 (org-defkey map [(left)] 'org-goto-left)
6939 (org-defkey map [(right)] 'org-goto-right)
6940 (org-defkey map [(control ?g)] 'org-goto-quit)
6941 (org-defkey map "\C-i" 'org-cycle)
6942 (org-defkey map [(tab)] 'org-cycle)
6943 (org-defkey map [(down)] 'outline-next-visible-heading)
6944 (org-defkey map [(up)] 'outline-previous-visible-heading)
6945 (if org-goto-auto-isearch
6946 (if (fboundp 'define-key-after)
6947 (define-key-after map [t] 'org-goto-local-auto-isearch)
6948 nil)
6949 (org-defkey map "q" 'org-goto-quit)
6950 (org-defkey map "n" 'outline-next-visible-heading)
6951 (org-defkey map "p" 'outline-previous-visible-heading)
6952 (org-defkey map "f" 'outline-forward-same-level)
6953 (org-defkey map "b" 'outline-backward-same-level)
6954 (org-defkey map "u" 'outline-up-heading))
6955 (org-defkey map "/" 'org-occur)
6956 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6957 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6958 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6959 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6960 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6961 map))
6963 (defconst org-goto-help
6964 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6965 RET=jump to location [Q]uit and return to previous location
6966 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6968 (defvar org-goto-start-pos) ; dynamically scoped parameter
6970 ;; FIXME: Docstring does not mention both interfaces
6971 (defun org-goto (&optional alternative-interface)
6972 "Look up a different location in the current file, keeping current visibility.
6974 When you want look-up or go to a different location in a
6975 document, the fastest way is often to fold the entire buffer and
6976 then dive into the tree. This method has the disadvantage, that
6977 the previous location will be folded, which may not be what you
6978 want.
6980 This command works around this by showing a copy of the current
6981 buffer in an indirect buffer, in overview mode. You can dive
6982 into the tree in that copy, use org-occur and incremental search
6983 to find a location. When pressing RET or `Q', the command
6984 returns to the original buffer in which the visibility is still
6985 unchanged. After RET it will also jump to the location selected
6986 in the indirect buffer and expose the headline hierarchy above.
6988 With a prefix argument, use the alternative interface: e.g. if
6989 `org-goto-interface' is 'outline use 'outline-path-completion."
6990 (interactive "P")
6991 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6992 (org-refile-use-outline-path t)
6993 (org-refile-target-verify-function nil)
6994 (interface
6995 (if (not alternative-interface)
6996 org-goto-interface
6997 (if (eq org-goto-interface 'outline)
6998 'outline-path-completion
6999 'outline)))
7000 (org-goto-start-pos (point))
7001 (selected-point
7002 (if (eq interface 'outline)
7003 (car (org-get-location (current-buffer) org-goto-help))
7004 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7005 (org-refile-check-position pa)
7006 (nth 3 pa)))))
7007 (if selected-point
7008 (progn
7009 (org-mark-ring-push org-goto-start-pos)
7010 (goto-char selected-point)
7011 (if (or (outline-invisible-p) (org-invisible-p2))
7012 (org-show-context 'org-goto)))
7013 (message "Quit"))))
7015 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7016 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7017 (defvar org-goto-local-auto-isearch-map) ; defined below
7019 (defun org-get-location (buf help)
7020 "Let the user select a location in the Org-mode buffer BUF.
7021 This function uses a recursive edit. It returns the selected position
7022 or nil."
7023 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7024 (isearch-hide-immediately nil)
7025 (isearch-search-fun-function
7026 (lambda () 'org-goto-local-search-headings))
7027 (org-goto-selected-point org-goto-exit-command)
7028 (pop-up-frames nil)
7029 (special-display-buffer-names nil)
7030 (special-display-regexps nil)
7031 (special-display-function nil))
7032 (save-excursion
7033 (save-window-excursion
7034 (delete-other-windows)
7035 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7036 (org-pop-to-buffer-same-window
7037 (condition-case nil
7038 (make-indirect-buffer (current-buffer) "*org-goto*")
7039 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7040 (with-output-to-temp-buffer "*Help*"
7041 (princ help))
7042 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7043 (setq buffer-read-only nil)
7044 (let ((org-startup-truncated t)
7045 (org-startup-folded nil)
7046 (org-startup-align-all-tables nil))
7047 (org-mode)
7048 (org-overview))
7049 (setq buffer-read-only t)
7050 (if (and (boundp 'org-goto-start-pos)
7051 (integer-or-marker-p org-goto-start-pos))
7052 (let ((org-show-hierarchy-above t)
7053 (org-show-siblings t)
7054 (org-show-following-heading t))
7055 (goto-char org-goto-start-pos)
7056 (and (outline-invisible-p) (org-show-context)))
7057 (goto-char (point-min)))
7058 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7059 (message "Select location and press RET")
7060 (use-local-map org-goto-map)
7061 (recursive-edit)
7063 (kill-buffer "*org-goto*")
7064 (cons org-goto-selected-point org-goto-exit-command)))
7066 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7067 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7068 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7069 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7071 (defun org-goto-local-search-headings (string bound noerror)
7072 "Search and make sure that any matches are in headlines."
7073 (catch 'return
7074 (while (if isearch-forward
7075 (search-forward string bound noerror)
7076 (search-backward string bound noerror))
7077 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7078 (and (member :headline context)
7079 (not (member :tags context))))
7080 (throw 'return (point))))))
7082 (defun org-goto-local-auto-isearch ()
7083 "Start isearch."
7084 (interactive)
7085 (goto-char (point-min))
7086 (let ((keys (this-command-keys)))
7087 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7088 (isearch-mode t)
7089 (isearch-process-search-char (string-to-char keys)))))
7091 (defun org-goto-ret (&optional arg)
7092 "Finish `org-goto' by going to the new location."
7093 (interactive "P")
7094 (setq org-goto-selected-point (point)
7095 org-goto-exit-command 'return)
7096 (throw 'exit nil))
7098 (defun org-goto-left ()
7099 "Finish `org-goto' by going to the new location."
7100 (interactive)
7101 (if (org-at-heading-p)
7102 (progn
7103 (beginning-of-line 1)
7104 (setq org-goto-selected-point (point)
7105 org-goto-exit-command 'left)
7106 (throw 'exit nil))
7107 (error "Not on a heading")))
7109 (defun org-goto-right ()
7110 "Finish `org-goto' by going to the new location."
7111 (interactive)
7112 (if (org-at-heading-p)
7113 (progn
7114 (setq org-goto-selected-point (point)
7115 org-goto-exit-command 'right)
7116 (throw 'exit nil))
7117 (error "Not on a heading")))
7119 (defun org-goto-quit ()
7120 "Finish `org-goto' without cursor motion."
7121 (interactive)
7122 (setq org-goto-selected-point nil)
7123 (setq org-goto-exit-command 'quit)
7124 (throw 'exit nil))
7126 ;;; Indirect buffer display of subtrees
7128 (defvar org-indirect-dedicated-frame nil
7129 "This is the frame being used for indirect tree display.")
7130 (defvar org-last-indirect-buffer nil)
7132 (defun org-tree-to-indirect-buffer (&optional arg)
7133 "Create indirect buffer and narrow it to current subtree.
7134 With numerical prefix ARG, go up to this level and then take that tree.
7135 If ARG is negative, go up that many levels.
7136 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7137 indirect buffer previously made with this command, to avoid proliferation of
7138 indirect buffers. However, when you call the command with a \
7139 \\[universal-argument] prefix, or
7140 when `org-indirect-buffer-display' is `new-frame', the last buffer
7141 is kept so that you can work with several indirect buffers at the same time.
7142 If `org-indirect-buffer-display' is `dedicated-frame', the \
7143 \\[universal-argument] prefix also
7144 requests that a new frame be made for the new buffer, so that the dedicated
7145 frame is not changed."
7146 (interactive "P")
7147 (let ((cbuf (current-buffer))
7148 (cwin (selected-window))
7149 (pos (point))
7150 beg end level heading ibuf)
7151 (save-excursion
7152 (org-back-to-heading t)
7153 (when (numberp arg)
7154 (setq level (org-outline-level))
7155 (if (< arg 0) (setq arg (+ level arg)))
7156 (while (> (setq level (org-outline-level)) arg)
7157 (outline-up-heading 1 t)))
7158 (setq beg (point)
7159 heading (org-get-heading))
7160 (org-end-of-subtree t t)
7161 (if (org-at-heading-p) (backward-char 1))
7162 (setq end (point)))
7163 (if (and (buffer-live-p org-last-indirect-buffer)
7164 (not (eq org-indirect-buffer-display 'new-frame))
7165 (not arg))
7166 (kill-buffer org-last-indirect-buffer))
7167 (setq ibuf (org-get-indirect-buffer cbuf)
7168 org-last-indirect-buffer ibuf)
7169 (cond
7170 ((or (eq org-indirect-buffer-display 'new-frame)
7171 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7172 (select-frame (make-frame))
7173 (delete-other-windows)
7174 (org-pop-to-buffer-same-window ibuf)
7175 (org-set-frame-title heading))
7176 ((eq org-indirect-buffer-display 'dedicated-frame)
7177 (raise-frame
7178 (select-frame (or (and org-indirect-dedicated-frame
7179 (frame-live-p org-indirect-dedicated-frame)
7180 org-indirect-dedicated-frame)
7181 (setq org-indirect-dedicated-frame (make-frame)))))
7182 (delete-other-windows)
7183 (org-pop-to-buffer-same-window ibuf)
7184 (org-set-frame-title (concat "Indirect: " heading)))
7185 ((eq org-indirect-buffer-display 'current-window)
7186 (org-pop-to-buffer-same-window ibuf))
7187 ((eq org-indirect-buffer-display 'other-window)
7188 (pop-to-buffer ibuf))
7189 (t (error "Invalid value")))
7190 (if (featurep 'xemacs)
7191 (save-excursion (org-mode) (turn-on-font-lock)))
7192 (narrow-to-region beg end)
7193 (show-all)
7194 (goto-char pos)
7195 (run-hook-with-args 'org-cycle-hook 'all)
7196 (and (window-live-p cwin) (select-window cwin))))
7198 (defun org-get-indirect-buffer (&optional buffer)
7199 (setq buffer (or buffer (current-buffer)))
7200 (let ((n 1) (base (buffer-name buffer)) bname)
7201 (while (buffer-live-p
7202 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7203 (setq n (1+ n)))
7204 (condition-case nil
7205 (make-indirect-buffer buffer bname 'clone)
7206 (error (make-indirect-buffer buffer bname)))))
7208 (defun org-set-frame-title (title)
7209 "Set the title of the current frame to the string TITLE."
7210 ;; FIXME: how to name a single frame in XEmacs???
7211 (unless (featurep 'xemacs)
7212 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7214 ;;;; Structure editing
7216 ;;; Inserting headlines
7218 (defun org-previous-line-empty-p ()
7219 (save-excursion
7220 (and (not (bobp))
7221 (or (beginning-of-line 0) t)
7222 (save-match-data
7223 (looking-at "[ \t]*$")))))
7225 (defun org-insert-heading (&optional force-heading invisible-ok)
7226 "Insert a new heading or item with same depth at point.
7227 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7228 If point is at the beginning of a headline, insert a sibling before the
7229 current headline. If point is not at the beginning, split the line,
7230 create the new headline with the text in the current line after point
7231 \(but see also the variable `org-M-RET-may-split-line').
7233 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7234 This is important for non-interactive uses of the command."
7235 (interactive "P")
7236 (if (or (= (buffer-size) 0)
7237 (and (not (save-excursion
7238 (and (ignore-errors (org-back-to-heading invisible-ok))
7239 (org-at-heading-p))))
7240 (or force-heading (not (org-in-item-p)))))
7241 (progn
7242 (insert "\n* ")
7243 (run-hooks 'org-insert-heading-hook))
7244 (when (or force-heading (not (org-insert-item)))
7245 (let* ((empty-line-p nil)
7246 (level nil)
7247 (on-heading (org-at-heading-p))
7248 (head (save-excursion
7249 (condition-case nil
7250 (progn
7251 (org-back-to-heading invisible-ok)
7252 (when (and (not on-heading)
7253 (featurep 'org-inlinetask)
7254 (integerp org-inlinetask-min-level)
7255 (>= (length (match-string 0))
7256 org-inlinetask-min-level))
7257 ;; Find a heading level before the inline task
7258 (while (and (setq level (org-up-heading-safe))
7259 (>= level org-inlinetask-min-level)))
7260 (if (org-at-heading-p)
7261 (org-back-to-heading invisible-ok)
7262 (error "This should not happen")))
7263 (setq empty-line-p (org-previous-line-empty-p))
7264 (match-string 0))
7265 (error "*"))))
7266 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7267 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7268 pos hide-previous previous-pos)
7269 (cond
7270 ((and (org-at-heading-p) (bolp)
7271 (or (bobp)
7272 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7273 ;; insert before the current line
7274 (open-line (if blank 2 1)))
7275 ((and (bolp)
7276 (not org-insert-heading-respect-content)
7277 (or (bobp)
7278 (save-excursion
7279 (backward-char 1) (not (outline-invisible-p)))))
7280 ;; insert right here
7281 nil)
7283 ;; somewhere in the line
7284 (save-excursion
7285 (setq previous-pos (point-at-bol))
7286 (end-of-line)
7287 (setq hide-previous (outline-invisible-p)))
7288 (and org-insert-heading-respect-content (org-show-subtree))
7289 (let ((split
7290 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7291 (save-excursion
7292 (let ((p (point)))
7293 (goto-char (point-at-bol))
7294 (and (looking-at org-complex-heading-regexp)
7295 (match-beginning 4)
7296 (> p (match-beginning 4)))))))
7297 tags pos)
7298 (cond
7299 (org-insert-heading-respect-content
7300 (org-end-of-subtree nil t)
7301 (when (featurep 'org-inlinetask)
7302 (while (and (not (eobp))
7303 (looking-at "\\(\\*+\\)[ \t]+")
7304 (>= (length (match-string 1))
7305 org-inlinetask-min-level))
7306 (org-end-of-subtree nil t)))
7307 (or (bolp) (newline))
7308 (or (org-previous-line-empty-p)
7309 (and blank (newline)))
7310 (open-line 1))
7311 ((org-at-heading-p)
7312 (when hide-previous
7313 (show-children)
7314 (org-show-entry))
7315 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7316 (setq tags (and (match-end 2) (match-string 2)))
7317 (and (match-end 1)
7318 (delete-region (match-beginning 1) (match-end 1)))
7319 (setq pos (point-at-bol))
7320 (or split (end-of-line 1))
7321 (delete-horizontal-space)
7322 (if (string-match "\\`\\*+\\'"
7323 (buffer-substring (point-at-bol) (point)))
7324 (insert " "))
7325 (newline (if blank 2 1))
7326 (when tags
7327 (save-excursion
7328 (goto-char pos)
7329 (end-of-line 1)
7330 (insert " " tags)
7331 (org-set-tags nil 'align))))
7333 (or split (end-of-line 1))
7334 (newline (if blank 2 1)))))))
7335 (insert head) (just-one-space)
7336 (setq pos (point))
7337 (end-of-line 1)
7338 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7339 (when (and org-insert-heading-respect-content hide-previous)
7340 (save-excursion
7341 (goto-char previous-pos)
7342 (hide-subtree)))
7343 (run-hooks 'org-insert-heading-hook)))))
7345 (defun org-get-heading (&optional no-tags no-todo)
7346 "Return the heading of the current entry, without the stars.
7347 When NO-TAGS is non-nil, don't include tags.
7348 When NO-TODO is non-nil, don't include TODO keywords."
7349 (save-excursion
7350 (org-back-to-heading t)
7351 (cond
7352 ((and no-tags no-todo)
7353 (looking-at org-complex-heading-regexp)
7354 (match-string 4))
7355 (no-tags
7356 (looking-at (concat org-outline-regexp
7357 "\\(.*?\\)"
7358 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7359 (match-string 1))
7360 (no-todo
7361 (looking-at org-todo-line-regexp)
7362 (match-string 3))
7363 (t (looking-at org-heading-regexp)
7364 (match-string 2)))))
7366 (defun org-heading-components ()
7367 "Return the components of the current heading.
7368 This is a list with the following elements:
7369 - the level as an integer
7370 - the reduced level, different if `org-odd-levels-only' is set.
7371 - the TODO keyword, or nil
7372 - the priority character, like ?A, or nil if no priority is given
7373 - the headline text itself, or the tags string if no headline text
7374 - the tags string, or nil."
7375 (save-excursion
7376 (org-back-to-heading t)
7377 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7378 (list (length (match-string 1))
7379 (org-reduced-level (length (match-string 1)))
7380 (org-match-string-no-properties 2)
7381 (and (match-end 3) (aref (match-string 3) 2))
7382 (org-match-string-no-properties 4)
7383 (org-match-string-no-properties 5)))))
7385 (defun org-get-entry ()
7386 "Get the entry text, after heading, entire subtree."
7387 (save-excursion
7388 (org-back-to-heading t)
7389 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7391 (defun org-insert-heading-after-current ()
7392 "Insert a new heading with same level as current, after current subtree."
7393 (interactive)
7394 (org-back-to-heading)
7395 (org-insert-heading)
7396 (org-move-subtree-down)
7397 (end-of-line 1))
7399 (defun org-insert-heading-respect-content ()
7400 (interactive)
7401 (let ((org-insert-heading-respect-content t))
7402 (org-insert-heading t)))
7404 (defun org-insert-todo-heading-respect-content (&optional force-state)
7405 (interactive "P")
7406 (let ((org-insert-heading-respect-content t))
7407 (org-insert-todo-heading force-state t)))
7409 (defun org-insert-todo-heading (arg &optional force-heading)
7410 "Insert a new heading with the same level and TODO state as current heading.
7411 If the heading has no TODO state, or if the state is DONE, use the first
7412 state (TODO by default). Also with prefix arg, force first state."
7413 (interactive "P")
7414 (when (or force-heading (not (org-insert-item 'checkbox)))
7415 (org-insert-heading force-heading)
7416 (save-excursion
7417 (org-back-to-heading)
7418 (outline-previous-heading)
7419 (looking-at org-todo-line-regexp))
7420 (let*
7421 ((new-mark-x
7422 (if (or arg
7423 (not (match-beginning 2))
7424 (member (match-string 2) org-done-keywords))
7425 (car org-todo-keywords-1)
7426 (match-string 2)))
7427 (new-mark
7429 (run-hook-with-args-until-success
7430 'org-todo-get-default-hook new-mark-x nil)
7431 new-mark-x)))
7432 (beginning-of-line 1)
7433 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7434 (if org-treat-insert-todo-heading-as-state-change
7435 (org-todo new-mark)
7436 (insert new-mark " "))))
7437 (when org-provide-todo-statistics
7438 (org-update-parent-todo-statistics))))
7440 (defun org-insert-subheading (arg)
7441 "Insert a new subheading and demote it.
7442 Works for outline headings and for plain lists alike."
7443 (interactive "P")
7444 (org-insert-heading arg)
7445 (cond
7446 ((org-at-heading-p) (org-do-demote))
7447 ((org-at-item-p) (org-indent-item))))
7449 (defun org-insert-todo-subheading (arg)
7450 "Insert a new subheading with TODO keyword or checkbox and demote it.
7451 Works for outline headings and for plain lists alike."
7452 (interactive "P")
7453 (org-insert-todo-heading arg)
7454 (cond
7455 ((org-at-heading-p) (org-do-demote))
7456 ((org-at-item-p) (org-indent-item))))
7458 ;;; Promotion and Demotion
7460 (defvar org-after-demote-entry-hook nil
7461 "Hook run after an entry has been demoted.
7462 The cursor will be at the beginning of the entry.
7463 When a subtree is being demoted, the hook will be called for each node.")
7465 (defvar org-after-promote-entry-hook nil
7466 "Hook run after an entry has been promoted.
7467 The cursor will be at the beginning of the entry.
7468 When a subtree is being promoted, the hook will be called for each node.")
7470 (defun org-promote-subtree ()
7471 "Promote the entire subtree.
7472 See also `org-promote'."
7473 (interactive)
7474 (save-excursion
7475 (org-with-limited-levels (org-map-tree 'org-promote)))
7476 (org-fix-position-after-promote))
7478 (defun org-demote-subtree ()
7479 "Demote the entire subtree. See `org-demote'.
7480 See also `org-promote'."
7481 (interactive)
7482 (save-excursion
7483 (org-with-limited-levels (org-map-tree 'org-demote)))
7484 (org-fix-position-after-promote))
7487 (defun org-do-promote ()
7488 "Promote the current heading higher up the tree.
7489 If the region is active in `transient-mark-mode', promote all headings
7490 in the region."
7491 (interactive)
7492 (save-excursion
7493 (if (org-region-active-p)
7494 (org-map-region 'org-promote (region-beginning) (region-end))
7495 (org-promote)))
7496 (org-fix-position-after-promote))
7498 (defun org-do-demote ()
7499 "Demote the current heading lower down the tree.
7500 If the region is active in `transient-mark-mode', demote all headings
7501 in the region."
7502 (interactive)
7503 (save-excursion
7504 (if (org-region-active-p)
7505 (org-map-region 'org-demote (region-beginning) (region-end))
7506 (org-demote)))
7507 (org-fix-position-after-promote))
7509 (defun org-fix-position-after-promote ()
7510 "Make sure that after pro/demotion cursor position is right."
7511 (let ((pos (point)))
7512 (when (save-excursion
7513 (beginning-of-line 1)
7514 (looking-at org-todo-line-regexp)
7515 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7516 (cond ((eobp) (insert " "))
7517 ((eolp) (insert " "))
7518 ((equal (char-after) ?\ ) (forward-char 1))))))
7520 (defun org-current-level ()
7521 "Return the level of the current entry, or nil if before the first headline.
7522 The level is the number of stars at the beginning of the headline."
7523 (save-excursion
7524 (org-with-limited-levels
7525 (if (ignore-errors (org-back-to-heading t))
7526 (funcall outline-level)))))
7528 (defun org-get-previous-line-level ()
7529 "Return the outline depth of the last headline before the current line.
7530 Returns 0 for the first headline in the buffer, and nil if before the
7531 first headline."
7532 (let ((current-level (org-current-level))
7533 (prev-level (when (> (line-number-at-pos) 1)
7534 (save-excursion
7535 (beginning-of-line 0)
7536 (org-current-level)))))
7537 (cond ((null current-level) nil) ; Before first headline
7538 ((null prev-level) 0) ; At first headline
7539 (prev-level))))
7541 (defun org-reduced-level (l)
7542 "Compute the effective level of a heading.
7543 This takes into account the setting of `org-odd-levels-only'."
7544 (cond
7545 ((zerop l) 0)
7546 (org-odd-levels-only (1+ (floor (/ l 2))))
7547 (t l)))
7549 (defun org-level-increment ()
7550 "Return the number of stars that will be added or removed at a
7551 time to headlines when structure editing, based on the value of
7552 `org-odd-levels-only'."
7553 (if org-odd-levels-only 2 1))
7555 (defun org-get-valid-level (level &optional change)
7556 "Rectify a level change under the influence of `org-odd-levels-only'
7557 LEVEL is a current level, CHANGE is by how much the level should be
7558 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7559 even level numbers will become the next higher odd number."
7560 (if org-odd-levels-only
7561 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7562 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7563 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7564 (max 1 (+ level (or change 0)))))
7566 (if (boundp 'define-obsolete-function-alias)
7567 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7568 (define-obsolete-function-alias 'org-get-legal-level
7569 'org-get-valid-level)
7570 (define-obsolete-function-alias 'org-get-legal-level
7571 'org-get-valid-level "23.1")))
7573 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7574 ;; ̀org-with-limited-levels'
7575 (defun org-promote ()
7576 "Promote the current heading higher up the tree.
7577 If the region is active in `transient-mark-mode', promote all headings
7578 in the region."
7579 (org-back-to-heading t)
7580 (let* ((level (save-match-data (funcall outline-level)))
7581 (after-change-functions (remove 'flyspell-after-change-function
7582 after-change-functions))
7583 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7584 (diff (abs (- level (length up-head) -1))))
7585 (cond ((and (= level 1) org-called-with-limited-levels
7586 org-allow-promoting-top-level-subtree)
7587 (replace-match "# " nil t))
7588 ((= level 1)
7589 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7590 (t (replace-match up-head nil t)))
7591 ;; Fixup tag positioning
7592 (unless (= level 1)
7593 (and org-auto-align-tags (org-set-tags nil t))
7594 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7595 (run-hooks 'org-after-promote-entry-hook)))
7597 (defun org-demote ()
7598 "Demote the current heading lower down the tree.
7599 If the region is active in `transient-mark-mode', demote all headings
7600 in the region."
7601 (org-back-to-heading t)
7602 (let* ((level (save-match-data (funcall outline-level)))
7603 (after-change-functions (remove 'flyspell-after-change-function
7604 after-change-functions))
7605 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7606 (diff (abs (- level (length down-head) -1))))
7607 (replace-match down-head nil t)
7608 ;; Fixup tag positioning
7609 (and org-auto-align-tags (org-set-tags nil t))
7610 (if org-adapt-indentation (org-fixup-indentation diff))
7611 (run-hooks 'org-after-demote-entry-hook)))
7613 (defun org-cycle-level ()
7614 "Cycle the level of an empty headline through possible states.
7615 This goes first to child, then to parent, level, then up the hierarchy.
7616 After top level, it switches back to sibling level."
7617 (interactive)
7618 (let ((org-adapt-indentation nil))
7619 (when (org-point-at-end-of-empty-headline)
7620 (setq this-command 'org-cycle-level) ; Only needed for caching
7621 (let ((cur-level (org-current-level))
7622 (prev-level (org-get-previous-line-level)))
7623 (cond
7624 ;; If first headline in file, promote to top-level.
7625 ((= prev-level 0)
7626 (loop repeat (/ (- cur-level 1) (org-level-increment))
7627 do (org-do-promote)))
7628 ;; If same level as prev, demote one.
7629 ((= prev-level cur-level)
7630 (org-do-demote))
7631 ;; If parent is top-level, promote to top level if not already.
7632 ((= prev-level 1)
7633 (loop repeat (/ (- cur-level 1) (org-level-increment))
7634 do (org-do-promote)))
7635 ;; If top-level, return to prev-level.
7636 ((= cur-level 1)
7637 (loop repeat (/ (- prev-level 1) (org-level-increment))
7638 do (org-do-demote)))
7639 ;; If less than prev-level, promote one.
7640 ((< cur-level prev-level)
7641 (org-do-promote))
7642 ;; If deeper than prev-level, promote until higher than
7643 ;; prev-level.
7644 ((> cur-level prev-level)
7645 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7646 do (org-do-promote))))
7647 t))))
7649 (defun org-map-tree (fun)
7650 "Call FUN for every heading underneath the current one."
7651 (org-back-to-heading)
7652 (let ((level (funcall outline-level)))
7653 (save-excursion
7654 (funcall fun)
7655 (while (and (progn
7656 (outline-next-heading)
7657 (> (funcall outline-level) level))
7658 (not (eobp)))
7659 (funcall fun)))))
7661 (defun org-map-region (fun beg end)
7662 "Call FUN for every heading between BEG and END."
7663 (let ((org-ignore-region t))
7664 (save-excursion
7665 (setq end (copy-marker end))
7666 (goto-char beg)
7667 (if (and (re-search-forward org-outline-regexp-bol nil t)
7668 (< (point) end))
7669 (funcall fun))
7670 (while (and (progn
7671 (outline-next-heading)
7672 (< (point) end))
7673 (not (eobp)))
7674 (funcall fun)))))
7676 (defvar org-property-end-re) ; silence byte-compiler
7677 (defun org-fixup-indentation (diff)
7678 "Change the indentation in the current entry by DIFF.
7679 However, if any line in the current entry has no indentation, or if it
7680 would end up with no indentation after the change, nothing at all is done."
7681 (save-excursion
7682 (let ((end (save-excursion (outline-next-heading)
7683 (point-marker)))
7684 (prohibit (if (> diff 0)
7685 "^\\S-"
7686 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7687 col)
7688 (unless (save-excursion (end-of-line 1)
7689 (re-search-forward prohibit end t))
7690 (while (and (< (point) end)
7691 (re-search-forward "^[ \t]+" end t))
7692 (goto-char (match-end 0))
7693 (setq col (current-column))
7694 (if (< diff 0) (replace-match ""))
7695 (org-indent-to-column (+ diff col))))
7696 (move-marker end nil))))
7698 (defun org-convert-to-odd-levels ()
7699 "Convert an org-mode file with all levels allowed to one with odd levels.
7700 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7701 level 5 etc."
7702 (interactive)
7703 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7704 (let ((outline-level 'org-outline-level)
7705 (org-odd-levels-only nil) n)
7706 (save-excursion
7707 (goto-char (point-min))
7708 (while (re-search-forward "^\\*\\*+ " nil t)
7709 (setq n (- (length (match-string 0)) 2))
7710 (while (>= (setq n (1- n)) 0)
7711 (org-demote))
7712 (end-of-line 1))))))
7714 (defun org-convert-to-oddeven-levels ()
7715 "Convert an org-mode file with only odd levels to one with odd/even levels.
7716 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7717 file contains a section with an even level, conversion would
7718 destroy the structure of the file. An error is signaled in this
7719 case."
7720 (interactive)
7721 (goto-char (point-min))
7722 ;; First check if there are no even levels
7723 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7724 (org-show-context t)
7725 (error "Not all levels are odd in this file. Conversion not possible"))
7726 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7727 (let ((outline-regexp org-outline-regexp)
7728 (outline-level 'org-outline-level)
7729 (org-odd-levels-only nil) n)
7730 (save-excursion
7731 (goto-char (point-min))
7732 (while (re-search-forward "^\\*\\*+ " nil t)
7733 (setq n (/ (1- (length (match-string 0))) 2))
7734 (while (>= (setq n (1- n)) 0)
7735 (org-promote))
7736 (end-of-line 1))))))
7738 (defun org-tr-level (n)
7739 "Make N odd if required."
7740 (if org-odd-levels-only (1+ (/ n 2)) n))
7742 ;;; Vertical tree motion, cutting and pasting of subtrees
7744 (defun org-move-subtree-up (&optional arg)
7745 "Move the current subtree up past ARG headlines of the same level."
7746 (interactive "p")
7747 (org-move-subtree-down (- (prefix-numeric-value arg))))
7749 (defun org-move-subtree-down (&optional arg)
7750 "Move the current subtree down past ARG headlines of the same level."
7751 (interactive "p")
7752 (setq arg (prefix-numeric-value arg))
7753 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7754 'org-get-last-sibling))
7755 (ins-point (make-marker))
7756 (cnt (abs arg))
7757 (col (current-column))
7758 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7759 ;; Select the tree
7760 (org-back-to-heading)
7761 (setq beg0 (point))
7762 (save-excursion
7763 (setq ne-beg (org-back-over-empty-lines))
7764 (setq beg (point)))
7765 (save-match-data
7766 (save-excursion (outline-end-of-heading)
7767 (setq folded (outline-invisible-p)))
7768 (outline-end-of-subtree))
7769 (outline-next-heading)
7770 (setq ne-end (org-back-over-empty-lines))
7771 (setq end (point))
7772 (goto-char beg0)
7773 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7774 ;; include less whitespace
7775 (save-excursion
7776 (goto-char beg)
7777 (forward-line (- ne-beg ne-end))
7778 (setq beg (point))))
7779 ;; Find insertion point, with error handling
7780 (while (> cnt 0)
7781 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7782 (progn (goto-char beg0)
7783 (error "Cannot move past superior level or buffer limit")))
7784 (setq cnt (1- cnt)))
7785 (if (> arg 0)
7786 ;; Moving forward - still need to move over subtree
7787 (progn (org-end-of-subtree t t)
7788 (save-excursion
7789 (org-back-over-empty-lines)
7790 (or (bolp) (newline)))))
7791 (setq ne-ins (org-back-over-empty-lines))
7792 (move-marker ins-point (point))
7793 (setq txt (buffer-substring beg end))
7794 (org-save-markers-in-region beg end)
7795 (delete-region beg end)
7796 (org-remove-empty-overlays-at beg)
7797 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7798 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7799 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7800 (let ((bbb (point)))
7801 (insert-before-markers txt)
7802 (org-reinstall-markers-in-region bbb)
7803 (move-marker ins-point bbb))
7804 (or (bolp) (insert "\n"))
7805 (setq ins-end (point))
7806 (goto-char ins-point)
7807 (org-skip-whitespace)
7808 (when (and (< arg 0)
7809 (org-first-sibling-p)
7810 (> ne-ins ne-beg))
7811 ;; Move whitespace back to beginning
7812 (save-excursion
7813 (goto-char ins-end)
7814 (let ((kill-whole-line t))
7815 (kill-line (- ne-ins ne-beg)) (point)))
7816 (insert (make-string (- ne-ins ne-beg) ?\n)))
7817 (move-marker ins-point nil)
7818 (if folded
7819 (hide-subtree)
7820 (org-show-entry)
7821 (show-children)
7822 (org-cycle-hide-drawers 'children))
7823 (org-clean-visibility-after-subtree-move)
7824 ;; move back to the initial column we were at
7825 (move-to-column col)))
7827 (defvar org-subtree-clip ""
7828 "Clipboard for cut and paste of subtrees.
7829 This is actually only a copy of the kill, because we use the normal kill
7830 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7832 (defvar org-subtree-clip-folded nil
7833 "Was the last copied subtree folded?
7834 This is used to fold the tree back after pasting.")
7836 (defun org-cut-subtree (&optional n)
7837 "Cut the current subtree into the clipboard.
7838 With prefix arg N, cut this many sequential subtrees.
7839 This is a short-hand for marking the subtree and then cutting it."
7840 (interactive "p")
7841 (org-copy-subtree n 'cut))
7843 (defun org-copy-subtree (&optional n cut force-store-markers)
7844 "Cut the current subtree into the clipboard.
7845 With prefix arg N, cut this many sequential subtrees.
7846 This is a short-hand for marking the subtree and then copying it.
7847 If CUT is non-nil, actually cut the subtree.
7848 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7849 of some markers in the region, even if CUT is non-nil. This is
7850 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7851 (interactive "p")
7852 (let (beg end folded (beg0 (point)))
7853 (if (org-called-interactively-p 'any)
7854 (org-back-to-heading nil) ; take what looks like a subtree
7855 (org-back-to-heading t)) ; take what is really there
7856 (org-back-over-empty-lines)
7857 (setq beg (point))
7858 (skip-chars-forward " \t\r\n")
7859 (save-match-data
7860 (save-excursion (outline-end-of-heading)
7861 (setq folded (outline-invisible-p)))
7862 (condition-case nil
7863 (org-forward-heading-same-level (1- n) t)
7864 (error nil))
7865 (org-end-of-subtree t t))
7866 (org-back-over-empty-lines)
7867 (setq end (point))
7868 (goto-char beg0)
7869 (when (> end beg)
7870 (setq org-subtree-clip-folded folded)
7871 (when (or cut force-store-markers)
7872 (org-save-markers-in-region beg end))
7873 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7874 (setq org-subtree-clip (current-kill 0))
7875 (message "%s: Subtree(s) with %d characters"
7876 (if cut "Cut" "Copied")
7877 (length org-subtree-clip)))))
7879 (defun org-paste-subtree (&optional level tree for-yank)
7880 "Paste the clipboard as a subtree, with modification of headline level.
7881 The entire subtree is promoted or demoted in order to match a new headline
7882 level.
7884 If the cursor is at the beginning of a headline, the same level as
7885 that headline is used to paste the tree
7887 If not, the new level is derived from the *visible* headings
7888 before and after the insertion point, and taken to be the inferior headline
7889 level of the two. So if the previous visible heading is level 3 and the
7890 next is level 4 (or vice versa), level 4 will be used for insertion.
7891 This makes sure that the subtree remains an independent subtree and does
7892 not swallow low level entries.
7894 You can also force a different level, either by using a numeric prefix
7895 argument, or by inserting the heading marker by hand. For example, if the
7896 cursor is after \"*****\", then the tree will be shifted to level 5.
7898 If optional TREE is given, use this text instead of the kill ring.
7900 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7901 move back over whitespace before inserting, and move point to the end of
7902 the inserted text when done."
7903 (interactive "P")
7904 (setq tree (or tree (and kill-ring (current-kill 0))))
7905 (unless (org-kill-is-subtree-p tree)
7906 (error "%s"
7907 (substitute-command-keys
7908 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7909 (org-with-limited-levels
7910 (let* ((visp (not (outline-invisible-p)))
7911 (txt tree)
7912 (^re_ "\\(\\*+\\)[ \t]*")
7913 (old-level (if (string-match org-outline-regexp-bol txt)
7914 (- (match-end 0) (match-beginning 0) 1)
7915 -1))
7916 (force-level (cond (level (prefix-numeric-value level))
7917 ((and (looking-at "[ \t]*$")
7918 (string-match
7919 "^\\*+$" (buffer-substring
7920 (point-at-bol) (point))))
7921 (- (match-end 1) (match-beginning 1)))
7922 ((and (bolp)
7923 (looking-at org-outline-regexp))
7924 (- (match-end 0) (point) 1))
7925 (t nil)))
7926 (previous-level (save-excursion
7927 (condition-case nil
7928 (progn
7929 (outline-previous-visible-heading 1)
7930 (if (looking-at ^re_)
7931 (- (match-end 0) (match-beginning 0) 1)
7933 (error 1))))
7934 (next-level (save-excursion
7935 (condition-case nil
7936 (progn
7937 (or (looking-at org-outline-regexp)
7938 (outline-next-visible-heading 1))
7939 (if (looking-at ^re_)
7940 (- (match-end 0) (match-beginning 0) 1)
7942 (error 1))))
7943 (new-level (or force-level (max previous-level next-level)))
7944 (shift (if (or (= old-level -1)
7945 (= new-level -1)
7946 (= old-level new-level))
7948 (- new-level old-level)))
7949 (delta (if (> shift 0) -1 1))
7950 (func (if (> shift 0) 'org-demote 'org-promote))
7951 (org-odd-levels-only nil)
7952 beg end newend)
7953 ;; Remove the forced level indicator
7954 (if force-level
7955 (delete-region (point-at-bol) (point)))
7956 ;; Paste
7957 (beginning-of-line (if (bolp) 1 2))
7958 (unless for-yank (org-back-over-empty-lines))
7959 (setq beg (point))
7960 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7961 (insert-before-markers txt)
7962 (unless (string-match "\n\\'" txt) (insert "\n"))
7963 (setq newend (point))
7964 (org-reinstall-markers-in-region beg)
7965 (setq end (point))
7966 (goto-char beg)
7967 (skip-chars-forward " \t\n\r")
7968 (setq beg (point))
7969 (if (and (outline-invisible-p) visp)
7970 (save-excursion (outline-show-heading)))
7971 ;; Shift if necessary
7972 (unless (= shift 0)
7973 (save-restriction
7974 (narrow-to-region beg end)
7975 (while (not (= shift 0))
7976 (org-map-region func (point-min) (point-max))
7977 (setq shift (+ delta shift)))
7978 (goto-char (point-min))
7979 (setq newend (point-max))))
7980 (when (or (org-called-interactively-p 'interactive) for-yank)
7981 (message "Clipboard pasted as level %d subtree" new-level))
7982 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7983 kill-ring
7984 (eq org-subtree-clip (current-kill 0))
7985 org-subtree-clip-folded)
7986 ;; The tree was folded before it was killed/copied
7987 (hide-subtree))
7988 (and for-yank (goto-char newend)))))
7990 (defun org-kill-is-subtree-p (&optional txt)
7991 "Check if the current kill is an outline subtree, or a set of trees.
7992 Returns nil if kill does not start with a headline, or if the first
7993 headline level is not the largest headline level in the tree.
7994 So this will actually accept several entries of equal levels as well,
7995 which is OK for `org-paste-subtree'.
7996 If optional TXT is given, check this string instead of the current kill."
7997 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7998 (re (org-get-limited-outline-regexp))
7999 (^re (concat "^" re))
8000 (start-level (and kill
8001 (string-match
8002 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8003 kill)
8004 (- (match-end 2) (match-beginning 2) 1)))
8005 (start (1+ (or (match-beginning 2) -1))))
8006 (if (not start-level)
8007 (progn
8008 nil) ;; does not even start with a heading
8009 (catch 'exit
8010 (while (setq start (string-match ^re kill (1+ start)))
8011 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8012 (throw 'exit nil)))
8013 t))))
8015 (defvar org-markers-to-move nil
8016 "Markers that should be moved with a cut-and-paste operation.
8017 Those markers are stored together with their positions relative to
8018 the start of the region.")
8020 (defun org-save-markers-in-region (beg end)
8021 "Check markers in region.
8022 If these markers are between BEG and END, record their position relative
8023 to BEG, so that after moving the block of text, we can put the markers back
8024 into place.
8025 This function gets called just before an entry or tree gets cut from the
8026 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8027 called immediately, to move the markers with the entries."
8028 (setq org-markers-to-move nil)
8029 (when (featurep 'org-clock)
8030 (org-clock-save-markers-for-cut-and-paste beg end))
8031 (when (featurep 'org-agenda)
8032 (org-agenda-save-markers-for-cut-and-paste beg end)))
8034 (defun org-check-and-save-marker (marker beg end)
8035 "Check if MARKER is between BEG and END.
8036 If yes, remember the marker and the distance to BEG."
8037 (when (and (marker-buffer marker)
8038 (equal (marker-buffer marker) (current-buffer)))
8039 (if (and (>= marker beg) (< marker end))
8040 (push (cons marker (- marker beg)) org-markers-to-move))))
8042 (defun org-reinstall-markers-in-region (beg)
8043 "Move all remembered markers to their position relative to BEG."
8044 (mapc (lambda (x)
8045 (move-marker (car x) (+ beg (cdr x))))
8046 org-markers-to-move)
8047 (setq org-markers-to-move nil))
8049 (defun org-narrow-to-subtree ()
8050 "Narrow buffer to the current subtree."
8051 (interactive)
8052 (save-excursion
8053 (save-match-data
8054 (org-with-limited-levels
8055 (narrow-to-region
8056 (progn (org-back-to-heading t) (point))
8057 (progn (org-end-of-subtree t t)
8058 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8059 (point)))))))
8061 (defun org-narrow-to-block ()
8062 "Narrow buffer to the current block."
8063 (interactive)
8064 (let* ((case-fold-search t)
8065 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8066 "^[ \t]*#\\+end_.*")))
8067 (if blockp
8068 (narrow-to-region (car blockp) (cdr blockp))
8069 (error "Not in a block"))))
8071 (eval-when-compile
8072 (defvar org-property-drawer-re))
8074 (defvar org-property-start-re) ;; defined below
8075 (defun org-clone-subtree-with-time-shift (n &optional shift)
8076 "Clone the task (subtree) at point N times.
8077 The clones will be inserted as siblings.
8079 In interactive use, the user will be prompted for the number of
8080 clones to be produced, and for a time SHIFT, which may be a
8081 repeater as used in time stamps, for example `+3d'.
8083 When a valid repeater is given and the entry contains any time
8084 stamps, the clones will become a sequence in time, with time
8085 stamps in the subtree shifted for each clone produced. If SHIFT
8086 is nil or the empty string, time stamps will be left alone. The
8087 ID property of the original subtree is removed.
8089 If the original subtree did contain time stamps with a repeater,
8090 the following will happen:
8091 - the repeater will be removed in each clone
8092 - an additional clone will be produced, with the current, unshifted
8093 date(s) in the entry.
8094 - the original entry will be placed *after* all the clones, with
8095 repeater intact.
8096 - the start days in the repeater in the original entry will be shifted
8097 to past the last clone.
8098 In this way you can spell out a number of instances of a repeating task,
8099 and still retain the repeater to cover future instances of the task."
8100 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8101 (let (beg end template task idprop
8102 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8103 (drawer-re org-drawer-regexp))
8104 (if (not (and (integerp n) (> n 0)))
8105 (error "Invalid number of replications %s" n))
8106 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8107 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8108 shift)))
8109 (error "Invalid shift specification %s" shift))
8110 (when doshift
8111 (setq shift-n (string-to-number (match-string 1 shift))
8112 shift-what (cdr (assoc (match-string 2 shift)
8113 '(("d" . day) ("w" . week)
8114 ("m" . month) ("y" . year))))))
8115 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8116 (setq nmin 1 nmax n)
8117 (org-back-to-heading t)
8118 (setq beg (point))
8119 (setq idprop (org-entry-get nil "ID"))
8120 (org-end-of-subtree t t)
8121 (or (bolp) (insert "\n"))
8122 (setq end (point))
8123 (setq template (buffer-substring beg end))
8124 (when (and doshift
8125 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8126 (delete-region beg end)
8127 (setq end beg)
8128 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8129 (goto-char end)
8130 (loop for n from nmin to nmax do
8131 ;; prepare clone
8132 (with-temp-buffer
8133 (insert template)
8134 (org-mode)
8135 (goto-char (point-min))
8136 (org-show-subtree)
8137 (and idprop (if org-clone-delete-id
8138 (org-entry-delete nil "ID")
8139 (org-id-get-create t)))
8140 (unless (= n 0)
8141 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8142 (kill-whole-line))
8143 (goto-char (point-min))
8144 (while (re-search-forward drawer-re nil t)
8145 (mapc (lambda (d)
8146 (org-remove-empty-drawer-at d (point))) org-drawers)))
8147 (goto-char (point-min))
8148 (when doshift
8149 (while (re-search-forward org-ts-regexp-both nil t)
8150 (org-timestamp-change (* n shift-n) shift-what))
8151 (unless (= n n-no-remove)
8152 (goto-char (point-min))
8153 (while (re-search-forward org-ts-regexp nil t)
8154 (save-excursion
8155 (goto-char (match-beginning 0))
8156 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8157 (delete-region (match-beginning 1) (match-end 1)))))))
8158 (setq task (buffer-string)))
8159 (insert task))
8160 (goto-char beg)))
8162 ;;; Outline Sorting
8164 (defun org-sort (with-case)
8165 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8166 Optional argument WITH-CASE means sort case-sensitively."
8167 (interactive "P")
8168 (cond
8169 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8170 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8172 (org-call-with-arg 'org-sort-entries with-case))))
8174 (defun org-sort-remove-invisible (s)
8175 (remove-text-properties 0 (length s) org-rm-props s)
8176 (while (string-match org-bracket-link-regexp s)
8177 (setq s (replace-match (if (match-end 2)
8178 (match-string 3 s)
8179 (match-string 1 s)) t t s)))
8182 (defvar org-priority-regexp) ; defined later in the file
8184 (defvar org-after-sorting-entries-or-items-hook nil
8185 "Hook that is run after a bunch of entries or items have been sorted.
8186 When children are sorted, the cursor is in the parent line when this
8187 hook gets called. When a region or a plain list is sorted, the cursor
8188 will be in the first entry of the sorted region/list.")
8190 (defun org-sort-entries
8191 (&optional with-case sorting-type getkey-func compare-func property)
8192 "Sort entries on a certain level of an outline tree.
8193 If there is an active region, the entries in the region are sorted.
8194 Else, if the cursor is before the first entry, sort the top-level items.
8195 Else, the children of the entry at point are sorted.
8197 Sorting can be alphabetically, numerically, by date/time as given by
8198 a time stamp, by a property or by priority.
8200 The command prompts for the sorting type unless it has been given to the
8201 function through the SORTING-TYPE argument, which needs to be a character,
8202 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8203 precise meaning of each character:
8205 n Numerically, by converting the beginning of the entry/item to a number.
8206 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8207 t By date/time, either the first active time stamp in the entry, or, if
8208 none exist, by the first inactive one.
8209 s By the scheduled date/time.
8210 d By deadline date/time.
8211 c By creation time, which is assumed to be the first inactive time stamp
8212 at the beginning of a line.
8213 p By priority according to the cookie.
8214 r By the value of a property.
8216 Capital letters will reverse the sort order.
8218 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8219 called with point at the beginning of the record. It must return either
8220 a string or a number that should serve as the sorting key for that record.
8222 Comparing entries ignores case by default. However, with an optional argument
8223 WITH-CASE, the sorting considers case as well."
8224 (interactive "P")
8225 (let ((case-func (if with-case 'identity 'downcase))
8226 start beg end stars re re2
8227 txt what tmp)
8228 ;; Find beginning and end of region to sort
8229 (cond
8230 ((org-region-active-p)
8231 ;; we will sort the region
8232 (setq end (region-end)
8233 what "region")
8234 (goto-char (region-beginning))
8235 (if (not (org-at-heading-p)) (outline-next-heading))
8236 (setq start (point)))
8237 ((or (org-at-heading-p)
8238 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8239 ;; we will sort the children of the current headline
8240 (org-back-to-heading)
8241 (setq start (point)
8242 end (progn (org-end-of-subtree t t)
8243 (or (bolp) (insert "\n"))
8244 (org-back-over-empty-lines)
8245 (point))
8246 what "children")
8247 (goto-char start)
8248 (show-subtree)
8249 (outline-next-heading))
8251 ;; we will sort the top-level entries in this file
8252 (goto-char (point-min))
8253 (or (org-at-heading-p) (outline-next-heading))
8254 (setq start (point))
8255 (goto-char (point-max))
8256 (beginning-of-line 1)
8257 (when (looking-at ".*?\\S-")
8258 ;; File ends in a non-white line
8259 (end-of-line 1)
8260 (insert "\n"))
8261 (setq end (point-max))
8262 (setq what "top-level")
8263 (goto-char start)
8264 (show-all)))
8266 (setq beg (point))
8267 (if (>= beg end) (error "Nothing to sort"))
8269 (looking-at "\\(\\*+\\)")
8270 (setq stars (match-string 1)
8271 re (concat "^" (regexp-quote stars) " +")
8272 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8273 txt (buffer-substring beg end))
8274 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8275 (if (and (not (equal stars "*")) (string-match re2 txt))
8276 (error "Region to sort contains a level above the first entry"))
8278 (unless sorting-type
8279 (message
8280 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8281 [t]ime [s]cheduled [d]eadline [c]reated
8282 A/N/T/S/D/C/P/O/F means reversed:"
8283 what)
8284 (setq sorting-type (read-char-exclusive))
8286 (and (= (downcase sorting-type) ?f)
8287 (setq getkey-func
8288 (org-icompleting-read "Sort using function: "
8289 obarray 'fboundp t nil nil))
8290 (setq getkey-func (intern getkey-func)))
8292 (and (= (downcase sorting-type) ?r)
8293 (setq property
8294 (org-icompleting-read "Property: "
8295 (mapcar 'list (org-buffer-property-keys t))
8296 nil t))))
8298 (message "Sorting entries...")
8300 (save-restriction
8301 (narrow-to-region start end)
8302 (let ((dcst (downcase sorting-type))
8303 (case-fold-search nil)
8304 (now (current-time)))
8305 (sort-subr
8306 (/= dcst sorting-type)
8307 ;; This function moves to the beginning character of the "record" to
8308 ;; be sorted.
8309 (lambda nil
8310 (if (re-search-forward re nil t)
8311 (goto-char (match-beginning 0))
8312 (goto-char (point-max))))
8313 ;; This function moves to the last character of the "record" being
8314 ;; sorted.
8315 (lambda nil
8316 (save-match-data
8317 (condition-case nil
8318 (outline-forward-same-level 1)
8319 (error
8320 (goto-char (point-max))))))
8321 ;; This function returns the value that gets sorted against.
8322 (lambda nil
8323 (cond
8324 ((= dcst ?n)
8325 (if (looking-at org-complex-heading-regexp)
8326 (string-to-number (match-string 4))
8327 nil))
8328 ((= dcst ?a)
8329 (if (looking-at org-complex-heading-regexp)
8330 (funcall case-func (match-string 4))
8331 nil))
8332 ((= dcst ?t)
8333 (let ((end (save-excursion (outline-next-heading) (point))))
8334 (if (or (re-search-forward org-ts-regexp end t)
8335 (re-search-forward org-ts-regexp-both end t))
8336 (org-time-string-to-seconds (match-string 0))
8337 (org-float-time now))))
8338 ((= dcst ?c)
8339 (let ((end (save-excursion (outline-next-heading) (point))))
8340 (if (re-search-forward
8341 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8342 end t)
8343 (org-time-string-to-seconds (match-string 0))
8344 (org-float-time now))))
8345 ((= dcst ?s)
8346 (let ((end (save-excursion (outline-next-heading) (point))))
8347 (if (re-search-forward org-scheduled-time-regexp end t)
8348 (org-time-string-to-seconds (match-string 1))
8349 (org-float-time now))))
8350 ((= dcst ?d)
8351 (let ((end (save-excursion (outline-next-heading) (point))))
8352 (if (re-search-forward org-deadline-time-regexp end t)
8353 (org-time-string-to-seconds (match-string 1))
8354 (org-float-time now))))
8355 ((= dcst ?p)
8356 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8357 (string-to-char (match-string 2))
8358 org-default-priority))
8359 ((= dcst ?r)
8360 (or (org-entry-get nil property) ""))
8361 ((= dcst ?o)
8362 (if (looking-at org-complex-heading-regexp)
8363 (- 9999 (length (member (match-string 2)
8364 org-todo-keywords-1)))))
8365 ((= dcst ?f)
8366 (if getkey-func
8367 (progn
8368 (setq tmp (funcall getkey-func))
8369 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8370 tmp)
8371 (error "Invalid key function `%s'" getkey-func)))
8372 (t (error "Invalid sorting type `%c'" sorting-type))))
8374 (cond
8375 ((= dcst ?a) 'string<)
8376 ((= dcst ?f) compare-func)
8377 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8378 (t nil)))))
8379 (run-hooks 'org-after-sorting-entries-or-items-hook)
8380 (message "Sorting entries...done")))
8382 (defun org-do-sort (table what &optional with-case sorting-type)
8383 "Sort TABLE of WHAT according to SORTING-TYPE.
8384 The user will be prompted for the SORTING-TYPE if the call to this
8385 function does not specify it. WHAT is only for the prompt, to indicate
8386 what is being sorted. The sorting key will be extracted from
8387 the car of the elements of the table.
8388 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8389 (unless sorting-type
8390 (message
8391 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8392 what)
8393 (setq sorting-type (read-char-exclusive)))
8394 (let ((dcst (downcase sorting-type))
8395 extractfun comparefun)
8396 ;; Define the appropriate functions
8397 (cond
8398 ((= dcst ?n)
8399 (setq extractfun 'string-to-number
8400 comparefun (if (= dcst sorting-type) '< '>)))
8401 ((= dcst ?a)
8402 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8403 (lambda(x) (downcase (org-sort-remove-invisible x))))
8404 comparefun (if (= dcst sorting-type)
8405 'string<
8406 (lambda (a b) (and (not (string< a b))
8407 (not (string= a b)))))))
8408 ((= dcst ?t)
8409 (setq extractfun
8410 (lambda (x)
8411 (if (or (string-match org-ts-regexp x)
8412 (string-match org-ts-regexp-both x))
8413 (org-float-time
8414 (org-time-string-to-time (match-string 0 x)))
8416 comparefun (if (= dcst sorting-type) '< '>)))
8417 (t (error "Invalid sorting type `%c'" sorting-type)))
8419 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8420 table)
8421 (lambda (a b) (funcall comparefun (car a) (car b))))))
8424 ;;; The orgstruct minor mode
8426 ;; Define a minor mode which can be used in other modes in order to
8427 ;; integrate the org-mode structure editing commands.
8429 ;; This is really a hack, because the org-mode structure commands use
8430 ;; keys which normally belong to the major mode. Here is how it
8431 ;; works: The minor mode defines all the keys necessary to operate the
8432 ;; structure commands, but wraps the commands into a function which
8433 ;; tests if the cursor is currently at a headline or a plain list
8434 ;; item. If that is the case, the structure command is used,
8435 ;; temporarily setting many Org-mode variables like regular
8436 ;; expressions for filling etc. However, when any of those keys is
8437 ;; used at a different location, function uses `key-binding' to look
8438 ;; up if the key has an associated command in another currently active
8439 ;; keymap (minor modes, major mode, global), and executes that
8440 ;; command. There might be problems if any of the keys is otherwise
8441 ;; used as a prefix key.
8443 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8444 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8445 ;; addresses this by checking explicitly for both bindings.
8447 (defvar orgstruct-mode-map (make-sparse-keymap)
8448 "Keymap for the minor `orgstruct-mode'.")
8450 (defvar org-local-vars nil
8451 "List of local variables, for use by `orgstruct-mode'.")
8453 ;;;###autoload
8454 (define-minor-mode orgstruct-mode
8455 "Toggle the minor mode `orgstruct-mode'.
8456 This mode is for using Org-mode structure commands in other
8457 modes. The following keys behave as if Org-mode were active, if
8458 the cursor is on a headline, or on a plain list item (both as
8459 defined by Org-mode).
8461 M-up Move entry/item up
8462 M-down Move entry/item down
8463 M-left Promote
8464 M-right Demote
8465 M-S-up Move entry/item up
8466 M-S-down Move entry/item down
8467 M-S-left Promote subtree
8468 M-S-right Demote subtree
8469 M-q Fill paragraph and items like in Org-mode
8470 C-c ^ Sort entries
8471 C-c - Cycle list bullet
8472 TAB Cycle item visibility
8473 M-RET Insert new heading/item
8474 S-M-RET Insert new TODO heading / Checkbox item
8475 C-c C-c Set tags / toggle checkbox"
8476 nil " OrgStruct" nil
8477 (org-load-modules-maybe)
8478 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8480 ;;;###autoload
8481 (defun turn-on-orgstruct ()
8482 "Unconditionally turn on `orgstruct-mode'."
8483 (orgstruct-mode 1))
8485 (defvar org-fb-vars nil)
8486 (make-variable-buffer-local 'org-fb-vars)
8487 (defun orgstruct++-mode (&optional arg)
8488 "Toggle `orgstruct-mode', the enhanced version of it.
8489 In addition to setting orgstruct-mode, this also exports all
8490 indentation and autofilling variables from org-mode into the
8491 buffer. It will also recognize item context in multiline items."
8492 (interactive "P")
8493 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8494 (if (< arg 1)
8495 (progn (orgstruct-mode -1)
8496 (mapc (lambda(v)
8497 (org-set-local (car v)
8498 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8499 org-fb-vars))
8500 (orgstruct-mode 1)
8501 (setq org-fb-vars nil)
8502 (let (var val)
8503 (mapc
8504 (lambda (x)
8505 (when (string-match
8506 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8507 (symbol-name (car x)))
8508 (setq var (car x) val (nth 1 x))
8509 (push (list var `(quote ,(eval var))) org-fb-vars)
8510 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8511 org-local-vars)
8512 (org-set-local 'orgstruct-is-++ t))))
8514 (defvar orgstruct-is-++ nil
8515 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8516 (make-variable-buffer-local 'orgstruct-is-++)
8518 ;;;###autoload
8519 (defun turn-on-orgstruct++ ()
8520 "Unconditionally turn on `orgstruct++-mode'."
8521 (orgstruct++-mode 1))
8523 (defun orgstruct-error ()
8524 "Error when there is no default binding for a structure key."
8525 (interactive)
8526 (error "This key has no function outside structure elements"))
8528 (defun orgstruct-setup ()
8529 "Setup orgstruct keymaps."
8530 (let ((nfunc 0)
8531 (bindings
8532 (list
8533 '([(meta up)] org-metaup)
8534 '([(meta down)] org-metadown)
8535 '([(meta left)] org-metaleft)
8536 '([(meta right)] org-metaright)
8537 '([(meta shift up)] org-shiftmetaup)
8538 '([(meta shift down)] org-shiftmetadown)
8539 '([(meta shift left)] org-shiftmetaleft)
8540 '([(meta shift right)] org-shiftmetaright)
8541 '([?\e (up)] org-metaup)
8542 '([?\e (down)] org-metadown)
8543 '([?\e (left)] org-metaleft)
8544 '([?\e (right)] org-metaright)
8545 '([?\e (shift up)] org-shiftmetaup)
8546 '([?\e (shift down)] org-shiftmetadown)
8547 '([?\e (shift left)] org-shiftmetaleft)
8548 '([?\e (shift right)] org-shiftmetaright)
8549 '([(shift up)] org-shiftup)
8550 '([(shift down)] org-shiftdown)
8551 '([(shift left)] org-shiftleft)
8552 '([(shift right)] org-shiftright)
8553 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8554 '("\M-q" fill-paragraph)
8555 '("\C-c^" org-sort)
8556 '("\C-c-" org-cycle-list-bullet)))
8557 elt key fun cmd)
8558 (while (setq elt (pop bindings))
8559 (setq nfunc (1+ nfunc))
8560 (setq key (org-key (car elt))
8561 fun (nth 1 elt)
8562 cmd (orgstruct-make-binding fun nfunc key))
8563 (org-defkey orgstruct-mode-map key cmd))
8565 ;; Prevent an error for users who forgot to make autoloads
8566 (require 'org-element)
8568 ;; Special treatment needed for TAB and RET
8569 (org-defkey orgstruct-mode-map [(tab)]
8570 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8571 (org-defkey orgstruct-mode-map "\C-i"
8572 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8574 (org-defkey orgstruct-mode-map "\M-\C-m"
8575 (orgstruct-make-binding 'org-insert-heading 105
8576 "\M-\C-m" [(meta return)]))
8577 (org-defkey orgstruct-mode-map [(meta return)]
8578 (orgstruct-make-binding 'org-insert-heading 106
8579 [(meta return)] "\M-\C-m"))
8581 (org-defkey orgstruct-mode-map [(shift meta return)]
8582 (orgstruct-make-binding 'org-insert-todo-heading 107
8583 [(meta return)] "\M-\C-m"))
8585 (org-defkey orgstruct-mode-map "\e\C-m"
8586 (orgstruct-make-binding 'org-insert-heading 108
8587 "\e\C-m" [?\e (return)]))
8588 (org-defkey orgstruct-mode-map [?\e (return)]
8589 (orgstruct-make-binding 'org-insert-heading 109
8590 [?\e (return)] "\e\C-m"))
8591 (org-defkey orgstruct-mode-map [?\e (shift return)]
8592 (orgstruct-make-binding 'org-insert-todo-heading 110
8593 [?\e (return)] "\e\C-m"))
8595 (unless org-local-vars
8596 (setq org-local-vars (org-get-local-variables)))
8600 (defun orgstruct-make-binding (fun n &rest keys)
8601 "Create a function for binding in the structure minor mode.
8602 FUN is the command to call inside a table. N is used to create a unique
8603 command name. KEYS are keys that should be checked in for a command
8604 to execute outside of tables."
8605 (eval
8606 (list 'defun
8607 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8608 '(arg)
8609 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8610 "Outside of structure, run the binding of `"
8611 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8612 "'.")
8613 '(interactive "p")
8614 (list 'if
8615 `(org-context-p 'headline 'item
8616 (and orgstruct-is-++
8617 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8618 'item-body))
8619 (list 'org-run-like-in-org-mode (list 'quote fun))
8620 (list 'let '(orgstruct-mode)
8621 (list 'call-interactively
8622 (append '(or)
8623 (mapcar (lambda (k)
8624 (list 'key-binding k))
8625 keys)
8626 '('orgstruct-error))))))))
8628 (defun org-context-p (&rest contexts)
8629 "Check if local context is any of CONTEXTS.
8630 Possible values in the list of contexts are `table', `headline', and `item'."
8631 (let ((pos (point)))
8632 (goto-char (point-at-bol))
8633 (prog1 (or (and (memq 'table contexts)
8634 (looking-at "[ \t]*|"))
8635 (and (memq 'headline contexts)
8636 (looking-at org-outline-regexp))
8637 (and (memq 'item contexts)
8638 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8639 (and (memq 'item-body contexts)
8640 (org-in-item-p)))
8641 (goto-char pos))))
8643 (defun org-get-local-variables ()
8644 "Return a list of all local variables in an Org mode buffer."
8645 (let (varlist)
8646 (with-current-buffer (get-buffer-create "*Org tmp*")
8647 (erase-buffer)
8648 (org-mode)
8649 (setq varlist (buffer-local-variables)))
8650 (kill-buffer "*Org tmp*")
8651 (delq nil
8652 (mapcar
8653 (lambda (x)
8654 (setq x
8655 (if (symbolp x)
8656 (list x)
8657 (list (car x) (list 'quote (cdr x)))))
8658 (if (string-match
8659 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8660 (symbol-name (car x)))
8661 x nil))
8662 varlist))))
8664 (defun org-clone-local-variables (from-buffer &optional regexp)
8665 "Clone local variables from FROM-BUFFER.
8666 Optional argument REGEXP selects variables to clone."
8667 (mapc
8668 (lambda (pair)
8669 (and (symbolp (car pair))
8670 (or (null regexp)
8671 (string-match regexp (symbol-name (car pair))))
8672 (set (make-local-variable (car pair))
8673 (cdr pair))))
8674 (buffer-local-variables from-buffer)))
8676 ;;;###autoload
8677 (defun org-run-like-in-org-mode (cmd)
8678 "Run a command, pretending that the current buffer is in Org-mode.
8679 This will temporarily bind local variables that are typically bound in
8680 Org-mode to the values they have in Org-mode, and then interactively
8681 call CMD."
8682 (org-load-modules-maybe)
8683 (unless org-local-vars
8684 (setq org-local-vars (org-get-local-variables)))
8685 (eval (list 'let org-local-vars
8686 (list 'call-interactively (list 'quote cmd)))))
8688 ;;;; Archiving
8690 (defun org-get-category (&optional pos force-refresh)
8691 "Get the category applying to position POS."
8692 (save-match-data
8693 (if force-refresh (org-refresh-category-properties))
8694 (let ((pos (or pos (point))))
8695 (or (get-text-property pos 'org-category)
8696 (progn (org-refresh-category-properties)
8697 (get-text-property pos 'org-category))))))
8699 (defun org-refresh-category-properties ()
8700 "Refresh category text properties in the buffer."
8701 (let ((inhibit-read-only t)
8702 (def-cat (cond
8703 ((null org-category)
8704 (if buffer-file-name
8705 (file-name-sans-extension
8706 (file-name-nondirectory buffer-file-name))
8707 "???"))
8708 ((symbolp org-category) (symbol-name org-category))
8709 (t org-category)))
8710 beg end cat pos optionp)
8711 (org-unmodified
8712 (save-excursion
8713 (save-restriction
8714 (widen)
8715 (goto-char (point-min))
8716 (put-text-property (point) (point-max) 'org-category def-cat)
8717 (while (re-search-forward
8718 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8719 (setq pos (match-end 0)
8720 optionp (equal (char-after (match-beginning 0)) ?#)
8721 cat (org-trim (match-string 2)))
8722 (if optionp
8723 (setq beg (point-at-bol) end (point-max))
8724 (org-back-to-heading t)
8725 (setq beg (point) end (org-end-of-subtree t t)))
8726 (put-text-property beg end 'org-category cat)
8727 (put-text-property beg end 'org-category-position beg)
8728 (goto-char pos)))))))
8731 ;;;; Link Stuff
8733 ;;; Link abbreviations
8735 (defun org-link-expand-abbrev (link)
8736 "Apply replacements as defined in `org-link-abbrev-alist'."
8737 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8738 (let* ((key (match-string 1 link))
8739 (as (or (assoc key org-link-abbrev-alist-local)
8740 (assoc key org-link-abbrev-alist)))
8741 (tag (and (match-end 2) (match-string 3 link)))
8742 rpl)
8743 (if (not as)
8744 link
8745 (setq rpl (cdr as))
8746 (cond
8747 ((symbolp rpl) (funcall rpl tag))
8748 ((string-match "%(\\([^)]+\\))" rpl)
8749 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8750 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8751 ((string-match "%h" rpl)
8752 (replace-match (url-hexify-string (or tag "")) t t rpl))
8753 (t (concat rpl tag)))))
8754 link))
8756 ;;; Storing and inserting links
8758 (defvar org-insert-link-history nil
8759 "Minibuffer history for links inserted with `org-insert-link'.")
8761 (defvar org-stored-links nil
8762 "Contains the links stored with `org-store-link'.")
8764 (defvar org-store-link-plist nil
8765 "Plist with info about the most recently link created with `org-store-link'.")
8767 (defvar org-link-protocols nil
8768 "Link protocols added to Org-mode using `org-add-link-type'.")
8770 (defvar org-store-link-functions nil
8771 "List of functions that are called to create and store a link.
8772 Each function will be called in turn until one returns a non-nil
8773 value. Each function should check if it is responsible for creating
8774 this link (for example by looking at the major mode).
8775 If not, it must exit and return nil.
8776 If yes, it should return a non-nil value after a calling
8777 `org-store-link-props' with a list of properties and values.
8778 Special properties are:
8780 :type The link prefix, like \"http\". This must be given.
8781 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8782 This is obligatory as well.
8783 :description Optional default description for the second pair
8784 of brackets in an Org-mode link. The user can still change
8785 this when inserting this link into an Org-mode buffer.
8787 In addition to these, any additional properties can be specified
8788 and then used in remember templates.")
8790 (defun org-add-link-type (type &optional follow export)
8791 "Add TYPE to the list of `org-link-types'.
8792 Re-compute all regular expressions depending on `org-link-types'
8794 FOLLOW and EXPORT are two functions.
8796 FOLLOW should take the link path as the single argument and do whatever
8797 is necessary to follow the link, for example find a file or display
8798 a mail message.
8800 EXPORT should format the link path for export to one of the export formats.
8801 It should be a function accepting three arguments:
8803 path the path of the link, the text after the prefix (like \"http:\")
8804 desc the description of the link, if any, or a description added by
8805 org-export-normalize-links if there is none
8806 format the export format, a symbol like `html' or `latex' or `ascii'..
8808 The function may use the FORMAT information to return different values
8809 depending on the format. The return value will be put literally into
8810 the exported file. If the return value is nil, this means Org should
8811 do what it normally does with links which do not have EXPORT defined.
8813 Org-mode has a built-in default for exporting links. If you are happy with
8814 this default, there is no need to define an export function for the link
8815 type. For a simple example of an export function, see `org-bbdb.el'."
8816 (add-to-list 'org-link-types type t)
8817 (org-make-link-regexps)
8818 (if (assoc type org-link-protocols)
8819 (setcdr (assoc type org-link-protocols) (list follow export))
8820 (push (list type follow export) org-link-protocols)))
8822 (defvar org-agenda-buffer-name)
8824 ;;;###autoload
8825 (defun org-store-link (arg)
8826 "\\<org-mode-map>Store an org-link to the current location.
8827 This link is added to `org-stored-links' and can later be inserted
8828 into an org-buffer with \\[org-insert-link].
8830 For some link types, a prefix arg is interpreted:
8831 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8832 For file links, arg negates `org-context-in-file-links'."
8833 (interactive "P")
8834 (org-load-modules-maybe)
8835 (setq org-store-link-plist nil) ; reset
8836 (org-with-limited-levels
8837 (let (link cpltxt desc description search txt custom-id agenda-link)
8838 (cond
8840 ((run-hook-with-args-until-success 'org-store-link-functions)
8841 (setq link (plist-get org-store-link-plist :link)
8842 desc (or (plist-get org-store-link-plist :description) link)))
8844 ((org-src-edit-buffer-p)
8845 (let (label gc)
8846 (while (or (not label)
8847 (save-excursion
8848 (save-restriction
8849 (widen)
8850 (goto-char (point-min))
8851 (re-search-forward
8852 (regexp-quote (format org-coderef-label-format label))
8853 nil t))))
8854 (when label (message "Label exists already") (sit-for 2))
8855 (setq label (read-string "Code line label: " label)))
8856 (end-of-line 1)
8857 (setq link (format org-coderef-label-format label))
8858 (setq gc (- 79 (length link)))
8859 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8860 (insert link)
8861 (setq link (concat "(" label ")") desc nil)))
8863 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8864 ;; We are in the agenda, link to referenced location
8865 (let ((m (or (get-text-property (point) 'org-hd-marker)
8866 (get-text-property (point) 'org-marker))))
8867 (when m
8868 (org-with-point-at m
8869 (setq agenda-link
8870 (if (org-called-interactively-p 'any)
8871 (call-interactively 'org-store-link)
8872 (org-store-link nil)))))))
8874 ((eq major-mode 'calendar-mode)
8875 (let ((cd (calendar-cursor-to-date)))
8876 (setq link
8877 (format-time-string
8878 (car org-time-stamp-formats)
8879 (apply 'encode-time
8880 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8881 nil nil nil))))
8882 (org-store-link-props :type "calendar" :date cd)))
8884 ((eq major-mode 'help-mode)
8885 (setq link (concat "help:" (save-excursion
8886 (goto-char (point-min))
8887 (looking-at "^[^ ]+")
8888 (match-string 0))))
8889 (org-store-link-props :type "help"))
8891 ((eq major-mode 'w3-mode)
8892 (setq cpltxt (if (and (buffer-name)
8893 (not (string-match "Untitled" (buffer-name))))
8894 (buffer-name)
8895 (url-view-url t))
8896 link (url-view-url t))
8897 (org-store-link-props :type "w3" :url (url-view-url t)))
8899 ((eq major-mode 'w3m-mode)
8900 (setq cpltxt (or w3m-current-title w3m-current-url)
8901 link w3m-current-url)
8902 (org-store-link-props :type "w3m" :url (url-view-url t)))
8904 ((setq search (run-hook-with-args-until-success
8905 'org-create-file-search-functions))
8906 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8907 "::" search))
8908 (setq cpltxt (or description link)))
8910 ((eq major-mode 'image-mode)
8911 (setq cpltxt (concat "file:"
8912 (abbreviate-file-name buffer-file-name))
8913 link cpltxt)
8914 (org-store-link-props :type "image" :file buffer-file-name))
8916 ((eq major-mode 'dired-mode)
8917 ;; link to the file in the current line
8918 (let ((file (dired-get-filename nil t)))
8919 (setq file (if file
8920 (abbreviate-file-name
8921 (expand-file-name (dired-get-filename nil t)))
8922 ;; otherwise, no file so use current directory.
8923 default-directory))
8924 (setq cpltxt (concat "file:" file)
8925 link cpltxt)))
8927 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8928 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8929 (cond
8930 ((org-in-regexp "<<\\(.*?\\)>>")
8931 (setq cpltxt
8932 (concat "file:"
8933 (abbreviate-file-name
8934 (buffer-file-name (buffer-base-buffer)))
8935 "::" (match-string 1))
8936 link cpltxt))
8937 ((and (featurep 'org-id)
8938 (or (eq org-link-to-org-use-id t)
8939 (and (org-called-interactively-p 'any)
8940 (or (eq org-link-to-org-use-id 'create-if-interactive)
8941 (and (eq org-link-to-org-use-id
8942 'create-if-interactive-and-no-custom-id)
8943 (not custom-id))))
8944 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8945 ;; We can make a link using the ID.
8946 (setq link (condition-case nil
8947 (prog1 (org-id-store-link)
8948 (setq desc (plist-get org-store-link-plist :description)))
8949 (error
8950 ;; probably before first headline, link to file only
8951 (concat "file:"
8952 (abbreviate-file-name
8953 (buffer-file-name (buffer-base-buffer))))))))
8955 ;; Just link to current headline
8956 (setq cpltxt (concat "file:"
8957 (abbreviate-file-name
8958 (buffer-file-name (buffer-base-buffer)))))
8959 ;; Add a context search string
8960 (when (org-xor org-context-in-file-links arg)
8961 (setq txt (cond
8962 ((org-at-heading-p) nil)
8963 ((org-region-active-p)
8964 (buffer-substring (region-beginning) (region-end)))
8965 (t nil)))
8966 (when (or (null txt) (string-match "\\S-" txt))
8967 (setq cpltxt
8968 (concat cpltxt "::"
8969 (condition-case nil
8970 (org-make-org-heading-search-string txt)
8971 (error "")))
8972 desc (or (nth 4 (ignore-errors
8973 (org-heading-components))) "NONE"))))
8974 (if (string-match "::\\'" cpltxt)
8975 (setq cpltxt (substring cpltxt 0 -2)))
8976 (setq link cpltxt))))
8978 ((buffer-file-name (buffer-base-buffer))
8979 ;; Just link to this file here.
8980 (setq cpltxt (concat "file:"
8981 (abbreviate-file-name
8982 (buffer-file-name (buffer-base-buffer)))))
8983 ;; Add a context string
8984 (when (org-xor org-context-in-file-links arg)
8985 (setq txt (if (org-region-active-p)
8986 (buffer-substring (region-beginning) (region-end))
8987 (buffer-substring (point-at-bol) (point-at-eol))))
8988 ;; Only use search option if there is some text.
8989 (when (string-match "\\S-" txt)
8990 (setq cpltxt
8991 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8992 desc "NONE")))
8993 (setq link cpltxt))
8995 ((org-called-interactively-p 'interactive)
8996 (error "Cannot link to a buffer which is not visiting a file"))
8998 (t (setq link nil)))
9000 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9001 (setq link (or link cpltxt)
9002 desc (or desc cpltxt))
9003 (if (equal desc "NONE") (setq desc nil))
9005 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9006 (progn
9007 (setq org-stored-links
9008 (cons (list link desc) org-stored-links))
9009 (message "Stored: %s" (or desc link))
9010 (when custom-id
9011 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9012 "::#" custom-id))
9013 (setq org-stored-links
9014 (cons (list link desc) org-stored-links))))
9015 (or agenda-link (and link (org-make-link-string link desc)))))))
9017 (defun org-store-link-props (&rest plist)
9018 "Store link properties, extract names and addresses."
9019 (let (x adr)
9020 (when (setq x (plist-get plist :from))
9021 (setq adr (mail-extract-address-components x))
9022 (setq plist (plist-put plist :fromname (car adr)))
9023 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9024 (when (setq x (plist-get plist :to))
9025 (setq adr (mail-extract-address-components x))
9026 (setq plist (plist-put plist :toname (car adr)))
9027 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9028 (let ((from (plist-get plist :from))
9029 (to (plist-get plist :to)))
9030 (when (and from to org-from-is-user-regexp)
9031 (setq plist
9032 (plist-put plist :fromto
9033 (if (string-match org-from-is-user-regexp from)
9034 (concat "to %t")
9035 (concat "from %f"))))))
9036 (setq org-store-link-plist plist))
9038 (defun org-add-link-props (&rest plist)
9039 "Add these properties to the link property list."
9040 (let (key value)
9041 (while plist
9042 (setq key (pop plist) value (pop plist))
9043 (setq org-store-link-plist
9044 (plist-put org-store-link-plist key value)))))
9046 (defun org-email-link-description (&optional fmt)
9047 "Return the description part of an email link.
9048 This takes information from `org-store-link-plist' and formats it
9049 according to FMT (default from `org-email-link-description-format')."
9050 (setq fmt (or fmt org-email-link-description-format))
9051 (let* ((p org-store-link-plist)
9052 (to (plist-get p :toaddress))
9053 (from (plist-get p :fromaddress))
9054 (table
9055 (list
9056 (cons "%c" (plist-get p :fromto))
9057 (cons "%F" (plist-get p :from))
9058 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9059 (cons "%T" (plist-get p :to))
9060 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9061 (cons "%s" (plist-get p :subject))
9062 (cons "%d" (plist-get p :date))
9063 (cons "%m" (plist-get p :message-id)))))
9064 (when (string-match "%c" fmt)
9065 ;; Check if the user wrote this message
9066 (if (and org-from-is-user-regexp from to
9067 (save-match-data (string-match org-from-is-user-regexp from)))
9068 (setq fmt (replace-match "to %t" t t fmt))
9069 (setq fmt (replace-match "from %f" t t fmt))))
9070 (org-replace-escapes fmt table)))
9072 (defun org-make-org-heading-search-string (&optional string heading)
9073 "Make search string for STRING or current headline."
9074 (interactive)
9075 (let ((s (or string (org-get-heading)))
9076 (lines org-context-in-file-links))
9077 (unless (and string (not heading))
9078 ;; We are using a headline, clean up garbage in there.
9079 (if (string-match org-todo-regexp s)
9080 (setq s (replace-match "" t t s)))
9081 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9082 (setq s (replace-match "" t t s)))
9083 (setq s (org-trim s))
9084 (if (string-match (concat "^\\(" org-quote-string "\\|"
9085 org-comment-string "\\)") s)
9086 (setq s (replace-match "" t t s)))
9087 (while (string-match org-ts-regexp s)
9088 (setq s (replace-match "" t t s))))
9089 (or string (setq s (concat "*" s))) ; Add * for headlines
9090 (when (and string (integerp lines) (> lines 0))
9091 (let ((slines (org-split-string s "\n")))
9092 (when (< lines (length slines))
9093 (setq s (mapconcat
9094 'identity
9095 (reverse (nthcdr (- (length slines) lines)
9096 (reverse slines))) "\n")))))
9097 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9099 (defun org-make-link-string (link &optional description)
9100 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9101 (unless (string-match "\\S-" link)
9102 (error "Empty link"))
9103 (when (and description
9104 (stringp description)
9105 (not (string-match "\\S-" description)))
9106 (setq description nil))
9107 (when (stringp description)
9108 ;; Remove brackets from the description, they are fatal.
9109 (while (string-match "\\[" description)
9110 (setq description (replace-match "{" t t description)))
9111 (while (string-match "\\]" description)
9112 (setq description (replace-match "}" t t description))))
9113 (when (equal link description)
9114 ;; No description needed, it is identical
9115 (setq description nil))
9116 (when (and (not description)
9117 (not (string-match (org-image-file-name-regexp) link))
9118 (not (equal link (org-link-escape link))))
9119 (setq description (org-extract-attributes link)))
9120 (setq link
9121 (cond ((string-match (org-image-file-name-regexp) link) link)
9122 ((string-match org-link-types-re link)
9123 (concat (match-string 1 link)
9124 (org-link-escape (substring link (match-end 1)))))
9125 (t (org-link-escape link))))
9126 (concat "[[" link "]"
9127 (if description (concat "[" description "]") "")
9128 "]"))
9130 (defconst org-link-escape-chars
9131 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9132 "List of characters that should be escaped in link.
9133 This is the list that is used for internal purposes.")
9135 (defconst org-link-escape-chars-browser
9136 '(?\ )
9137 "List of escapes for characters that are problematic in links.
9138 This is the list that is used before handing over to the browser.")
9140 (defun org-link-escape (text &optional table merge)
9141 "Return percent escaped representation of TEXT.
9142 TEXT is a string with the text to escape.
9143 Optional argument TABLE is a list with characters that should be
9144 escaped. When nil, `org-link-escape-chars' is used.
9145 If optional argument MERGE is set, merge TABLE into
9146 `org-link-escape-chars'."
9147 (cond
9148 ((and table merge)
9149 (mapc (lambda (defchr)
9150 (unless (member defchr table)
9151 (setq table (cons defchr table)))) org-link-escape-chars))
9152 ((null table)
9153 (setq table org-link-escape-chars)))
9154 (mapconcat
9155 (lambda (char)
9156 (if (or (member char table)
9157 (and (or (< char 32) (= char 37) (> char 126))
9158 org-url-hexify-p))
9159 (mapconcat (lambda (sequence-element)
9160 (format "%%%.2X" sequence-element))
9161 (or (encode-coding-char char 'utf-8)
9162 (error "Unable to percent escape character: %s"
9163 (char-to-string char))) "")
9164 (char-to-string char))) text ""))
9166 (defun org-link-unescape (str)
9167 "Unhex hexified Unicode strings as returned from the JavaScript function
9168 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9169 (unless (and (null str) (string= "" str))
9170 (let ((pos 0) (case-fold-search t) unhexed)
9171 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9172 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9173 (setq str (replace-match unhexed t t str))
9174 (setq pos (+ pos (length unhexed))))))
9175 str)
9177 (defun org-link-unescape-compound (hex)
9178 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9179 Note: this function also decodes single byte encodings like
9180 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9181 (save-match-data
9182 (let* ((bytes (cdr (split-string hex "%")))
9183 (ret "")
9184 (eat 0)
9185 (sum 0))
9186 (while bytes
9187 (let* ((val (string-to-number (pop bytes) 16))
9188 (shift-xor
9189 (if (= 0 eat)
9190 (cond
9191 ((>= val 252) (cons 6 252))
9192 ((>= val 248) (cons 5 248))
9193 ((>= val 240) (cons 4 240))
9194 ((>= val 224) (cons 3 224))
9195 ((>= val 192) (cons 2 192))
9196 (t (cons 0 0)))
9197 (cons 6 128))))
9198 (if (>= val 192) (setq eat (car shift-xor)))
9199 (setq val (logxor val (cdr shift-xor)))
9200 (setq sum (+ (lsh sum (car shift-xor)) val))
9201 (if (> eat 0) (setq eat (- eat 1)))
9202 (cond
9203 ((= 0 eat) ;multi byte
9204 (setq ret (concat ret (org-char-to-string sum)))
9205 (setq sum 0))
9206 ((not bytes) ; single byte(s)
9207 (setq ret (org-link-unescape-single-byte-sequence hex))))
9208 )) ;; end (while bytes
9209 ret )))
9211 (defun org-link-unescape-single-byte-sequence (hex)
9212 "Unhexify hex-encoded single byte character sequences."
9213 (mapconcat (lambda (byte)
9214 (char-to-string (string-to-number byte 16)))
9215 (cdr (split-string hex "%")) ""))
9217 (defun org-xor (a b)
9218 "Exclusive or."
9219 (if a (not b) b))
9221 (defun org-fixup-message-id-for-http (s)
9222 "Replace special characters in a message id, so it can be used in an http query."
9223 (when (string-match "%" s)
9224 (setq s (mapconcat (lambda (c)
9225 (if (eq c ?%)
9226 "%25"
9227 (char-to-string c)))
9228 s "")))
9229 (while (string-match "<" s)
9230 (setq s (replace-match "%3C" t t s)))
9231 (while (string-match ">" s)
9232 (setq s (replace-match "%3E" t t s)))
9233 (while (string-match "@" s)
9234 (setq s (replace-match "%40" t t s)))
9237 (defun org-link-prettify (link)
9238 "Return a human-readable representation of LINK.
9239 The car of LINK must be a raw link the cdr of LINK must be either
9240 a link description or nil."
9241 (let ((desc (or (cadr link) "<no description>")))
9242 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9243 "<" (car link) ">")))
9245 ;;;###autoload
9246 (defun org-insert-link-global ()
9247 "Insert a link like Org-mode does.
9248 This command can be called in any mode to insert a link in Org-mode syntax."
9249 (interactive)
9250 (org-load-modules-maybe)
9251 (org-run-like-in-org-mode 'org-insert-link))
9253 (defun org-insert-all-links (&optional keep)
9254 "Insert all links in `org-stored-links'."
9255 (interactive "P")
9256 (let ((links (copy-sequence org-stored-links)) l)
9257 (while (setq l (if keep (pop links) (pop org-stored-links)))
9258 (insert "- ")
9259 (org-insert-link nil (car l) (cadr l))
9260 (insert "\n"))))
9262 (defun org-link-fontify-links-to-this-file ()
9263 "Fontify links to the current file in `org-stored-links'."
9264 (let ((f (buffer-file-name)) a b)
9265 (setq a (mapcar (lambda(l)
9266 (let ((ll (car l)))
9267 (when (and (string-match "^file:\\(.+\\)::" ll)
9268 (equal f (expand-file-name (match-string 1 ll))))
9269 ll)))
9270 org-stored-links))
9271 (when (featurep 'org-id)
9272 (setq b (mapcar (lambda(l)
9273 (let ((ll (car l)))
9274 (when (and (string-match "^id:\\(.+\\)$" ll)
9275 (equal f (expand-file-name
9276 (or (org-id-find-id-file
9277 (match-string 1 ll)) ""))))
9278 ll)))
9279 org-stored-links)))
9280 (mapcar (lambda(l)
9281 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9282 (delq nil (append a b)))))
9284 (defvar org-link-links-in-this-file nil)
9285 (defun org-insert-link (&optional complete-file link-location default-description)
9286 "Insert a link. At the prompt, enter the link.
9288 Completion can be used to insert any of the link protocol prefixes like
9289 http or ftp in use.
9291 The history can be used to select a link previously stored with
9292 `org-store-link'. When the empty string is entered (i.e. if you just
9293 press RET at the prompt), the link defaults to the most recently
9294 stored link. As SPC triggers completion in the minibuffer, you need to
9295 use M-SPC or C-q SPC to force the insertion of a space character.
9297 You will also be prompted for a description, and if one is given, it will
9298 be displayed in the buffer instead of the link.
9300 If there is already a link at point, this command will allow you to edit link
9301 and description parts.
9303 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9304 be selected using completion. The path to the file will be relative to the
9305 current directory if the file is in the current directory or a subdirectory.
9306 Otherwise, the link will be the absolute path as completed in the minibuffer
9307 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9308 option `org-link-file-path-type'.
9310 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9311 the current directory or below.
9313 With three \\[universal-argument] prefixes, negate the meaning of
9314 `org-keep-stored-link-after-insertion'.
9316 If `org-make-link-description-function' is non-nil, this function will be
9317 called with the link target, and the result will be the default
9318 link description.
9320 If the LINK-LOCATION parameter is non-nil, this value will be
9321 used as the link location instead of reading one interactively.
9323 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9324 be used as the default description."
9325 (interactive "P")
9326 (let* ((wcf (current-window-configuration))
9327 (region (if (org-region-active-p)
9328 (buffer-substring (region-beginning) (region-end))))
9329 (remove (and region (list (region-beginning) (region-end))))
9330 (desc region)
9331 tmphist ; byte-compile incorrectly complains about this
9332 (link link-location)
9333 entry file all-prefixes auto-desc)
9334 (cond
9335 (link-location) ; specified by arg, just use it.
9336 ((org-in-regexp org-bracket-link-regexp 1)
9337 ;; We do have a link at point, and we are going to edit it.
9338 (setq remove (list (match-beginning 0) (match-end 0)))
9339 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9340 (setq link (read-string "Link: "
9341 (org-link-unescape
9342 (org-match-string-no-properties 1)))))
9343 ((or (org-in-regexp org-angle-link-re)
9344 (org-in-regexp org-plain-link-re))
9345 ;; Convert to bracket link
9346 (setq remove (list (match-beginning 0) (match-end 0))
9347 link (read-string "Link: "
9348 (org-remove-angle-brackets (match-string 0)))))
9349 ((member complete-file '((4) (16)))
9350 ;; Completing read for file names.
9351 (setq link (org-file-complete-link complete-file)))
9353 ;; Read link, with completion for stored links.
9354 (org-link-fontify-links-to-this-file)
9355 (org-switch-to-buffer-other-window "*Org Links*")
9356 (with-current-buffer "*Org Links*"
9357 (erase-buffer)
9358 (insert "Insert a link.
9359 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9360 (when org-stored-links
9361 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9362 (insert (mapconcat 'org-link-prettify
9363 (reverse org-stored-links) "\n")))
9364 (goto-char (point-min)))
9365 (let ((cw (selected-window)))
9366 (select-window (get-buffer-window "*Org Links*" 'visible))
9367 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9368 (unless (pos-visible-in-window-p (point-max))
9369 (org-fit-window-to-buffer))
9370 (and (window-live-p cw) (select-window cw)))
9371 ;; Fake a link history, containing the stored links.
9372 (setq tmphist (append (mapcar 'car org-stored-links)
9373 org-insert-link-history))
9374 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9375 (mapcar 'car org-link-abbrev-alist)
9376 org-link-types))
9377 (unwind-protect
9378 (progn
9379 (setq link
9380 (let ((org-completion-use-ido nil)
9381 (org-completion-use-iswitchb nil))
9382 (org-completing-read
9383 "Link: "
9384 (append
9385 (mapcar (lambda (x) (list (concat x ":")))
9386 all-prefixes)
9387 (mapcar 'car org-stored-links)
9388 (mapcar 'cadr org-stored-links))
9389 nil nil nil
9390 'tmphist
9391 (caar org-stored-links))))
9392 (if (not (string-match "\\S-" link))
9393 (error "No link selected"))
9394 (mapc (lambda(l)
9395 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9396 org-stored-links)
9397 (if (or (member link all-prefixes)
9398 (and (equal ":" (substring link -1))
9399 (member (substring link 0 -1) all-prefixes)
9400 (setq link (substring link 0 -1))))
9401 (setq link (org-link-try-special-completion link))))
9402 (set-window-configuration wcf)
9403 (kill-buffer "*Org Links*"))
9404 (setq entry (assoc link org-stored-links))
9405 (or entry (push link org-insert-link-history))
9406 (setq desc (or desc (nth 1 entry)))))
9408 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9409 (not org-keep-stored-link-after-insertion))
9410 (setq org-stored-links (delq (assoc link org-stored-links)
9411 org-stored-links)))
9413 (if (string-match org-plain-link-re link)
9414 ;; URL-like link, normalize the use of angular brackets.
9415 (setq link (org-remove-angle-brackets link)))
9417 ;; Check if we are linking to the current file with a search option
9418 ;; If yes, simplify the link by using only the search option.
9419 (when (and buffer-file-name
9420 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9421 (let* ((path (match-string 1 link))
9422 (case-fold-search nil)
9423 (search (match-string 2 link)))
9424 (save-match-data
9425 (if (equal (file-truename buffer-file-name) (file-truename path))
9426 ;; We are linking to this same file, with a search option
9427 (setq link search)))))
9429 ;; Check if we can/should use a relative path. If yes, simplify the link
9430 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9431 (let* ((type (match-string 1 link))
9432 (path (match-string 2 link))
9433 (origpath path)
9434 (case-fold-search nil))
9435 (cond
9436 ((or (eq org-link-file-path-type 'absolute)
9437 (equal complete-file '(16)))
9438 (setq path (abbreviate-file-name (expand-file-name path))))
9439 ((eq org-link-file-path-type 'noabbrev)
9440 (setq path (expand-file-name path)))
9441 ((eq org-link-file-path-type 'relative)
9442 (setq path (file-relative-name path)))
9444 (save-match-data
9445 (if (string-match (concat "^" (regexp-quote
9446 (expand-file-name
9447 (file-name-as-directory
9448 default-directory))))
9449 (expand-file-name path))
9450 ;; We are linking a file with relative path name.
9451 (setq path (substring (expand-file-name path)
9452 (match-end 0)))
9453 (setq path (abbreviate-file-name (expand-file-name path)))))))
9454 (setq link (concat type path))
9455 (if (equal desc origpath)
9456 (setq desc path))))
9458 (if org-make-link-description-function
9459 (setq desc (funcall org-make-link-description-function link desc))
9460 (if default-description (setq desc default-description)
9461 (setq desc (or (and auto-desc desc)
9462 (read-string "Description: " desc)))))
9464 (unless (string-match "\\S-" desc) (setq desc nil))
9465 (if remove (apply 'delete-region remove))
9466 (insert (org-make-link-string link desc))))
9468 (defun org-link-try-special-completion (type)
9469 "If there is completion support for link type TYPE, offer it."
9470 (let ((fun (intern (concat "org-" type "-complete-link"))))
9471 (if (functionp fun)
9472 (funcall fun)
9473 (read-string "Link (no completion support): " (concat type ":")))))
9475 (defun org-file-complete-link (&optional arg)
9476 "Create a file link using completion."
9477 (let (file link)
9478 (setq file (read-file-name "File: "))
9479 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9480 (pwd1 (file-name-as-directory (abbreviate-file-name
9481 (expand-file-name ".")))))
9482 (cond
9483 ((equal arg '(16))
9484 (setq link (concat
9485 "file:"
9486 (abbreviate-file-name (expand-file-name file)))))
9487 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9488 (setq link (concat "file:" (match-string 1 file))))
9489 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9490 (expand-file-name file))
9491 (setq link (concat
9492 "file:" (match-string 1 (expand-file-name file)))))
9493 (t (setq link (concat "file:" file)))))
9494 link))
9496 (defun org-completing-read (&rest args)
9497 "Completing-read with SPACE being a normal character."
9498 (let ((enable-recursive-minibuffers t)
9499 (minibuffer-local-completion-map
9500 (copy-keymap minibuffer-local-completion-map)))
9501 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9502 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9503 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9504 (apply 'org-icompleting-read args)))
9506 (defun org-completing-read-no-i (&rest args)
9507 (let (org-completion-use-ido org-completion-use-iswitchb)
9508 (apply 'org-completing-read args)))
9510 (defun org-iswitchb-completing-read (prompt choices &rest args)
9511 "Use iswitch as a completing-read replacement to choose from choices.
9512 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9513 from."
9514 (let* ((iswitchb-use-virtual-buffers nil)
9515 (iswitchb-make-buflist-hook
9516 (lambda ()
9517 (setq iswitchb-temp-buflist choices))))
9518 (iswitchb-read-buffer prompt)))
9520 (defun org-icompleting-read (&rest args)
9521 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9522 (org-without-partial-completion
9523 (if (and org-completion-use-ido
9524 (fboundp 'ido-completing-read)
9525 (boundp 'ido-mode) ido-mode
9526 (listp (second args)))
9527 (let ((ido-enter-matching-directory nil))
9528 (apply 'ido-completing-read (concat (car args))
9529 (if (consp (car (nth 1 args)))
9530 (mapcar 'car (nth 1 args))
9531 (nth 1 args))
9532 (cddr args)))
9533 (if (and org-completion-use-iswitchb
9534 (boundp 'iswitchb-mode) iswitchb-mode
9535 (listp (second args)))
9536 (apply 'org-iswitchb-completing-read (concat (car args))
9537 (if (consp (car (nth 1 args)))
9538 (mapcar 'car (nth 1 args))
9539 (nth 1 args))
9540 (cddr args))
9541 (apply 'completing-read args)))))
9543 (defun org-extract-attributes (s)
9544 "Extract the attributes cookie from a string and set as text property."
9545 (let (a attr (start 0) key value)
9546 (save-match-data
9547 (when (string-match "{{\\([^}]+\\)}}$" s)
9548 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9549 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9550 (setq key (match-string 1 a) value (match-string 2 a)
9551 start (match-end 0)
9552 attr (plist-put attr (intern key) value))))
9553 (org-add-props s nil 'org-attr attr))
9556 (defun org-extract-attributes-from-string (tag)
9557 (let (key value attr)
9558 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9559 (setq key (match-string 1 tag) value (match-string 2 tag)
9560 tag (replace-match "" t t tag)
9561 attr (plist-put attr (intern key) value)))
9562 (cons tag attr)))
9564 (defun org-attributes-to-string (plist)
9565 "Format a property list into an HTML attribute list."
9566 (let ((s "") key value)
9567 (while plist
9568 (setq key (pop plist) value (pop plist))
9569 (and value
9570 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9573 ;;; Opening/following a link
9575 (defvar org-link-search-failed nil)
9577 (defvar org-open-link-functions nil
9578 "Hook for functions finding a plain text link.
9579 These functions must take a single argument, the link content.
9580 They will be called for links that look like [[link text][description]]
9581 when LINK TEXT does not have a protocol like \"http:\" and does not look
9582 like a filename (e.g. \"./blue.png\").
9584 These functions will be called *before* Org attempts to resolve the
9585 link by doing text searches in the current buffer - so if you want a
9586 link \"[[target]]\" to still find \"<<target>>\", your function should
9587 handle this as a special case.
9589 When the function does handle the link, it must return a non-nil value.
9590 If it decides that it is not responsible for this link, it must return
9591 nil to indicate that that Org-mode can continue with other options
9592 like exact and fuzzy text search.")
9594 (defun org-next-link ()
9595 "Move forward to the next link.
9596 If the link is in hidden text, expose it."
9597 (interactive)
9598 (when (and org-link-search-failed (eq this-command last-command))
9599 (goto-char (point-min))
9600 (message "Link search wrapped back to beginning of buffer"))
9601 (setq org-link-search-failed nil)
9602 (let* ((pos (point))
9603 (ct (org-context))
9604 (a (assoc :link ct)))
9605 (if a (goto-char (nth 2 a)))
9606 (if (re-search-forward org-any-link-re nil t)
9607 (progn
9608 (goto-char (match-beginning 0))
9609 (if (outline-invisible-p) (org-show-context)))
9610 (goto-char pos)
9611 (setq org-link-search-failed t)
9612 (error "No further link found"))))
9614 (defun org-previous-link ()
9615 "Move backward to the previous link.
9616 If the link is in hidden text, expose it."
9617 (interactive)
9618 (when (and org-link-search-failed (eq this-command last-command))
9619 (goto-char (point-max))
9620 (message "Link search wrapped back to end of buffer"))
9621 (setq org-link-search-failed nil)
9622 (let* ((pos (point))
9623 (ct (org-context))
9624 (a (assoc :link ct)))
9625 (if a (goto-char (nth 1 a)))
9626 (if (re-search-backward org-any-link-re nil t)
9627 (progn
9628 (goto-char (match-beginning 0))
9629 (if (outline-invisible-p) (org-show-context)))
9630 (goto-char pos)
9631 (setq org-link-search-failed t)
9632 (error "No further link found"))))
9634 (defun org-translate-link (s)
9635 "Translate a link string if a translation function has been defined."
9636 (if (and org-link-translation-function
9637 (fboundp org-link-translation-function)
9638 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9639 (progn
9640 (setq s (funcall org-link-translation-function
9641 (match-string 1 s) (match-string 2 s)))
9642 (concat (car s) ":" (cdr s)))
9645 (defun org-translate-link-from-planner (type path)
9646 "Translate a link from Emacs Planner syntax so that Org can follow it.
9647 This is still an experimental function, your mileage may vary."
9648 (cond
9649 ((member type '("http" "https" "news" "ftp"))
9650 ;; standard Internet links are the same.
9651 nil)
9652 ((and (equal type "irc") (string-match "^//" path))
9653 ;; Planner has two / at the beginning of an irc link, we have 1.
9654 ;; We should have zero, actually....
9655 (setq path (substring path 1)))
9656 ((and (equal type "lisp") (string-match "^/" path))
9657 ;; Planner has a slash, we do not.
9658 (setq type "elisp" path (substring path 1)))
9659 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9660 ;; A typical message link. Planner has the id after the final slash,
9661 ;; we separate it with a hash mark
9662 (setq path (concat (match-string 1 path) "#"
9663 (org-remove-angle-brackets (match-string 2 path)))))
9665 (cons type path))
9667 (defun org-find-file-at-mouse (ev)
9668 "Open file link or URL at mouse."
9669 (interactive "e")
9670 (mouse-set-point ev)
9671 (org-open-at-point 'in-emacs))
9673 (defun org-open-at-mouse (ev)
9674 "Open file link or URL at mouse.
9675 See the docstring of `org-open-file' for details."
9676 (interactive "e")
9677 (mouse-set-point ev)
9678 (if (eq major-mode 'org-agenda-mode)
9679 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9680 (org-open-at-point))
9682 (defvar org-window-config-before-follow-link nil
9683 "The window configuration before following a link.
9684 This is saved in case the need arises to restore it.")
9686 (defvar org-open-link-marker (make-marker)
9687 "Marker pointing to the location where `org-open-at-point; was called.")
9689 ;;;###autoload
9690 (defun org-open-at-point-global ()
9691 "Follow a link like Org-mode does.
9692 This command can be called in any mode to follow a link that has
9693 Org-mode syntax."
9694 (interactive)
9695 (org-run-like-in-org-mode 'org-open-at-point))
9697 ;;;###autoload
9698 (defun org-open-link-from-string (s &optional arg reference-buffer)
9699 "Open a link in the string S, as if it was in Org-mode."
9700 (interactive "sLink: \nP")
9701 (let ((reference-buffer (or reference-buffer (current-buffer))))
9702 (with-temp-buffer
9703 (let ((org-inhibit-startup (not reference-buffer)))
9704 (org-mode)
9705 (insert s)
9706 (goto-char (point-min))
9707 (when reference-buffer
9708 (setq org-link-abbrev-alist-local
9709 (with-current-buffer reference-buffer
9710 org-link-abbrev-alist-local)))
9711 (org-open-at-point arg reference-buffer)))))
9713 (defvar org-open-at-point-functions nil
9714 "Hook that is run when following a link at point.
9716 Functions in this hook must return t if they identify and follow
9717 a link at point. If they don't find anything interesting at point,
9718 they must return nil.")
9720 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9721 (defun org-open-at-point (&optional arg reference-buffer)
9722 "Open link at or after point.
9723 If there is no link at point, this function will search forward up to
9724 the end of the current line.
9725 Normally, files will be opened by an appropriate application. If the
9726 optional prefix argument ARG is non-nil, Emacs will visit the file.
9727 With a double prefix argument, try to open outside of Emacs, in the
9728 application the system uses for this file type."
9729 (interactive "P")
9730 ;; if in a code block, then open the block's results
9731 (unless (call-interactively #'org-babel-open-src-block-result)
9732 (org-load-modules-maybe)
9733 (move-marker org-open-link-marker (point))
9734 (setq org-window-config-before-follow-link (current-window-configuration))
9735 (org-remove-occur-highlights nil nil t)
9736 (cond
9737 ((and (org-at-heading-p)
9738 (not (org-at-timestamp-p t))
9739 (not (org-in-regexp
9740 (concat org-plain-link-re "\\|"
9741 org-bracket-link-regexp "\\|"
9742 org-angle-link-re "\\|"
9743 "[ \t]:[^ \t\n]+:[ \t]*$")))
9744 (not (get-text-property (point) 'org-linked-text)))
9745 (or (org-offer-links-in-entry arg)
9746 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9747 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9748 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9749 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9750 (not (org-in-regexp org-bracket-link-regexp)))
9751 (org-footnote-action))
9753 (let (type path link line search (pos (point)))
9754 (catch 'match
9755 (save-excursion
9756 (skip-chars-forward "^]\n\r")
9757 (when (org-in-regexp org-bracket-link-regexp 1)
9758 (setq link (org-extract-attributes
9759 (org-link-unescape (org-match-string-no-properties 1))))
9760 (while (string-match " *\n *" link)
9761 (setq link (replace-match " " t t link)))
9762 (setq link (org-link-expand-abbrev link))
9763 (cond
9764 ((or (file-name-absolute-p link)
9765 (string-match "^\\.\\.?/" link))
9766 (setq type "file" path link))
9767 ((string-match org-link-re-with-space3 link)
9768 (setq type (match-string 1 link) path (match-string 2 link)))
9769 ((string-match "^help:+\\(.+\\)" link)
9770 (setq type "help" path (match-string 1 link)))
9771 (t (setq type "thisfile" path link)))
9772 (throw 'match t)))
9774 (when (get-text-property (point) 'org-linked-text)
9775 (setq type "thisfile"
9776 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9777 (1+ (point)) (point))
9778 path (buffer-substring
9779 (or (previous-single-property-change pos 'org-linked-text)
9780 (point-min))
9781 (or (next-single-property-change pos 'org-linked-text)
9782 (point-max))))
9783 (throw 'match t))
9785 (save-excursion
9786 (when (or (org-in-regexp org-angle-link-re)
9787 (org-in-regexp org-plain-link-re))
9788 (setq type (match-string 1)
9789 path (org-link-unescape (match-string 2)))
9790 (throw 'match t)))
9791 (save-excursion
9792 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9793 (setq type "tags"
9794 path (match-string 1))
9795 (while (string-match ":" path)
9796 (setq path (replace-match "+" t t path)))
9797 (throw 'match t)))
9798 (when (org-in-regexp "<\\([^><\n]+\\)>")
9799 (setq type "tree-match"
9800 path (match-string 1))
9801 (throw 'match t)))
9802 (unless path
9803 (error "No link found"))
9805 ;; switch back to reference buffer
9806 ;; needed when if called in a temporary buffer through
9807 ;; org-open-link-from-string
9808 (with-current-buffer (or reference-buffer (current-buffer))
9810 ;; Remove any trailing spaces in path
9811 (if (string-match " +\\'" path)
9812 (setq path (replace-match "" t t path)))
9813 (if (and org-link-translation-function
9814 (fboundp org-link-translation-function))
9815 ;; Check if we need to translate the link
9816 (let ((tmp (funcall org-link-translation-function type path)))
9817 (setq type (car tmp) path (cdr tmp))))
9819 (cond
9821 ((assoc type org-link-protocols)
9822 (funcall (nth 1 (assoc type org-link-protocols)) path))
9824 ((equal type "help")
9825 (let ((f-or-v (intern path)))
9826 (cond ((fboundp f-or-v)
9827 (describe-function f-or-v))
9828 ((boundp f-or-v)
9829 (describe-variable f-or-v))
9830 (t (error "Not a known function or variable")))))
9832 ((equal type "mailto")
9833 (let ((cmd (car org-link-mailto-program))
9834 (args (cdr org-link-mailto-program)) args1
9835 (address path) (subject "") a)
9836 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9837 (setq address (match-string 1 path)
9838 subject (org-link-escape (match-string 2 path))))
9839 (while args
9840 (cond
9841 ((not (stringp (car args))) (push (pop args) args1))
9842 (t (setq a (pop args))
9843 (if (string-match "%a" a)
9844 (setq a (replace-match address t t a)))
9845 (if (string-match "%s" a)
9846 (setq a (replace-match subject t t a)))
9847 (push a args1))))
9848 (apply cmd (nreverse args1))))
9850 ((member type '("http" "https" "ftp" "news"))
9851 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9852 (org-link-escape
9853 path org-link-escape-chars-browser)
9854 path))))
9856 ((string= type "doi")
9857 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9858 (org-link-escape
9859 path org-link-escape-chars-browser)
9860 path))))
9862 ((member type '("message"))
9863 (browse-url (concat type ":" path)))
9865 ((string= type "tags")
9866 (org-tags-view arg path))
9868 ((string= type "tree-match")
9869 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9871 ((string= type "file")
9872 (if (string-match "::\\([0-9]+\\)\\'" path)
9873 (setq line (string-to-number (match-string 1 path))
9874 path (substring path 0 (match-beginning 0)))
9875 (if (string-match "::\\(.+\\)\\'" path)
9876 (setq search (match-string 1 path)
9877 path (substring path 0 (match-beginning 0)))))
9878 (if (string-match "[*?{]" (file-name-nondirectory path))
9879 (dired path)
9880 (org-open-file path arg line search)))
9882 ((string= type "shell")
9883 (let ((buf (generate-new-buffer "*Org Shell Output"))
9884 (cmd path))
9885 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9886 (string-match org-confirm-shell-link-not-regexp cmd))
9887 (not org-confirm-shell-link-function)
9888 (funcall org-confirm-shell-link-function
9889 (format "Execute \"%s\" in shell? "
9890 (org-add-props cmd nil
9891 'face 'org-warning))))
9892 (progn
9893 (message "Executing %s" cmd)
9894 (shell-command cmd buf)
9895 (if (featurep 'midnight)
9896 (setq clean-buffer-list-kill-buffer-names
9897 (cons buf clean-buffer-list-kill-buffer-names))))
9898 (error "Abort"))))
9900 ((string= type "elisp")
9901 (let ((cmd path))
9902 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9903 (string-match org-confirm-elisp-link-not-regexp cmd))
9904 (not org-confirm-elisp-link-function)
9905 (funcall org-confirm-elisp-link-function
9906 (format "Execute \"%s\" as elisp? "
9907 (org-add-props cmd nil
9908 'face 'org-warning))))
9909 (message "%s => %s" cmd
9910 (if (equal (string-to-char cmd) ?\()
9911 (eval (read cmd))
9912 (call-interactively (read cmd))))
9913 (error "Abort"))))
9915 ((and (string= type "thisfile")
9916 (run-hook-with-args-until-success
9917 'org-open-link-functions path)))
9919 ((string= type "thisfile")
9920 (if arg
9921 (switch-to-buffer-other-window
9922 (org-get-buffer-for-internal-link (current-buffer)))
9923 (org-mark-ring-push))
9924 (let ((cmd `(org-link-search
9925 ,path
9926 ,(cond ((equal arg '(4)) ''occur)
9927 ((equal arg '(16)) ''org-occur)
9928 (t nil))
9929 ,pos)))
9930 (condition-case nil (let ((org-link-search-inhibit-query t))
9931 (eval cmd))
9932 (error (progn (widen) (eval cmd))))))
9935 (browse-url-at-point)))))))
9936 (move-marker org-open-link-marker nil)
9937 (run-hook-with-args 'org-follow-link-hook)))
9939 (defun org-offer-links-in-entry (&optional nth zero)
9940 "Offer links in the current entry and follow the selected link.
9941 If there is only one link, follow it immediately as well.
9942 If NTH is an integer, immediately pick the NTH link found.
9943 If ZERO is a string, check also this string for a link, and if
9944 there is one, offer it as link number zero."
9945 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9946 "\\(" org-angle-link-re "\\)\\|"
9947 "\\(" org-plain-link-re "\\)"))
9948 (cnt ?0)
9949 (in-emacs (if (integerp nth) nil nth))
9950 have-zero end links link c)
9951 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9952 (push (match-string 0 zero) links)
9953 (setq cnt (1- cnt) have-zero t))
9954 (save-excursion
9955 (org-back-to-heading t)
9956 (setq end (save-excursion (outline-next-heading) (point)))
9957 (while (re-search-forward re end t)
9958 (push (match-string 0) links))
9959 (setq links (org-uniquify (reverse links))))
9961 (cond
9962 ((null links)
9963 (message "No links"))
9964 ((equal (length links) 1)
9965 (setq link (list (car links))))
9966 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9967 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9968 (t ; we have to select a link
9969 (save-excursion
9970 (save-window-excursion
9971 (delete-other-windows)
9972 (with-output-to-temp-buffer "*Select Link*"
9973 (mapc (lambda (l)
9974 (if (not (string-match org-bracket-link-regexp l))
9975 (princ (format "[%c] %s\n" (incf cnt)
9976 (org-remove-angle-brackets l)))
9977 (if (match-end 3)
9978 (princ (format "[%c] %s (%s)\n" (incf cnt)
9979 (match-string 3 l) (match-string 1 l)))
9980 (princ (format "[%c] %s\n" (incf cnt)
9981 (match-string 1 l))))))
9982 links))
9983 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9984 (message "Select link to open, RET to open all:")
9985 (setq c (read-char-exclusive))
9986 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9987 (when (equal c ?q) (error "Abort"))
9988 (if (equal c ?\C-m)
9989 (setq link links)
9990 (setq nth (- c ?0))
9991 (if have-zero (setq nth (1+ nth)))
9992 (unless (and (integerp nth) (>= (length links) nth))
9993 (error "Invalid link selection"))
9994 (setq link (list (nth (1- nth) links))))))
9995 (if link
9996 (let ((buf (current-buffer)))
9997 (dolist (l link)
9998 (org-open-link-from-string l in-emacs buf))
10000 nil)))
10002 ;; Add special file links that specify the way of opening
10004 (org-add-link-type "file+sys" 'org-open-file-with-system)
10005 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10006 (defun org-open-file-with-system (path)
10007 "Open file at PATH using the system way of opening it."
10008 (org-open-file path 'system))
10009 (defun org-open-file-with-emacs (path)
10010 "Open file at PATH in Emacs."
10011 (org-open-file path 'emacs))
10012 (defun org-remove-file-link-modifiers ()
10013 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10014 (goto-char (point-min))
10015 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10016 (org-if-unprotected
10017 (replace-match "file:" t t))))
10018 (eval-after-load "org-exp"
10019 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10020 'org-remove-file-link-modifiers))
10022 ;;;; Time estimates
10024 (defun org-get-effort (&optional pom)
10025 "Get the effort estimate for the current entry."
10026 (org-entry-get pom org-effort-property))
10028 ;;; File search
10030 (defvar org-create-file-search-functions nil
10031 "List of functions to construct the right search string for a file link.
10032 These functions are called in turn with point at the location to
10033 which the link should point.
10035 A function in the hook should first test if it would like to
10036 handle this file type, for example by checking the `major-mode'
10037 or the file extension. If it decides not to handle this file, it
10038 should just return nil to give other functions a chance. If it
10039 does handle the file, it must return the search string to be used
10040 when following the link. The search string will be part of the
10041 file link, given after a double colon, and `org-open-at-point'
10042 will automatically search for it. If special measures must be
10043 taken to make the search successful, another function should be
10044 added to the companion hook `org-execute-file-search-functions',
10045 which see.
10047 A function in this hook may also use `setq' to set the variable
10048 `description' to provide a suggestion for the descriptive text to
10049 be used for this link when it gets inserted into an Org-mode
10050 buffer with \\[org-insert-link].")
10052 (defvar org-execute-file-search-functions nil
10053 "List of functions to execute a file search triggered by a link.
10055 Functions added to this hook must accept a single argument, the
10056 search string that was part of the file link, the part after the
10057 double colon. The function must first check if it would like to
10058 handle this search, for example by checking the `major-mode' or
10059 the file extension. If it decides not to handle this search, it
10060 should just return nil to give other functions a chance. If it
10061 does handle the search, it must return a non-nil value to keep
10062 other functions from trying.
10064 Each function can access the current prefix argument through the
10065 variable `current-prefix-argument'. Note that a single prefix is
10066 used to force opening a link in Emacs, so it may be good to only
10067 use a numeric or double prefix to guide the search function.
10069 In case this is needed, a function in this hook can also restore
10070 the window configuration before `org-open-at-point' was called using:
10072 (set-window-configuration org-window-config-before-follow-link)")
10074 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10075 (defun org-link-search (s &optional type avoid-pos stealth)
10076 "Search for a link search option.
10077 If S is surrounded by forward slashes, it is interpreted as a
10078 regular expression. In org-mode files, this will create an `org-occur'
10079 sparse tree. In ordinary files, `occur' will be used to list matches.
10080 If the current buffer is in `dired-mode', grep will be used to search
10081 in all files. If AVOID-POS is given, ignore matches near that position.
10083 When optional argument STEALTH is non-nil, do not modify
10084 visibility around point, thus ignoring
10085 `org-show-hierarchy-above', `org-show-following-heading' and
10086 `org-show-siblings' variables."
10087 (let ((case-fold-search t)
10088 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10089 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10090 (append '(("") (" ") ("\t") ("\n"))
10091 org-emphasis-alist)
10092 "\\|") "\\)"))
10093 (pos (point))
10094 (pre nil) (post nil)
10095 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10096 (cond
10097 ;; First check if there are any special search functions
10098 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10099 ;; Now try the builtin stuff
10100 ((and (equal (string-to-char s0) ?#)
10101 (> (length s0) 1)
10102 (save-excursion
10103 (goto-char (point-min))
10104 (and
10105 (re-search-forward
10106 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10107 (setq type 'dedicated
10108 pos (match-beginning 0))))
10109 ;; There is an exact target for this
10110 (goto-char pos)
10111 (org-back-to-heading t)))
10112 ((save-excursion
10113 (goto-char (point-min))
10114 (and
10115 (re-search-forward
10116 (concat "<<" (regexp-quote s0) ">>") nil t)
10117 (setq type 'dedicated
10118 pos (match-beginning 0))))
10119 ;; There is an exact target for this
10120 (goto-char pos))
10121 ((save-excursion
10122 (goto-char (point-min))
10123 (and
10124 (re-search-forward
10125 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10126 (setq type 'dedicated pos (match-beginning 0))))
10127 ;; Found an invisible target.
10128 (goto-char pos))
10129 ((save-excursion
10130 (goto-char (point-min))
10131 (and
10132 (re-search-forward
10133 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10134 (setq type 'dedicated pos (match-beginning 0))))
10135 ;; Found an element with a matching #+name affiliated keyword.
10136 (goto-char pos))
10137 ((and (string-match "^(\\(.*\\))$" s0)
10138 (save-excursion
10139 (goto-char (point-min))
10140 (and
10141 (re-search-forward
10142 (concat "[^[]" (regexp-quote
10143 (format org-coderef-label-format
10144 (match-string 1 s0))))
10145 nil t)
10146 (setq type 'dedicated
10147 pos (1+ (match-beginning 0))))))
10148 ;; There is a coderef target for this
10149 (goto-char pos))
10150 ((string-match "^/\\(.*\\)/$" s)
10151 ;; A regular expression
10152 (cond
10153 ((derived-mode-p 'org-mode)
10154 (org-occur (match-string 1 s)))
10155 ;;((eq major-mode 'dired-mode)
10156 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10157 (t (org-do-occur (match-string 1 s)))))
10158 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10159 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10160 (goto-char (point-min))
10161 (cond
10162 ((let (case-fold-search)
10163 (re-search-forward (format org-complex-heading-regexp-format
10164 (regexp-quote s))
10165 nil t))
10166 ;; OK, found a match
10167 (setq type 'dedicated)
10168 (goto-char (match-beginning 0)))
10169 ((and (not org-link-search-inhibit-query)
10170 (eq org-link-search-must-match-exact-headline 'query-to-create)
10171 (y-or-n-p "No match - create this as a new heading? "))
10172 (goto-char (point-max))
10173 (or (bolp) (newline))
10174 (insert "* " s "\n")
10175 (beginning-of-line 0))
10177 (goto-char pos)
10178 (error "No match"))))
10180 ;; A normal search string
10181 (when (equal (string-to-char s) ?*)
10182 ;; Anchor on headlines, post may include tags.
10183 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10184 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10185 s (substring s 1)))
10186 (remove-text-properties
10187 0 (length s)
10188 '(face nil mouse-face nil keymap nil fontified nil) s)
10189 ;; Make a series of regular expressions to find a match
10190 (setq words (org-split-string s "[ \n\r\t]+")
10192 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10193 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10194 "\\)" markers)
10195 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10196 re2a (concat "[ \t\r\n]" re2a_)
10197 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10198 re4 (concat "[^a-zA-Z_]" re4_)
10200 re1 (concat pre re2 post)
10201 re3 (concat pre (if pre re4_ re4) post)
10202 re5 (concat pre ".*" re4)
10203 re2 (concat pre re2)
10204 re2a (concat pre (if pre re2a_ re2a))
10205 re4 (concat pre (if pre re4_ re4))
10206 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10207 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10208 re5 "\\)"
10210 (cond
10211 ((eq type 'org-occur) (org-occur reall))
10212 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10213 (t (goto-char (point-min))
10214 (setq type 'fuzzy)
10215 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10216 (org-search-not-self 1 re1 nil t)
10217 (org-search-not-self 1 re2 nil t)
10218 (org-search-not-self 1 re2a nil t)
10219 (org-search-not-self 1 re3 nil t)
10220 (org-search-not-self 1 re4 nil t)
10221 (org-search-not-self 1 re5 nil t)
10223 (goto-char (match-beginning 1))
10224 (goto-char pos)
10225 (error "No match"))))))
10226 (and (derived-mode-p 'org-mode)
10227 (not stealth)
10228 (org-show-context 'link-search))
10229 type))
10231 (defun org-search-not-self (group &rest args)
10232 "Execute `re-search-forward', but only accept matches that do not
10233 enclose the position of `org-open-link-marker'."
10234 (let ((m org-open-link-marker))
10235 (catch 'exit
10236 (while (apply 're-search-forward args)
10237 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10238 (goto-char (match-end group))
10239 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10240 (> (match-beginning 0) (marker-position m))
10241 (< (match-end 0) (marker-position m)))
10242 (save-match-data
10243 (or (not (org-in-regexp
10244 org-bracket-link-analytic-regexp 1))
10245 (not (match-end 4)) ; no description
10246 (and (<= (match-beginning 4) (point))
10247 (>= (match-end 4) (point))))))
10248 (throw 'exit (point))))))))
10250 (defun org-get-buffer-for-internal-link (buffer)
10251 "Return a buffer to be used for displaying the link target of internal links."
10252 (cond
10253 ((not org-display-internal-link-with-indirect-buffer)
10254 buffer)
10255 ((string-match "(Clone)$" (buffer-name buffer))
10256 (message "Buffer is already a clone, not making another one")
10257 ;; we also do not modify visibility in this case
10258 buffer)
10259 (t ; make a new indirect buffer for displaying the link
10260 (let* ((bn (buffer-name buffer))
10261 (ibn (concat bn "(Clone)"))
10262 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10263 (with-current-buffer ib (org-overview))
10264 ib))))
10266 (defun org-do-occur (regexp &optional cleanup)
10267 "Call the Emacs command `occur'.
10268 If CLEANUP is non-nil, remove the printout of the regular expression
10269 in the *Occur* buffer. This is useful if the regex is long and not useful
10270 to read."
10271 (occur regexp)
10272 (when cleanup
10273 (let ((cwin (selected-window)) win beg end)
10274 (when (setq win (get-buffer-window "*Occur*"))
10275 (select-window win))
10276 (goto-char (point-min))
10277 (when (re-search-forward "match[a-z]+" nil t)
10278 (setq beg (match-end 0))
10279 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10280 (setq end (1- (match-beginning 0)))))
10281 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10282 (goto-char (point-min))
10283 (select-window cwin))))
10285 ;;; The mark ring for links jumps
10287 (defvar org-mark-ring nil
10288 "Mark ring for positions before jumps in Org-mode.")
10289 (defvar org-mark-ring-last-goto nil
10290 "Last position in the mark ring used to go back.")
10291 ;; Fill and close the ring
10292 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10293 (loop for i from 1 to org-mark-ring-length do
10294 (push (make-marker) org-mark-ring))
10295 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10296 org-mark-ring)
10298 (defun org-mark-ring-push (&optional pos buffer)
10299 "Put the current position or POS into the mark ring and rotate it."
10300 (interactive)
10301 (setq pos (or pos (point)))
10302 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10303 (move-marker (car org-mark-ring)
10304 (or pos (point))
10305 (or buffer (current-buffer)))
10306 (message "%s"
10307 (substitute-command-keys
10308 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10310 (defun org-mark-ring-goto (&optional n)
10311 "Jump to the previous position in the mark ring.
10312 With prefix arg N, jump back that many stored positions. When
10313 called several times in succession, walk through the entire ring.
10314 Org-mode commands jumping to a different position in the current file,
10315 or to another Org-mode file, automatically push the old position
10316 onto the ring."
10317 (interactive "p")
10318 (let (p m)
10319 (if (eq last-command this-command)
10320 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10321 (setq p org-mark-ring))
10322 (setq org-mark-ring-last-goto p)
10323 (setq m (car p))
10324 (org-pop-to-buffer-same-window (marker-buffer m))
10325 (goto-char m)
10326 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10328 (defun org-remove-angle-brackets (s)
10329 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10330 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10332 (defun org-add-angle-brackets (s)
10333 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10334 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10336 (defun org-remove-double-quotes (s)
10337 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10338 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10341 ;;; Following specific links
10343 (defun org-follow-timestamp-link ()
10344 (cond
10345 ((org-at-date-range-p t)
10346 (let ((org-agenda-start-on-weekday)
10347 (t1 (match-string 1))
10348 (t2 (match-string 2)))
10349 (setq t1 (time-to-days (org-time-string-to-time t1))
10350 t2 (time-to-days (org-time-string-to-time t2)))
10351 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10352 ((org-at-timestamp-p t)
10353 (org-agenda-list nil (time-to-days (org-time-string-to-time
10354 (substring (match-string 1) 0 10)))
10356 (t (error "This should not happen"))))
10359 ;;; Following file links
10360 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10361 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10362 (declare-function mailcap-mime-info
10363 "mailcap" (string &optional request no-decode))
10364 (defvar org-wait nil)
10365 (defun org-open-file (path &optional in-emacs line search)
10366 "Open the file at PATH.
10367 First, this expands any special file name abbreviations. Then the
10368 configuration variable `org-file-apps' is checked if it contains an
10369 entry for this file type, and if yes, the corresponding command is launched.
10371 If no application is found, Emacs simply visits the file.
10373 With optional prefix argument IN-EMACS, Emacs will visit the file.
10374 With a double \\[universal-argument] \\[universal-argument] \
10375 prefix arg, Org tries to avoid opening in Emacs
10376 and to use an external application to visit the file.
10378 Optional LINE specifies a line to go to, optional SEARCH a string
10379 to search for. If LINE or SEARCH is given, the file will be
10380 opened in Emacs, unless an entry from org-file-apps that makes
10381 use of groups in a regexp matches.
10383 If you want to change the way frames are used when following a
10384 link, please customize `org-link-frame-setup'.
10386 If the file does not exist, an error is thrown."
10387 (let* ((file (if (equal path "")
10388 buffer-file-name
10389 (substitute-in-file-name (expand-file-name path))))
10390 (file-apps (append org-file-apps (org-default-apps)))
10391 (apps (org-remove-if
10392 'org-file-apps-entry-match-against-dlink-p file-apps))
10393 (apps-dlink (org-remove-if-not
10394 'org-file-apps-entry-match-against-dlink-p file-apps))
10395 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10396 (dirp (if remp nil (file-directory-p file)))
10397 (file (if (and dirp org-open-directory-means-index-dot-org)
10398 (concat (file-name-as-directory file) "index.org")
10399 file))
10400 (a-m-a-p (assq 'auto-mode apps))
10401 (dfile (downcase file))
10402 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10403 (link (cond ((and (eq line nil)
10404 (eq search nil))
10405 file)
10406 (line
10407 (concat file "::" (number-to-string line)))
10408 (search
10409 (concat file "::" search))))
10410 (dlink (downcase link))
10411 (old-buffer (current-buffer))
10412 (old-pos (point))
10413 (old-mode major-mode)
10414 ext cmd link-match-data)
10415 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10416 (setq ext (match-string 1 dfile))
10417 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10418 (setq ext (match-string 1 dfile))))
10419 (cond
10420 ((member in-emacs '((16) system))
10421 (setq cmd (cdr (assoc 'system apps))))
10422 (in-emacs (setq cmd 'emacs))
10424 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10425 (and dirp (cdr (assoc 'directory apps)))
10426 ; first, try matching against apps-dlink
10427 ; if we get a match here, store the match data for later
10428 (let ((match (assoc-default dlink apps-dlink
10429 'string-match)))
10430 (if match
10431 (progn (setq link-match-data (match-data))
10432 match)
10433 (progn (setq in-emacs (or in-emacs line search))
10434 nil))) ; if we have no match in apps-dlink,
10435 ; always open the file in emacs if line or search
10436 ; is given (for backwards compatibility)
10437 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10438 'string-match)
10439 (cdr (assoc ext apps))
10440 (cdr (assoc t apps))))))
10441 (when (eq cmd 'system)
10442 (setq cmd (cdr (assoc 'system apps))))
10443 (when (eq cmd 'default)
10444 (setq cmd (cdr (assoc t apps))))
10445 (when (eq cmd 'mailcap)
10446 (require 'mailcap)
10447 (mailcap-parse-mailcaps)
10448 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10449 (command (mailcap-mime-info mime-type)))
10450 (if (stringp command)
10451 (setq cmd command)
10452 (setq cmd 'emacs))))
10453 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10454 (not (file-exists-p file))
10455 (not org-open-non-existing-files))
10456 (error "No such file: %s" file))
10457 (cond
10458 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10459 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10460 (while (string-match "['\"]%s['\"]" cmd)
10461 (setq cmd (replace-match "%s" t t cmd)))
10462 (while (string-match "%s" cmd)
10463 (setq cmd (replace-match
10464 (save-match-data
10465 (shell-quote-argument
10466 (convert-standard-filename file)))
10467 t t cmd)))
10469 ;; Replace "%1", "%2" etc. in command with group matches from regex
10470 (save-match-data
10471 (let ((match-index 1)
10472 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10473 (set-match-data link-match-data)
10474 (while (<= match-index number-of-groups)
10475 (let ((regex (concat "%" (number-to-string match-index)))
10476 (replace-with (match-string match-index dlink)))
10477 (while (string-match regex cmd)
10478 (setq cmd (replace-match replace-with t t cmd))))
10479 (setq match-index (+ match-index 1)))))
10481 (save-window-excursion
10482 (start-process-shell-command cmd nil cmd)
10483 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10485 ((or (stringp cmd)
10486 (eq cmd 'emacs))
10487 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10488 (widen)
10489 (if line (org-goto-line line)
10490 (if search (org-link-search search))))
10491 ((consp cmd)
10492 (let ((file (convert-standard-filename file)))
10493 (save-match-data
10494 (set-match-data link-match-data)
10495 (eval cmd))))
10496 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10497 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10498 (or (not (equal old-buffer (current-buffer)))
10499 (not (equal old-pos (point))))
10500 (org-mark-ring-push old-pos old-buffer))))
10502 (defun org-file-apps-entry-match-against-dlink-p (entry)
10503 "This function returns non-nil if `entry' uses a regular
10504 expression which should be matched against the whole link by
10505 org-open-file.
10507 It assumes that is the case when the entry uses a regular
10508 expression which has at least one grouping construct and the
10509 action is either a lisp form or a command string containing
10510 '%1', i.e. using at least one subexpression match as a
10511 parameter."
10512 (let ((selector (car entry))
10513 (action (cdr entry)))
10514 (if (stringp selector)
10515 (and (> (regexp-opt-depth selector) 0)
10516 (or (and (stringp action)
10517 (string-match "%[0-9]" action))
10518 (consp action)))
10519 nil)))
10521 (defun org-default-apps ()
10522 "Return the default applications for this operating system."
10523 (cond
10524 ((eq system-type 'darwin)
10525 org-file-apps-defaults-macosx)
10526 ((eq system-type 'windows-nt)
10527 org-file-apps-defaults-windowsnt)
10528 (t org-file-apps-defaults-gnu)))
10530 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10531 "Convert extensions to regular expressions in the cars of LIST.
10532 Also, weed out any non-string entries, because the return value is used
10533 only for regexp matching.
10534 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10535 point to the symbol `emacs', indicating that the file should
10536 be opened in Emacs."
10537 (append
10538 (delq nil
10539 (mapcar (lambda (x)
10540 (if (not (stringp (car x)))
10542 (if (string-match "\\W" (car x))
10544 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10545 list))
10546 (if add-auto-mode
10547 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10549 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10550 (defun org-file-remote-p (file)
10551 "Test whether FILE specifies a location on a remote system.
10552 Return non-nil if the location is indeed remote.
10554 For example, the filename \"/user@host:/foo\" specifies a location
10555 on the system \"/user@host:\"."
10556 (cond ((fboundp 'file-remote-p)
10557 (file-remote-p file))
10558 ((fboundp 'tramp-handle-file-remote-p)
10559 (tramp-handle-file-remote-p file))
10560 ((and (boundp 'ange-ftp-name-format)
10561 (string-match (car ange-ftp-name-format) file))
10563 (t nil)))
10566 ;;;; Refiling
10568 (defun org-get-org-file ()
10569 "Read a filename, with default directory `org-directory'."
10570 (let ((default (or org-default-notes-file remember-data-file)))
10571 (read-file-name (format "File name [%s]: " default)
10572 (file-name-as-directory org-directory)
10573 default)))
10575 (defun org-notes-order-reversed-p ()
10576 "Check if the current file should receive notes in reversed order."
10577 (cond
10578 ((not org-reverse-note-order) nil)
10579 ((eq t org-reverse-note-order) t)
10580 ((not (listp org-reverse-note-order)) nil)
10581 (t (catch 'exit
10582 (let ((all org-reverse-note-order)
10583 entry)
10584 (while (setq entry (pop all))
10585 (if (string-match (car entry) buffer-file-name)
10586 (throw 'exit (cdr entry))))
10587 nil)))))
10589 (defvar org-refile-target-table nil
10590 "The list of refile targets, created by `org-refile'.")
10592 (defvar org-agenda-new-buffers nil
10593 "Buffers created to visit agenda files.")
10595 (defvar org-refile-cache nil
10596 "Cache for refile targets.")
10598 (defvar org-refile-markers nil
10599 "All the markers used for caching refile locations.")
10601 (defun org-refile-marker (pos)
10602 "Get a new refile marker, but only if caching is in use."
10603 (if (not org-refile-use-cache)
10605 (let ((m (make-marker)))
10606 (move-marker m pos)
10607 (push m org-refile-markers)
10608 m)))
10610 (defun org-refile-cache-clear ()
10611 "Clear the refile cache and disable all the markers."
10612 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10613 (setq org-refile-markers nil)
10614 (setq org-refile-cache nil)
10615 (message "Refile cache has been cleared"))
10617 (defun org-refile-cache-check-set (set)
10618 "Check if all the markers in the cache still have live buffers."
10619 (let (marker)
10620 (catch 'exit
10621 (while (and set (setq marker (nth 3 (pop set))))
10622 ;; if org-refile-use-outline-path is 'file, marker may be nil
10623 (when (and marker (null (marker-buffer marker)))
10624 (message "not found") (sit-for 3)
10625 (throw 'exit nil)))
10626 t)))
10628 (defun org-refile-cache-put (set &rest identifiers)
10629 "Push the refile targets SET into the cache, under IDENTIFIERS."
10630 (let* ((key (sha1 (prin1-to-string identifiers)))
10631 (entry (assoc key org-refile-cache)))
10632 (if entry
10633 (setcdr entry set)
10634 (push (cons key set) org-refile-cache))))
10636 (defun org-refile-cache-get (&rest identifiers)
10637 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10638 (cond
10639 ((not org-refile-cache) nil)
10640 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10642 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10643 org-refile-cache))))
10644 (and set (org-refile-cache-check-set set) set)))))
10646 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10647 "Produce a table with refile targets."
10648 (let ((case-fold-search nil)
10649 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10650 (entries (or org-refile-targets '((nil . (:level . 1)))))
10651 targets tgs txt re files f desc descre fast-path-p level pos0)
10652 (message "Getting targets...")
10653 (with-current-buffer (or default-buffer (current-buffer))
10654 (while (setq entry (pop entries))
10655 (setq files (car entry) desc (cdr entry))
10656 (setq fast-path-p nil)
10657 (cond
10658 ((null files) (setq files (list (current-buffer))))
10659 ((eq files 'org-agenda-files)
10660 (setq files (org-agenda-files 'unrestricted)))
10661 ((and (symbolp files) (fboundp files))
10662 (setq files (funcall files)))
10663 ((and (symbolp files) (boundp files))
10664 (setq files (symbol-value files))))
10665 (if (stringp files) (setq files (list files)))
10666 (cond
10667 ((eq (car desc) :tag)
10668 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10669 ((eq (car desc) :todo)
10670 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10671 ((eq (car desc) :regexp)
10672 (setq descre (cdr desc)))
10673 ((eq (car desc) :level)
10674 (setq descre (concat "^\\*\\{" (number-to-string
10675 (if org-odd-levels-only
10676 (1- (* 2 (cdr desc)))
10677 (cdr desc)))
10678 "\\}[ \t]")))
10679 ((eq (car desc) :maxlevel)
10680 (setq fast-path-p t)
10681 (setq descre (concat "^\\*\\{1," (number-to-string
10682 (if org-odd-levels-only
10683 (1- (* 2 (cdr desc)))
10684 (cdr desc)))
10685 "\\}[ \t]")))
10686 (t (error "Bad refiling target description %s" desc)))
10687 (while (setq f (pop files))
10688 (with-current-buffer
10689 (if (bufferp f) f (org-get-agenda-file-buffer f))
10691 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10692 (progn
10693 (if (bufferp f) (setq f (buffer-file-name
10694 (buffer-base-buffer f))))
10695 (setq f (and f (expand-file-name f)))
10696 (if (eq org-refile-use-outline-path 'file)
10697 (push (list (file-name-nondirectory f) f nil nil) tgs))
10698 (save-excursion
10699 (save-restriction
10700 (widen)
10701 (goto-char (point-min))
10702 (while (re-search-forward descre nil t)
10703 (goto-char (setq pos0 (point-at-bol)))
10704 (catch 'next
10705 (when org-refile-target-verify-function
10706 (save-match-data
10707 (or (funcall org-refile-target-verify-function)
10708 (throw 'next t))))
10709 (when (and (looking-at org-complex-heading-regexp)
10710 (not (member (match-string 4) excluded-entries))
10711 (match-string 4))
10712 (setq level (org-reduced-level
10713 (- (match-end 1) (match-beginning 1)))
10714 txt (org-link-display-format (match-string 4))
10715 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10716 re (format org-complex-heading-regexp-format
10717 (regexp-quote (match-string 4))))
10718 (when org-refile-use-outline-path
10719 (setq txt (mapconcat
10720 'org-protect-slash
10721 (append
10722 (if (eq org-refile-use-outline-path
10723 'file)
10724 (list (file-name-nondirectory
10725 (buffer-file-name
10726 (buffer-base-buffer))))
10727 (if (eq org-refile-use-outline-path
10728 'full-file-path)
10729 (list (buffer-file-name
10730 (buffer-base-buffer)))))
10731 (org-get-outline-path fast-path-p
10732 level txt)
10733 (list txt))
10734 "/")))
10735 (push (list txt f re (org-refile-marker (point)))
10736 tgs)))
10737 (when (= (point) pos0)
10738 ;; verification function has not moved point
10739 (goto-char (point-at-eol))))))))
10740 (when org-refile-use-cache
10741 (org-refile-cache-put tgs (buffer-file-name) descre))
10742 (setq targets (append tgs targets))
10743 ))))
10744 (message "Getting targets...done")
10745 (nreverse targets)))
10747 (defun org-protect-slash (s)
10748 (while (string-match "/" s)
10749 (setq s (replace-match "\\" t t s)))
10752 (defvar org-olpa (make-vector 20 nil))
10754 (defun org-get-outline-path (&optional fastp level heading)
10755 "Return the outline path to the current entry, as a list.
10757 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10758 routine which makes outline path derivations for an entire file,
10759 avoiding backtracing. Refile target collection makes use of that."
10760 (if fastp
10761 (progn
10762 (if (> level 19)
10763 (error "Outline path failure, more than 19 levels"))
10764 (loop for i from level upto 19 do
10765 (aset org-olpa i nil))
10766 (prog1
10767 (delq nil (append org-olpa nil))
10768 (aset org-olpa level heading)))
10769 (let (rtn case-fold-search)
10770 (save-excursion
10771 (save-restriction
10772 (widen)
10773 (while (org-up-heading-safe)
10774 (when (looking-at org-complex-heading-regexp)
10775 (push (org-match-string-no-properties 4) rtn)))
10776 rtn)))))
10778 (defun org-format-outline-path (path &optional width prefix)
10779 "Format the outline path PATH for display.
10780 Width is the maximum number of characters that is available.
10781 Prefix is a prefix to be included in the returned string,
10782 such as the file name."
10783 (setq width (or width 79))
10784 (if prefix (setq width (- width (length prefix))))
10785 (if (not path)
10786 (or prefix "")
10787 (let* ((nsteps (length path))
10788 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10789 (maxwidth (if (<= total-width width)
10790 10000 ;; everything fits
10791 ;; we need to shorten the level headings
10792 (/ (- width nsteps) nsteps)))
10793 (org-odd-levels-only nil)
10794 (n 0)
10795 (total (1+ (length prefix))))
10796 (setq maxwidth (max maxwidth 10))
10797 (concat prefix
10798 (mapconcat
10799 (lambda (h)
10800 (setq n (1+ n))
10801 (if (and (= n nsteps) (< maxwidth 10000))
10802 (setq maxwidth (- total-width total)))
10803 (if (< (length h) maxwidth)
10804 (progn (setq total (+ total (length h) 1)) h)
10805 (setq h (substring h 0 (- maxwidth 2))
10806 total (+ total maxwidth 1))
10807 (if (string-match "[ \t]+\\'" h)
10808 (setq h (substring h 0 (match-beginning 0))))
10809 (setq h (concat h "..")))
10810 (org-add-props h nil 'face
10811 (nth (% (1- n) org-n-level-faces)
10812 org-level-faces))
10814 path "/")))))
10816 (defun org-display-outline-path (&optional file current)
10817 "Display the current outline path in the echo area."
10818 (interactive "P")
10819 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10820 (case-fold-search nil)
10821 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10822 (if current (setq path (append path
10823 (save-excursion
10824 (org-back-to-heading t)
10825 (if (looking-at org-complex-heading-regexp)
10826 (list (match-string 4)))))))
10827 (message "%s"
10828 (org-format-outline-path
10829 path
10830 (1- (frame-width))
10831 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10833 (defvar org-refile-history nil
10834 "History for refiling operations.")
10836 (defvar org-after-refile-insert-hook nil
10837 "Hook run after `org-refile' has inserted its stuff at the new location.
10838 Note that this is still *before* the stuff will be removed from
10839 the *old* location.")
10841 (defvar org-capture-last-stored-marker)
10842 (defun org-refile (&optional goto default-buffer rfloc)
10843 "Move the entry or entries at point to another heading.
10844 The list of target headings is compiled using the information in
10845 `org-refile-targets', which see.
10847 At the target location, the entry is filed as a subitem of the target
10848 heading. Depending on `org-reverse-note-order', the new subitem will
10849 either be the first or the last subitem.
10851 If there is an active region, all entries in that region will be moved.
10852 However, the region must fulfill the requirement that the first heading
10853 is the first one sets the top-level of the moved text - at most siblings
10854 below it are allowed.
10856 With prefix arg GOTO, the command will only visit the target location
10857 and not actually move anything.
10859 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10860 go to the location where the last refiling operation has put the subtree.
10861 With a prefix argument of `2', refile to the running clock.
10863 RFLOC can be a refile location obtained in a different way.
10865 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10867 If you are using target caching (see `org-refile-use-cache'),
10868 you have to clear the target cache in order to find new targets.
10869 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10870 prefix argument (`C-u C-u C-u C-c C-w')."
10872 (interactive "P")
10873 (if (member goto '(0 (64)))
10874 (org-refile-cache-clear)
10875 (let* ((cbuf (current-buffer))
10876 (regionp (org-region-active-p))
10877 (region-start (and regionp (region-beginning)))
10878 (region-end (and regionp (region-end)))
10879 (region-length (and regionp (- region-end region-start)))
10880 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10881 pos it nbuf file re level reversed)
10882 (setq last-command nil)
10883 (when regionp
10884 (goto-char region-start)
10885 (or (bolp) (goto-char (point-at-bol)))
10886 (setq region-start (point))
10887 (unless (or (org-kill-is-subtree-p
10888 (buffer-substring region-start region-end))
10889 (prog1 org-refile-active-region-within-subtree
10890 (org-toggle-heading)))
10891 (error "The region is not a (sequence of) subtree(s)")))
10892 (if (equal goto '(16))
10893 (org-refile-goto-last-stored)
10894 (when (or
10895 (and (equal goto 2)
10896 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10897 (prog1
10898 (setq it (list (or org-clock-heading "running clock")
10899 (buffer-file-name
10900 (marker-buffer org-clock-hd-marker))
10902 (marker-position org-clock-hd-marker)))
10903 (setq goto nil)))
10904 (setq it (or rfloc
10905 (let (heading-text)
10906 (save-excursion
10907 (unless goto
10908 (org-back-to-heading t)
10909 (setq heading-text
10910 (nth 4 (org-heading-components))))
10911 (org-refile-get-location
10912 (cond (goto "Goto")
10913 (regionp "Refile region to")
10914 (t (concat "Refile subtree \""
10915 heading-text "\" to")))
10916 default-buffer
10917 (and (not (equal '(4) goto))
10918 org-refile-allow-creating-parent-nodes)
10919 goto))))))
10920 (setq file (nth 1 it)
10921 re (nth 2 it)
10922 pos (nth 3 it))
10923 (if (and (not goto)
10925 (equal (buffer-file-name) file)
10926 (if regionp
10927 (and (>= pos region-start)
10928 (<= pos region-end))
10929 (and (>= pos (point))
10930 (< pos (save-excursion
10931 (org-end-of-subtree t t))))))
10932 (error "Cannot refile to position inside the tree or region"))
10934 (setq nbuf (or (find-buffer-visiting file)
10935 (find-file-noselect file)))
10936 (if goto
10937 (progn
10938 (org-pop-to-buffer-same-window nbuf)
10939 (goto-char pos)
10940 (org-show-context 'org-goto))
10941 (if regionp
10942 (progn
10943 (org-kill-new (buffer-substring region-start region-end))
10944 (org-save-markers-in-region region-start region-end))
10945 (org-copy-subtree 1 nil t))
10946 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10947 (find-file-noselect file)))
10948 (setq reversed (org-notes-order-reversed-p))
10949 (save-excursion
10950 (save-restriction
10951 (widen)
10952 (if pos
10953 (progn
10954 (goto-char pos)
10955 (looking-at org-outline-regexp)
10956 (setq level (org-get-valid-level (funcall outline-level) 1))
10957 (goto-char
10958 (if reversed
10959 (or (outline-next-heading) (point-max))
10960 (or (save-excursion (org-get-next-sibling))
10961 (org-end-of-subtree t t)
10962 (point-max)))))
10963 (setq level 1)
10964 (if (not reversed)
10965 (goto-char (point-max))
10966 (goto-char (point-min))
10967 (or (outline-next-heading) (goto-char (point-max)))))
10968 (if (not (bolp)) (newline))
10969 (org-paste-subtree level)
10970 (when org-log-refile
10971 (org-add-log-setup 'refile nil nil 'findpos
10972 org-log-refile)
10973 (unless (eq org-log-refile 'note)
10974 (save-excursion (org-add-log-note))))
10975 (and org-auto-align-tags
10976 (let ((org-loop-over-headlines-in-active-region nil))
10977 (org-set-tags nil t)))
10978 (bookmark-set "org-refile-last-stored")
10979 ;; If we are refiling for capture, make sure that the
10980 ;; last-capture pointers point here
10981 (when (org-bound-and-true-p org-refile-for-capture)
10982 (bookmark-set "org-capture-last-stored-marker")
10983 (move-marker org-capture-last-stored-marker (point)))
10984 (if (fboundp 'deactivate-mark) (deactivate-mark))
10985 (run-hooks 'org-after-refile-insert-hook))))
10986 (if regionp
10987 (delete-region (point) (+ (point) region-length))
10988 (org-cut-subtree))
10989 (when (featurep 'org-inlinetask)
10990 (org-inlinetask-remove-END-maybe))
10991 (setq org-markers-to-move nil)
10992 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10994 (defun org-refile-goto-last-stored ()
10995 "Go to the location where the last refile was stored."
10996 (interactive)
10997 (bookmark-jump "org-refile-last-stored")
10998 (message "This is the location of the last refile"))
11000 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11001 no-exclude)
11002 "Prompt the user for a refile location, using PROMPT.
11003 PROMPT should not be suffixed with a colon and a space, because
11004 this function appends the default value from
11005 `org-refile-history' automatically, if that is not empty.
11006 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11007 this is used for the GOTO interface."
11008 (let ((org-refile-targets org-refile-targets)
11009 (org-refile-use-outline-path org-refile-use-outline-path)
11010 excluded-entries)
11011 (when (and (derived-mode-p 'org-mode)
11012 (not org-refile-use-cache)
11013 (not no-exclude))
11014 (org-map-tree
11015 (lambda()
11016 (setq excluded-entries
11017 (append excluded-entries (list (org-get-heading t t)))))))
11018 (setq org-refile-target-table
11019 (org-refile-get-targets default-buffer excluded-entries)))
11020 (unless org-refile-target-table
11021 (error "No refile targets"))
11022 (let* ((prompt (concat prompt
11023 (and (car org-refile-history)
11024 (concat " (default " (car org-refile-history) ")"))
11025 ": "))
11026 (cbuf (current-buffer))
11027 (partial-completion-mode nil)
11028 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11029 (cfunc (if (and org-refile-use-outline-path
11030 org-outline-path-complete-in-steps)
11031 'org-olpath-completing-read
11032 'org-icompleting-read))
11033 (extra (if org-refile-use-outline-path "/" ""))
11034 (filename (and cfn (expand-file-name cfn)))
11035 (tbl (mapcar
11036 (lambda (x)
11037 (if (and (not (member org-refile-use-outline-path
11038 '(file full-file-path)))
11039 (not (equal filename (nth 1 x))))
11040 (cons (concat (car x) extra " ("
11041 (file-name-nondirectory (nth 1 x)) ")")
11042 (cdr x))
11043 (cons (concat (car x) extra) (cdr x))))
11044 org-refile-target-table))
11045 (completion-ignore-case t)
11046 pa answ parent-target child parent old-hist)
11047 (setq old-hist org-refile-history)
11048 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11049 nil 'org-refile-history (car org-refile-history)))
11050 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11051 (org-refile-check-position pa)
11052 (if pa
11053 (progn
11054 (when (or (not org-refile-history)
11055 (not (eq old-hist org-refile-history))
11056 (not (equal (car pa) (car org-refile-history))))
11057 (setq org-refile-history
11058 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11059 org-refile-history
11060 (cdr org-refile-history))))
11061 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11062 (pop org-refile-history)))
11064 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11065 (progn
11066 (setq parent (match-string 1 answ)
11067 child (match-string 2 answ))
11068 (setq parent-target (or (assoc parent tbl)
11069 (assoc (concat parent "/") tbl)))
11070 (when (and parent-target
11071 (or (eq new-nodes t)
11072 (and (eq new-nodes 'confirm)
11073 (y-or-n-p (format "Create new node \"%s\"? "
11074 child)))))
11075 (org-refile-new-child parent-target child)))
11076 (error "Invalid target location")))))
11078 (declare-function org-string-nw-p "org-macs.el" (s))
11079 (defun org-refile-check-position (refile-pointer)
11080 "Check if the refile pointer matches the readline to which it points."
11081 (let* ((file (nth 1 refile-pointer))
11082 (re (nth 2 refile-pointer))
11083 (pos (nth 3 refile-pointer))
11084 buffer)
11085 (when (org-string-nw-p re)
11086 (setq buffer (if (markerp pos)
11087 (marker-buffer pos)
11088 (or (find-buffer-visiting file)
11089 (find-file-noselect file))))
11090 (with-current-buffer buffer
11091 (save-excursion
11092 (save-restriction
11093 (widen)
11094 (goto-char pos)
11095 (beginning-of-line 1)
11096 (unless (org-looking-at-p re)
11097 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11099 (defun org-refile-new-child (parent-target child)
11100 "Use refile target PARENT-TARGET to add new CHILD below it."
11101 (unless parent-target
11102 (error "Cannot find parent for new node"))
11103 (let ((file (nth 1 parent-target))
11104 (pos (nth 3 parent-target))
11105 level)
11106 (with-current-buffer (or (find-buffer-visiting file)
11107 (find-file-noselect file))
11108 (save-excursion
11109 (save-restriction
11110 (widen)
11111 (if pos
11112 (goto-char pos)
11113 (goto-char (point-max))
11114 (if (not (bolp)) (newline)))
11115 (when (looking-at org-outline-regexp)
11116 (setq level (funcall outline-level))
11117 (org-end-of-subtree t t))
11118 (org-back-over-empty-lines)
11119 (insert "\n" (make-string
11120 (if pos (org-get-valid-level level 1) 1) ?*)
11121 " " child "\n")
11122 (beginning-of-line 0)
11123 (list (concat (car parent-target) "/" child) file "" (point)))))))
11125 (defun org-olpath-completing-read (prompt collection &rest args)
11126 "Read an outline path like a file name."
11127 (let ((thetable collection)
11128 (org-completion-use-ido nil) ; does not work with ido.
11129 (org-completion-use-iswitchb nil)) ; or iswitchb
11130 (apply
11131 'org-icompleting-read prompt
11132 (lambda (string predicate &optional flag)
11133 (let (rtn r f (l (length string)))
11134 (cond
11135 ((eq flag nil)
11136 ;; try completion
11137 (try-completion string thetable))
11138 ((eq flag t)
11139 ;; all-completions
11140 (setq rtn (all-completions string thetable predicate))
11141 (mapcar
11142 (lambda (x)
11143 (setq r (substring x l))
11144 (if (string-match " ([^)]*)$" x)
11145 (setq f (match-string 0 x))
11146 (setq f ""))
11147 (if (string-match "/" r)
11148 (concat string (substring r 0 (match-end 0)) f)
11150 rtn))
11151 ((eq flag 'lambda)
11152 ;; exact match?
11153 (assoc string thetable)))))
11154 args)))
11156 ;;;; Dynamic blocks
11158 (defun org-find-dblock (name)
11159 "Find the first dynamic block with name NAME in the buffer.
11160 If not found, stay at current position and return nil."
11161 (let (pos)
11162 (save-excursion
11163 (goto-char (point-min))
11164 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11165 nil t)
11166 (match-beginning 0))))
11167 (if pos (goto-char pos))
11168 pos))
11170 (defconst org-dblock-start-re
11171 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11172 "Matches the start line of a dynamic block, with parameters.")
11174 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11175 "Matches the end of a dynamic block.")
11177 (defun org-create-dblock (plist)
11178 "Create a dynamic block section, with parameters taken from PLIST.
11179 PLIST must contain a :name entry which is used as name of the block."
11180 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11181 (end-of-line 1)
11182 (newline))
11183 (let ((col (current-column))
11184 (name (plist-get plist :name)))
11185 (insert "#+BEGIN: " name)
11186 (while plist
11187 (if (eq (car plist) :name)
11188 (setq plist (cddr plist))
11189 (insert " " (prin1-to-string (pop plist)))))
11190 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11191 (beginning-of-line -2)))
11193 (defun org-prepare-dblock ()
11194 "Prepare dynamic block for refresh.
11195 This empties the block, puts the cursor at the insert position and returns
11196 the property list including an extra property :name with the block name."
11197 (unless (looking-at org-dblock-start-re)
11198 (error "Not at a dynamic block"))
11199 (let* ((begdel (1+ (match-end 0)))
11200 (name (org-no-properties (match-string 1)))
11201 (params (append (list :name name)
11202 (read (concat "(" (match-string 3) ")")))))
11203 (save-excursion
11204 (beginning-of-line 1)
11205 (skip-chars-forward " \t")
11206 (setq params (plist-put params :indentation-column (current-column))))
11207 (unless (re-search-forward org-dblock-end-re nil t)
11208 (error "Dynamic block not terminated"))
11209 (setq params
11210 (append params
11211 (list :content (buffer-substring
11212 begdel (match-beginning 0)))))
11213 (delete-region begdel (match-beginning 0))
11214 (goto-char begdel)
11215 (open-line 1)
11216 params))
11218 (defun org-map-dblocks (&optional command)
11219 "Apply COMMAND to all dynamic blocks in the current buffer.
11220 If COMMAND is not given, use `org-update-dblock'."
11221 (let ((cmd (or command 'org-update-dblock)))
11222 (save-excursion
11223 (goto-char (point-min))
11224 (while (re-search-forward org-dblock-start-re nil t)
11225 (goto-char (match-beginning 0))
11226 (save-excursion
11227 (condition-case nil
11228 (funcall cmd)
11229 (error (message "Error during update of dynamic block"))))
11230 (unless (re-search-forward org-dblock-end-re nil t)
11231 (error "Dynamic block not terminated"))))))
11233 (defun org-dblock-update (&optional arg)
11234 "User command for updating dynamic blocks.
11235 Update the dynamic block at point. With prefix ARG, update all dynamic
11236 blocks in the buffer."
11237 (interactive "P")
11238 (if arg
11239 (org-update-all-dblocks)
11240 (or (looking-at org-dblock-start-re)
11241 (org-beginning-of-dblock))
11242 (org-update-dblock)))
11244 (defun org-update-dblock ()
11245 "Update the dynamic block at point.
11246 This means to empty the block, parse for parameters and then call
11247 the correct writing function."
11248 (interactive)
11249 (save-window-excursion
11250 (let* ((pos (point))
11251 (line (org-current-line))
11252 (params (org-prepare-dblock))
11253 (name (plist-get params :name))
11254 (indent (plist-get params :indentation-column))
11255 (cmd (intern (concat "org-dblock-write:" name))))
11256 (message "Updating dynamic block `%s' at line %d..." name line)
11257 (funcall cmd params)
11258 (message "Updating dynamic block `%s' at line %d...done" name line)
11259 (goto-char pos)
11260 (when (and indent (> indent 0))
11261 (setq indent (make-string indent ?\ ))
11262 (save-excursion
11263 (org-beginning-of-dblock)
11264 (forward-line 1)
11265 (while (not (looking-at org-dblock-end-re))
11266 (insert indent)
11267 (beginning-of-line 2))
11268 (when (looking-at org-dblock-end-re)
11269 (and (looking-at "[ \t]+")
11270 (replace-match ""))
11271 (insert indent)))))))
11273 (defun org-beginning-of-dblock ()
11274 "Find the beginning of the dynamic block at point.
11275 Error if there is no such block at point."
11276 (let ((pos (point))
11277 beg)
11278 (end-of-line 1)
11279 (if (and (re-search-backward org-dblock-start-re nil t)
11280 (setq beg (match-beginning 0))
11281 (re-search-forward org-dblock-end-re nil t)
11282 (> (match-end 0) pos))
11283 (goto-char beg)
11284 (goto-char pos)
11285 (error "Not in a dynamic block"))))
11287 ;;;###autoload
11288 (defun org-update-all-dblocks ()
11289 "Update all dynamic blocks in the buffer.
11290 This function can be used in a hook."
11291 (interactive)
11292 (when (derived-mode-p 'org-mode)
11293 (org-map-dblocks 'org-update-dblock)))
11296 ;;;; Completion
11298 (defconst org-additional-option-like-keywords
11299 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11300 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11301 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11302 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11303 "BEGIN:" "END:"
11304 "ORGTBL" "TBLFM:" "TBLNAME:"
11305 "BEGIN_EXAMPLE" "END_EXAMPLE"
11306 "BEGIN_VERBATIM" "END_VERBATIM"
11307 "BEGIN_QUOTE" "END_QUOTE"
11308 "BEGIN_VERSE" "END_VERSE"
11309 "BEGIN_CENTER" "END_CENTER"
11310 "BEGIN_SRC" "END_SRC"
11311 "BEGIN_RESULT" "END_RESULT"
11312 "BEGIN_lstlisting" "END_lstlisting"
11313 "NAME:" "RESULTS:"
11314 "HEADER:" "HEADERS:"
11315 "COLUMNS:" "PROPERTY:"
11316 "CAPTION:" "LABEL:"
11317 "SETUPFILE:"
11318 "INCLUDE:"
11319 "BIND:"
11320 "MACRO:"))
11322 (defconst org-options-keywords
11323 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11324 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11325 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11326 "LINK_UP:" "LINK_HOME:" "LINK:"
11327 "XSLT:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11328 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11329 "FILETAGS:" "ARCHIVE:"))
11331 (defconst org-additional-option-like-keywords-for-flyspell
11332 (delete-dups
11333 (split-string
11334 (mapconcat (lambda(k)
11335 (replace-regexp-in-string
11336 "_\\|:" " "
11337 (concat k " " (downcase k) " " (upcase k))))
11338 (append org-options-keywords org-additional-option-like-keywords)
11339 " ")
11340 " +" t)))
11342 (defcustom org-structure-template-alist
11344 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11345 "<src lang=\"?\">\n\n</src>")
11346 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11347 "<example>\n?\n</example>")
11348 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11349 "<quote>\n?\n</quote>")
11350 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11351 "<verse>\n?\n</verse>")
11352 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11353 "<center>\n?\n</center>")
11354 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11355 "<literal style=\"latex\">\n?\n</literal>")
11356 ("L" "#+LaTeX: "
11357 "<literal style=\"latex\">?</literal>")
11358 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11359 "<literal style=\"html\">\n?\n</literal>")
11360 ("H" "#+HTML: "
11361 "<literal style=\"html\">?</literal>")
11362 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11363 ("A" "#+ASCII: ")
11364 ("i" "#+INDEX: ?"
11365 "#+INDEX: ?")
11366 ("I" "#+INCLUDE %file ?"
11367 "<include file=%file markup=\"?\">")
11369 "Structure completion elements.
11370 This is a list of abbreviation keys and values. The value gets inserted
11371 if you type `<' followed by the key and then press the completion key,
11372 usually `M-TAB'. %file will be replaced by a file name after prompting
11373 for the file using completion. The cursor will be placed at the position
11374 of the `?` in the template.
11375 There are two templates for each key, the first uses the original Org syntax,
11376 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11377 the default when the /org-mtags.el/ module has been loaded. See also the
11378 variable `org-mtags-prefer-muse-templates'."
11379 :group 'org-completion
11380 :type '(repeat
11381 (string :tag "Key")
11382 (string :tag "Template")
11383 (string :tag "Muse Template")))
11385 (defun org-try-structure-completion ()
11386 "Try to complete a structure template before point.
11387 This looks for strings like \"<e\" on an otherwise empty line and
11388 expands them."
11389 (let ((l (buffer-substring (point-at-bol) (point)))
11391 (when (and (looking-at "[ \t]*$")
11392 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11393 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11394 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11395 (match-beginning 1)) a)
11396 t)))
11398 (defun org-complete-expand-structure-template (start cell)
11399 "Expand a structure template."
11400 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11401 (rpl (nth (if musep 2 1) cell))
11402 (ind ""))
11403 (delete-region start (point))
11404 (when (string-match "\\`#\\+" rpl)
11405 (cond
11406 ((bolp))
11407 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11408 (setq ind (buffer-substring (point-at-bol) (point))))
11409 (t (newline))))
11410 (setq start (point))
11411 (if (string-match "%file" rpl)
11412 (setq rpl (replace-match
11413 (concat
11414 "\""
11415 (save-match-data
11416 (abbreviate-file-name (read-file-name "Include file: ")))
11417 "\"")
11418 t t rpl)))
11419 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11420 (concat "\n" ind)))
11421 (insert rpl)
11422 (if (re-search-backward "\\?" start t) (delete-char 1))))
11424 ;;;; TODO, DEADLINE, Comments
11426 (defun org-toggle-comment ()
11427 "Change the COMMENT state of an entry."
11428 (interactive)
11429 (save-excursion
11430 (org-back-to-heading)
11431 (let (case-fold-search)
11432 (cond
11433 ((looking-at (format org-heading-keyword-regexp-format
11434 org-comment-string))
11435 (goto-char (match-end 1))
11436 (looking-at (concat " +" org-comment-string))
11437 (replace-match "" t t)
11438 (when (eolp) (insert " ")))
11439 ((looking-at org-outline-regexp)
11440 (goto-char (match-end 0))
11441 (insert org-comment-string " "))))))
11443 (defvar org-last-todo-state-is-todo nil
11444 "This is non-nil when the last TODO state change led to a TODO state.
11445 If the last change removed the TODO tag or switched to DONE, then
11446 this is nil.")
11448 (defvar org-setting-tags nil) ; dynamically skipped
11450 (defvar org-todo-setup-filter-hook nil
11451 "Hook for functions that pre-filter todo specs.
11452 Each function takes a todo spec and returns either nil or the spec
11453 transformed into canonical form." )
11455 (defvar org-todo-get-default-hook nil
11456 "Hook for functions that get a default item for todo.
11457 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11458 nil or a string to be used for the todo mark." )
11460 (defvar org-agenda-headline-snapshot-before-repeat)
11462 (defun org-current-effective-time ()
11463 "Return current time adjusted for `org-extend-today-until' variable."
11464 (let* ((ct (org-current-time))
11465 (dct (decode-time ct))
11466 (ct1
11467 (if (and org-use-effective-time
11468 (< (nth 2 dct) org-extend-today-until))
11469 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11470 ct)))
11471 ct1))
11473 (defun org-todo-yesterday (&optional arg)
11474 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11475 (interactive "P")
11476 (if (eq major-mode 'org-agenda-mode)
11477 (apply 'org-agenda-todo-yesterday arg)
11478 (let* ((hour (third (decode-time
11479 (org-current-time))))
11480 (org-extend-today-until (1+ hour)))
11481 (org-todo arg))))
11483 (defun org-todo (&optional arg)
11484 "Change the TODO state of an item.
11485 The state of an item is given by a keyword at the start of the heading,
11486 like
11487 *** TODO Write paper
11488 *** DONE Call mom
11490 The different keywords are specified in the variable `org-todo-keywords'.
11491 By default the available states are \"TODO\" and \"DONE\".
11492 So for this example: when the item starts with TODO, it is changed to DONE.
11493 When it starts with DONE, the DONE is removed. And when neither TODO nor
11494 DONE are present, add TODO at the beginning of the heading.
11496 With \\[universal-argument] prefix arg, use completion to determine the new \
11497 state.
11498 With numeric prefix arg, switch to that state.
11499 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11500 keywords (nextset).
11501 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11502 With a numeric prefix arg of 0, inhibit note taking for the change.
11504 For calling through lisp, arg is also interpreted in the following way:
11505 'none -> empty state
11506 \"\"(empty string) -> switch to empty state
11507 'done -> switch to DONE
11508 'nextset -> switch to the next set of keywords
11509 'previousset -> switch to the previous set of keywords
11510 \"WAITING\" -> switch to the specified keyword, but only if it
11511 really is a member of `org-todo-keywords'."
11512 (interactive "P")
11513 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11514 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11515 'region-start-level 'region))
11516 org-loop-over-headlines-in-active-region)
11517 (org-map-entries
11518 `(org-todo ,arg)
11519 org-loop-over-headlines-in-active-region
11520 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11521 (if (equal arg '(16)) (setq arg 'nextset))
11522 (let ((org-blocker-hook org-blocker-hook)
11523 (case-fold-search nil))
11524 (when (equal arg '(64))
11525 (setq arg nil org-blocker-hook nil))
11526 (when (and org-blocker-hook
11527 (or org-inhibit-blocking
11528 (org-entry-get nil "NOBLOCKING")))
11529 (setq org-blocker-hook nil))
11530 (save-excursion
11531 (catch 'exit
11532 (org-back-to-heading t)
11533 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11534 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11535 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11536 (let* ((match-data (match-data))
11537 (startpos (point-at-bol))
11538 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11539 (org-log-done org-log-done)
11540 (org-log-repeat org-log-repeat)
11541 (org-todo-log-states org-todo-log-states)
11542 (org-inhibit-logging
11543 (if (equal arg 0)
11544 (progn (setq arg nil) 'note) org-inhibit-logging))
11545 (this (match-string 1))
11546 (hl-pos (match-beginning 0))
11547 (head (org-get-todo-sequence-head this))
11548 (ass (assoc head org-todo-kwd-alist))
11549 (interpret (nth 1 ass))
11550 (done-word (nth 3 ass))
11551 (final-done-word (nth 4 ass))
11552 (org-last-state (or this ""))
11553 (completion-ignore-case t)
11554 (member (member this org-todo-keywords-1))
11555 (tail (cdr member))
11556 (org-state (cond
11557 ((and org-todo-key-trigger
11558 (or (and (equal arg '(4))
11559 (eq org-use-fast-todo-selection 'prefix))
11560 (and (not arg) org-use-fast-todo-selection
11561 (not (eq org-use-fast-todo-selection
11562 'prefix)))))
11563 ;; Use fast selection
11564 (org-fast-todo-selection))
11565 ((and (equal arg '(4))
11566 (or (not org-use-fast-todo-selection)
11567 (not org-todo-key-trigger)))
11568 ;; Read a state with completion
11569 (org-icompleting-read
11570 "State: " (mapcar (lambda(x) (list x))
11571 org-todo-keywords-1)
11572 nil t))
11573 ((eq arg 'right)
11574 (if this
11575 (if tail (car tail) nil)
11576 (car org-todo-keywords-1)))
11577 ((eq arg 'left)
11578 (if (equal member org-todo-keywords-1)
11580 (if this
11581 (nth (- (length org-todo-keywords-1)
11582 (length tail) 2)
11583 org-todo-keywords-1)
11584 (org-last org-todo-keywords-1))))
11585 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11586 (setq arg nil))) ; hack to fall back to cycling
11587 (arg
11588 ;; user or caller requests a specific state
11589 (cond
11590 ((equal arg "") nil)
11591 ((eq arg 'none) nil)
11592 ((eq arg 'done) (or done-word (car org-done-keywords)))
11593 ((eq arg 'nextset)
11594 (or (car (cdr (member head org-todo-heads)))
11595 (car org-todo-heads)))
11596 ((eq arg 'previousset)
11597 (let ((org-todo-heads (reverse org-todo-heads)))
11598 (or (car (cdr (member head org-todo-heads)))
11599 (car org-todo-heads))))
11600 ((car (member arg org-todo-keywords-1)))
11601 ((stringp arg)
11602 (error "State `%s' not valid in this file" arg))
11603 ((nth (1- (prefix-numeric-value arg))
11604 org-todo-keywords-1))))
11605 ((null member) (or head (car org-todo-keywords-1)))
11606 ((equal this final-done-word) nil) ;; -> make empty
11607 ((null tail) nil) ;; -> first entry
11608 ((memq interpret '(type priority))
11609 (if (eq this-command last-command)
11610 (car tail)
11611 (if (> (length tail) 0)
11612 (or done-word (car org-done-keywords))
11613 nil)))
11615 (car tail))))
11616 (org-state (or
11617 (run-hook-with-args-until-success
11618 'org-todo-get-default-hook org-state org-last-state)
11619 org-state))
11620 (next (if org-state (concat " " org-state " ") " "))
11621 (change-plist (list :type 'todo-state-change :from this :to org-state
11622 :position startpos))
11623 dolog now-done-p)
11624 (when org-blocker-hook
11625 (setq org-last-todo-state-is-todo
11626 (not (member this org-done-keywords)))
11627 (unless (save-excursion
11628 (save-match-data
11629 (org-with-wide-buffer
11630 (run-hook-with-args-until-failure
11631 'org-blocker-hook change-plist))))
11632 (if (org-called-interactively-p 'interactive)
11633 (error "TODO state change from %s to %s blocked" this org-state)
11634 ;; fail silently
11635 (message "TODO state change from %s to %s blocked" this org-state)
11636 (throw 'exit nil))))
11637 (store-match-data match-data)
11638 (replace-match next t t)
11639 (unless (pos-visible-in-window-p hl-pos)
11640 (message "TODO state changed to %s" (org-trim next)))
11641 (unless head
11642 (setq head (org-get-todo-sequence-head org-state)
11643 ass (assoc head org-todo-kwd-alist)
11644 interpret (nth 1 ass)
11645 done-word (nth 3 ass)
11646 final-done-word (nth 4 ass)))
11647 (when (memq arg '(nextset previousset))
11648 (message "Keyword-Set %d/%d: %s"
11649 (- (length org-todo-sets) -1
11650 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11651 (length org-todo-sets)
11652 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11653 (setq org-last-todo-state-is-todo
11654 (not (member org-state org-done-keywords)))
11655 (setq now-done-p (and (member org-state org-done-keywords)
11656 (not (member this org-done-keywords))))
11657 (and logging (org-local-logging logging))
11658 (when (and (or org-todo-log-states org-log-done)
11659 (not (eq org-inhibit-logging t))
11660 (not (memq arg '(nextset previousset))))
11661 ;; we need to look at recording a time and note
11662 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11663 (nth 2 (assoc this org-todo-log-states))))
11664 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11665 (setq dolog 'time))
11666 (when (and org-state
11667 (member org-state org-not-done-keywords)
11668 (not (member this org-not-done-keywords)))
11669 ;; This is now a todo state and was not one before
11670 ;; If there was a CLOSED time stamp, get rid of it.
11671 (org-add-planning-info nil nil 'closed))
11672 (when (and now-done-p org-log-done)
11673 ;; It is now done, and it was not done before
11674 (org-add-planning-info 'closed (org-current-effective-time))
11675 (if (and (not dolog) (eq 'note org-log-done))
11676 (org-add-log-setup 'done org-state this 'findpos 'note)))
11677 (when (and org-state dolog)
11678 ;; This is a non-nil state, and we need to log it
11679 (org-add-log-setup 'state org-state this 'findpos dolog)))
11680 ;; Fixup tag positioning
11681 (org-todo-trigger-tag-changes org-state)
11682 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11683 (when org-provide-todo-statistics
11684 (org-update-parent-todo-statistics))
11685 (run-hooks 'org-after-todo-state-change-hook)
11686 (if (and arg (not (member org-state org-done-keywords)))
11687 (setq head (org-get-todo-sequence-head org-state)))
11688 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11689 ;; Do we need to trigger a repeat?
11690 (when now-done-p
11691 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11692 ;; This is for the agenda, take a snapshot of the headline.
11693 (save-match-data
11694 (setq org-agenda-headline-snapshot-before-repeat
11695 (org-get-heading))))
11696 (org-auto-repeat-maybe org-state))
11697 ;; Fixup cursor location if close to the keyword
11698 (if (and (outline-on-heading-p)
11699 (not (bolp))
11700 (save-excursion (beginning-of-line 1)
11701 (looking-at org-todo-line-regexp))
11702 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11703 (progn
11704 (goto-char (or (match-end 2) (match-end 1)))
11705 (and (looking-at " ") (just-one-space))))
11706 (when org-trigger-hook
11707 (save-excursion
11708 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11710 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11711 "Block turning an entry into a TODO, using the hierarchy.
11712 This checks whether the current task should be blocked from state
11713 changes. Such blocking occurs when:
11715 1. The task has children which are not all in a completed state.
11717 2. A task has a parent with the property :ORDERED:, and there
11718 are siblings prior to the current task with incomplete
11719 status.
11721 3. The parent of the task is blocked because it has siblings that should
11722 be done first, or is child of a block grandparent TODO entry."
11724 (if (not org-enforce-todo-dependencies)
11725 t ; if locally turned off don't block
11726 (catch 'dont-block
11727 ;; If this is not a todo state change, or if this entry is already DONE,
11728 ;; do not block
11729 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11730 (member (plist-get change-plist :from)
11731 (cons 'done org-done-keywords))
11732 (member (plist-get change-plist :to)
11733 (cons 'todo org-not-done-keywords))
11734 (not (plist-get change-plist :to)))
11735 (throw 'dont-block t))
11736 ;; If this task has children, and any are undone, it's blocked
11737 (save-excursion
11738 (org-back-to-heading t)
11739 (let ((this-level (funcall outline-level)))
11740 (outline-next-heading)
11741 (let ((child-level (funcall outline-level)))
11742 (while (and (not (eobp))
11743 (> child-level this-level))
11744 ;; this todo has children, check whether they are all
11745 ;; completed
11746 (if (and (not (org-entry-is-done-p))
11747 (org-entry-is-todo-p))
11748 (throw 'dont-block nil))
11749 (outline-next-heading)
11750 (setq child-level (funcall outline-level))))))
11751 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11752 ;; any previous siblings are undone, it's blocked
11753 (save-excursion
11754 (org-back-to-heading t)
11755 (let* ((pos (point))
11756 (parent-pos (and (org-up-heading-safe) (point))))
11757 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11758 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11759 (forward-line 1)
11760 (re-search-forward org-not-done-heading-regexp pos t))
11761 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11762 ;; Search further up the hierarchy, to see if an ancestor is blocked
11763 (while t
11764 (goto-char parent-pos)
11765 (if (not (looking-at org-not-done-heading-regexp))
11766 (throw 'dont-block t)) ; do not block, parent is not a TODO
11767 (setq pos (point))
11768 (setq parent-pos (and (org-up-heading-safe) (point)))
11769 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11770 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11771 (forward-line 1)
11772 (re-search-forward org-not-done-heading-regexp pos t))
11773 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11775 (defcustom org-track-ordered-property-with-tag nil
11776 "Should the ORDERED property also be shown as a tag?
11777 The ORDERED property decides if an entry should require subtasks to be
11778 completed in sequence. Since a property is not very visible, setting
11779 this option means that toggling the ORDERED property with the command
11780 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11781 not relevant for the behavior, but it makes things more visible.
11783 Note that toggling the tag with tags commands will not change the property
11784 and therefore not influence behavior!
11786 This can be t, meaning the tag ORDERED should be used, It can also be a
11787 string to select a different tag for this task."
11788 :group 'org-todo
11789 :type '(choice
11790 (const :tag "No tracking" nil)
11791 (const :tag "Track with ORDERED tag" t)
11792 (string :tag "Use other tag")))
11794 (defun org-toggle-ordered-property ()
11795 "Toggle the ORDERED property of the current entry.
11796 For better visibility, you can track the value of this property with a tag.
11797 See variable `org-track-ordered-property-with-tag'."
11798 (interactive)
11799 (let* ((t1 org-track-ordered-property-with-tag)
11800 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11801 (save-excursion
11802 (org-back-to-heading)
11803 (if (org-entry-get nil "ORDERED")
11804 (progn
11805 (org-delete-property "ORDERED")
11806 (and tag (org-toggle-tag tag 'off))
11807 (message "Subtasks can be completed in arbitrary order"))
11808 (org-entry-put nil "ORDERED" "t")
11809 (and tag (org-toggle-tag tag 'on))
11810 (message "Subtasks must be completed in sequence")))))
11812 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11813 (defun org-block-todo-from-checkboxes (change-plist)
11814 "Block turning an entry into a TODO, using checkboxes.
11815 This checks whether the current task should be blocked from state
11816 changes because there are unchecked boxes in this entry."
11817 (if (not org-enforce-todo-checkbox-dependencies)
11818 t ; if locally turned off don't block
11819 (catch 'dont-block
11820 ;; If this is not a todo state change, or if this entry is already DONE,
11821 ;; do not block
11822 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11823 (member (plist-get change-plist :from)
11824 (cons 'done org-done-keywords))
11825 (member (plist-get change-plist :to)
11826 (cons 'todo org-not-done-keywords))
11827 (not (plist-get change-plist :to)))
11828 (throw 'dont-block t))
11829 ;; If this task has checkboxes that are not checked, it's blocked
11830 (save-excursion
11831 (org-back-to-heading t)
11832 (let ((beg (point)) end)
11833 (outline-next-heading)
11834 (setq end (point))
11835 (goto-char beg)
11836 (if (org-list-search-forward
11837 (concat (org-item-beginning-re)
11838 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11839 "\\[[- ]\\]")
11840 end t)
11841 (progn
11842 (if (boundp 'org-blocked-by-checkboxes)
11843 (setq org-blocked-by-checkboxes t))
11844 (throw 'dont-block nil)))))
11845 t))) ; do not block
11847 (defun org-entry-blocked-p ()
11848 "Is the current entry blocked?"
11849 (if (org-entry-get nil "NOBLOCKING")
11850 nil ;; Never block this entry
11851 (not
11852 (run-hook-with-args-until-failure
11853 'org-blocker-hook
11854 (list :type 'todo-state-change
11855 :position (point)
11856 :from 'todo
11857 :to 'done)))))
11859 (defun org-update-statistics-cookies (all)
11860 "Update the statistics cookie, either from TODO or from checkboxes.
11861 This should be called with the cursor in a line with a statistics cookie."
11862 (interactive "P")
11863 (if all
11864 (progn
11865 (org-update-checkbox-count 'all)
11866 (org-map-entries 'org-update-parent-todo-statistics))
11867 (if (not (org-at-heading-p))
11868 (org-update-checkbox-count)
11869 (let ((pos (move-marker (make-marker) (point)))
11870 end l1 l2)
11871 (ignore-errors (org-back-to-heading t))
11872 (if (not (org-at-heading-p))
11873 (org-update-checkbox-count)
11874 (setq l1 (org-outline-level))
11875 (setq end (save-excursion
11876 (outline-next-heading)
11877 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11878 (point)))
11879 (if (and (save-excursion
11880 (re-search-forward
11881 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11882 (not (save-excursion (re-search-forward
11883 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11884 (org-update-checkbox-count)
11885 (if (and l2 (> l2 l1))
11886 (progn
11887 (goto-char end)
11888 (org-update-parent-todo-statistics))
11889 (goto-char pos)
11890 (beginning-of-line 1)
11891 (while (re-search-forward
11892 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11893 (point-at-eol) t)
11894 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11895 (goto-char pos)
11896 (move-marker pos nil)))))
11898 (defvar org-entry-property-inherited-from) ;; defined below
11899 (defun org-update-parent-todo-statistics ()
11900 "Update any statistics cookie in the parent of the current headline.
11901 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11902 the entire subtree and this will travel up the hierarchy and update
11903 statistics everywhere."
11904 (let* ((prop (save-excursion (org-up-heading-safe)
11905 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11906 (recursive (or (not org-hierarchical-todo-statistics)
11907 (and prop (string-match "\\<recursive\\>" prop))))
11908 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11910 (first t)
11911 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11912 level ltoggle l1 new ndel
11913 (cnt-all 0) (cnt-done 0) is-percent kwd
11914 checkbox-beg ov ovs ove cookie-present)
11915 (catch 'exit
11916 (save-excursion
11917 (beginning-of-line 1)
11918 (setq ltoggle (funcall outline-level))
11919 ;; Three situations are to consider:
11921 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11922 ;; to the top-level ancestor on the headline;
11924 ;; 2. If parent has "recursive" property, repeat up to the
11925 ;; headline setting that property, taking inheritance into
11926 ;; account;
11928 ;; 3. Else, move up to direct parent and proceed only once.
11929 (while (and (setq level (org-up-heading-safe))
11930 (or recursive first)
11931 (>= (point) lim))
11932 (setq first nil cookie-present nil)
11933 (unless (and level
11934 (not (string-match
11935 "\\<checkbox\\>"
11936 (downcase (or (org-entry-get nil "COOKIE_DATA")
11937 "")))))
11938 (throw 'exit nil))
11939 (while (re-search-forward box-re (point-at-eol) t)
11940 (setq cnt-all 0 cnt-done 0 cookie-present t)
11941 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11942 (save-match-data
11943 (unless (outline-next-heading) (throw 'exit nil))
11944 (while (and (looking-at org-complex-heading-regexp)
11945 (> (setq l1 (length (match-string 1))) level))
11946 (setq kwd (and (or recursive (= l1 ltoggle))
11947 (match-string 2)))
11948 (if (or (eq org-provide-todo-statistics 'all-headlines)
11949 (and (listp org-provide-todo-statistics)
11950 (or (member kwd org-provide-todo-statistics)
11951 (member kwd org-done-keywords))))
11952 (setq cnt-all (1+ cnt-all))
11953 (if (eq org-provide-todo-statistics t)
11954 (and kwd (setq cnt-all (1+ cnt-all)))))
11955 (and (member kwd org-done-keywords)
11956 (setq cnt-done (1+ cnt-done)))
11957 (outline-next-heading)))
11958 (setq new
11959 (if is-percent
11960 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11961 (format "[%d/%d]" cnt-done cnt-all))
11962 ndel (- (match-end 0) checkbox-beg))
11963 ;; handle overlays when updating cookie from column view
11964 (when (setq ov (car (overlays-at checkbox-beg)))
11965 (setq ovs (overlay-start ov) ove (overlay-end ov))
11966 (delete-overlay ov))
11967 (goto-char checkbox-beg)
11968 (insert new)
11969 (delete-region (point) (+ (point) ndel))
11970 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11971 (when ov (move-overlay ov ovs ove)))
11972 (when cookie-present
11973 (run-hook-with-args 'org-after-todo-statistics-hook
11974 cnt-done (- cnt-all cnt-done))))))
11975 (run-hooks 'org-todo-statistics-hook)))
11977 (defvar org-after-todo-statistics-hook nil
11978 "Hook that is called after a TODO statistics cookie has been updated.
11979 Each function is called with two arguments: the number of not-done entries
11980 and the number of done entries.
11982 For example, the following function, when added to this hook, will switch
11983 an entry to DONE when all children are done, and back to TODO when new
11984 entries are set to a TODO status. Note that this hook is only called
11985 when there is a statistics cookie in the headline!
11987 (defun org-summary-todo (n-done n-not-done)
11988 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11989 (let (org-log-done org-log-states) ; turn off logging
11990 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11993 (defvar org-todo-statistics-hook nil
11994 "Hook that is run whenever Org thinks TODO statistics should be updated.
11995 This hook runs even if there is no statistics cookie present, in which case
11996 `org-after-todo-statistics-hook' would not run.")
11998 (defun org-todo-trigger-tag-changes (state)
11999 "Apply the changes defined in `org-todo-state-tags-triggers'."
12000 (let ((l org-todo-state-tags-triggers)
12001 changes)
12002 (when (or (not state) (equal state ""))
12003 (setq changes (append changes (cdr (assoc "" l)))))
12004 (when (and (stringp state) (> (length state) 0))
12005 (setq changes (append changes (cdr (assoc state l)))))
12006 (when (member state org-not-done-keywords)
12007 (setq changes (append changes (cdr (assoc 'todo l)))))
12008 (when (member state org-done-keywords)
12009 (setq changes (append changes (cdr (assoc 'done l)))))
12010 (dolist (c changes)
12011 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12013 (defun org-local-logging (value)
12014 "Get logging settings from a property VALUE."
12015 (let* (words w a)
12016 ;; directly set the variables, they are already local.
12017 (setq org-log-done nil
12018 org-log-repeat nil
12019 org-todo-log-states nil)
12020 (setq words (org-split-string value))
12021 (while (setq w (pop words))
12022 (cond
12023 ((setq a (assoc w org-startup-options))
12024 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12025 (set (nth 1 a) (nth 2 a))))
12026 ((setq a (org-extract-log-state-settings w))
12027 (and (member (car a) org-todo-keywords-1)
12028 (push a org-todo-log-states)))))))
12030 (defun org-get-todo-sequence-head (kwd)
12031 "Return the head of the TODO sequence to which KWD belongs.
12032 If KWD is not set, check if there is a text property remembering the
12033 right sequence."
12034 (let (p)
12035 (cond
12036 ((not kwd)
12037 (or (get-text-property (point-at-bol) 'org-todo-head)
12038 (progn
12039 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12040 nil (point-at-eol)))
12041 (get-text-property p 'org-todo-head))))
12042 ((not (member kwd org-todo-keywords-1))
12043 (car org-todo-keywords-1))
12044 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12046 (defun org-fast-todo-selection ()
12047 "Fast TODO keyword selection with single keys.
12048 Returns the new TODO keyword, or nil if no state change should occur."
12049 (let* ((fulltable org-todo-key-alist)
12050 (done-keywords org-done-keywords) ;; needed for the faces.
12051 (maxlen (apply 'max (mapcar
12052 (lambda (x)
12053 (if (stringp (car x)) (string-width (car x)) 0))
12054 fulltable)))
12055 (expert nil)
12056 (fwidth (+ maxlen 3 1 3))
12057 (ncol (/ (- (window-width) 4) fwidth))
12058 tg cnt e c tbl
12059 groups ingroup)
12060 (save-excursion
12061 (save-window-excursion
12062 (if expert
12063 (set-buffer (get-buffer-create " *Org todo*"))
12064 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12065 (erase-buffer)
12066 (org-set-local 'org-done-keywords done-keywords)
12067 (setq tbl fulltable cnt 0)
12068 (while (setq e (pop tbl))
12069 (cond
12070 ((equal e '(:startgroup))
12071 (push '() groups) (setq ingroup t)
12072 (when (not (= cnt 0))
12073 (setq cnt 0)
12074 (insert "\n"))
12075 (insert "{ "))
12076 ((equal e '(:endgroup))
12077 (setq ingroup nil cnt 0)
12078 (insert "}\n"))
12079 ((equal e '(:newline))
12080 (when (not (= cnt 0))
12081 (setq cnt 0)
12082 (insert "\n")
12083 (setq e (car tbl))
12084 (while (equal (car tbl) '(:newline))
12085 (insert "\n")
12086 (setq tbl (cdr tbl)))))
12088 (setq tg (car e) c (cdr e))
12089 (if ingroup (push tg (car groups)))
12090 (setq tg (org-add-props tg nil 'face
12091 (org-get-todo-face tg)))
12092 (if (and (= cnt 0) (not ingroup)) (insert " "))
12093 (insert "[" c "] " tg (make-string
12094 (- fwidth 4 (length tg)) ?\ ))
12095 (when (= (setq cnt (1+ cnt)) ncol)
12096 (insert "\n")
12097 (if ingroup (insert " "))
12098 (setq cnt 0)))))
12099 (insert "\n")
12100 (goto-char (point-min))
12101 (if (not expert) (org-fit-window-to-buffer))
12102 (message "[a-z..]:Set [SPC]:clear")
12103 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12104 (cond
12105 ((or (= c ?\C-g)
12106 (and (= c ?q) (not (rassoc c fulltable))))
12107 (setq quit-flag t))
12108 ((= c ?\ ) nil)
12109 ((setq e (rassoc c fulltable) tg (car e))
12111 (t (setq quit-flag t)))))))
12113 (defun org-entry-is-todo-p ()
12114 (member (org-get-todo-state) org-not-done-keywords))
12116 (defun org-entry-is-done-p ()
12117 (member (org-get-todo-state) org-done-keywords))
12119 (defun org-get-todo-state ()
12120 (save-excursion
12121 (org-back-to-heading t)
12122 (and (looking-at org-todo-line-regexp)
12123 (match-end 2)
12124 (match-string 2))))
12126 (defun org-at-date-range-p (&optional inactive-ok)
12127 "Is the cursor inside a date range?"
12128 (interactive)
12129 (save-excursion
12130 (catch 'exit
12131 (let ((pos (point)))
12132 (skip-chars-backward "^[<\r\n")
12133 (skip-chars-backward "<[")
12134 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12135 (>= (match-end 0) pos)
12136 (throw 'exit t))
12137 (skip-chars-backward "^<[\r\n")
12138 (skip-chars-backward "<[")
12139 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12140 (>= (match-end 0) pos)
12141 (throw 'exit t)))
12142 nil)))
12144 (defun org-get-repeat (&optional tagline)
12145 "Check if there is a deadline/schedule with repeater in this entry."
12146 (save-match-data
12147 (save-excursion
12148 (org-back-to-heading t)
12149 (and (re-search-forward (if tagline
12150 (concat tagline "\\s-*" org-repeat-re)
12151 org-repeat-re)
12152 (org-entry-end-position) t)
12153 (match-string-no-properties 1)))))
12155 (defvar org-last-changed-timestamp)
12156 (defvar org-last-inserted-timestamp)
12157 (defvar org-log-post-message)
12158 (defvar org-log-note-purpose)
12159 (defvar org-log-note-how)
12160 (defvar org-log-note-extra)
12161 (defun org-auto-repeat-maybe (done-word)
12162 "Check if the current headline contains a repeated deadline/schedule.
12163 If yes, set TODO state back to what it was and change the base date
12164 of repeating deadline/scheduled time stamps to new date.
12165 This function is run automatically after each state change to a DONE state."
12166 ;; last-state is dynamically scoped into this function
12167 (let* ((repeat (org-get-repeat))
12168 (aa (assoc org-last-state org-todo-kwd-alist))
12169 (interpret (nth 1 aa))
12170 (head (nth 2 aa))
12171 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12172 (msg "Entry repeats: ")
12173 (org-log-done nil)
12174 (org-todo-log-states nil)
12175 re type n what ts time to-state)
12176 (when repeat
12177 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12178 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12179 org-todo-repeat-to-state))
12180 (unless (and to-state (member to-state org-todo-keywords-1))
12181 (setq to-state (if (eq interpret 'type) org-last-state head)))
12182 (org-todo to-state)
12183 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12184 (org-entry-put nil "LAST_REPEAT" (format-time-string
12185 (org-time-stamp-format t t))))
12186 (when org-log-repeat
12187 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12188 (memq 'org-add-log-note post-command-hook))
12189 ;; OK, we are already setup for some record
12190 (if (eq org-log-repeat 'note)
12191 ;; make sure we take a note, not only a time stamp
12192 (setq org-log-note-how 'note))
12193 ;; Set up for taking a record
12194 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12195 org-last-state
12196 'findpos org-log-repeat)))
12197 (org-back-to-heading t)
12198 (org-add-planning-info nil nil 'closed)
12199 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12200 org-deadline-time-regexp "\\)\\|\\("
12201 org-ts-regexp "\\)"))
12202 (while (re-search-forward
12203 re (save-excursion (outline-next-heading) (point)) t)
12204 (setq type (if (match-end 1) org-scheduled-string
12205 (if (match-end 3) org-deadline-string "Plain:"))
12206 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12207 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12208 (setq n (string-to-number (match-string 2 ts))
12209 what (match-string 3 ts))
12210 (if (equal what "w") (setq n (* n 7) what "d"))
12211 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12212 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12213 ;; Preparation, see if we need to modify the start date for the change
12214 (when (match-end 1)
12215 (setq time (save-match-data (org-time-string-to-time ts)))
12216 (cond
12217 ((equal (match-string 1 ts) ".")
12218 ;; Shift starting date to today
12219 (org-timestamp-change
12220 (- (org-today) (time-to-days time))
12221 'day))
12222 ((equal (match-string 1 ts) "+")
12223 (let ((nshiftmax 10) (nshift 0))
12224 (while (or (= nshift 0)
12225 (<= (time-to-days time)
12226 (time-to-days (current-time))))
12227 (when (= (incf nshift) nshiftmax)
12228 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12229 (error "Abort")))
12230 (org-timestamp-change n (cdr (assoc what whata)))
12231 (org-at-timestamp-p t)
12232 (setq ts (match-string 1))
12233 (setq time (save-match-data (org-time-string-to-time ts)))))
12234 (org-timestamp-change (- n) (cdr (assoc what whata)))
12235 ;; rematch, so that we have everything in place for the real shift
12236 (org-at-timestamp-p t)
12237 (setq ts (match-string 1))
12238 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12239 (org-timestamp-change n (cdr (assoc what whata)))
12240 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12241 (setq org-log-post-message msg)
12242 (message "%s" msg))))
12244 (defun org-show-todo-tree (arg)
12245 "Make a compact tree which shows all headlines marked with TODO.
12246 The tree will show the lines where the regexp matches, and all higher
12247 headlines above the match.
12248 With a \\[universal-argument] prefix, prompt for a regexp to match.
12249 With a numeric prefix N, construct a sparse tree for the Nth element
12250 of `org-todo-keywords-1'."
12251 (interactive "P")
12252 (let ((case-fold-search nil)
12253 (kwd-re
12254 (cond ((null arg) org-not-done-regexp)
12255 ((equal arg '(4))
12256 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12257 (mapcar 'list org-todo-keywords-1))))
12258 (concat "\\("
12259 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12260 "\\)\\>")))
12261 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12262 (regexp-quote (nth (1- (prefix-numeric-value arg))
12263 org-todo-keywords-1)))
12264 (t (error "Invalid prefix argument: %s" arg)))))
12265 (message "%d TODO entries found"
12266 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12268 (defun org-deadline (&optional remove time)
12269 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12270 With argument REMOVE, remove any deadline from the item.
12271 With argument TIME, set the deadline at the corresponding date. TIME
12272 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12273 (interactive "P")
12274 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12275 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12276 'region-start-level 'region))
12277 org-loop-over-headlines-in-active-region)
12278 (org-map-entries
12279 `(org-deadline ',remove ,time)
12280 org-loop-over-headlines-in-active-region
12281 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12282 (let* ((old-date (org-entry-get nil "DEADLINE"))
12283 (repeater (and old-date
12284 (string-match
12285 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12286 old-date)
12287 (match-string 1 old-date))))
12288 (if remove
12289 (progn
12290 (when (and old-date org-log-redeadline)
12291 (org-add-log-setup 'deldeadline nil old-date 'findpos
12292 org-log-redeadline))
12293 (org-remove-timestamp-with-keyword org-deadline-string)
12294 (message "Item no longer has a deadline."))
12295 (org-add-planning-info 'deadline time 'closed)
12296 (when (and old-date org-log-redeadline
12297 (not (equal old-date
12298 (substring org-last-inserted-timestamp 1 -1))))
12299 (org-add-log-setup 'redeadline nil old-date 'findpos
12300 org-log-redeadline))
12301 (when repeater
12302 (save-excursion
12303 (org-back-to-heading t)
12304 (when (re-search-forward (concat org-deadline-string " "
12305 org-last-inserted-timestamp)
12306 (save-excursion
12307 (outline-next-heading) (point)) t)
12308 (goto-char (1- (match-end 0)))
12309 (insert " " repeater)
12310 (setq org-last-inserted-timestamp
12311 (concat (substring org-last-inserted-timestamp 0 -1)
12312 " " repeater
12313 (substring org-last-inserted-timestamp -1))))))
12314 (message "Deadline on %s" org-last-inserted-timestamp)))))
12316 (defun org-schedule (&optional remove time)
12317 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12318 With argument REMOVE, remove any scheduling date from the item.
12319 With argument TIME, scheduled at the corresponding date. TIME can
12320 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12321 (interactive "P")
12322 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12323 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12324 'region-start-level 'region))
12325 org-loop-over-headlines-in-active-region)
12326 (org-map-entries
12327 `(org-schedule ',remove ,time)
12328 org-loop-over-headlines-in-active-region
12329 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12330 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12331 (repeater (and old-date
12332 (string-match
12333 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12334 old-date)
12335 (match-string 1 old-date))))
12336 (if remove
12337 (progn
12338 (when (and old-date org-log-reschedule)
12339 (org-add-log-setup 'delschedule nil old-date 'findpos
12340 org-log-reschedule))
12341 (org-remove-timestamp-with-keyword org-scheduled-string)
12342 (message "Item is no longer scheduled."))
12343 (org-add-planning-info 'scheduled time 'closed)
12344 (when (and old-date org-log-reschedule
12345 (not (equal old-date
12346 (substring org-last-inserted-timestamp 1 -1))))
12347 (org-add-log-setup 'reschedule nil old-date 'findpos
12348 org-log-reschedule))
12349 (when repeater
12350 (save-excursion
12351 (org-back-to-heading t)
12352 (when (re-search-forward (concat org-scheduled-string " "
12353 org-last-inserted-timestamp)
12354 (save-excursion
12355 (outline-next-heading) (point)) t)
12356 (goto-char (1- (match-end 0)))
12357 (insert " " repeater)
12358 (setq org-last-inserted-timestamp
12359 (concat (substring org-last-inserted-timestamp 0 -1)
12360 " " repeater
12361 (substring org-last-inserted-timestamp -1))))))
12362 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12364 (defun org-get-scheduled-time (pom &optional inherit)
12365 "Get the scheduled time as a time tuple, of a format suitable
12366 for calling org-schedule with, or if there is no scheduling,
12367 returns nil."
12368 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12369 (when time
12370 (apply 'encode-time (org-parse-time-string time)))))
12372 (defun org-get-deadline-time (pom &optional inherit)
12373 "Get the deadline as a time tuple, of a format suitable for
12374 calling org-deadline with, or if there is no scheduling, returns
12375 nil."
12376 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12377 (when time
12378 (apply 'encode-time (org-parse-time-string time)))))
12380 (defun org-remove-timestamp-with-keyword (keyword)
12381 "Remove all time stamps with KEYWORD in the current entry."
12382 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12383 beg)
12384 (save-excursion
12385 (org-back-to-heading t)
12386 (setq beg (point))
12387 (outline-next-heading)
12388 (while (re-search-backward re beg t)
12389 (replace-match "")
12390 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12391 (equal (char-before) ?\ ))
12392 (backward-delete-char 1)
12393 (if (string-match "^[ \t]*$" (buffer-substring
12394 (point-at-bol) (point-at-eol)))
12395 (delete-region (point-at-bol)
12396 (min (point-max) (1+ (point-at-eol))))))))))
12398 (defun org-add-planning-info (what &optional time &rest remove)
12399 "Insert new timestamp with keyword in the line directly after the headline.
12400 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12401 If non is given, the user is prompted for a date.
12402 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12403 be removed."
12404 (interactive)
12405 (let (org-time-was-given org-end-time-was-given ts
12406 end default-time default-input)
12408 (catch 'exit
12409 (when (and (memq what '(scheduled deadline))
12410 (or (not time)
12411 (and (stringp time)
12412 (string-match "^[-+]+[0-9]" time))))
12413 ;; Try to get a default date/time from existing timestamp
12414 (save-excursion
12415 (org-back-to-heading t)
12416 (setq end (save-excursion (outline-next-heading) (point)))
12417 (when (re-search-forward (if (eq what 'scheduled)
12418 org-scheduled-time-regexp
12419 org-deadline-time-regexp)
12420 end t)
12421 (setq ts (match-string 1)
12422 default-time
12423 (apply 'encode-time (org-parse-time-string ts))
12424 default-input (and ts (org-get-compact-tod ts))))))
12425 (when what
12426 (setq time
12427 (if (stringp time)
12428 ;; This is a string (relative or absolute), set proper date
12429 (apply 'encode-time
12430 (org-read-date-analyze
12431 time default-time (decode-time default-time)))
12432 ;; If necessary, get the time from the user
12433 (or time (org-read-date nil 'to-time nil nil
12434 default-time default-input)))))
12436 (when (and org-insert-labeled-timestamps-at-point
12437 (member what '(scheduled deadline)))
12438 (insert
12439 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12440 (org-insert-time-stamp time org-time-was-given
12441 nil nil nil (list org-end-time-was-given))
12442 (setq what nil))
12443 (save-excursion
12444 (save-restriction
12445 (let (col list elt ts buffer-invisibility-spec)
12446 (org-back-to-heading t)
12447 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12448 (goto-char (match-end 1))
12449 (setq col (current-column))
12450 (goto-char (match-end 0))
12451 (if (eobp) (insert "\n") (forward-char 1))
12452 (when (and (not what)
12453 (not (looking-at
12454 (concat "[ \t]*"
12455 org-keyword-time-not-clock-regexp))))
12456 ;; Nothing to add, nothing to remove...... :-)
12457 (throw 'exit nil))
12458 (if (and (not (looking-at org-outline-regexp))
12459 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12460 "[^\r\n]*"))
12461 (not (equal (match-string 1) org-clock-string)))
12462 (narrow-to-region (match-beginning 0) (match-end 0))
12463 (insert-before-markers "\n")
12464 (backward-char 1)
12465 (narrow-to-region (point) (point))
12466 (and org-adapt-indentation (org-indent-to-column col)))
12467 ;; Check if we have to remove something.
12468 (setq list (cons what remove))
12469 (while list
12470 (setq elt (pop list))
12471 (when (or (and (eq elt 'scheduled)
12472 (re-search-forward org-scheduled-time-regexp nil t))
12473 (and (eq elt 'deadline)
12474 (re-search-forward org-deadline-time-regexp nil t))
12475 (and (eq elt 'closed)
12476 (re-search-forward org-closed-time-regexp nil t)))
12477 (replace-match "")
12478 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12479 (and (looking-at "[ \t]+") (replace-match ""))
12480 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12481 (when what
12482 (insert
12483 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12484 (cond ((eq what 'scheduled) org-scheduled-string)
12485 ((eq what 'deadline) org-deadline-string)
12486 ((eq what 'closed) org-closed-string))
12487 " ")
12488 (setq ts (org-insert-time-stamp
12489 time
12490 (or org-time-was-given
12491 (and (eq what 'closed) org-log-done-with-time))
12492 (eq what 'closed)
12493 nil nil (list org-end-time-was-given)))
12494 (insert
12495 (if (not (or (bolp) (eq (char-before) ?\ )
12496 (memq (char-after) '(32 10))
12497 (eobp))) " " ""))
12498 (end-of-line 1))
12499 (goto-char (point-min))
12500 (widen)
12501 (if (and (looking-at "[ \t]*\n")
12502 (equal (char-before) ?\n))
12503 (delete-region (1- (point)) (point-at-eol)))
12504 ts))))))
12506 (defvar org-log-note-marker (make-marker))
12507 (defvar org-log-note-purpose nil)
12508 (defvar org-log-note-state nil)
12509 (defvar org-log-note-previous-state nil)
12510 (defvar org-log-note-how nil)
12511 (defvar org-log-note-extra nil)
12512 (defvar org-log-note-window-configuration nil)
12513 (defvar org-log-note-return-to (make-marker))
12514 (defvar org-log-note-effective-time nil
12515 "Remembered current time so that dynamically scoped
12516 `org-extend-today-until' affects tha timestamps in state change
12517 log")
12519 (defvar org-log-post-message nil
12520 "Message to be displayed after a log note has been stored.
12521 The auto-repeater uses this.")
12523 (defun org-add-note ()
12524 "Add a note to the current entry.
12525 This is done in the same way as adding a state change note."
12526 (interactive)
12527 (org-add-log-setup 'note nil nil 'findpos nil))
12529 (defvar org-property-end-re)
12530 (defun org-add-log-setup (&optional purpose state prev-state
12531 findpos how extra)
12532 "Set up the post command hook to take a note.
12533 If this is about to TODO state change, the new state is expected in STATE.
12534 When FINDPOS is non-nil, find the correct position for the note in
12535 the current entry. If not, assume that it can be inserted at point.
12536 HOW is an indicator what kind of note should be created.
12537 EXTRA is additional text that will be inserted into the notes buffer."
12538 (let* ((org-log-into-drawer (org-log-into-drawer))
12539 (drawer (cond ((stringp org-log-into-drawer)
12540 org-log-into-drawer)
12541 (org-log-into-drawer "LOGBOOK")
12542 (t nil))))
12543 (save-restriction
12544 (save-excursion
12545 (when findpos
12546 (org-back-to-heading t)
12547 (narrow-to-region (point) (save-excursion
12548 (outline-next-heading) (point)))
12549 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12550 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12551 "[^\r\n]*\\)?"))
12552 (goto-char (match-end 0))
12553 (cond
12554 (drawer
12555 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12556 nil t)
12557 (progn
12558 (goto-char (match-end 0))
12559 (or org-log-states-order-reversed
12560 (and (re-search-forward org-property-end-re nil t)
12561 (goto-char (1- (match-beginning 0))))))
12562 (insert "\n:" drawer ":\n:END:")
12563 (beginning-of-line 0)
12564 (org-indent-line)
12565 (beginning-of-line 2)
12566 (org-indent-line)
12567 (end-of-line 0)))
12568 ((and org-log-state-notes-insert-after-drawers
12569 (save-excursion
12570 (forward-line) (looking-at org-drawer-regexp)))
12571 (forward-line)
12572 (while (looking-at org-drawer-regexp)
12573 (goto-char (match-end 0))
12574 (re-search-forward org-property-end-re (point-max) t)
12575 (forward-line))
12576 (forward-line -1)))
12577 (unless org-log-states-order-reversed
12578 (and (= (char-after) ?\n) (forward-char 1))
12579 (org-skip-over-state-notes)
12580 (skip-chars-backward " \t\n\r")))
12581 (move-marker org-log-note-marker (point))
12582 (setq org-log-note-purpose purpose
12583 org-log-note-state state
12584 org-log-note-previous-state prev-state
12585 org-log-note-how how
12586 org-log-note-extra extra
12587 org-log-note-effective-time (org-current-effective-time))
12588 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12590 (defun org-skip-over-state-notes ()
12591 "Skip past the list of State notes in an entry."
12592 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12593 (when (ignore-errors (goto-char (org-in-item-p)))
12594 (let* ((struct (org-list-struct))
12595 (prevs (org-list-prevs-alist struct)))
12596 (while (looking-at "[ \t]*- State")
12597 (goto-char (or (org-list-get-next-item (point) struct prevs)
12598 (org-list-get-item-end (point) struct)))))))
12600 (defun org-add-log-note (&optional purpose)
12601 "Pop up a window for taking a note, and add this note later at point."
12602 (remove-hook 'post-command-hook 'org-add-log-note)
12603 (setq org-log-note-window-configuration (current-window-configuration))
12604 (delete-other-windows)
12605 (move-marker org-log-note-return-to (point))
12606 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12607 (goto-char org-log-note-marker)
12608 (org-switch-to-buffer-other-window "*Org Note*")
12609 (erase-buffer)
12610 (if (memq org-log-note-how '(time state))
12611 (let (current-prefix-arg) (org-store-log-note))
12612 (let ((org-inhibit-startup t)) (org-mode))
12613 (insert (format "# Insert note for %s.
12614 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12615 (cond
12616 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12617 ((eq org-log-note-purpose 'done) "closed todo item")
12618 ((eq org-log-note-purpose 'state)
12619 (format "state change from \"%s\" to \"%s\""
12620 (or org-log-note-previous-state "")
12621 (or org-log-note-state "")))
12622 ((eq org-log-note-purpose 'reschedule)
12623 "rescheduling")
12624 ((eq org-log-note-purpose 'delschedule)
12625 "no longer scheduled")
12626 ((eq org-log-note-purpose 'redeadline)
12627 "changing deadline")
12628 ((eq org-log-note-purpose 'deldeadline)
12629 "removing deadline")
12630 ((eq org-log-note-purpose 'refile)
12631 "refiling")
12632 ((eq org-log-note-purpose 'note)
12633 "this entry")
12634 (t (error "This should not happen")))))
12635 (if org-log-note-extra (insert org-log-note-extra))
12636 (org-set-local 'org-finish-function 'org-store-log-note)
12637 (run-hooks 'org-log-buffer-setup-hook)))
12639 (defvar org-note-abort nil) ; dynamically scoped
12640 (defun org-store-log-note ()
12641 "Finish taking a log note, and insert it to where it belongs."
12642 (let ((txt (buffer-string))
12643 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12644 lines ind bul)
12645 (kill-buffer (current-buffer))
12646 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12647 (setq txt (replace-match "" t t txt)))
12648 (if (string-match "\\s-+\\'" txt)
12649 (setq txt (replace-match "" t t txt)))
12650 (setq lines (org-split-string txt "\n"))
12651 (when (and note (string-match "\\S-" note))
12652 (setq note
12653 (org-replace-escapes
12654 note
12655 (list (cons "%u" (user-login-name))
12656 (cons "%U" user-full-name)
12657 (cons "%t" (format-time-string
12658 (org-time-stamp-format 'long 'inactive)
12659 org-log-note-effective-time))
12660 (cons "%T" (format-time-string
12661 (org-time-stamp-format 'long nil)
12662 org-log-note-effective-time))
12663 (cons "%d" (format-time-string
12664 (org-time-stamp-format nil 'inactive)
12665 org-log-note-effective-time))
12666 (cons "%D" (format-time-string
12667 (org-time-stamp-format nil nil)
12668 org-log-note-effective-time))
12669 (cons "%s" (if org-log-note-state
12670 (concat "\"" org-log-note-state "\"")
12671 ""))
12672 (cons "%S" (if org-log-note-previous-state
12673 (concat "\"" org-log-note-previous-state "\"")
12674 "\"\"")))))
12675 (if lines (setq note (concat note " \\\\")))
12676 (push note lines))
12677 (when (or current-prefix-arg org-note-abort)
12678 (when org-log-into-drawer
12679 (org-remove-empty-drawer-at
12680 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12681 org-log-note-marker))
12682 (setq lines nil))
12683 (when lines
12684 (with-current-buffer (marker-buffer org-log-note-marker)
12685 (save-excursion
12686 (goto-char org-log-note-marker)
12687 (move-marker org-log-note-marker nil)
12688 (end-of-line 1)
12689 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12690 (setq ind (save-excursion
12691 (if (ignore-errors (goto-char (org-in-item-p)))
12692 (let ((struct (org-list-struct)))
12693 (org-list-get-ind
12694 (org-list-get-top-point struct) struct))
12695 (skip-chars-backward " \r\t\n")
12696 (cond
12697 ((and (org-at-heading-p)
12698 org-adapt-indentation)
12699 (1+ (org-current-level)))
12700 ((org-at-heading-p) 0)
12701 (t (org-get-indentation))))))
12702 (setq bul (org-list-bullet-string "-"))
12703 (org-indent-line-to ind)
12704 (insert bul (pop lines))
12705 (let ((ind-body (+ (length bul) ind)))
12706 (while lines
12707 (insert "\n")
12708 (org-indent-line-to ind-body)
12709 (insert (pop lines))))
12710 (message "Note stored")
12711 (org-back-to-heading t)
12712 (org-cycle-hide-drawers 'children)))))
12713 (set-window-configuration org-log-note-window-configuration)
12714 (with-current-buffer (marker-buffer org-log-note-return-to)
12715 (goto-char org-log-note-return-to))
12716 (move-marker org-log-note-return-to nil)
12717 (and org-log-post-message (message "%s" org-log-post-message)))
12719 (defun org-remove-empty-drawer-at (drawer pos)
12720 "Remove an empty drawer DRAWER at position POS.
12721 POS may also be a marker."
12722 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12723 (save-excursion
12724 (save-restriction
12725 (widen)
12726 (goto-char pos)
12727 (if (org-in-regexp
12728 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12729 (replace-match ""))))))
12731 (defvar org-ts-type nil)
12732 (defun org-sparse-tree (&optional arg type)
12733 "Create a sparse tree, prompt for the details.
12734 This command can create sparse trees. You first need to select the type
12735 of match used to create the tree:
12737 t Show all TODO entries.
12738 T Show entries with a specific TODO keyword.
12739 m Show entries selected by a tags/property match.
12740 p Enter a property name and its value (both with completion on existing
12741 names/values) and show entries with that property.
12742 r Show entries matching a regular expression (`/' can be used as well).
12743 b Show deadlines and scheduled items before a date.
12744 a Show deadlines and scheduled items after a date.
12745 d Show deadlines due within `org-deadline-warning-days'.
12746 D Show deadlines and scheduled items between a date range."
12747 (interactive "P")
12748 (let (ans kwd value ts-type)
12749 (setq type (or type org-sparse-tree-default-date-type))
12750 (setq org-ts-type type)
12751 (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"
12752 (cond ((eq type 'all) "all timestamps")
12753 ((eq type 'scheduled) "only scheduled")
12754 ((eq type 'deadline) "only deadline")
12755 ((eq type 'active) "only active timestamps")
12756 ((eq type 'inactive) "only inactive timestamps")
12757 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12758 (t "scheduled/deadline")))
12759 (setq ans (read-char-exclusive))
12760 (cond
12761 ((equal ans ?c)
12762 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12763 ((equal ans ?d)
12764 (call-interactively 'org-check-deadlines))
12765 ((equal ans ?b)
12766 (call-interactively 'org-check-before-date))
12767 ((equal ans ?a)
12768 (call-interactively 'org-check-after-date))
12769 ((equal ans ?D)
12770 (call-interactively 'org-check-dates-range))
12771 ((equal ans ?t)
12772 (org-show-todo-tree nil))
12773 ((equal ans ?T)
12774 (org-show-todo-tree '(4)))
12775 ((member ans '(?T ?m))
12776 (call-interactively 'org-match-sparse-tree))
12777 ((member ans '(?p ?P))
12778 (setq kwd (org-icompleting-read "Property: "
12779 (mapcar 'list (org-buffer-property-keys))))
12780 (setq value (org-icompleting-read "Value: "
12781 (mapcar 'list (org-property-values kwd))))
12782 (unless (string-match "\\`{.*}\\'" value)
12783 (setq value (concat "\"" value "\"")))
12784 (org-match-sparse-tree arg (concat kwd "=" value)))
12785 ((member ans '(?r ?R ?/))
12786 (call-interactively 'org-occur))
12787 (t (error "No such sparse tree command \"%c\"" ans)))))
12789 (defvar org-occur-highlights nil
12790 "List of overlays used for occur matches.")
12791 (make-variable-buffer-local 'org-occur-highlights)
12792 (defvar org-occur-parameters nil
12793 "Parameters of the active org-occur calls.
12794 This is a list, each call to org-occur pushes as cons cell,
12795 containing the regular expression and the callback, onto the list.
12796 The list can contain several entries if `org-occur' has been called
12797 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12798 will only contain one set of parameters. When the highlights are
12799 removed (for example with `C-c C-c', or with the next edit (depending
12800 on `org-remove-highlights-with-change'), this variable is emptied
12801 as well.")
12802 (make-variable-buffer-local 'org-occur-parameters)
12804 (defun org-occur (regexp &optional keep-previous callback)
12805 "Make a compact tree which shows all matches of REGEXP.
12806 The tree will show the lines where the regexp matches, and all higher
12807 headlines above the match. It will also show the heading after the match,
12808 to make sure editing the matching entry is easy.
12809 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12810 call to `org-occur' will be kept, to allow stacking of calls to this
12811 command.
12812 If CALLBACK is non-nil, it is a function which is called to confirm
12813 that the match should indeed be shown."
12814 (interactive "sRegexp: \nP")
12815 (when (equal regexp "")
12816 (error "Regexp cannot be empty"))
12817 (unless keep-previous
12818 (org-remove-occur-highlights nil nil t))
12819 (push (cons regexp callback) org-occur-parameters)
12820 (let ((cnt 0))
12821 (save-excursion
12822 (goto-char (point-min))
12823 (if (or (not keep-previous) ; do not want to keep
12824 (not org-occur-highlights)) ; no previous matches
12825 ;; hide everything
12826 (org-overview))
12827 (while (re-search-forward regexp nil t)
12828 (when (or (not callback)
12829 (save-match-data (funcall callback)))
12830 (setq cnt (1+ cnt))
12831 (when org-highlight-sparse-tree-matches
12832 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12833 (org-show-context 'occur-tree))))
12834 (when org-remove-highlights-with-change
12835 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12836 nil 'local))
12837 (unless org-sparse-tree-open-archived-trees
12838 (org-hide-archived-subtrees (point-min) (point-max)))
12839 (run-hooks 'org-occur-hook)
12840 (if (org-called-interactively-p 'interactive)
12841 (message "%d match(es) for regexp %s" cnt regexp))
12842 cnt))
12844 (defun org-occur-next-match (&optional n reset)
12845 "Function for `next-error-function' to find sparse tree matches.
12846 N is the number of matches to move, when negative move backwards.
12847 RESET is entirely ignored - this function always goes back to the
12848 starting point when no match is found."
12849 (let* ((limit (if (< n 0) (point-min) (point-max)))
12850 (search-func (if (< n 0)
12851 'previous-single-char-property-change
12852 'next-single-char-property-change))
12853 (n (abs n))
12854 (pos (point))
12856 (catch 'exit
12857 (while (setq p1 (funcall search-func (point) 'org-type))
12858 (when (equal p1 limit)
12859 (goto-char pos)
12860 (error "No more matches"))
12861 (when (equal (get-char-property p1 'org-type) 'org-occur)
12862 (setq n (1- n))
12863 (when (= n 0)
12864 (goto-char p1)
12865 (throw 'exit (point))))
12866 (goto-char p1))
12867 (goto-char p1)
12868 (error "No more matches"))))
12870 (defun org-show-context (&optional key)
12871 "Make sure point and context are visible.
12872 How much context is shown depends upon the variables
12873 `org-show-hierarchy-above', `org-show-following-heading',
12874 `org-show-entry-below' and `org-show-siblings'."
12875 (let ((heading-p (org-at-heading-p t))
12876 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12877 (following-p (org-get-alist-option org-show-following-heading key))
12878 (entry-p (org-get-alist-option org-show-entry-below key))
12879 (siblings-p (org-get-alist-option org-show-siblings key)))
12880 (catch 'exit
12881 ;; Show heading or entry text
12882 (if (and heading-p (not entry-p))
12883 (org-flag-heading nil) ; only show the heading
12884 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12885 (org-show-hidden-entry))) ; show entire entry
12886 (when following-p
12887 ;; Show next sibling, or heading below text
12888 (save-excursion
12889 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12890 (org-flag-heading nil))))
12891 (when siblings-p (org-show-siblings))
12892 (when hierarchy-p
12893 ;; show all higher headings, possibly with siblings
12894 (save-excursion
12895 (while (and (condition-case nil
12896 (progn (org-up-heading-all 1) t)
12897 (error nil))
12898 (not (bobp)))
12899 (org-flag-heading nil)
12900 (when siblings-p (org-show-siblings))))))))
12902 (defvar org-reveal-start-hook nil
12903 "Hook run before revealing a location.")
12905 (defun org-reveal (&optional siblings)
12906 "Show current entry, hierarchy above it, and the following headline.
12907 This can be used to show a consistent set of context around locations
12908 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12909 not t for the search context.
12911 With optional argument SIBLINGS, on each level of the hierarchy all
12912 siblings are shown. This repairs the tree structure to what it would
12913 look like when opened with hierarchical calls to `org-cycle'.
12914 With double optional argument \\[universal-argument] \\[universal-argument], \
12915 go to the parent and show the
12916 entire tree."
12917 (interactive "P")
12918 (run-hooks 'org-reveal-start-hook)
12919 (let ((org-show-hierarchy-above t)
12920 (org-show-following-heading t)
12921 (org-show-siblings (if siblings t org-show-siblings)))
12922 (org-show-context nil))
12923 (when (equal siblings '(16))
12924 (save-excursion
12925 (when (org-up-heading-safe)
12926 (org-show-subtree)
12927 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12929 (defun org-highlight-new-match (beg end)
12930 "Highlight from BEG to END and mark the highlight is an occur headline."
12931 (let ((ov (make-overlay beg end)))
12932 (overlay-put ov 'face 'secondary-selection)
12933 (overlay-put ov 'org-type 'org-occur)
12934 (push ov org-occur-highlights)))
12936 (defun org-remove-occur-highlights (&optional beg end noremove)
12937 "Remove the occur highlights from the buffer.
12938 BEG and END are ignored. If NOREMOVE is nil, remove this function
12939 from the `before-change-functions' in the current buffer."
12940 (interactive)
12941 (unless org-inhibit-highlight-removal
12942 (mapc 'delete-overlay org-occur-highlights)
12943 (setq org-occur-highlights nil)
12944 (setq org-occur-parameters nil)
12945 (unless noremove
12946 (remove-hook 'before-change-functions
12947 'org-remove-occur-highlights 'local))))
12949 ;;;; Priorities
12951 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12952 "Regular expression matching the priority indicator.")
12954 (defvar org-remove-priority-next-time nil)
12956 (defun org-priority-up ()
12957 "Increase the priority of the current item."
12958 (interactive)
12959 (org-priority 'up))
12961 (defun org-priority-down ()
12962 "Decrease the priority of the current item."
12963 (interactive)
12964 (org-priority 'down))
12966 (defun org-priority (&optional action)
12967 "Change the priority of an item.
12968 ACTION can be `set', `up', `down', or a character."
12969 (interactive)
12970 (unless org-enable-priority-commands
12971 (error "Priority commands are disabled"))
12972 (setq action (or action 'set))
12973 (let (current new news have remove)
12974 (save-excursion
12975 (org-back-to-heading t)
12976 (if (looking-at org-priority-regexp)
12977 (setq current (string-to-char (match-string 2))
12978 have t))
12979 (cond
12980 ((eq action 'remove)
12981 (setq remove t new ?\ ))
12982 ((or (eq action 'set)
12983 (if (featurep 'xemacs) (characterp action) (integerp action)))
12984 (if (not (eq action 'set))
12985 (setq new action)
12986 (message "Priority %c-%c, SPC to remove: "
12987 org-highest-priority org-lowest-priority)
12988 (save-match-data
12989 (setq new (read-char-exclusive))))
12990 (if (and (= (upcase org-highest-priority) org-highest-priority)
12991 (= (upcase org-lowest-priority) org-lowest-priority))
12992 (setq new (upcase new)))
12993 (cond ((equal new ?\ ) (setq remove t))
12994 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12995 (error "Priority must be between `%c' and `%c'"
12996 org-highest-priority org-lowest-priority))))
12997 ((eq action 'up)
12998 (setq new (if have
12999 (1- current) ; normal cycling
13000 ;; last priority was empty
13001 (if (eq last-command this-command)
13002 org-lowest-priority ; wrap around empty to lowest
13003 ;; default
13004 (if org-priority-start-cycle-with-default
13005 org-default-priority
13006 (1- org-default-priority))))))
13007 ((eq action 'down)
13008 (setq new (if have
13009 (1+ current) ; normal cycling
13010 ;; last priority was empty
13011 (if (eq last-command this-command)
13012 org-highest-priority ; wrap around empty to highest
13013 ;; default
13014 (if org-priority-start-cycle-with-default
13015 org-default-priority
13016 (1+ org-default-priority))))))
13017 (t (error "Invalid action")))
13018 (if (or (< (upcase new) org-highest-priority)
13019 (> (upcase new) org-lowest-priority))
13020 (if (and (memq action '(up down))
13021 (not have) (not (eq last-command this-command)))
13022 ;; `new' is from default priority
13023 (error
13024 "The default can not be set, see `org-default-priority' why")
13025 ;; normal cycling: `new' is beyond highest/lowest priority
13026 ;; and is wrapped around to the empty priority
13027 (setq remove t)))
13028 (setq news (format "%c" new))
13029 (if have
13030 (if remove
13031 (replace-match "" t t nil 1)
13032 (replace-match news t t nil 2))
13033 (if remove
13034 (error "No priority cookie found in line")
13035 (let ((case-fold-search nil))
13036 (looking-at org-todo-line-regexp))
13037 (if (match-end 2)
13038 (progn
13039 (goto-char (match-end 2))
13040 (insert " [#" news "]"))
13041 (goto-char (match-beginning 3))
13042 (insert "[#" news "] "))))
13043 (org-preserve-lc (org-set-tags nil 'align)))
13044 (if remove
13045 (message "Priority removed")
13046 (message "Priority of current item set to %s" news))))
13048 (defun org-get-priority (s)
13049 "Find priority cookie and return priority."
13050 (if (functionp org-get-priority-function)
13051 (funcall org-get-priority-function)
13052 (save-match-data
13053 (if (not (string-match org-priority-regexp s))
13054 (* 1000 (- org-lowest-priority org-default-priority))
13055 (* 1000 (- org-lowest-priority
13056 (string-to-char (match-string 2 s))))))))
13058 ;;;; Tags
13060 (defvar org-agenda-archives-mode)
13061 (defvar org-map-continue-from nil
13062 "Position from where mapping should continue.
13063 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13065 (defvar org-scanner-tags nil
13066 "The current tag list while the tags scanner is running.")
13067 (defvar org-trust-scanner-tags nil
13068 "Should `org-get-tags-at' use the tags for the scanner.
13069 This is for internal dynamical scoping only.
13070 When this is non-nil, the function `org-get-tags-at' will return the value
13071 of `org-scanner-tags' instead of building the list by itself. This
13072 can lead to large speed-ups when the tags scanner is used in a file with
13073 many entries, and when the list of tags is retrieved, for example to
13074 obtain a list of properties. Building the tags list for each entry in such
13075 a file becomes an N^2 operation - but with this variable set, it scales
13076 as N.")
13078 (defun org-scan-tags (action matcher todo-only &optional start-level)
13079 "Scan headline tags with inheritance and produce output ACTION.
13081 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13082 or `agenda' to produce an entry list for an agenda view. It can also be
13083 a Lisp form or a function that should be called at each matched headline, in
13084 this case the return value is a list of all return values from these calls.
13086 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13087 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13088 only lines with a not-done TODO keyword are included in the output.
13089 This should be the same variable that was scoped into
13090 and set by `org-make-tags-matcher' when it constructed MATCHER.
13092 START-LEVEL can be a string with asterisks, reducing the scope to
13093 headlines matching this string."
13094 (require 'org-agenda)
13095 (let* ((re (concat "^"
13096 (if start-level
13097 ;; Get the correct level to match
13098 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13099 org-outline-regexp)
13100 " *\\(\\<\\("
13101 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13102 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13103 (props (list 'face 'default
13104 'done-face 'org-agenda-done
13105 'undone-face 'default
13106 'mouse-face 'highlight
13107 'org-not-done-regexp org-not-done-regexp
13108 'org-todo-regexp org-todo-regexp
13109 'org-complex-heading-regexp org-complex-heading-regexp
13110 'help-echo
13111 (format "mouse-2 or RET jump to org file %s"
13112 (abbreviate-file-name
13113 (or (buffer-file-name (buffer-base-buffer))
13114 (buffer-name (buffer-base-buffer)))))))
13115 (case-fold-search nil)
13116 (org-map-continue-from nil)
13117 lspos tags tags-list
13118 (tags-alist (list (cons 0 org-file-tags)))
13119 (llast 0) rtn rtn1 level category i txt
13120 todo marker entry priority)
13121 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13122 (setq action (list 'lambda nil action)))
13123 (save-excursion
13124 (goto-char (point-min))
13125 (when (eq action 'sparse-tree)
13126 (org-overview)
13127 (org-remove-occur-highlights))
13128 (while (re-search-forward re nil t)
13129 (setq org-map-continue-from nil)
13130 (catch :skip
13131 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13132 tags (if (match-end 4) (org-match-string-no-properties 4)))
13133 (goto-char (setq lspos (match-beginning 0)))
13134 (setq level (org-reduced-level (funcall outline-level))
13135 category (org-get-category))
13136 (setq i llast llast level)
13137 ;; remove tag lists from same and sublevels
13138 (while (>= i level)
13139 (when (setq entry (assoc i tags-alist))
13140 (setq tags-alist (delete entry tags-alist)))
13141 (setq i (1- i)))
13142 ;; add the next tags
13143 (when tags
13144 (setq tags (org-split-string tags ":")
13145 tags-alist
13146 (cons (cons level tags) tags-alist)))
13147 ;; compile tags for current headline
13148 (setq tags-list
13149 (if org-use-tag-inheritance
13150 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13151 tags)
13152 org-scanner-tags tags-list)
13153 (when org-use-tag-inheritance
13154 (setcdr (car tags-alist)
13155 (mapcar (lambda (x)
13156 (setq x (copy-sequence x))
13157 (org-add-prop-inherited x))
13158 (cdar tags-alist))))
13159 (when (and tags org-use-tag-inheritance
13160 (or (not (eq t org-use-tag-inheritance))
13161 org-tags-exclude-from-inheritance))
13162 ;; selective inheritance, remove uninherited ones
13163 (setcdr (car tags-alist)
13164 (org-remove-uninherited-tags (cdar tags-alist))))
13165 (when (and
13167 ;; eval matcher only when the todo condition is OK
13168 (and (or (not todo-only) (member todo org-not-done-keywords))
13169 (let ((case-fold-search t) (org-trust-scanner-tags t))
13170 (eval matcher)))
13172 ;; Call the skipper, but return t if it does not skip,
13173 ;; so that the `and' form continues evaluating
13174 (progn
13175 (unless (eq action 'sparse-tree) (org-agenda-skip))
13178 ;; Check if timestamps are deselecting this entry
13179 (or (not todo-only)
13180 (and (member todo org-not-done-keywords)
13181 (or (not org-agenda-tags-todo-honor-ignore-options)
13182 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13184 ;; Extra check for the archive tag
13185 ;; FIXME: Does the skipper already do this????
13187 (not (member org-archive-tag tags-list))
13188 ;; we have an archive tag, should we use this anyway?
13189 (or (not org-agenda-skip-archived-trees)
13190 (and (eq action 'agenda) org-agenda-archives-mode))))
13192 ;; select this headline
13194 (cond
13195 ((eq action 'sparse-tree)
13196 (and org-highlight-sparse-tree-matches
13197 (org-get-heading) (match-end 0)
13198 (org-highlight-new-match
13199 (match-beginning 1) (match-end 1)))
13200 (org-show-context 'tags-tree))
13201 ((eq action 'agenda)
13202 (setq txt (org-agenda-format-item
13204 (concat
13205 (if (eq org-tags-match-list-sublevels 'indented)
13206 (make-string (1- level) ?.) "")
13207 (org-get-heading))
13208 category
13209 tags-list)
13210 priority (org-get-priority txt))
13211 (goto-char lspos)
13212 (setq marker (org-agenda-new-marker))
13213 (org-add-props txt props
13214 'org-marker marker 'org-hd-marker marker 'org-category category
13215 'todo-state todo
13216 'priority priority 'type "tagsmatch")
13217 (push txt rtn))
13218 ((functionp action)
13219 (setq org-map-continue-from nil)
13220 (save-excursion
13221 (setq rtn1 (funcall action))
13222 (push rtn1 rtn)))
13223 (t (error "Invalid action")))
13225 ;; if we are to skip sublevels, jump to end of subtree
13226 (unless org-tags-match-list-sublevels
13227 (org-end-of-subtree t)
13228 (backward-char 1))))
13229 ;; Get the correct position from where to continue
13230 (if org-map-continue-from
13231 (goto-char org-map-continue-from)
13232 (and (= (point) lspos) (end-of-line 1)))))
13233 (when (and (eq action 'sparse-tree)
13234 (not org-sparse-tree-open-archived-trees))
13235 (org-hide-archived-subtrees (point-min) (point-max)))
13236 (nreverse rtn)))
13238 (defun org-remove-uninherited-tags (tags)
13239 "Remove all tags that are not inherited from the list TAGS."
13240 (cond
13241 ((eq org-use-tag-inheritance t)
13242 (if org-tags-exclude-from-inheritance
13243 (org-delete-all org-tags-exclude-from-inheritance tags)
13244 tags))
13245 ((not org-use-tag-inheritance) nil)
13246 ((stringp org-use-tag-inheritance)
13247 (delq nil (mapcar
13248 (lambda (x)
13249 (if (and (string-match org-use-tag-inheritance x)
13250 (not (member x org-tags-exclude-from-inheritance)))
13251 x nil))
13252 tags)))
13253 ((listp org-use-tag-inheritance)
13254 (delq nil (mapcar
13255 (lambda (x)
13256 (if (member x org-use-tag-inheritance) x nil))
13257 tags)))))
13259 (defun org-match-sparse-tree (&optional todo-only match)
13260 "Create a sparse tree according to tags string MATCH.
13261 MATCH can contain positive and negative selection of tags, like
13262 \"+WORK+URGENT-WITHBOSS\".
13263 If optional argument TODO-ONLY is non-nil, only select lines that are
13264 also TODO lines."
13265 (interactive "P")
13266 (org-prepare-agenda-buffers (list (current-buffer)))
13267 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13269 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13271 (defvar org-cached-props nil)
13272 (defun org-cached-entry-get (pom property)
13273 (if (or (eq t org-use-property-inheritance)
13274 (and (stringp org-use-property-inheritance)
13275 (string-match org-use-property-inheritance property))
13276 (and (listp org-use-property-inheritance)
13277 (member property org-use-property-inheritance)))
13278 ;; Caching is not possible, check it directly
13279 (org-entry-get pom property 'inherit)
13280 ;; Get all properties, so that we can do complicated checks easily
13281 (cdr (assoc property (or org-cached-props
13282 (setq org-cached-props
13283 (org-entry-properties pom)))))))
13285 (defun org-global-tags-completion-table (&optional files)
13286 "Return the list of all tags in all agenda buffer/files.
13287 Optional FILES argument is a list of files which can be used
13288 instead of the agenda files."
13289 (save-excursion
13290 (org-uniquify
13291 (delq nil
13292 (apply 'append
13293 (mapcar
13294 (lambda (file)
13295 (set-buffer (find-file-noselect file))
13296 (append (org-get-buffer-tags)
13297 (mapcar (lambda (x) (if (stringp (car-safe x))
13298 (list (car-safe x)) nil))
13299 org-tag-alist)))
13300 (if (and files (car files))
13301 files
13302 (org-agenda-files))))))))
13304 (defun org-make-tags-matcher (match)
13305 "Create the TAGS/TODO matcher form for the selection string MATCH.
13307 The variable `todo-only' is scoped dynamically into this function; it will be
13308 set to t if the matcher restricts matching to TODO entries,
13309 otherwise will not be touched.
13311 Returns a cons of the selection string MATCH and the constructed
13312 lisp form implementing the matcher. The matcher is to be
13313 evaluated at an Org entry, with point on the headline,
13314 and returns t if the entry matches the
13315 selection string MATCH. The returned lisp form references
13316 two variables with information about the entry, which must be
13317 bound around the form's evaluation: todo, the TODO keyword at the
13318 entry (or nil of none); and tags-list, the list of all tags at the
13319 entry including inherited ones. Additionally, the category
13320 of the entry (if any) must be specified as the text property
13321 'org-category on the headline.
13323 See also `org-scan-tags'.
13325 (declare (special todo-only))
13326 (unless (boundp 'todo-only)
13327 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13328 (unless match
13329 ;; Get a new match request, with completion
13330 (let ((org-last-tags-completion-table
13331 (org-global-tags-completion-table)))
13332 (setq match (org-completing-read-no-i
13333 "Match: " 'org-tags-completion-function nil nil nil
13334 'org-tags-history))))
13336 ;; Parse the string and create a lisp form
13337 (let ((match0 match)
13338 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13339 minus tag mm
13340 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13341 orterms term orlist re-p str-p level-p level-op time-p
13342 prop-p pn pv po gv rest)
13343 (if (string-match "/+" match)
13344 ;; match contains also a todo-matching request
13345 (progn
13346 (setq tagsmatch (substring match 0 (match-beginning 0))
13347 todomatch (substring match (match-end 0)))
13348 (if (string-match "^!" todomatch)
13349 (setq todo-only t todomatch (substring todomatch 1)))
13350 (if (string-match "^\\s-*$" todomatch)
13351 (setq todomatch nil)))
13352 ;; only matching tags
13353 (setq tagsmatch match todomatch nil))
13355 ;; Make the tags matcher
13356 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13357 (setq tagsmatcher t)
13358 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13359 (while (setq term (pop orterms))
13360 (while (and (equal (substring term -1) "\\") orterms)
13361 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13362 (while (string-match re term)
13363 (setq rest (substring term (match-end 0))
13364 minus (and (match-end 1)
13365 (equal (match-string 1 term) "-"))
13366 tag (save-match-data (replace-regexp-in-string
13367 "\\\\-" "-"
13368 (match-string 2 term)))
13369 re-p (equal (string-to-char tag) ?{)
13370 level-p (match-end 4)
13371 prop-p (match-end 5)
13372 mm (cond
13373 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13374 (level-p
13375 (setq level-op (org-op-to-function (match-string 3 term)))
13376 `(,level-op level ,(string-to-number
13377 (match-string 4 term))))
13378 (prop-p
13379 (setq pn (match-string 5 term)
13380 po (match-string 6 term)
13381 pv (match-string 7 term)
13382 re-p (equal (string-to-char pv) ?{)
13383 str-p (equal (string-to-char pv) ?\")
13384 time-p (save-match-data
13385 (string-match "^\"[[<].*[]>]\"$" pv))
13386 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13387 (if time-p (setq pv (org-matcher-time pv)))
13388 (setq po (org-op-to-function po (if time-p 'time str-p)))
13389 (cond
13390 ((equal pn "CATEGORY")
13391 (setq gv '(get-text-property (point) 'org-category)))
13392 ((equal pn "TODO")
13393 (setq gv 'todo))
13395 (setq gv `(org-cached-entry-get nil ,pn))))
13396 (if re-p
13397 (if (eq po 'org<>)
13398 `(not (string-match ,pv (or ,gv "")))
13399 `(string-match ,pv (or ,gv "")))
13400 (if str-p
13401 `(,po (or ,gv "") ,pv)
13402 `(,po (string-to-number (or ,gv ""))
13403 ,(string-to-number pv) ))))
13404 (t `(member ,tag tags-list)))
13405 mm (if minus (list 'not mm) mm)
13406 term rest)
13407 (push mm tagsmatcher))
13408 (push (if (> (length tagsmatcher) 1)
13409 (cons 'and tagsmatcher)
13410 (car tagsmatcher))
13411 orlist)
13412 (setq tagsmatcher nil))
13413 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13414 (setq tagsmatcher
13415 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13416 ;; Make the todo matcher
13417 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13418 (setq todomatcher t)
13419 (setq orterms (org-split-string todomatch "|") orlist nil)
13420 (while (setq term (pop orterms))
13421 (while (string-match re term)
13422 (setq minus (and (match-end 1)
13423 (equal (match-string 1 term) "-"))
13424 kwd (match-string 2 term)
13425 re-p (equal (string-to-char kwd) ?{)
13426 term (substring term (match-end 0))
13427 mm (if re-p
13428 `(string-match ,(substring kwd 1 -1) todo)
13429 (list 'equal 'todo kwd))
13430 mm (if minus (list 'not mm) mm))
13431 (push mm todomatcher))
13432 (push (if (> (length todomatcher) 1)
13433 (cons 'and todomatcher)
13434 (car todomatcher))
13435 orlist)
13436 (setq todomatcher nil))
13437 (setq todomatcher (if (> (length orlist) 1)
13438 (cons 'or orlist) (car orlist))))
13440 ;; Return the string and lisp forms of the matcher
13441 (setq matcher (if todomatcher
13442 (list 'and tagsmatcher todomatcher)
13443 tagsmatcher))
13444 (when todo-only
13445 (setq matcher (list 'and '(member todo org-not-done-keywords)
13446 matcher)))
13447 (cons match0 matcher)))
13449 (defun org-op-to-function (op &optional stringp)
13450 "Turn an operator into the appropriate function."
13451 (setq op
13452 (cond
13453 ((equal op "<" ) '(< string< org-time<))
13454 ((equal op ">" ) '(> org-string> org-time>))
13455 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13456 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13457 ((member op '("=" "==")) '(= string= org-time=))
13458 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13459 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13461 (defun org<> (a b) (not (= a b)))
13462 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13463 (defun org-string>= (a b) (not (string< a b)))
13464 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13465 (defun org-string<> (a b) (not (string= a b)))
13466 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13467 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13468 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13469 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13470 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13471 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13472 (defun org-2ft (s)
13473 "Convert S to a floating point time.
13474 If S is already a number, just return it. If it is a string, parse
13475 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13476 (cond
13477 ((numberp s) s)
13478 ((stringp s)
13479 (condition-case nil
13480 (float-time (apply 'encode-time (org-parse-time-string s)))
13481 (error 0.)))
13482 (t 0.)))
13484 (defun org-time-today ()
13485 "Time in seconds today at 0:00.
13486 Returns the float number of seconds since the beginning of the
13487 epoch to the beginning of today (00:00)."
13488 (float-time (apply 'encode-time
13489 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13491 (defun org-matcher-time (s)
13492 "Interpret a time comparison value."
13493 (save-match-data
13494 (cond
13495 ((string= s "<now>") (float-time))
13496 ((string= s "<today>") (org-time-today))
13497 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13498 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13499 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13500 (+ (org-time-today)
13501 (* (string-to-number (match-string 1 s))
13502 (cdr (assoc (match-string 2 s)
13503 '(("d" . 86400.0) ("w" . 604800.0)
13504 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13505 (t (org-2ft s)))))
13507 (defun org-match-any-p (re list)
13508 "Does re match any element of list?"
13509 (setq list (mapcar (lambda (x) (string-match re x)) list))
13510 (delq nil list))
13512 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13513 (defvar org-tags-overlay (make-overlay 1 1))
13514 (org-detach-overlay org-tags-overlay)
13516 (defun org-get-local-tags-at (&optional pos)
13517 "Get a list of tags defined in the current headline."
13518 (org-get-tags-at pos 'local))
13520 (defun org-get-local-tags ()
13521 "Get a list of tags defined in the current headline."
13522 (org-get-tags-at nil 'local))
13524 (defun org-get-tags-at (&optional pos local)
13525 "Get a list of all headline tags applicable at POS.
13526 POS defaults to point. If tags are inherited, the list contains
13527 the targets in the same sequence as the headlines appear, i.e.
13528 the tags of the current headline come last.
13529 When LOCAL is non-nil, only return tags from the current headline,
13530 ignore inherited ones."
13531 (interactive)
13532 (if (and org-trust-scanner-tags
13533 (or (not pos) (equal pos (point)))
13534 (not local))
13535 org-scanner-tags
13536 (let (tags ltags lastpos parent)
13537 (save-excursion
13538 (save-restriction
13539 (widen)
13540 (goto-char (or pos (point)))
13541 (save-match-data
13542 (catch 'done
13543 (condition-case nil
13544 (progn
13545 (org-back-to-heading t)
13546 (while (not (equal lastpos (point)))
13547 (setq lastpos (point))
13548 (when (looking-at
13549 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13550 (setq ltags (org-split-string
13551 (org-match-string-no-properties 1) ":"))
13552 (when parent
13553 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13554 (setq tags (append
13555 (if parent
13556 (org-remove-uninherited-tags ltags)
13557 ltags)
13558 tags)))
13559 (or org-use-tag-inheritance (throw 'done t))
13560 (if local (throw 'done t))
13561 (or (org-up-heading-safe) (error nil))
13562 (setq parent t)))
13563 (error nil)))))
13564 (if local
13565 tags
13566 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13568 (defun org-add-prop-inherited (s)
13569 (add-text-properties 0 (length s) '(inherited t) s)
13572 (defun org-toggle-tag (tag &optional onoff)
13573 "Toggle the tag TAG for the current line.
13574 If ONOFF is `on' or `off', don't toggle but set to this state."
13575 (let (res current)
13576 (save-excursion
13577 (org-back-to-heading t)
13578 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13579 (point-at-eol) t)
13580 (progn
13581 (setq current (match-string 1))
13582 (replace-match ""))
13583 (setq current ""))
13584 (setq current (nreverse (org-split-string current ":")))
13585 (cond
13586 ((eq onoff 'on)
13587 (setq res t)
13588 (or (member tag current) (push tag current)))
13589 ((eq onoff 'off)
13590 (or (not (member tag current)) (setq current (delete tag current))))
13591 (t (if (member tag current)
13592 (setq current (delete tag current))
13593 (setq res t)
13594 (push tag current))))
13595 (end-of-line 1)
13596 (if current
13597 (progn
13598 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13599 (org-set-tags nil t))
13600 (delete-horizontal-space))
13601 (run-hooks 'org-after-tags-change-hook))
13602 res))
13604 (defun org-align-tags-here (to-col)
13605 ;; Assumes that this is a headline
13606 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13607 (beginning-of-line 1)
13608 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13609 (< pos (match-beginning 2)))
13610 (progn
13611 (setq tags-l (- (match-end 2) (match-beginning 2)))
13612 (goto-char (match-beginning 1))
13613 (insert " ")
13614 (delete-region (point) (1+ (match-beginning 2)))
13615 (setq ncol (max (current-column)
13616 (1+ col)
13617 (if (> to-col 0)
13618 to-col
13619 (- (abs to-col) tags-l))))
13620 (setq p (point))
13621 (insert (make-string (- ncol (current-column)) ?\ ))
13622 (setq ncol (current-column))
13623 (when indent-tabs-mode (tabify p (point-at-eol)))
13624 (org-move-to-column (min ncol col) t))
13625 (goto-char pos))))
13627 (defun org-set-tags-command (&optional arg just-align)
13628 "Call the set-tags command for the current entry."
13629 (interactive "P")
13630 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13631 (org-set-tags arg just-align)
13632 (save-excursion
13633 (org-back-to-heading t)
13634 (org-set-tags arg just-align))))
13636 (defun org-set-tags-to (data)
13637 "Set the tags of the current entry to DATA, replacing the current tags.
13638 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13639 If DATA is nil or the empty string, any tags will be removed."
13640 (interactive "sTags: ")
13641 (setq data
13642 (cond
13643 ((eq data nil) "")
13644 ((equal data "") "")
13645 ((stringp data)
13646 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13647 ":"))
13648 ((listp data)
13649 (concat ":" (mapconcat 'identity data ":") ":"))
13650 (t nil)))
13651 (when data
13652 (save-excursion
13653 (org-back-to-heading t)
13654 (when (looking-at org-complex-heading-regexp)
13655 (if (match-end 5)
13656 (progn
13657 (goto-char (match-beginning 5))
13658 (insert data)
13659 (delete-region (point) (point-at-eol))
13660 (org-set-tags nil 'align))
13661 (goto-char (point-at-eol))
13662 (insert " " data)
13663 (org-set-tags nil 'align)))
13664 (beginning-of-line 1)
13665 (if (looking-at ".*?\\([ \t]+\\)$")
13666 (delete-region (match-beginning 1) (match-end 1))))))
13668 (defun org-align-all-tags ()
13669 "Align the tags i all headings."
13670 (interactive)
13671 (save-excursion
13672 (or (ignore-errors (org-back-to-heading t))
13673 (outline-next-heading))
13674 (if (org-at-heading-p)
13675 (org-set-tags t)
13676 (message "No headings"))))
13678 (defvar org-indent-indentation-per-level)
13679 (defun org-set-tags (&optional arg just-align)
13680 "Set the tags for the current headline.
13681 With prefix ARG, realign all tags in headings in the current buffer."
13682 (interactive "P")
13683 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13684 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13685 'region-start-level 'region))
13686 org-loop-over-headlines-in-active-region)
13687 (org-map-entries
13688 ;; We don't use ARG and JUST-ALIGN here these args are not
13689 ;; useful when looping over headlines
13690 `(org-set-tags)
13691 org-loop-over-headlines-in-active-region
13692 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13693 (let* ((re org-outline-regexp-bol)
13694 (current (unless arg (org-get-tags-string)))
13695 (col (current-column))
13696 (org-setting-tags t)
13697 table current-tags inherited-tags ; computed below when needed
13698 tags p0 c0 c1 rpl di tc level)
13699 (if arg
13700 (save-excursion
13701 (goto-char (point-min))
13702 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13703 (while (re-search-forward re nil t)
13704 (org-set-tags nil t)
13705 (end-of-line 1)))
13706 (message "All tags realigned to column %d" org-tags-column))
13707 (if just-align
13708 (setq tags current)
13709 ;; Get a new set of tags from the user
13710 (save-excursion
13711 (setq table (append org-tag-persistent-alist
13712 (or org-tag-alist (org-get-buffer-tags))
13713 (and
13714 org-complete-tags-always-offer-all-agenda-tags
13715 (org-global-tags-completion-table
13716 (org-agenda-files))))
13717 org-last-tags-completion-table table
13718 current-tags (org-split-string current ":")
13719 inherited-tags (nreverse
13720 (nthcdr (length current-tags)
13721 (nreverse (org-get-tags-at))))
13722 tags
13723 (if (or (eq t org-use-fast-tag-selection)
13724 (and org-use-fast-tag-selection
13725 (delq nil (mapcar 'cdr table))))
13726 (org-fast-tag-selection
13727 current-tags inherited-tags table
13728 (if org-fast-tag-selection-include-todo
13729 org-todo-key-alist))
13730 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13731 (org-trim
13732 (org-icompleting-read "Tags: "
13733 'org-tags-completion-function
13734 nil nil current 'org-tags-history))))))
13735 (while (string-match "[-+&]+" tags)
13736 ;; No boolean logic, just a list
13737 (setq tags (replace-match ":" t t tags))))
13739 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13741 (if org-tags-sort-function
13742 (setq tags (mapconcat 'identity
13743 (sort (org-split-string
13744 tags (org-re "[^[:alnum:]_@#%]+"))
13745 org-tags-sort-function) ":")))
13747 (if (string-match "\\`[\t ]*\\'" tags)
13748 (setq tags "")
13749 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13750 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13752 ;; Insert new tags at the correct column
13753 (beginning-of-line 1)
13754 (setq level (or (and (looking-at org-outline-regexp)
13755 (- (match-end 0) (point) 1))
13757 (cond
13758 ((and (equal current "") (equal tags "")))
13759 ((re-search-forward
13760 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13761 (point-at-eol) t)
13762 (if (equal tags "")
13763 (setq rpl "")
13764 (goto-char (match-beginning 0))
13765 (setq c0 (current-column)
13766 ;; compute offset for the case of org-indent-mode active
13767 di (if org-indent-mode
13768 (* (1- org-indent-indentation-per-level) (1- level))
13770 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13771 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13772 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13773 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13774 (replace-match rpl t t)
13775 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13776 tags)
13777 (t (error "Tags alignment failed")))
13778 (org-move-to-column col)
13779 (unless just-align
13780 (run-hooks 'org-after-tags-change-hook))))))
13782 (defun org-change-tag-in-region (beg end tag off)
13783 "Add or remove TAG for each entry in the region.
13784 This works in the agenda, and also in an org-mode buffer."
13785 (interactive
13786 (list (region-beginning) (region-end)
13787 (let ((org-last-tags-completion-table
13788 (if (derived-mode-p 'org-mode)
13789 (org-get-buffer-tags)
13790 (org-global-tags-completion-table))))
13791 (org-icompleting-read
13792 "Tag: " 'org-tags-completion-function nil nil nil
13793 'org-tags-history))
13794 (progn
13795 (message "[s]et or [r]emove? ")
13796 (equal (read-char-exclusive) ?r))))
13797 (if (fboundp 'deactivate-mark) (deactivate-mark))
13798 (let ((agendap (equal major-mode 'org-agenda-mode))
13799 l1 l2 m buf pos newhead (cnt 0))
13800 (goto-char end)
13801 (setq l2 (1- (org-current-line)))
13802 (goto-char beg)
13803 (setq l1 (org-current-line))
13804 (loop for l from l1 to l2 do
13805 (org-goto-line l)
13806 (setq m (get-text-property (point) 'org-hd-marker))
13807 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13808 (and agendap m))
13809 (setq buf (if agendap (marker-buffer m) (current-buffer))
13810 pos (if agendap m (point)))
13811 (with-current-buffer buf
13812 (save-excursion
13813 (save-restriction
13814 (goto-char pos)
13815 (setq cnt (1+ cnt))
13816 (org-toggle-tag tag (if off 'off 'on))
13817 (setq newhead (org-get-heading)))))
13818 (and agendap (org-agenda-change-all-lines newhead m))))
13819 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13821 (defun org-tags-completion-function (string predicate &optional flag)
13822 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13823 (confirm (lambda (x) (stringp (car x)))))
13824 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13825 (setq s1 (match-string 1 string)
13826 s2 (match-string 2 string))
13827 (setq s1 "" s2 string))
13828 (cond
13829 ((eq flag nil)
13830 ;; try completion
13831 (setq rtn (try-completion s2 ctable confirm))
13832 (if (stringp rtn)
13833 (setq rtn
13834 (concat s1 s2 (substring rtn (length s2))
13835 (if (and org-add-colon-after-tag-completion
13836 (assoc rtn ctable))
13837 ":" ""))))
13838 rtn)
13839 ((eq flag t)
13840 ;; all-completions
13841 (all-completions s2 ctable confirm)
13843 ((eq flag 'lambda)
13844 ;; exact match?
13845 (assoc s2 ctable)))
13848 (defun org-fast-tag-insert (kwd tags face &optional end)
13849 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13850 (insert (format "%-12s" (concat kwd ":"))
13851 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13852 (or end "")))
13854 (defun org-fast-tag-show-exit (flag)
13855 (save-excursion
13856 (org-goto-line 3)
13857 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13858 (replace-match ""))
13859 (when flag
13860 (end-of-line 1)
13861 (org-move-to-column (- (window-width) 19) t)
13862 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13864 (defun org-set-current-tags-overlay (current prefix)
13865 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13866 (if (featurep 'xemacs)
13867 (org-overlay-display org-tags-overlay (concat prefix s)
13868 'secondary-selection)
13869 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13870 (org-overlay-display org-tags-overlay (concat prefix s)))))
13872 (defvar org-last-tag-selection-key nil)
13873 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13874 "Fast tag selection with single keys.
13875 CURRENT is the current list of tags in the headline, INHERITED is the
13876 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13877 possibly with grouping information. TODO-TABLE is a similar table with
13878 TODO keywords, should these have keys assigned to them.
13879 If the keys are nil, a-z are automatically assigned.
13880 Returns the new tags string, or nil to not change the current settings."
13881 (let* ((fulltable (append table todo-table))
13882 (maxlen (apply 'max (mapcar
13883 (lambda (x)
13884 (if (stringp (car x)) (string-width (car x)) 0))
13885 fulltable)))
13886 (buf (current-buffer))
13887 (expert (eq org-fast-tag-selection-single-key 'expert))
13888 (buffer-tags nil)
13889 (fwidth (+ maxlen 3 1 3))
13890 (ncol (/ (- (window-width) 4) fwidth))
13891 (i-face 'org-done)
13892 (c-face 'org-todo)
13893 tg cnt e c char c1 c2 ntable tbl rtn
13894 ov-start ov-end ov-prefix
13895 (exit-after-next org-fast-tag-selection-single-key)
13896 (done-keywords org-done-keywords)
13897 groups ingroup)
13898 (save-excursion
13899 (beginning-of-line 1)
13900 (if (looking-at
13901 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13902 (setq ov-start (match-beginning 1)
13903 ov-end (match-end 1)
13904 ov-prefix "")
13905 (setq ov-start (1- (point-at-eol))
13906 ov-end (1+ ov-start))
13907 (skip-chars-forward "^\n\r")
13908 (setq ov-prefix
13909 (concat
13910 (buffer-substring (1- (point)) (point))
13911 (if (> (current-column) org-tags-column)
13913 (make-string (- org-tags-column (current-column)) ?\ ))))))
13914 (move-overlay org-tags-overlay ov-start ov-end)
13915 (save-window-excursion
13916 (if expert
13917 (set-buffer (get-buffer-create " *Org tags*"))
13918 (delete-other-windows)
13919 (split-window-vertically)
13920 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13921 (erase-buffer)
13922 (org-set-local 'org-done-keywords done-keywords)
13923 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13924 (org-fast-tag-insert "Current" current c-face "\n\n")
13925 (org-fast-tag-show-exit exit-after-next)
13926 (org-set-current-tags-overlay current ov-prefix)
13927 (setq tbl fulltable char ?a cnt 0)
13928 (while (setq e (pop tbl))
13929 (cond
13930 ((equal (car e) :startgroup)
13931 (push '() groups) (setq ingroup t)
13932 (when (not (= cnt 0))
13933 (setq cnt 0)
13934 (insert "\n"))
13935 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13936 ((equal (car e) :endgroup)
13937 (setq ingroup nil cnt 0)
13938 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13939 ((equal e '(:newline))
13940 (when (not (= cnt 0))
13941 (setq cnt 0)
13942 (insert "\n")
13943 (setq e (car tbl))
13944 (while (equal (car tbl) '(:newline))
13945 (insert "\n")
13946 (setq tbl (cdr tbl)))))
13948 (setq tg (copy-sequence (car e)) c2 nil)
13949 (if (cdr e)
13950 (setq c (cdr e))
13951 ;; automatically assign a character.
13952 (setq c1 (string-to-char
13953 (downcase (substring
13954 tg (if (= (string-to-char tg) ?@) 1 0)))))
13955 (if (or (rassoc c1 ntable) (rassoc c1 table))
13956 (while (or (rassoc char ntable) (rassoc char table))
13957 (setq char (1+ char)))
13958 (setq c2 c1))
13959 (setq c (or c2 char)))
13960 (if ingroup (push tg (car groups)))
13961 (setq tg (org-add-props tg nil 'face
13962 (cond
13963 ((not (assoc tg table))
13964 (org-get-todo-face tg))
13965 ((member tg current) c-face)
13966 ((member tg inherited) i-face)
13967 (t nil))))
13968 (if (and (= cnt 0) (not ingroup)) (insert " "))
13969 (insert "[" c "] " tg (make-string
13970 (- fwidth 4 (length tg)) ?\ ))
13971 (push (cons tg c) ntable)
13972 (when (= (setq cnt (1+ cnt)) ncol)
13973 (insert "\n")
13974 (if ingroup (insert " "))
13975 (setq cnt 0)))))
13976 (setq ntable (nreverse ntable))
13977 (insert "\n")
13978 (goto-char (point-min))
13979 (if (not expert) (org-fit-window-to-buffer))
13980 (setq rtn
13981 (catch 'exit
13982 (while t
13983 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13984 (if (not groups) "no " "")
13985 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13986 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13987 (setq org-last-tag-selection-key c)
13988 (cond
13989 ((= c ?\r) (throw 'exit t))
13990 ((= c ?!)
13991 (setq groups (not groups))
13992 (goto-char (point-min))
13993 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13994 ((= c ?\C-c)
13995 (if (not expert)
13996 (org-fast-tag-show-exit
13997 (setq exit-after-next (not exit-after-next)))
13998 (setq expert nil)
13999 (delete-other-windows)
14000 (set-window-buffer (split-window-vertically) " *Org tags*")
14001 (org-switch-to-buffer-other-window " *Org tags*")
14002 (org-fit-window-to-buffer)))
14003 ((or (= c ?\C-g)
14004 (and (= c ?q) (not (rassoc c ntable))))
14005 (org-detach-overlay org-tags-overlay)
14006 (setq quit-flag t))
14007 ((= c ?\ )
14008 (setq current nil)
14009 (if exit-after-next (setq exit-after-next 'now)))
14010 ((= c ?\t)
14011 (condition-case nil
14012 (setq tg (org-icompleting-read
14013 "Tag: "
14014 (or buffer-tags
14015 (with-current-buffer buf
14016 (org-get-buffer-tags)))))
14017 (quit (setq tg "")))
14018 (when (string-match "\\S-" tg)
14019 (add-to-list 'buffer-tags (list tg))
14020 (if (member tg current)
14021 (setq current (delete tg current))
14022 (push tg current)))
14023 (if exit-after-next (setq exit-after-next 'now)))
14024 ((setq e (rassoc c todo-table) tg (car e))
14025 (with-current-buffer buf
14026 (save-excursion (org-todo tg)))
14027 (if exit-after-next (setq exit-after-next 'now)))
14028 ((setq e (rassoc c ntable) tg (car e))
14029 (if (member tg current)
14030 (setq current (delete tg current))
14031 (loop for g in groups do
14032 (if (member tg g)
14033 (mapc (lambda (x)
14034 (setq current (delete x current)))
14035 g)))
14036 (push tg current))
14037 (if exit-after-next (setq exit-after-next 'now))))
14039 ;; Create a sorted list
14040 (setq current
14041 (sort current
14042 (lambda (a b)
14043 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14044 (if (eq exit-after-next 'now) (throw 'exit t))
14045 (goto-char (point-min))
14046 (beginning-of-line 2)
14047 (delete-region (point) (point-at-eol))
14048 (org-fast-tag-insert "Current" current c-face)
14049 (org-set-current-tags-overlay current ov-prefix)
14050 (while (re-search-forward
14051 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14052 (setq tg (match-string 1))
14053 (add-text-properties
14054 (match-beginning 1) (match-end 1)
14055 (list 'face
14056 (cond
14057 ((member tg current) c-face)
14058 ((member tg inherited) i-face)
14059 (t (get-text-property (match-beginning 1) 'face))))))
14060 (goto-char (point-min)))))
14061 (org-detach-overlay org-tags-overlay)
14062 (if rtn
14063 (mapconcat 'identity current ":")
14064 nil))))
14066 (defun org-get-tags-string ()
14067 "Get the TAGS string in the current headline."
14068 (unless (org-at-heading-p t)
14069 (error "Not on a heading"))
14070 (save-excursion
14071 (beginning-of-line 1)
14072 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14073 (org-match-string-no-properties 1)
14074 "")))
14076 (defun org-get-tags ()
14077 "Get the list of tags specified in the current headline."
14078 (org-split-string (org-get-tags-string) ":"))
14080 (defun org-get-buffer-tags ()
14081 "Get a table of all tags used in the buffer, for completion."
14082 (let (tags)
14083 (save-excursion
14084 (goto-char (point-min))
14085 (while (re-search-forward
14086 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14087 (when (equal (char-after (point-at-bol 0)) ?*)
14088 (mapc (lambda (x) (add-to-list 'tags x))
14089 (org-split-string (org-match-string-no-properties 1) ":")))))
14090 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14091 (mapcar 'list tags)))
14093 ;;;; The mapping API
14095 ;;;###autoload
14096 (defun org-map-entries (func &optional match scope &rest skip)
14097 "Call FUNC at each headline selected by MATCH in SCOPE.
14099 FUNC is a function or a lisp form. The function will be called without
14100 arguments, with the cursor positioned at the beginning of the headline.
14101 The return values of all calls to the function will be collected and
14102 returned as a list.
14104 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14105 does not need to preserve point. After evaluation, the cursor will be
14106 moved to the end of the line (presumably of the headline of the
14107 processed entry) and search continues from there. Under some
14108 circumstances, this may not produce the wanted results. For example,
14109 if you have removed (e.g. archived) the current (sub)tree it could
14110 mean that the next entry will be skipped entirely. In such cases, you
14111 can specify the position from where search should continue by making
14112 FUNC set the variable `org-map-continue-from' to the desired buffer
14113 position.
14115 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14116 Only headlines that are matched by this query will be considered during
14117 the iteration. When MATCH is nil or t, all headlines will be
14118 visited by the iteration.
14120 SCOPE determines the scope of this command. It can be any of:
14122 nil The current buffer, respecting the restriction if any
14123 tree The subtree started with the entry at point
14124 region The entries within the active region, if any
14125 region-start-level
14126 The entries within the active region, but only those at
14127 the same level than the first one.
14128 file The current buffer, without restriction
14129 file-with-archives
14130 The current buffer, and any archives associated with it
14131 agenda All agenda files
14132 agenda-with-archives
14133 All agenda files with any archive files associated with them
14134 \(file1 file2 ...)
14135 If this is a list, all files in the list will be scanned
14137 The remaining args are treated as settings for the skipping facilities of
14138 the scanner. The following items can be given here:
14140 archive skip trees with the archive tag.
14141 comment skip trees with the COMMENT keyword
14142 function or Emacs Lisp form:
14143 will be used as value for `org-agenda-skip-function', so whenever
14144 the function returns t, FUNC will not be called for that
14145 entry and search will continue from the point where the
14146 function leaves it.
14148 If your function needs to retrieve the tags including inherited tags
14149 at the *current* entry, you can use the value of the variable
14150 `org-scanner-tags' which will be much faster than getting the value
14151 with `org-get-tags-at'. If your function gets properties with
14152 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14153 to t around the call to `org-entry-properties' to get the same speedup.
14154 Note that if your function moves around to retrieve tags and properties at
14155 a *different* entry, you cannot use these techniques."
14156 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14157 (not (org-region-active-p)))
14158 (let* ((org-agenda-archives-mode nil) ; just to make sure
14159 (org-agenda-skip-archived-trees (memq 'archive skip))
14160 (org-agenda-skip-comment-trees (memq 'comment skip))
14161 (org-agenda-skip-function
14162 (car (org-delete-all '(comment archive) skip)))
14163 (org-tags-match-list-sublevels t)
14164 (start-level (eq scope 'region-start-level))
14165 matcher file res
14166 org-todo-keywords-for-agenda
14167 org-done-keywords-for-agenda
14168 org-todo-keyword-alist-for-agenda
14169 org-drawers-for-agenda
14170 org-tag-alist-for-agenda
14171 todo-only)
14173 (cond
14174 ((eq match t) (setq matcher t))
14175 ((eq match nil) (setq matcher t))
14176 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14178 (save-excursion
14179 (save-restriction
14180 (cond ((eq scope 'tree)
14181 (org-back-to-heading t)
14182 (org-narrow-to-subtree)
14183 (setq scope nil))
14184 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14185 (org-region-active-p))
14186 ;; If needed, set start-level to a string like "2"
14187 (when start-level
14188 (save-excursion
14189 (goto-char (region-beginning))
14190 (unless (org-at-heading-p) (outline-next-heading))
14191 (setq start-level (org-current-level))))
14192 (narrow-to-region (region-beginning)
14193 (save-excursion
14194 (goto-char (region-end))
14195 (unless (and (bolp) (org-at-heading-p))
14196 (outline-next-heading))
14197 (point)))
14198 (setq scope nil)))
14200 (if (not scope)
14201 (progn
14202 (org-prepare-agenda-buffers
14203 (list (buffer-file-name (current-buffer))))
14204 (setq res (org-scan-tags func matcher todo-only start-level)))
14205 ;; Get the right scope
14206 (cond
14207 ((and scope (listp scope) (symbolp (car scope)))
14208 (setq scope (eval scope)))
14209 ((eq scope 'agenda)
14210 (setq scope (org-agenda-files t)))
14211 ((eq scope 'agenda-with-archives)
14212 (setq scope (org-agenda-files t))
14213 (setq scope (org-add-archive-files scope)))
14214 ((eq scope 'file)
14215 (setq scope (list (buffer-file-name))))
14216 ((eq scope 'file-with-archives)
14217 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14218 (org-prepare-agenda-buffers scope)
14219 (while (setq file (pop scope))
14220 (with-current-buffer (org-find-base-buffer-visiting file)
14221 (save-excursion
14222 (save-restriction
14223 (widen)
14224 (goto-char (point-min))
14225 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14226 res)))
14228 ;;;; Properties
14230 ;;; Setting and retrieving properties
14232 (defconst org-special-properties
14233 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14234 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14235 "The special properties valid in Org-mode.
14237 These are properties that are not defined in the property drawer,
14238 but in some other way.")
14240 (defconst org-default-properties
14241 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14242 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14243 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14244 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14245 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14246 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14247 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14248 "Some properties that are used by Org-mode for various purposes.
14249 Being in this list makes sure that they are offered for completion.")
14251 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14252 "Regular expression matching the first line of a property drawer.")
14254 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14255 "Regular expression matching the last line of a property drawer.")
14257 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14258 "Regular expression matching the first line of a property drawer.")
14260 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14261 "Regular expression matching the first line of a property drawer.")
14263 (defconst org-property-drawer-re
14264 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14265 org-property-end-re "\\)\n?")
14266 "Matches an entire property drawer.")
14268 (defconst org-clock-drawer-re
14269 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14270 org-property-end-re "\\)\n?")
14271 "Matches an entire clock drawer.")
14273 (defsubst org-re-property (property)
14274 "Return a regexp matching a PROPERTY line.
14275 Match group 1 will be set to the value."
14276 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14278 (defsubst org-re-property-keyword (property)
14279 "Return a regexp matching a PROPERTY line, possibly with no
14280 value for the property."
14281 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14283 (defun org-property-action ()
14284 "Do an action on properties."
14285 (interactive)
14286 (let (c)
14287 (org-at-property-p)
14288 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14289 (setq c (read-char-exclusive))
14290 (cond
14291 ((equal c ?s)
14292 (call-interactively 'org-set-property))
14293 ((equal c ?d)
14294 (call-interactively 'org-delete-property))
14295 ((equal c ?D)
14296 (call-interactively 'org-delete-property-globally))
14297 ((equal c ?c)
14298 (call-interactively 'org-compute-property-at-point))
14299 (t (error "No such property action %c" c)))))
14301 (defun org-inc-effort ()
14302 "Increment the value of the effort property in the current entry."
14303 (interactive)
14304 (org-set-effort nil t))
14306 (defun org-set-effort (&optional value increment)
14307 "Set the effort property of the current entry.
14308 With numerical prefix arg, use the nth allowed value, 0 stands for the
14309 10th allowed value.
14311 When INCREMENT is non-nil, set the property to the next allowed value."
14312 (interactive "P")
14313 (if (equal value 0) (setq value 10))
14314 (let* ((completion-ignore-case t)
14315 (prop org-effort-property)
14316 (cur (org-entry-get nil prop))
14317 (allowed (org-property-get-allowed-values nil prop 'table))
14318 (existing (mapcar 'list (org-property-values prop)))
14320 (val (cond
14321 ((stringp value) value)
14322 ((and allowed (integerp value))
14323 (or (car (nth (1- value) allowed))
14324 (car (org-last allowed))))
14325 ((and allowed increment)
14326 (or (caadr (member (list cur) allowed))
14327 (error "Allowed effort values are not set")))
14328 (allowed
14329 (message "Select 1-9,0, [RET%s]: %s"
14330 (if cur (concat "=" cur) "")
14331 (mapconcat 'car allowed " "))
14332 (setq rpl (read-char-exclusive))
14333 (if (equal rpl ?\r)
14335 (setq rpl (- rpl ?0))
14336 (if (equal rpl 0) (setq rpl 10))
14337 (if (and (> rpl 0) (<= rpl (length allowed)))
14338 (car (nth (1- rpl) allowed))
14339 (org-completing-read "Effort: " allowed nil))))
14341 (let (org-completion-use-ido org-completion-use-iswitchb)
14342 (org-completing-read
14343 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14344 (concat "[" cur "]") "")
14345 ": ")
14346 existing nil nil "" nil cur))))))
14347 (unless (equal (org-entry-get nil prop) val)
14348 (org-entry-put nil prop val))
14349 (message "%s is now %s" prop val)))
14351 (defun org-at-property-p ()
14352 "Is cursor inside a property drawer?"
14353 (save-excursion
14354 (beginning-of-line 1)
14355 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14356 (save-match-data ;; Used by calling procedures
14357 (let ((p (point))
14358 (range (unless (org-before-first-heading-p)
14359 (org-get-property-block))))
14360 (and range (<= (car range) p) (< p (cdr range))))))))
14362 (defun org-get-property-block (&optional beg end force)
14363 "Return the (beg . end) range of the body of the property drawer.
14364 BEG and END are the beginning and end of the current subtree, or of
14365 the part before the first headline. If they are not given, they will
14366 be found. If the drawer does not exist and FORCE is non-nil, create
14367 the drawer."
14368 (catch 'exit
14369 (save-excursion
14370 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14371 (progn (org-back-to-heading t) (point))))
14372 (end (or end (and (not (outline-next-heading)) (point-max))
14373 (point))))
14374 (goto-char beg)
14375 (if (re-search-forward org-property-start-re end t)
14376 (setq beg (1+ (match-end 0)))
14377 (if force
14378 (save-excursion
14379 (org-insert-property-drawer)
14380 (setq end (progn (outline-next-heading) (point))))
14381 (throw 'exit nil))
14382 (goto-char beg)
14383 (if (re-search-forward org-property-start-re end t)
14384 (setq beg (1+ (match-end 0)))))
14385 (if (re-search-forward org-property-end-re end t)
14386 (setq end (match-beginning 0))
14387 (or force (throw 'exit nil))
14388 (goto-char beg)
14389 (setq end beg)
14390 (org-indent-line)
14391 (insert ":END:\n"))
14392 (cons beg end)))))
14394 (defun org-entry-properties (&optional pom which specific)
14395 "Get all properties of the entry at point-or-marker POM.
14396 This includes the TODO keyword, the tags, time strings for deadline,
14397 scheduled, and clocking, and any additional properties defined in the
14398 entry. The return value is an alist, keys may occur multiple times
14399 if the property key was used several times.
14400 POM may also be nil, in which case the current entry is used.
14401 If WHICH is nil or `all', get all properties. If WHICH is
14402 `special' or `standard', only get that subclass. If WHICH
14403 is a string only get exactly this property. SPECIFIC can be a string, the
14404 specific property we are interested in. Specifying it can speed
14405 things up because then unnecessary parsing is avoided."
14406 (setq which (or which 'all))
14407 (org-with-point-at pom
14408 (let ((clockstr (substring org-clock-string 0 -1))
14409 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14410 (case-fold-search nil)
14411 beg end range props sum-props key key1 value string clocksum clocksumt)
14412 (save-excursion
14413 (when (condition-case nil
14414 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14415 (error nil))
14416 (setq beg (point))
14417 (setq sum-props (get-text-property (point) 'org-summaries))
14418 (setq clocksum (get-text-property (point) :org-clock-minutes)
14419 clocksumt (get-text-property (point) :org-clock-minutes-today))
14420 (outline-next-heading)
14421 (setq end (point))
14422 (when (memq which '(all special))
14423 ;; Get the special properties, like TODO and tags
14424 (goto-char beg)
14425 (when (and (or (not specific) (string= specific "TODO"))
14426 (looking-at org-todo-line-regexp) (match-end 2))
14427 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14428 (when (and (or (not specific) (string= specific "PRIORITY"))
14429 (looking-at org-priority-regexp))
14430 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14431 (when (or (not specific) (string= specific "FILE"))
14432 (push (cons "FILE" buffer-file-name) props))
14433 (when (and (or (not specific) (string= specific "TAGS"))
14434 (setq value (org-get-tags-string))
14435 (string-match "\\S-" value))
14436 (push (cons "TAGS" value) props))
14437 (when (and (or (not specific) (string= specific "ALLTAGS"))
14438 (setq value (org-get-tags-at)))
14439 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14440 ":"))
14441 props))
14442 (when (or (not specific) (string= specific "BLOCKED"))
14443 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14444 (when (or (not specific)
14445 (member specific
14446 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14447 "TIMESTAMP" "TIMESTAMP_IA")))
14448 (catch 'match
14449 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14450 (setq key (if (match-end 1)
14451 (substring (org-match-string-no-properties 1)
14452 0 -1))
14453 string (if (equal key clockstr)
14454 (org-trim
14455 (buffer-substring-no-properties
14456 (match-beginning 3) (goto-char
14457 (point-at-eol))))
14458 (substring (org-match-string-no-properties 3)
14459 1 -1)))
14460 ;; Get the correct property name from the key. This is
14461 ;; necessary if the user has configured time keywords.
14462 (setq key1 (concat key ":"))
14463 (cond
14464 ((not key)
14465 (setq key
14466 (if (= (char-after (match-beginning 3)) ?\[)
14467 "TIMESTAMP_IA" "TIMESTAMP")))
14468 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14469 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14470 ((equal key1 org-closed-string) (setq key "CLOSED"))
14471 ((equal key1 org-clock-string) (setq key "CLOCK")))
14472 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14473 (progn
14474 (push (cons key string) props)
14475 ;; no need to search further if match is found
14476 (throw 'match t))
14477 (when (or (equal key "CLOCK") (not (assoc key props)))
14478 (push (cons key string) props)))))))
14480 (when (memq which '(all standard))
14481 ;; Get the standard properties, like :PROP: ...
14482 (setq range (org-get-property-block beg end))
14483 (when range
14484 (goto-char (car range))
14485 (while (re-search-forward
14486 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14487 (cdr range) t)
14488 (setq key (org-match-string-no-properties 1)
14489 value (org-trim (or (org-match-string-no-properties 2) "")))
14490 (unless (member key excluded)
14491 (push (cons key (or value "")) props)))))
14492 (if clocksum
14493 (push (cons "CLOCKSUM"
14494 (org-columns-number-to-string (/ (float clocksum) 60.)
14495 'add_times))
14496 props))
14497 (if clocksumt
14498 (push (cons "CLOCKSUM_T"
14499 (org-columns-number-to-string (/ (float clocksumt) 60.)
14500 'add_times))
14501 props))
14502 (unless (assoc "CATEGORY" props)
14503 (push (cons "CATEGORY" (org-get-category)) props))
14504 (append sum-props (nreverse props)))))))
14506 (defun org-entry-get (pom property &optional inherit literal-nil)
14507 "Get value of PROPERTY for entry or content at point-or-marker POM.
14508 If INHERIT is non-nil and the entry does not have the property,
14509 then also check higher levels of the hierarchy.
14510 If INHERIT is the symbol `selective', use inheritance only if the setting
14511 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14512 If the property is present but empty, the return value is the empty string.
14513 If the property is not present at all, nil is returned.
14515 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14516 do not interpret it as the list atom nil. This is used for inheritance
14517 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14518 (org-with-point-at pom
14519 (if (and inherit (if (eq inherit 'selective)
14520 (org-property-inherit-p property)
14522 (org-entry-get-with-inheritance property literal-nil)
14523 (if (member property org-special-properties)
14524 ;; We need a special property. Use `org-entry-properties' to
14525 ;; retrieve it, but specify the wanted property
14526 (cdr (assoc property (org-entry-properties nil 'special property)))
14527 (let* ((range (org-get-property-block))
14528 (props (list (or (assoc property org-file-properties)
14529 (assoc property org-global-properties)
14530 (assoc property org-global-properties-fixed))))
14531 (ap (lambda (key)
14532 (when (re-search-forward
14533 (org-re-property key) (cdr range) t)
14534 (setq props
14535 (org-update-property-plist
14537 (if (match-end 1)
14538 (org-match-string-no-properties 1) "")
14539 props)))))
14540 val)
14541 (when (and range (goto-char (car range)))
14542 (funcall ap property)
14543 (goto-char (car range))
14544 (while (funcall ap (concat property "+")))
14545 (setq val (cdr (assoc property props)))
14546 (when val (if literal-nil val (org-not-nil val)))))))))
14548 (defun org-property-or-variable-value (var &optional inherit)
14549 "Check if there is a property fixing the value of VAR.
14550 If yes, return this value. If not, return the current value of the variable."
14551 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14552 (if (and prop (stringp prop) (string-match "\\S-" prop))
14553 (read prop)
14554 (symbol-value var))))
14556 (defun org-entry-delete (pom property)
14557 "Delete the property PROPERTY from entry at point-or-marker POM."
14558 (org-with-point-at pom
14559 (if (member property org-special-properties)
14560 nil ; cannot delete these properties.
14561 (let ((range (org-get-property-block)))
14562 (if (and range
14563 (goto-char (car range))
14564 (re-search-forward
14565 (org-re-property property)
14566 (cdr range) t))
14567 (progn
14568 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14570 nil)))))
14572 ;; Multi-values properties are properties that contain multiple values
14573 ;; These values are assumed to be single words, separated by whitespace.
14574 (defun org-entry-add-to-multivalued-property (pom property value)
14575 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14576 (let* ((old (org-entry-get pom property))
14577 (values (and old (org-split-string old "[ \t]"))))
14578 (setq value (org-entry-protect-space value))
14579 (unless (member value values)
14580 (setq values (cons value values))
14581 (org-entry-put pom property
14582 (mapconcat 'identity values " ")))))
14584 (defun org-entry-remove-from-multivalued-property (pom property value)
14585 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14586 (let* ((old (org-entry-get pom property))
14587 (values (and old (org-split-string old "[ \t]"))))
14588 (setq value (org-entry-protect-space value))
14589 (when (member value values)
14590 (setq values (delete value values))
14591 (org-entry-put pom property
14592 (mapconcat 'identity values " ")))))
14594 (defun org-entry-member-in-multivalued-property (pom property value)
14595 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14596 (let* ((old (org-entry-get pom property))
14597 (values (and old (org-split-string old "[ \t]"))))
14598 (setq value (org-entry-protect-space value))
14599 (member value values)))
14601 (defun org-entry-get-multivalued-property (pom property)
14602 "Return a list of values in a multivalued property."
14603 (let* ((value (org-entry-get pom property))
14604 (values (and value (org-split-string value "[ \t]"))))
14605 (mapcar 'org-entry-restore-space values)))
14607 (defun org-entry-put-multivalued-property (pom property &rest values)
14608 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14609 VALUES should be a list of strings. Spaces will be protected."
14610 (org-entry-put pom property
14611 (mapconcat 'org-entry-protect-space values " "))
14612 (let* ((value (org-entry-get pom property))
14613 (values (and value (org-split-string value "[ \t]"))))
14614 (mapcar 'org-entry-restore-space values)))
14616 (defun org-entry-protect-space (s)
14617 "Protect spaces and newline in string S."
14618 (while (string-match " " s)
14619 (setq s (replace-match "%20" t t s)))
14620 (while (string-match "\n" s)
14621 (setq s (replace-match "%0A" t t s)))
14624 (defun org-entry-restore-space (s)
14625 "Restore spaces and newline in string S."
14626 (while (string-match "%20" s)
14627 (setq s (replace-match " " t t s)))
14628 (while (string-match "%0A" s)
14629 (setq s (replace-match "\n" t t s)))
14632 (defvar org-entry-property-inherited-from (make-marker)
14633 "Marker pointing to the entry from where a property was inherited.
14634 Each call to `org-entry-get-with-inheritance' will set this marker to the
14635 location of the entry where the inheritance search matched. If there was
14636 no match, the marker will point nowhere.
14637 Note that also `org-entry-get' calls this function, if the INHERIT flag
14638 is set.")
14640 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14641 "Get PROPERTY of entry or content at point, search higher levels if needed.
14642 The search will stop at the first ancestor which has the property defined.
14643 If the value found is \"nil\", return nil to show that the property
14644 should be considered as undefined (this is the meaning of nil here).
14645 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14646 (move-marker org-entry-property-inherited-from nil)
14647 (let (tmp)
14648 (save-excursion
14649 (save-restriction
14650 (widen)
14651 (catch 'ex
14652 (while t
14653 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14654 (or (ignore-errors (org-back-to-heading t))
14655 (goto-char (point-min)))
14656 (move-marker org-entry-property-inherited-from (point))
14657 (throw 'ex tmp))
14658 (or (ignore-errors (org-up-heading-safe))
14659 (throw 'ex nil))))))
14660 (setq tmp (or tmp
14661 (cdr (assoc property org-file-properties))
14662 (cdr (assoc property org-global-properties))
14663 (cdr (assoc property org-global-properties-fixed))))
14664 (if literal-nil tmp (org-not-nil tmp))))
14666 (defvar org-property-changed-functions nil
14667 "Hook called when the value of a property has changed.
14668 Each hook function should accept two arguments, the name of the property
14669 and the new value.")
14671 (defun org-entry-put (pom property value)
14672 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14673 (org-with-point-at pom
14674 (org-back-to-heading t)
14675 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14676 range)
14677 (cond
14678 ((equal property "TODO")
14679 (when (and (stringp value) (string-match "\\S-" value)
14680 (not (member value org-todo-keywords-1)))
14681 (error "\"%s\" is not a valid TODO state" value))
14682 (if (or (not value)
14683 (not (string-match "\\S-" value)))
14684 (setq value 'none))
14685 (org-todo value)
14686 (org-set-tags nil 'align))
14687 ((equal property "PRIORITY")
14688 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14689 (string-to-char value) ?\ ))
14690 (org-set-tags nil 'align))
14691 ((equal property "SCHEDULED")
14692 (if (re-search-forward org-scheduled-time-regexp end t)
14693 (cond
14694 ((eq value 'earlier) (org-timestamp-change -1 'day))
14695 ((eq value 'later) (org-timestamp-change 1 'day))
14696 (t (call-interactively 'org-schedule)))
14697 (call-interactively 'org-schedule)))
14698 ((equal property "DEADLINE")
14699 (if (re-search-forward org-deadline-time-regexp end t)
14700 (cond
14701 ((eq value 'earlier) (org-timestamp-change -1 'day))
14702 ((eq value 'later) (org-timestamp-change 1 'day))
14703 (t (call-interactively 'org-deadline)))
14704 (call-interactively 'org-deadline)))
14705 ((member property org-special-properties)
14706 (error "The %s property can not yet be set with `org-entry-put'"
14707 property))
14708 (t ; a non-special property
14709 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14710 (setq range (org-get-property-block beg end 'force))
14711 (goto-char (car range))
14712 (if (re-search-forward
14713 (org-re-property-keyword property) (cdr range) t)
14714 (progn
14715 (delete-region (match-beginning 0) (match-end 0))
14716 (goto-char (match-beginning 0)))
14717 (goto-char (cdr range))
14718 (insert "\n")
14719 (backward-char 1)
14720 (org-indent-line))
14721 (insert ":" property ":")
14722 (and value (insert " " value))
14723 (org-indent-line)))))
14724 (run-hook-with-args 'org-property-changed-functions property value)))
14726 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14727 "Get all property keys in the current buffer.
14728 With INCLUDE-SPECIALS, also list the special properties that reflect things
14729 like tags and TODO state.
14730 With INCLUDE-DEFAULTS, also include properties that has special meaning
14731 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14732 and others.
14733 With INCLUDE-COLUMNS, also include property names given in COLUMN
14734 formats in the current buffer."
14735 (let (rtn range cfmt s p)
14736 (save-excursion
14737 (save-restriction
14738 (widen)
14739 (goto-char (point-min))
14740 (while (re-search-forward org-property-start-re nil t)
14741 (setq range (org-get-property-block))
14742 (goto-char (car range))
14743 (while (re-search-forward
14744 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14745 (cdr range) t)
14746 (add-to-list 'rtn (org-match-string-no-properties 1)))
14747 (outline-next-heading))))
14749 (when include-specials
14750 (setq rtn (append org-special-properties rtn)))
14752 (when include-defaults
14753 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14754 (add-to-list 'rtn org-effort-property))
14756 (when include-columns
14757 (save-excursion
14758 (save-restriction
14759 (widen)
14760 (goto-char (point-min))
14761 (while (re-search-forward
14762 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14763 nil t)
14764 (setq cfmt (match-string 2) s 0)
14765 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14766 cfmt s)
14767 (setq s (match-end 0)
14768 p (match-string 1 cfmt))
14769 (unless (or (equal p "ITEM")
14770 (member p org-special-properties))
14771 (add-to-list 'rtn (match-string 1 cfmt))))))))
14773 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14775 (defun org-property-values (key)
14776 "Return a list of all values of property KEY in the current buffer."
14777 (save-excursion
14778 (save-restriction
14779 (widen)
14780 (goto-char (point-min))
14781 (let ((re (org-re-property key))
14782 values)
14783 (while (re-search-forward re nil t)
14784 (add-to-list 'values (org-trim (match-string 1))))
14785 (delete "" values)))))
14787 (defun org-insert-property-drawer ()
14788 "Insert a property drawer into the current entry."
14789 (org-back-to-heading t)
14790 (looking-at org-outline-regexp)
14791 (let ((indent (if org-adapt-indentation
14792 (- (match-end 0) (match-beginning 0))
14794 (beg (point))
14795 (re (concat "^[ \t]*" org-keyword-time-regexp))
14796 end hiddenp)
14797 (outline-next-heading)
14798 (setq end (point))
14799 (goto-char beg)
14800 (while (re-search-forward re end t))
14801 (setq hiddenp (outline-invisible-p))
14802 (end-of-line 1)
14803 (and (equal (char-after) ?\n) (forward-char 1))
14804 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14805 (if (member (match-string 1) '("CLOCK:" ":END:"))
14806 ;; just skip this line
14807 (beginning-of-line 2)
14808 ;; Drawer start, find the end
14809 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14810 (beginning-of-line 1)))
14811 (org-skip-over-state-notes)
14812 (skip-chars-backward " \t\n\r")
14813 (if (eq (char-before) ?*) (forward-char 1))
14814 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14815 (beginning-of-line 0)
14816 (org-indent-to-column indent)
14817 (beginning-of-line 2)
14818 (org-indent-to-column indent)
14819 (beginning-of-line 0)
14820 (if hiddenp
14821 (save-excursion
14822 (org-back-to-heading t)
14823 (hide-entry))
14824 (org-flag-drawer t))))
14826 (defun org-insert-drawer (&optional arg drawer)
14827 "Insert a drawer at point.
14829 Optional argument DRAWER, when non-nil, is a string representing
14830 drawer's name. Otherwise, the user is prompted for a name.
14832 If a region is active, insert the drawer around that region
14833 instead.
14835 Point is left between drawer's boundaries."
14836 (interactive "P")
14837 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14838 "LOGBOOK"))
14839 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14840 ;; internally by Org. They are meant to be inserted
14841 ;; automatically.
14842 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14843 ;; Remove system drawers from list. Note: For some reason,
14844 ;; `org-completing-read' ignores the predicate while
14845 ;; `completing-read' handles it fine.
14846 (drawer (if arg "PROPERTIES"
14847 (or drawer
14848 (completing-read
14849 "Drawer: " org-drawers
14850 (lambda (d) (not (member d system-drawers))))))))
14851 (cond
14852 ;; With C-u, fall back on `org-insert-property-drawer'
14853 (arg (org-insert-property-drawer))
14854 ;; With an active region, insert a drawer at point.
14855 ((not (org-region-active-p))
14856 (progn
14857 (unless (bolp) (insert "\n"))
14858 (insert (format ":%s:\n\n:END:\n" drawer))
14859 (forward-line -2)))
14860 ;; Otherwise, insert the drawer at point
14862 (let ((rbeg (region-beginning))
14863 (rend (copy-marker (region-end))))
14864 (unwind-protect
14865 (progn
14866 (goto-char rbeg)
14867 (beginning-of-line)
14868 (when (save-excursion
14869 (re-search-forward org-outline-regexp-bol rend t))
14870 (error "Drawers cannot contain headlines"))
14871 ;; Position point at the beginning of the first
14872 ;; non-blank line in region. Insert drawer's opening
14873 ;; there, then indent it.
14874 (org-skip-whitespace)
14875 (beginning-of-line)
14876 (insert ":" drawer ":\n")
14877 (forward-line -1)
14878 (indent-for-tab-command)
14879 ;; Move point to the beginning of the first blank line
14880 ;; after the last non-blank line in region. Insert
14881 ;; drawer's closing, then indent it.
14882 (goto-char rend)
14883 (skip-chars-backward " \r\t\n")
14884 (insert "\n:END:")
14885 (indent-for-tab-command)
14886 (unless (eolp) (insert "\n")))
14887 ;; Clear marker, whatever the outcome of insertion is.
14888 (set-marker rend nil)))))))
14890 (defvar org-property-set-functions-alist nil
14891 "Property set function alist.
14892 Each entry should have the following format:
14894 (PROPERTY . READ-FUNCTION)
14896 The read function will be called with the same argument as
14897 `org-completing-read'.")
14899 (defun org-set-property-function (property)
14900 "Get the function that should be used to set PROPERTY.
14901 This is computed according to `org-property-set-functions-alist'."
14902 (or (cdr (assoc property org-property-set-functions-alist))
14903 'org-completing-read))
14905 (defun org-read-property-value (property)
14906 "Read PROPERTY value from user."
14907 (let* ((completion-ignore-case t)
14908 (allowed (org-property-get-allowed-values nil property 'table))
14909 (cur (org-entry-get nil property))
14910 (prompt (concat property " value"
14911 (if (and cur (string-match "\\S-" cur))
14912 (concat " [" cur "]") "") ": "))
14913 (set-function (org-set-property-function property))
14914 (val (if allowed
14915 (funcall set-function prompt allowed nil
14916 (not (get-text-property 0 'org-unrestricted
14917 (caar allowed))))
14918 (let (org-completion-use-ido org-completion-use-iswitchb)
14919 (funcall set-function prompt
14920 (mapcar 'list (org-property-values property))
14921 nil nil "" nil cur)))))
14922 (if (equal val "")
14924 val)))
14926 (defvar org-last-set-property nil)
14927 (defun org-read-property-name ()
14928 "Read a property name."
14929 (let* ((completion-ignore-case t)
14930 (keys (org-buffer-property-keys nil t t))
14931 (default-prop (or (save-excursion
14932 (save-match-data
14933 (beginning-of-line)
14934 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14935 (null (string= (match-string 1) "END"))
14936 (match-string 1))))
14937 org-last-set-property))
14938 (property (org-icompleting-read
14939 (concat "Property"
14940 (if default-prop (concat " [" default-prop "]") "")
14941 ": ")
14942 (mapcar 'list keys)
14943 nil nil nil nil
14944 default-prop
14946 (if (member property keys)
14947 property
14948 (or (cdr (assoc (downcase property)
14949 (mapcar (lambda (x) (cons (downcase x) x))
14950 keys)))
14951 property))))
14953 (defun org-set-property (property value)
14954 "In the current entry, set PROPERTY to VALUE.
14955 When called interactively, this will prompt for a property name, offering
14956 completion on existing and default properties. And then it will prompt
14957 for a value, offering completion either on allowed values (via an inherited
14958 xxx_ALL property) or on existing values in other instances of this property
14959 in the current file."
14960 (interactive (list nil nil))
14961 (let* ((property (or property (org-read-property-name)))
14962 (value (or value (org-read-property-value property)))
14963 (fn (cdr (assoc property org-properties-postprocess-alist))))
14964 (setq org-last-set-property property)
14965 ;; Possibly postprocess the inserted value:
14966 (when fn (setq value (funcall fn value)))
14967 (unless (equal (org-entry-get nil property) value)
14968 (org-entry-put nil property value))))
14970 (defun org-delete-property (property)
14971 "In the current entry, delete PROPERTY."
14972 (interactive
14973 (let* ((completion-ignore-case t)
14974 (prop (org-icompleting-read "Property: "
14975 (org-entry-properties nil 'standard))))
14976 (list prop)))
14977 (message "Property %s %s" property
14978 (if (org-entry-delete nil property)
14979 "deleted"
14980 "was not present in the entry")))
14982 (defun org-delete-property-globally (property)
14983 "Remove PROPERTY globally, from all entries."
14984 (interactive
14985 (let* ((completion-ignore-case t)
14986 (prop (org-icompleting-read
14987 "Globally remove property: "
14988 (mapcar 'list (org-buffer-property-keys)))))
14989 (list prop)))
14990 (save-excursion
14991 (save-restriction
14992 (widen)
14993 (goto-char (point-min))
14994 (let ((cnt 0))
14995 (while (re-search-forward
14996 (org-re-property property)
14997 nil t)
14998 (setq cnt (1+ cnt))
14999 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15000 (message "Property \"%s\" removed from %d entries" property cnt)))))
15002 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15004 (defun org-compute-property-at-point ()
15005 "Compute the property at point.
15006 This looks for an enclosing column format, extracts the operator and
15007 then applies it to the property in the column format's scope."
15008 (interactive)
15009 (unless (org-at-property-p)
15010 (error "Not at a property"))
15011 (let ((prop (org-match-string-no-properties 2)))
15012 (org-columns-get-format-and-top-level)
15013 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15014 (error "No operator defined for property %s" prop))
15015 (org-columns-compute prop)))
15017 (defvar org-property-allowed-value-functions nil
15018 "Hook for functions supplying allowed values for a specific property.
15019 The functions must take a single argument, the name of the property, and
15020 return a flat list of allowed values. If \":ETC\" is one of
15021 the values, this means that these values are intended as defaults for
15022 completion, but that other values should be allowed too.
15023 The functions must return nil if they are not responsible for this
15024 property.")
15026 (defun org-property-get-allowed-values (pom property &optional table)
15027 "Get allowed values for the property PROPERTY.
15028 When TABLE is non-nil, return an alist that can directly be used for
15029 completion."
15030 (let (vals)
15031 (cond
15032 ((equal property "TODO")
15033 (setq vals (org-with-point-at pom
15034 (append org-todo-keywords-1 '("")))))
15035 ((equal property "PRIORITY")
15036 (let ((n org-lowest-priority))
15037 (while (>= n org-highest-priority)
15038 (push (char-to-string n) vals)
15039 (setq n (1- n)))))
15040 ((member property org-special-properties))
15041 ((setq vals (run-hook-with-args-until-success
15042 'org-property-allowed-value-functions property)))
15044 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15045 (when (and vals (string-match "\\S-" vals))
15046 (setq vals (car (read-from-string (concat "(" vals ")"))))
15047 (setq vals (mapcar (lambda (x)
15048 (cond ((stringp x) x)
15049 ((numberp x) (number-to-string x))
15050 ((symbolp x) (symbol-name x))
15051 (t "???")))
15052 vals)))))
15053 (when (member ":ETC" vals)
15054 (setq vals (remove ":ETC" vals))
15055 (org-add-props (car vals) '(org-unrestricted t)))
15056 (if table (mapcar 'list vals) vals)))
15058 (defun org-property-previous-allowed-value (&optional previous)
15059 "Switch to the next allowed value for this property."
15060 (interactive)
15061 (org-property-next-allowed-value t))
15063 (defun org-property-next-allowed-value (&optional previous)
15064 "Switch to the next allowed value for this property."
15065 (interactive)
15066 (unless (org-at-property-p)
15067 (error "Not at a property"))
15068 (let* ((key (match-string 2))
15069 (value (match-string 3))
15070 (allowed (or (org-property-get-allowed-values (point) key)
15071 (and (member value '("[ ]" "[-]" "[X]"))
15072 '("[ ]" "[X]"))))
15073 nval)
15074 (unless allowed
15075 (error "Allowed values for this property have not been defined"))
15076 (if previous (setq allowed (reverse allowed)))
15077 (if (member value allowed)
15078 (setq nval (car (cdr (member value allowed)))))
15079 (setq nval (or nval (car allowed)))
15080 (if (equal nval value)
15081 (error "Only one allowed value for this property"))
15082 (org-at-property-p)
15083 (replace-match (concat " :" key ": " nval) t t)
15084 (org-indent-line)
15085 (beginning-of-line 1)
15086 (skip-chars-forward " \t")
15087 (run-hook-with-args 'org-property-changed-functions key nval)))
15089 (defun org-find-olp (path &optional this-buffer)
15090 "Return a marker pointing to the entry at outline path OLP.
15091 If anything goes wrong, throw an error.
15092 You can wrap this call to catch the error like this:
15094 (condition-case msg
15095 (org-mobile-locate-entry (match-string 4))
15096 (error (nth 1 msg)))
15098 The return value will then be either a string with the error message,
15099 or a marker if everything is OK.
15101 If THIS-BUFFER is set, the outline path does not contain a file,
15102 only headings."
15103 (let* ((file (if this-buffer buffer-file-name (pop path)))
15104 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15105 (level 1)
15106 (lmin 1)
15107 (lmax 1)
15108 limit re end found pos heading cnt flevel)
15109 (unless buffer (error "File not found :%s" file))
15110 (with-current-buffer buffer
15111 (save-excursion
15112 (save-restriction
15113 (widen)
15114 (setq limit (point-max))
15115 (goto-char (point-min))
15116 (while (setq heading (pop path))
15117 (setq re (format org-complex-heading-regexp-format
15118 (regexp-quote heading)))
15119 (setq cnt 0 pos (point))
15120 (while (re-search-forward re end t)
15121 (setq level (- (match-end 1) (match-beginning 1)))
15122 (if (and (>= level lmin) (<= level lmax))
15123 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15124 (when (= cnt 0) (error "Heading not found on level %d: %s"
15125 lmax heading))
15126 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15127 lmax heading))
15128 (goto-char found)
15129 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15130 (setq end (save-excursion (org-end-of-subtree t t))))
15131 (when (org-at-heading-p)
15132 (move-marker (make-marker) (point))))))))
15134 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15135 "Find node HEADING in BUFFER.
15136 Return a marker to the heading if it was found, or nil if not.
15137 If POS-ONLY is set, return just the position instead of a marker.
15139 The heading text must match exact, but it may have a TODO keyword,
15140 a priority cookie and tags in the standard locations."
15141 (with-current-buffer (or buffer (current-buffer))
15142 (save-excursion
15143 (save-restriction
15144 (widen)
15145 (goto-char (point-min))
15146 (let (case-fold-search)
15147 (if (re-search-forward
15148 (format org-complex-heading-regexp-format
15149 (regexp-quote heading)) nil t)
15150 (if pos-only
15151 (match-beginning 0)
15152 (move-marker (make-marker) (match-beginning 0)))))))))
15154 (defun org-find-exact-heading-in-directory (heading &optional dir)
15155 "Find Org node headline HEADING in all .org files in directory DIR.
15156 When the target headline is found, return a marker to this location."
15157 (let ((files (directory-files (or dir default-directory)
15158 nil "\\`[^.#].*\\.org\\'"))
15159 file visiting m buffer)
15160 (catch 'found
15161 (while (setq file (pop files))
15162 (message "trying %s" file)
15163 (setq visiting (org-find-base-buffer-visiting file))
15164 (setq buffer (or visiting (find-file-noselect file)))
15165 (setq m (org-find-exact-headline-in-buffer
15166 heading buffer))
15167 (when (and (not m) (not visiting)) (kill-buffer buffer))
15168 (and m (throw 'found m))))))
15170 (defun org-find-entry-with-id (ident)
15171 "Locate the entry that contains the ID property with exact value IDENT.
15172 IDENT can be a string, a symbol or a number, this function will search for
15173 the string representation of it.
15174 Return the position where this entry starts, or nil if there is no such entry."
15175 (interactive "sID: ")
15176 (let ((id (cond
15177 ((stringp ident) ident)
15178 ((symbol-name ident) (symbol-name ident))
15179 ((numberp ident) (number-to-string ident))
15180 (t (error "IDENT %s must be a string, symbol or number" ident))))
15181 (case-fold-search nil))
15182 (save-excursion
15183 (save-restriction
15184 (widen)
15185 (goto-char (point-min))
15186 (when (re-search-forward
15187 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15188 nil t)
15189 (org-back-to-heading t)
15190 (point))))))
15192 ;;;; Timestamps
15194 (defvar org-last-changed-timestamp nil)
15195 (defvar org-last-inserted-timestamp nil
15196 "The last time stamp inserted with `org-insert-time-stamp'.")
15197 (defvar org-time-was-given) ; dynamically scoped parameter
15198 (defvar org-end-time-was-given) ; dynamically scoped parameter
15199 (defvar org-ts-what) ; dynamically scoped parameter
15201 (defun org-time-stamp (arg &optional inactive)
15202 "Prompt for a date/time and insert a time stamp.
15203 If the user specifies a time like HH:MM or if this command is
15204 called with at least one prefix argument, the time stamp contains
15205 the date and the time. Otherwise, only the date is be included.
15207 All parts of a date not specified by the user is filled in from
15208 the current date/time. So if you just press return without
15209 typing anything, the time stamp will represent the current
15210 date/time.
15212 If there is already a timestamp at the cursor, it will be
15213 modified.
15215 With two universal prefix arguments, insert an active timestamp
15216 with the current time without prompting the user."
15217 (interactive "P")
15218 (let* ((ts nil)
15219 (default-time
15220 ;; Default time is either today, or, when entering a range,
15221 ;; the range start.
15222 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15223 (save-excursion
15224 (re-search-backward
15225 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15226 (- (point) 20) t)))
15227 (apply 'encode-time (org-parse-time-string (match-string 1)))
15228 (current-time)))
15229 (default-input (and ts (org-get-compact-tod ts)))
15230 (repeater (save-excursion
15231 (save-match-data
15232 (beginning-of-line)
15233 (when (re-search-forward
15234 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15235 (save-excursion (progn (end-of-line) (point))) t)
15236 (match-string 0)))))
15237 org-time-was-given org-end-time-was-given time)
15238 (cond
15239 ((and (org-at-timestamp-p t)
15240 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15241 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15242 (insert "--")
15243 (setq time (let ((this-command this-command))
15244 (org-read-date arg 'totime nil nil
15245 default-time default-input inactive)))
15246 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15247 ((org-at-timestamp-p t)
15248 (setq time (let ((this-command this-command))
15249 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15250 (when (org-at-timestamp-p t) ; just to get the match data
15251 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15252 (replace-match "")
15253 (setq org-last-changed-timestamp
15254 (org-insert-time-stamp
15255 time (or org-time-was-given arg)
15256 inactive nil nil (list org-end-time-was-given)))
15257 (when repeater (goto-char (1- (point))) (insert " " repeater)
15258 (setq org-last-changed-timestamp
15259 (concat (substring org-last-inserted-timestamp 0 -1)
15260 " " repeater ">"))))
15261 (message "Timestamp updated"))
15262 ((equal arg '(16))
15263 (org-insert-time-stamp (current-time) t))
15265 (setq time (let ((this-command this-command))
15266 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15267 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15268 nil nil (list org-end-time-was-given))))))
15270 ;; FIXME: can we use this for something else, like computing time differences?
15271 (defun org-get-compact-tod (s)
15272 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15273 (let* ((t1 (match-string 1 s))
15274 (h1 (string-to-number (match-string 2 s)))
15275 (m1 (string-to-number (match-string 3 s)))
15276 (t2 (and (match-end 4) (match-string 5 s)))
15277 (h2 (and t2 (string-to-number (match-string 6 s))))
15278 (m2 (and t2 (string-to-number (match-string 7 s))))
15279 dh dm)
15280 (if (not t2)
15282 (setq dh (- h2 h1) dm (- m2 m1))
15283 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15284 (concat t1 "+" (number-to-string dh)
15285 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15287 (defun org-time-stamp-inactive (&optional arg)
15288 "Insert an inactive time stamp.
15289 An inactive time stamp is enclosed in square brackets instead of angle
15290 brackets. It is inactive in the sense that it does not trigger agenda entries,
15291 does not link to the calendar and cannot be changed with the S-cursor keys.
15292 So these are more for recording a certain time/date."
15293 (interactive "P")
15294 (org-time-stamp arg 'inactive))
15296 (defvar org-date-ovl (make-overlay 1 1))
15297 (overlay-put org-date-ovl 'face 'org-date-selected)
15298 (org-detach-overlay org-date-ovl)
15300 (defvar org-ans1) ; dynamically scoped parameter
15301 (defvar org-ans2) ; dynamically scoped parameter
15303 (defvar org-plain-time-of-day-regexp) ; defined below
15305 (defvar org-overriding-default-time nil) ; dynamically scoped
15306 (defvar org-read-date-overlay nil)
15307 (defvar org-dcst nil) ; dynamically scoped
15308 (defvar org-read-date-history nil)
15309 (defvar org-read-date-final-answer nil)
15310 (defvar org-read-date-analyze-futurep nil)
15311 (defvar org-read-date-analyze-forced-year nil)
15312 (defvar org-read-date-inactive)
15314 (defun org-read-date (&optional org-with-time to-time from-string prompt
15315 default-time default-input inactive)
15316 "Read a date, possibly a time, and make things smooth for the user.
15317 The prompt will suggest to enter an ISO date, but you can also enter anything
15318 which will at least partially be understood by `parse-time-string'.
15319 Unrecognized parts of the date will default to the current day, month, year,
15320 hour and minute. If this command is called to replace a timestamp at point,
15321 or to enter the second timestamp of a range, the default time is taken
15322 from the existing stamp. Furthermore, the command prefers the future,
15323 so if you are giving a date where the year is not given, and the day-month
15324 combination is already past in the current year, it will assume you
15325 mean next year. For details, see the manual. A few examples:
15327 3-2-5 --> 2003-02-05
15328 feb 15 --> currentyear-02-15
15329 2/15 --> currentyear-02-15
15330 sep 12 9 --> 2009-09-12
15331 12:45 --> today 12:45
15332 22 sept 0:34 --> currentyear-09-22 0:34
15333 12 --> currentyear-currentmonth-12
15334 Fri --> nearest Friday (today or later)
15335 etc.
15337 Furthermore you can specify a relative date by giving, as the *first* thing
15338 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15339 change in days weeks, months, years.
15340 With a single plus or minus, the date is relative to today. With a double
15341 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15342 +4d --> four days from today
15343 +4 --> same as above
15344 +2w --> two weeks from today
15345 ++5 --> five days from default date
15347 The function understands only English month and weekday abbreviations.
15349 While prompting, a calendar is popped up - you can also select the
15350 date with the mouse (button 1). The calendar shows a period of three
15351 months. To scroll it to other months, use the keys `>' and `<'.
15352 If you don't like the calendar, turn it off with
15353 \(setq org-read-date-popup-calendar nil)
15355 With optional argument TO-TIME, the date will immediately be converted
15356 to an internal time.
15357 With an optional argument WITH-TIME, the prompt will suggest to also
15358 insert a time. Note that when WITH-TIME is not set, you can still
15359 enter a time, and this function will inform the calling routine about
15360 this change. The calling routine may then choose to change the format
15361 used to insert the time stamp into the buffer to include the time.
15362 With optional argument FROM-STRING, read from this string instead from
15363 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15364 the time/date that is used for everything that is not specified by the
15365 user."
15366 (require 'parse-time)
15367 (let* ((org-time-stamp-rounding-minutes
15368 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15369 (org-dcst org-display-custom-times)
15370 (ct (org-current-time))
15371 (org-def (or org-overriding-default-time default-time ct))
15372 (org-defdecode (decode-time org-def))
15373 (dummy (progn
15374 (when (< (nth 2 org-defdecode) org-extend-today-until)
15375 (setcar (nthcdr 2 org-defdecode) -1)
15376 (setcar (nthcdr 1 org-defdecode) 59)
15377 (setq org-def (apply 'encode-time org-defdecode)
15378 org-defdecode (decode-time org-def)))))
15379 (calendar-frame-setup nil)
15380 (calendar-setup nil)
15381 (calendar-move-hook nil)
15382 (calendar-view-diary-initially-flag nil)
15383 (calendar-view-holidays-initially-flag nil)
15384 (timestr (format-time-string
15385 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15386 (prompt (concat (if prompt (concat prompt " ") "")
15387 (format "Date+time [%s]: " timestr)))
15388 ans (org-ans0 "") org-ans1 org-ans2 final)
15390 (cond
15391 (from-string (setq ans from-string))
15392 (org-read-date-popup-calendar
15393 (save-excursion
15394 (save-window-excursion
15395 (calendar)
15396 (org-eval-in-calendar '(setq cursor-type nil) t)
15397 (unwind-protect
15398 (progn
15399 (calendar-forward-day (- (time-to-days org-def)
15400 (calendar-absolute-from-gregorian
15401 (calendar-current-date))))
15402 (org-eval-in-calendar nil t)
15403 (let* ((old-map (current-local-map))
15404 (map (copy-keymap calendar-mode-map))
15405 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15406 (org-defkey map (kbd "RET") 'org-calendar-select)
15407 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15408 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15409 (org-defkey minibuffer-local-map [(meta shift left)]
15410 (lambda () (interactive)
15411 (org-eval-in-calendar '(calendar-backward-month 1))))
15412 (org-defkey minibuffer-local-map [(meta shift right)]
15413 (lambda () (interactive)
15414 (org-eval-in-calendar '(calendar-forward-month 1))))
15415 (org-defkey minibuffer-local-map [(meta shift up)]
15416 (lambda () (interactive)
15417 (org-eval-in-calendar '(calendar-backward-year 1))))
15418 (org-defkey minibuffer-local-map [(meta shift down)]
15419 (lambda () (interactive)
15420 (org-eval-in-calendar '(calendar-forward-year 1))))
15421 (org-defkey minibuffer-local-map [?\e (shift left)]
15422 (lambda () (interactive)
15423 (org-eval-in-calendar '(calendar-backward-month 1))))
15424 (org-defkey minibuffer-local-map [?\e (shift right)]
15425 (lambda () (interactive)
15426 (org-eval-in-calendar '(calendar-forward-month 1))))
15427 (org-defkey minibuffer-local-map [?\e (shift up)]
15428 (lambda () (interactive)
15429 (org-eval-in-calendar '(calendar-backward-year 1))))
15430 (org-defkey minibuffer-local-map [?\e (shift down)]
15431 (lambda () (interactive)
15432 (org-eval-in-calendar '(calendar-forward-year 1))))
15433 (org-defkey minibuffer-local-map [(shift up)]
15434 (lambda () (interactive)
15435 (org-eval-in-calendar '(calendar-backward-week 1))))
15436 (org-defkey minibuffer-local-map [(shift down)]
15437 (lambda () (interactive)
15438 (org-eval-in-calendar '(calendar-forward-week 1))))
15439 (org-defkey minibuffer-local-map [(shift left)]
15440 (lambda () (interactive)
15441 (org-eval-in-calendar '(calendar-backward-day 1))))
15442 (org-defkey minibuffer-local-map [(shift right)]
15443 (lambda () (interactive)
15444 (org-eval-in-calendar '(calendar-forward-day 1))))
15445 (org-defkey minibuffer-local-map ">"
15446 (lambda () (interactive)
15447 (org-eval-in-calendar '(scroll-calendar-left 1))))
15448 (org-defkey minibuffer-local-map "<"
15449 (lambda () (interactive)
15450 (org-eval-in-calendar '(scroll-calendar-right 1))))
15451 (org-defkey minibuffer-local-map "\C-v"
15452 (lambda () (interactive)
15453 (org-eval-in-calendar
15454 '(calendar-scroll-left-three-months 1))))
15455 (org-defkey minibuffer-local-map "\M-v"
15456 (lambda () (interactive)
15457 (org-eval-in-calendar
15458 '(calendar-scroll-right-three-months 1))))
15459 (run-hooks 'org-read-date-minibuffer-setup-hook)
15460 (unwind-protect
15461 (progn
15462 (use-local-map map)
15463 (setq org-read-date-inactive inactive)
15464 (add-hook 'post-command-hook 'org-read-date-display)
15465 (setq org-ans0 (read-string prompt default-input
15466 'org-read-date-history nil))
15467 ;; org-ans0: from prompt
15468 ;; org-ans1: from mouse click
15469 ;; org-ans2: from calendar motion
15470 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15471 (remove-hook 'post-command-hook 'org-read-date-display)
15472 (use-local-map old-map)
15473 (when org-read-date-overlay
15474 (delete-overlay org-read-date-overlay)
15475 (setq org-read-date-overlay nil)))))
15476 (bury-buffer "*Calendar*")))))
15478 (t ; Naked prompt only
15479 (unwind-protect
15480 (setq ans (read-string prompt default-input
15481 'org-read-date-history timestr))
15482 (when org-read-date-overlay
15483 (delete-overlay org-read-date-overlay)
15484 (setq org-read-date-overlay nil)))))
15486 (setq final (org-read-date-analyze ans org-def org-defdecode))
15488 (when org-read-date-analyze-forced-year
15489 (message "Year was forced into %s"
15490 (if org-read-date-force-compatible-dates
15491 "compatible range (1970-2037)"
15492 "range representable on this machine"))
15493 (ding))
15495 ;; One round trip to get rid of 34th of August and stuff like that....
15496 (setq final (decode-time (apply 'encode-time final)))
15498 (setq org-read-date-final-answer ans)
15500 (if to-time
15501 (apply 'encode-time final)
15502 (if (and (boundp 'org-time-was-given) org-time-was-given)
15503 (format "%04d-%02d-%02d %02d:%02d"
15504 (nth 5 final) (nth 4 final) (nth 3 final)
15505 (nth 2 final) (nth 1 final))
15506 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15508 (defvar org-def)
15509 (defvar org-defdecode)
15510 (defvar org-with-time)
15511 (defun org-read-date-display ()
15512 "Display the current date prompt interpretation in the minibuffer."
15513 (when org-read-date-display-live
15514 (when org-read-date-overlay
15515 (delete-overlay org-read-date-overlay))
15516 (when (minibufferp (current-buffer))
15517 (save-excursion
15518 (end-of-line 1)
15519 (while (not (equal (buffer-substring
15520 (max (point-min) (- (point) 4)) (point))
15521 " "))
15522 (insert " ")))
15523 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15524 " " (or org-ans1 org-ans2)))
15525 (org-end-time-was-given nil)
15526 (f (org-read-date-analyze ans org-def org-defdecode))
15527 (fmts (if org-dcst
15528 org-time-stamp-custom-formats
15529 org-time-stamp-formats))
15530 (fmt (if (or org-with-time
15531 (and (boundp 'org-time-was-given) org-time-was-given))
15532 (cdr fmts)
15533 (car fmts)))
15534 (txt (format-time-string fmt (apply 'encode-time f)))
15535 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15536 (txt (concat "=> " txt)))
15537 (when (and org-end-time-was-given
15538 (string-match org-plain-time-of-day-regexp txt))
15539 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15540 org-end-time-was-given
15541 (substring txt (match-end 0)))))
15542 (when org-read-date-analyze-futurep
15543 (setq txt (concat txt " (=>F)")))
15544 (setq org-read-date-overlay
15545 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15546 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15548 (defun org-read-date-analyze (ans org-def org-defdecode)
15549 "Analyze the combined answer of the date prompt."
15550 ;; FIXME: cleanup and comment
15551 (let ((nowdecode (decode-time (current-time)))
15552 delta deltan deltaw deltadef year month day
15553 hour minute second wday pm h2 m2 tl wday1
15554 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15555 (setq org-read-date-analyze-futurep nil
15556 org-read-date-analyze-forced-year nil)
15557 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15558 (setq ans "+0"))
15560 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15561 (unless (save-match-data (string-match org-plain-time-of-day-regexp ans))
15562 (setq ans (replace-match "" t t ans)
15563 deltan (car delta)
15564 deltaw (nth 1 delta)
15565 deltadef (nth 2 delta))))
15567 ;; Check if there is an iso week date in there
15568 ;; If yes, store the info and postpone interpreting it until the rest
15569 ;; of the parsing is done
15570 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15571 (setq iso-year (if (match-end 1)
15572 (org-small-year-to-year
15573 (string-to-number (match-string 1 ans))))
15574 iso-weekday (if (match-end 3)
15575 (string-to-number (match-string 3 ans)))
15576 iso-week (string-to-number (match-string 2 ans)))
15577 (setq ans (replace-match "" t t ans)))
15579 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15580 (when (string-match
15581 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15582 (setq year (if (match-end 2)
15583 (string-to-number (match-string 2 ans))
15584 (progn (setq kill-year t)
15585 (string-to-number (format-time-string "%Y"))))
15586 month (string-to-number (match-string 3 ans))
15587 day (string-to-number (match-string 4 ans)))
15588 (if (< year 100) (setq year (+ 2000 year)))
15589 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15590 t nil ans)))
15592 ;; Help matching dotted european dates
15593 (when (string-match
15594 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15595 (setq year (if (match-end 3)
15596 (string-to-number (match-string 3 ans))
15597 (progn (setq kill-year t)
15598 (string-to-number (format-time-string "%Y"))))
15599 day (string-to-number (match-string 1 ans))
15600 month (string-to-number (match-string 2 ans))
15601 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15602 t nil ans)))
15604 ;; Help matching american dates, like 5/30 or 5/30/7
15605 (when (string-match
15606 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15607 (setq year (if (match-end 4)
15608 (string-to-number (match-string 4 ans))
15609 (progn (setq kill-year t)
15610 (string-to-number (format-time-string "%Y"))))
15611 month (string-to-number (match-string 1 ans))
15612 day (string-to-number (match-string 2 ans)))
15613 (if (< year 100) (setq year (+ 2000 year)))
15614 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15615 t nil ans)))
15616 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15617 ;; If there is a time with am/pm, and *no* time without it, we convert
15618 ;; so that matching will be successful.
15619 (loop for i from 1 to 2 do ; twice, for end time as well
15620 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15621 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15622 (setq hour (string-to-number (match-string 1 ans))
15623 minute (if (match-end 3)
15624 (string-to-number (match-string 3 ans))
15626 pm (equal ?p
15627 (string-to-char (downcase (match-string 4 ans)))))
15628 (if (and (= hour 12) (not pm))
15629 (setq hour 0)
15630 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15631 (setq ans (replace-match (format "%02d:%02d" hour minute)
15632 t t ans))))
15634 ;; Check if a time range is given as a duration
15635 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15636 (setq hour (string-to-number (match-string 1 ans))
15637 h2 (+ hour (string-to-number (match-string 3 ans)))
15638 minute (string-to-number (match-string 2 ans))
15639 m2 (+ minute (if (match-end 5) (string-to-number
15640 (match-string 5 ans))0)))
15641 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15642 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15643 t t ans)))
15645 ;; Check if there is a time range
15646 (when (boundp 'org-end-time-was-given)
15647 (setq org-time-was-given nil)
15648 (when (and (string-match org-plain-time-of-day-regexp ans)
15649 (match-end 8))
15650 (setq org-end-time-was-given (match-string 8 ans))
15651 (setq ans (concat (substring ans 0 (match-beginning 7))
15652 (substring ans (match-end 7))))))
15654 (setq tl (parse-time-string ans)
15655 day (or (nth 3 tl) (nth 3 org-defdecode))
15656 month (or (nth 4 tl)
15657 (if (and org-read-date-prefer-future
15658 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15659 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15660 (nth 4 org-defdecode)))
15661 year (or (and (not kill-year) (nth 5 tl))
15662 (if (and org-read-date-prefer-future
15663 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15664 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15665 (nth 5 org-defdecode)))
15666 hour (or (nth 2 tl) (nth 2 org-defdecode))
15667 minute (or (nth 1 tl) (nth 1 org-defdecode))
15668 second (or (nth 0 tl) 0)
15669 wday (nth 6 tl))
15671 (when (and (eq org-read-date-prefer-future 'time)
15672 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15673 (equal day (nth 3 nowdecode))
15674 (equal month (nth 4 nowdecode))
15675 (equal year (nth 5 nowdecode))
15676 (nth 2 tl)
15677 (or (< (nth 2 tl) (nth 2 nowdecode))
15678 (and (= (nth 2 tl) (nth 2 nowdecode))
15679 (nth 1 tl)
15680 (< (nth 1 tl) (nth 1 nowdecode)))))
15681 (setq day (1+ day)
15682 futurep t))
15684 ;; Special date definitions below
15685 (cond
15686 (iso-week
15687 ;; There was an iso week
15688 (require 'cal-iso)
15689 (setq futurep nil)
15690 (setq year (or iso-year year)
15691 day (or iso-weekday wday 1)
15692 wday nil ; to make sure that the trigger below does not match
15693 iso-date (calendar-gregorian-from-absolute
15694 (calendar-absolute-from-iso
15695 (list iso-week day year))))
15696 ; FIXME: Should we also push ISO weeks into the future?
15697 ; (when (and org-read-date-prefer-future
15698 ; (not iso-year)
15699 ; (< (calendar-absolute-from-gregorian iso-date)
15700 ; (time-to-days (current-time))))
15701 ; (setq year (1+ year)
15702 ; iso-date (calendar-gregorian-from-absolute
15703 ; (calendar-absolute-from-iso
15704 ; (list iso-week day year)))))
15705 (setq month (car iso-date)
15706 year (nth 2 iso-date)
15707 day (nth 1 iso-date)))
15708 (deltan
15709 (setq futurep nil)
15710 (unless deltadef
15711 (let ((now (decode-time (current-time))))
15712 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15713 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15714 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15715 ((equal deltaw "m") (setq month (+ month deltan)))
15716 ((equal deltaw "y") (setq year (+ year deltan)))))
15717 ((and wday (not (nth 3 tl)))
15718 ;; Weekday was given, but no day, so pick that day in the week
15719 ;; on or after the derived date.
15720 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15721 (unless (equal wday wday1)
15722 (setq day (+ day (% (- wday wday1 -7) 7))))))
15723 (if (and (boundp 'org-time-was-given)
15724 (nth 2 tl))
15725 (setq org-time-was-given t))
15726 (if (< year 100) (setq year (+ 2000 year)))
15727 ;; Check of the date is representable
15728 (if org-read-date-force-compatible-dates
15729 (progn
15730 (if (< year 1970)
15731 (setq year 1970 org-read-date-analyze-forced-year t))
15732 (if (> year 2037)
15733 (setq year 2037 org-read-date-analyze-forced-year t)))
15734 (condition-case nil
15735 (ignore (encode-time second minute hour day month year))
15736 (error
15737 (setq year (nth 5 org-defdecode))
15738 (setq org-read-date-analyze-forced-year t))))
15739 (setq org-read-date-analyze-futurep futurep)
15740 (list second minute hour day month year)))
15742 (defvar parse-time-weekdays)
15743 (defun org-read-date-get-relative (s today default)
15744 "Check string S for special relative date string.
15745 TODAY and DEFAULT are internal times, for today and for a default.
15746 Return shift list (N what def-flag)
15747 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15748 N is the number of WHATs to shift.
15749 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15750 the DEFAULT date rather than TODAY."
15751 (require 'parse-time)
15752 (when (and
15753 (string-match
15754 (concat
15755 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15756 "\\([0-9]+\\)?"
15757 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15758 "\\([ \t]\\|$\\)") s)
15759 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15760 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15761 (string-to-char (substring (match-string 1 s) -1))
15762 ?+))
15763 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15764 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15765 (what (if (match-end 3) (match-string 3 s) "d"))
15766 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15767 (date (if rel default today))
15768 (wday (nth 6 (decode-time date)))
15769 delta)
15770 (if wday1
15771 (progn
15772 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15773 (if (= dir ?-) (setq delta (- delta 7)))
15774 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15775 (list delta "d" rel))
15776 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15778 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15779 "Turn a user-specified date into the internal representation.
15780 The internal representation needed by the calendar is (month day year).
15781 This is a wrapper to handle the brain-dead convention in calendar that
15782 user function argument order change dependent on argument order."
15783 (if (boundp 'calendar-date-style)
15784 (cond
15785 ((eq calendar-date-style 'american)
15786 (list arg1 arg2 arg3))
15787 ((eq calendar-date-style 'european)
15788 (list arg2 arg1 arg3))
15789 ((eq calendar-date-style 'iso)
15790 (list arg2 arg3 arg1)))
15791 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15792 (if (org-bound-and-true-p european-calendar-style)
15793 (list arg2 arg1 arg3)
15794 (list arg1 arg2 arg3)))))
15796 (defun org-eval-in-calendar (form &optional keepdate)
15797 "Eval FORM in the calendar window and return to current window.
15798 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15799 otherwise stick to the current value of `org-ans2'."
15800 (let ((sf (selected-frame))
15801 (sw (selected-window)))
15802 (select-window (get-buffer-window "*Calendar*" t))
15803 (eval form)
15804 (when (and (not keepdate) (calendar-cursor-to-date))
15805 (let* ((date (calendar-cursor-to-date))
15806 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15807 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15808 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15809 (select-window sw)
15810 (org-select-frame-set-input-focus sf)))
15812 (defun org-calendar-select ()
15813 "Return to `org-read-date' with the date currently selected.
15814 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15815 (interactive)
15816 (when (calendar-cursor-to-date)
15817 (let* ((date (calendar-cursor-to-date))
15818 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15819 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15820 (if (active-minibuffer-window) (exit-minibuffer))))
15822 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15823 "Insert a date stamp for the date given by the internal TIME.
15824 WITH-HM means use the stamp format that includes the time of the day.
15825 INACTIVE means use square brackets instead of angular ones, so that the
15826 stamp will not contribute to the agenda.
15827 PRE and POST are optional strings to be inserted before and after the
15828 stamp.
15829 The command returns the inserted time stamp."
15830 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15831 stamp)
15832 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15833 (insert-before-markers (or pre ""))
15834 (when (listp extra)
15835 (setq extra (car extra))
15836 (if (and (stringp extra)
15837 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15838 (setq extra (format "-%02d:%02d"
15839 (string-to-number (match-string 1 extra))
15840 (string-to-number (match-string 2 extra))))
15841 (setq extra nil)))
15842 (when extra
15843 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15844 (insert-before-markers (setq stamp (format-time-string fmt time)))
15845 (insert-before-markers (or post ""))
15846 (setq org-last-inserted-timestamp stamp)))
15848 (defun org-toggle-time-stamp-overlays ()
15849 "Toggle the use of custom time stamp formats."
15850 (interactive)
15851 (setq org-display-custom-times (not org-display-custom-times))
15852 (unless org-display-custom-times
15853 (let ((p (point-min)) (bmp (buffer-modified-p)))
15854 (while (setq p (next-single-property-change p 'display))
15855 (if (and (get-text-property p 'display)
15856 (eq (get-text-property p 'face) 'org-date))
15857 (remove-text-properties
15858 p (setq p (next-single-property-change p 'display))
15859 '(display t))))
15860 (set-buffer-modified-p bmp)))
15861 (if (featurep 'xemacs)
15862 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15863 (org-restart-font-lock)
15864 (setq org-table-may-need-update t)
15865 (if org-display-custom-times
15866 (message "Time stamps are overlaid with custom format")
15867 (message "Time stamp overlays removed")))
15869 (defun org-display-custom-time (beg end)
15870 "Overlay modified time stamp format over timestamp between BEG and END."
15871 (let* ((ts (buffer-substring beg end))
15872 t1 w1 with-hm tf time str w2 (off 0))
15873 (save-match-data
15874 (setq t1 (org-parse-time-string ts t))
15875 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15876 (setq off (- (match-end 0) (match-beginning 0)))))
15877 (setq end (- end off))
15878 (setq w1 (- end beg)
15879 with-hm (and (nth 1 t1) (nth 2 t1))
15880 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15881 time (org-fix-decoded-time t1)
15882 str (org-add-props
15883 (format-time-string
15884 (substring tf 1 -1) (apply 'encode-time time))
15885 nil 'mouse-face 'highlight)
15886 w2 (length str))
15887 (if (not (= w2 w1))
15888 (add-text-properties (1+ beg) (+ 2 beg)
15889 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15890 (if (featurep 'xemacs)
15891 (progn
15892 (put-text-property beg end 'invisible t)
15893 (put-text-property beg end 'end-glyph (make-glyph str)))
15894 (put-text-property beg end 'display str))))
15896 (defun org-translate-time (string)
15897 "Translate all timestamps in STRING to custom format.
15898 But do this only if the variable `org-display-custom-times' is set."
15899 (when org-display-custom-times
15900 (save-match-data
15901 (let* ((start 0)
15902 (re org-ts-regexp-both)
15903 t1 with-hm inactive tf time str beg end)
15904 (while (setq start (string-match re string start))
15905 (setq beg (match-beginning 0)
15906 end (match-end 0)
15907 t1 (save-match-data
15908 (org-parse-time-string (substring string beg end) t))
15909 with-hm (and (nth 1 t1) (nth 2 t1))
15910 inactive (equal (substring string beg (1+ beg)) "[")
15911 tf (funcall (if with-hm 'cdr 'car)
15912 org-time-stamp-custom-formats)
15913 time (org-fix-decoded-time t1)
15914 str (format-time-string
15915 (concat
15916 (if inactive "[" "<") (substring tf 1 -1)
15917 (if inactive "]" ">"))
15918 (apply 'encode-time time))
15919 string (replace-match str t t string)
15920 start (+ start (length str)))))))
15921 string)
15923 (defun org-fix-decoded-time (time)
15924 "Set 0 instead of nil for the first 6 elements of time.
15925 Don't touch the rest."
15926 (let ((n 0))
15927 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15929 (defun org-days-to-time (timestamp-string)
15930 "Difference between TIMESTAMP-STRING and now in days."
15931 (- (time-to-days (org-time-string-to-time timestamp-string))
15932 (time-to-days (current-time))))
15934 (defun org-deadline-close (timestamp-string &optional ndays)
15935 "Is the time in TIMESTAMP-STRING close to the current date?"
15936 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15937 (and (< (org-days-to-time timestamp-string) ndays)
15938 (not (org-entry-is-done-p))))
15940 (defun org-get-wdays (ts)
15941 "Get the deadline lead time appropriate for timestring TS."
15942 (cond
15943 ((<= org-deadline-warning-days 0)
15944 ;; 0 or negative, enforce this value no matter what
15945 (- org-deadline-warning-days))
15946 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15947 ;; lead time is specified.
15948 (floor (* (string-to-number (match-string 1 ts))
15949 (cdr (assoc (match-string 2 ts)
15950 '(("d" . 1) ("w" . 7)
15951 ("m" . 30.4) ("y" . 365.25)))))))
15952 ;; go for the default.
15953 (t org-deadline-warning-days)))
15955 (defun org-calendar-select-mouse (ev)
15956 "Return to `org-read-date' with the date currently selected.
15957 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15958 (interactive "e")
15959 (mouse-set-point ev)
15960 (when (calendar-cursor-to-date)
15961 (let* ((date (calendar-cursor-to-date))
15962 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15963 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15964 (if (active-minibuffer-window) (exit-minibuffer))))
15966 (defun org-check-deadlines (ndays)
15967 "Check if there are any deadlines due or past due.
15968 A deadline is considered due if it happens within `org-deadline-warning-days'
15969 days from today's date. If the deadline appears in an entry marked DONE,
15970 it is not shown. The prefix arg NDAYS can be used to test that many
15971 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15972 (interactive "P")
15973 (let* ((org-warn-days
15974 (cond
15975 ((equal ndays '(4)) 100000)
15976 (ndays (prefix-numeric-value ndays))
15977 (t (abs org-deadline-warning-days))))
15978 (case-fold-search nil)
15979 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15980 (callback
15981 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15983 (message "%d deadlines past-due or due within %d days"
15984 (org-occur regexp nil callback)
15985 org-warn-days)))
15987 (defsubst org-re-timestamp (type)
15988 "Return a regexp for timestamp TYPE.
15989 Allowed values for TYPE are:
15991 all: all timestamps
15992 active: only active timestamps (<...>)
15993 inactive: only inactive timestamps ([...])
15994 scheduled: only scheduled timestamps
15995 deadline: only deadline timestamps
15997 When TYPE is nil, fall back on returning a regexp that matches
15998 both scheduled and deadline timestamps."
15999 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16000 ((eq type 'active) org-ts-regexp)
16001 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16002 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16003 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16004 ((eq type 'scheduled-or-deadline)
16005 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16007 (defun org-check-before-date (date)
16008 "Check if there are deadlines or scheduled entries before DATE."
16009 (interactive (list (org-read-date)))
16010 (let ((case-fold-search nil)
16011 (regexp (org-re-timestamp org-ts-type))
16012 (callback
16013 (lambda () (time-less-p
16014 (org-time-string-to-time (match-string 1))
16015 (org-time-string-to-time date)))))
16016 (message "%d entries before %s"
16017 (org-occur regexp nil callback) date)))
16019 (defun org-check-after-date (date)
16020 "Check if there are deadlines or scheduled entries after DATE."
16021 (interactive (list (org-read-date)))
16022 (let ((case-fold-search nil)
16023 (regexp (org-re-timestamp org-ts-type))
16024 (callback
16025 (lambda () (not
16026 (time-less-p
16027 (org-time-string-to-time (match-string 1))
16028 (org-time-string-to-time date))))))
16029 (message "%d entries after %s"
16030 (org-occur regexp nil callback) date)))
16032 (defun org-check-dates-range (start-date end-date)
16033 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16034 (interactive (list (org-read-date nil nil nil "Range starts")
16035 (org-read-date nil nil nil "Range end")))
16036 (let ((case-fold-search nil)
16037 (regexp (org-re-timestamp org-ts-type))
16038 (callback
16039 (lambda ()
16040 (let ((match (match-string 1)))
16041 (and
16042 (not (time-less-p
16043 (org-time-string-to-time match)
16044 (org-time-string-to-time start-date)))
16045 (time-less-p
16046 (org-time-string-to-time match)
16047 (org-time-string-to-time end-date)))))))
16048 (message "%d entries between %s and %s"
16049 (org-occur regexp nil callback) start-date end-date)))
16051 (defun org-evaluate-time-range (&optional to-buffer)
16052 "Evaluate a time range by computing the difference between start and end.
16053 Normally the result is just printed in the echo area, but with prefix arg
16054 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16055 If the time range is actually in a table, the result is inserted into the
16056 next column.
16057 For time difference computation, a year is assumed to be exactly 365
16058 days in order to avoid rounding problems."
16059 (interactive "P")
16061 (org-clock-update-time-maybe)
16062 (save-excursion
16063 (unless (org-at-date-range-p t)
16064 (goto-char (point-at-bol))
16065 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16066 (if (not (org-at-date-range-p t))
16067 (error "Not at a time-stamp range, and none found in current line")))
16068 (let* ((ts1 (match-string 1))
16069 (ts2 (match-string 2))
16070 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16071 (match-end (match-end 0))
16072 (time1 (org-time-string-to-time ts1))
16073 (time2 (org-time-string-to-time ts2))
16074 (t1 (org-float-time time1))
16075 (t2 (org-float-time time2))
16076 (diff (abs (- t2 t1)))
16077 (negative (< (- t2 t1) 0))
16078 ;; (ys (floor (* 365 24 60 60)))
16079 (ds (* 24 60 60))
16080 (hs (* 60 60))
16081 (fy "%dy %dd %02d:%02d")
16082 (fy1 "%dy %dd")
16083 (fd "%dd %02d:%02d")
16084 (fd1 "%dd")
16085 (fh "%02d:%02d")
16086 y d h m align)
16087 (if havetime
16088 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16090 d (floor (/ diff ds)) diff (mod diff ds)
16091 h (floor (/ diff hs)) diff (mod diff hs)
16092 m (floor (/ diff 60)))
16093 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16095 d (floor (+ (/ diff ds) 0.5))
16096 h 0 m 0))
16097 (if (not to-buffer)
16098 (message "%s" (org-make-tdiff-string y d h m))
16099 (if (org-at-table-p)
16100 (progn
16101 (goto-char match-end)
16102 (setq align t)
16103 (and (looking-at " *|") (goto-char (match-end 0))))
16104 (goto-char match-end))
16105 (if (looking-at
16106 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16107 (replace-match ""))
16108 (if negative (insert " -"))
16109 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16110 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16111 (insert " " (format fh h m))))
16112 (if align (org-table-align))
16113 (message "Time difference inserted")))))
16115 (defun org-make-tdiff-string (y d h m)
16116 (let ((fmt "")
16117 (l nil))
16118 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16119 l (push y l)))
16120 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16121 l (push d l)))
16122 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16123 l (push h l)))
16124 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16125 l (push m l)))
16126 (apply 'format fmt (nreverse l))))
16128 (defun org-time-string-to-time (s &optional buffer pos)
16129 (condition-case errdata
16130 (apply 'encode-time (org-parse-time-string s))
16131 (error (error "Bad timestamp `%s'%s\nError was: %s"
16132 s (if (not (and buffer pos))
16134 (format " at %d in buffer `%s'" pos buffer))
16135 (cdr errdata)))))
16137 (defun org-time-string-to-seconds (s)
16138 (org-float-time (org-time-string-to-time s)))
16140 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16141 "Convert a time stamp to an absolute day number.
16142 If there is a specifier for a cyclic time stamp, get the closest date to
16143 DAYNR.
16144 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16145 The variable date is bound by the calendar when this is called."
16146 (cond
16147 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16148 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16149 daynr
16150 (+ daynr 1000)))
16151 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16152 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16153 (time-to-days (current-time))) (match-string 0 s)
16154 prefer show-all))
16155 (t (time-to-days
16156 (condition-case errdata
16157 (apply 'encode-time (org-parse-time-string s))
16158 (error (error "Bad timestamp `%s'%s\nError was: %s"
16159 s (if (not (and buffer pos))
16161 (format " at %d in buffer `%s'" pos buffer))
16162 (cdr errdata))))))))
16164 (defun org-days-to-iso-week (days)
16165 "Return the iso week number."
16166 (require 'cal-iso)
16167 (car (calendar-iso-from-absolute days)))
16169 (defun org-small-year-to-year (year)
16170 "Convert 2-digit years into 4-digit years.
16171 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16172 The year 2000 cannot be abbreviated. Any year larger than 99
16173 is returned unchanged."
16174 (if (< year 38)
16175 (setq year (+ 2000 year))
16176 (if (< year 100)
16177 (setq year (+ 1900 year))))
16178 year)
16180 (defun org-time-from-absolute (d)
16181 "Return the time corresponding to date D.
16182 D may be an absolute day number, or a calendar-type list (month day year)."
16183 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16184 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16186 (defun org-calendar-holiday ()
16187 "List of holidays, for Diary display in Org-mode."
16188 (require 'holidays)
16189 (let ((hl (funcall
16190 (if (fboundp 'calendar-check-holidays)
16191 'calendar-check-holidays 'check-calendar-holidays) date)))
16192 (if hl (mapconcat 'identity hl "; "))))
16194 (defun org-diary-sexp-entry (sexp entry date)
16195 "Process a SEXP diary ENTRY for DATE."
16196 (require 'diary-lib)
16197 (let ((result (if calendar-debug-sexp
16198 (let ((stack-trace-on-error t))
16199 (eval (car (read-from-string sexp))))
16200 (condition-case nil
16201 (eval (car (read-from-string sexp)))
16202 (error
16203 (beep)
16204 (message "Bad sexp at line %d in %s: %s"
16205 (org-current-line)
16206 (buffer-file-name) sexp)
16207 (sleep-for 2))))))
16208 (cond ((stringp result) (split-string result "; "))
16209 ((and (consp result)
16210 (not (consp (cdr result)))
16211 (stringp (cdr result))) (cdr result))
16212 ((and (consp result)
16213 (stringp (car result))) result)
16214 (result entry)
16215 (t nil))))
16217 (defun org-diary-to-ical-string (frombuf)
16218 "Get iCalendar entries from diary entries in buffer FROMBUF.
16219 This uses the icalendar.el library."
16220 (let* ((tmpdir (if (featurep 'xemacs)
16221 (temp-directory)
16222 temporary-file-directory))
16223 (tmpfile (make-temp-name
16224 (expand-file-name "orgics" tmpdir)))
16225 buf rtn b e)
16226 (with-current-buffer frombuf
16227 (icalendar-export-region (point-min) (point-max) tmpfile)
16228 (setq buf (find-buffer-visiting tmpfile))
16229 (set-buffer buf)
16230 (goto-char (point-min))
16231 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16232 (setq b (match-beginning 0)))
16233 (goto-char (point-max))
16234 (if (re-search-backward "^END:VEVENT" nil t)
16235 (setq e (match-end 0)))
16236 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16237 (kill-buffer buf)
16238 (delete-file tmpfile)
16239 rtn))
16241 (defun org-closest-date (start current change prefer show-all)
16242 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16243 When PREFER is `past', return a date that is either CURRENT or past.
16244 When PREFER is `future', return a date that is either CURRENT or future.
16245 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16246 ;; Make the proper lists from the dates
16247 (catch 'exit
16248 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16249 dn dw sday cday n1 n2 n0
16250 d m y y1 y2 date1 date2 nmonths nm ny m2)
16252 (setq start (org-date-to-gregorian start)
16253 current (org-date-to-gregorian
16254 (if show-all
16255 current
16256 (time-to-days (current-time))))
16257 sday (calendar-absolute-from-gregorian start)
16258 cday (calendar-absolute-from-gregorian current))
16260 (if (<= cday sday) (throw 'exit sday))
16262 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16263 (setq dn (string-to-number (match-string 1 change))
16264 dw (cdr (assoc (match-string 2 change) a1)))
16265 (error "Invalid change specifier: %s" change))
16266 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16267 (cond
16268 ((eq dw 'day)
16269 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16270 n2 (+ n1 dn)))
16271 ((eq dw 'year)
16272 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16273 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16274 (setq date1 (list m d y1)
16275 n1 (calendar-absolute-from-gregorian date1)
16276 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16277 n2 (calendar-absolute-from-gregorian date2)))
16278 ((eq dw 'month)
16279 ;; approx number of month between the two dates
16280 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16281 ;; How often does dn fit in there?
16282 (setq d (nth 1 start) m (car start) y (nth 2 start)
16283 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16284 m (+ m nm)
16285 ny (floor (/ m 12))
16286 y (+ y ny)
16287 m (- m (* ny 12)))
16288 (while (> m 12) (setq m (- m 12) y (1+ y)))
16289 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16290 (setq m2 (+ m dn) y2 y)
16291 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16292 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16293 (while (<= n2 cday)
16294 (setq n1 n2 m m2 y y2)
16295 (setq m2 (+ m dn) y2 y)
16296 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16297 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16298 ;; Make sure n1 is the earlier date
16299 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16300 (if show-all
16301 (cond
16302 ((eq prefer 'past) (if (= cday n2) n2 n1))
16303 ((eq prefer 'future) (if (= cday n1) n1 n2))
16304 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16305 (cond
16306 ((eq prefer 'past) (if (= cday n2) n2 n1))
16307 ((eq prefer 'future) (if (= cday n1) n1 n2))
16308 (t (if (= cday n1) n1 n2)))))))
16310 (defun org-date-to-gregorian (date)
16311 "Turn any specification of DATE into a Gregorian date for the calendar."
16312 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16313 ((and (listp date) (= (length date) 3)) date)
16314 ((stringp date)
16315 (setq date (org-parse-time-string date))
16316 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16317 ((listp date)
16318 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16320 (defun org-parse-time-string (s &optional nodefault)
16321 "Parse the standard Org-mode time string.
16322 This should be a lot faster than the normal `parse-time-string'.
16323 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16324 hour and minute fields will be nil if not given."
16325 (if (string-match org-ts-regexp0 s)
16326 (list 0
16327 (if (or (match-beginning 8) (not nodefault))
16328 (string-to-number (or (match-string 8 s) "0")))
16329 (if (or (match-beginning 7) (not nodefault))
16330 (string-to-number (or (match-string 7 s) "0")))
16331 (string-to-number (match-string 4 s))
16332 (string-to-number (match-string 3 s))
16333 (string-to-number (match-string 2 s))
16334 nil nil nil)
16335 (error "Not a standard Org-mode time string: %s" s)))
16337 (defun org-timestamp-up (&optional arg)
16338 "Increase the date item at the cursor by one.
16339 If the cursor is on the year, change the year. If it is on the month,
16340 the day or the time, change that.
16341 With prefix ARG, change by that many units."
16342 (interactive "p")
16343 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16345 (defun org-timestamp-down (&optional arg)
16346 "Decrease the date item at the cursor by one.
16347 If the cursor is on the year, change the year. If it is on the month,
16348 the day or the time, change that.
16349 With prefix ARG, change by that many units."
16350 (interactive "p")
16351 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16353 (defun org-timestamp-up-day (&optional arg)
16354 "Increase the date in the time stamp by one day.
16355 With prefix ARG, change that many days."
16356 (interactive "p")
16357 (if (and (not (org-at-timestamp-p t))
16358 (org-at-heading-p))
16359 (org-todo 'up)
16360 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16362 (defun org-timestamp-down-day (&optional arg)
16363 "Decrease the date in the time stamp by one day.
16364 With prefix ARG, change that many days."
16365 (interactive "p")
16366 (if (and (not (org-at-timestamp-p t))
16367 (org-at-heading-p))
16368 (org-todo 'down)
16369 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16371 (defun org-at-timestamp-p (&optional inactive-ok)
16372 "Determine if the cursor is in or at a timestamp."
16373 (interactive)
16374 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16375 (pos (point))
16376 (ans (or (looking-at tsr)
16377 (save-excursion
16378 (skip-chars-backward "^[<\n\r\t")
16379 (if (> (point) (point-min)) (backward-char 1))
16380 (and (looking-at tsr)
16381 (> (- (match-end 0) pos) -1))))))
16382 (and ans
16383 (boundp 'org-ts-what)
16384 (setq org-ts-what
16385 (cond
16386 ((= pos (match-beginning 0)) 'bracket)
16387 ;; Point is considered to be "on the bracket" whether
16388 ;; it's really on it or right after it.
16389 ((= pos (1- (match-end 0))) 'bracket)
16390 ((= pos (match-end 0)) 'after)
16391 ((org-pos-in-match-range pos 2) 'year)
16392 ((org-pos-in-match-range pos 3) 'month)
16393 ((org-pos-in-match-range pos 7) 'hour)
16394 ((org-pos-in-match-range pos 8) 'minute)
16395 ((or (org-pos-in-match-range pos 4)
16396 (org-pos-in-match-range pos 5)) 'day)
16397 ((and (> pos (or (match-end 8) (match-end 5)))
16398 (< pos (match-end 0)))
16399 (- pos (or (match-end 8) (match-end 5))))
16400 (t 'day))))
16401 ans))
16403 (defun org-toggle-timestamp-type ()
16404 "Toggle the type (<active> or [inactive]) of a time stamp."
16405 (interactive)
16406 (when (org-at-timestamp-p t)
16407 (let ((beg (match-beginning 0)) (end (match-end 0))
16408 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16409 (save-excursion
16410 (goto-char beg)
16411 (while (re-search-forward "[][<>]" end t)
16412 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16413 t t)))
16414 (message "Timestamp is now %sactive"
16415 (if (equal (char-after beg) ?<) "" "in")))))
16417 (defvar org-clock-history) ; defined in org-clock.el
16418 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16419 (defun org-timestamp-change (n &optional what updown)
16420 "Change the date in the time stamp at point.
16421 The date will be changed by N times WHAT. WHAT can be `day', `month',
16422 `year', `minute', `second'. If WHAT is not given, the cursor position
16423 in the timestamp determines what will be changed."
16424 (let ((origin (point)) origin-cat
16425 with-hm inactive
16426 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16427 org-ts-what
16428 extra rem
16429 ts time time0 fixnext clrgx)
16430 (if (not (org-at-timestamp-p t))
16431 (error "Not at a timestamp"))
16432 (if (and (not what) (eq org-ts-what 'bracket))
16433 (org-toggle-timestamp-type)
16434 ;; Point isn't on brackets. Remember the part of the time-stamp
16435 ;; the point was in. Indeed, size of time-stamps may change,
16436 ;; but point must be kept in the same category nonetheless.
16437 (setq origin-cat org-ts-what)
16438 (if (and (not what) (not (eq org-ts-what 'day))
16439 org-display-custom-times
16440 (get-text-property (point) 'display)
16441 (not (get-text-property (1- (point)) 'display)))
16442 (setq org-ts-what 'day))
16443 (setq org-ts-what (or what org-ts-what)
16444 inactive (= (char-after (match-beginning 0)) ?\[)
16445 ts (match-string 0))
16446 (replace-match "")
16447 (if (string-match
16448 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16450 (setq extra (match-string 1 ts)))
16451 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16452 (setq with-hm t))
16453 (setq time0 (org-parse-time-string ts))
16454 (when (and updown
16455 (eq org-ts-what 'minute)
16456 (not current-prefix-arg))
16457 ;; This looks like s-up and s-down. Change by one rounding step.
16458 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16459 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16460 (setcar (cdr time0) (+ (nth 1 time0)
16461 (if (> n 0) (- rem) (- dm rem))))))
16462 (setq time
16463 (encode-time (or (car time0) 0)
16464 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16465 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16466 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16467 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16468 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16469 (nthcdr 6 time0)))
16470 (when (and (member org-ts-what '(hour minute))
16471 extra
16472 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16473 (setq extra (org-modify-ts-extra
16474 extra
16475 (if (eq org-ts-what 'hour) 2 5)
16476 n dm)))
16477 (when (integerp org-ts-what)
16478 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16479 (if (eq what 'calendar)
16480 (let ((cal-date (org-get-date-from-calendar)))
16481 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16482 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16483 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16484 (setcar time0 (or (car time0) 0))
16485 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16486 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16487 (setq time (apply 'encode-time time0))))
16488 ;; Insert the new time-stamp, and ensure point stays in the same
16489 ;; category as before (i.e. not after the last position in that
16490 ;; category).
16491 (let ((pos (point)))
16492 ;; Stay before inserted string. `save-excursion' is of no use.
16493 (setq org-last-changed-timestamp
16494 (org-insert-time-stamp time with-hm inactive nil nil extra))
16495 (goto-char pos))
16496 (save-match-data
16497 (looking-at org-ts-regexp3)
16498 (goto-char (cond
16499 ;; `day' category ends before `hour' if any, or at
16500 ;; the end of the day name.
16501 ((eq origin-cat 'day)
16502 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16503 ((eq origin-cat 'hour) (min (match-end 7) origin))
16504 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16505 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16506 ;; `year' and `month' have both fixed size: point
16507 ;; couldn't have moved into another part.
16508 (t origin))))
16509 ;; Update clock if on a CLOCK line.
16510 (org-clock-update-time-maybe)
16511 ;; Maybe adjust the closest clock in `org-clock-history'
16512 (when org-clock-adjust-closest
16513 (if (not (and (org-at-clock-log-p)
16514 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16515 org-clock-history))))))
16516 (message "No clock to adjust")
16517 (cond ((save-excursion ; fix previous clock?
16518 (re-search-backward org-ts-regexp0 nil t)
16519 (org-looking-back (concat org-clock-string " \\[")))
16520 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16521 ((save-excursion ; fix next clock?
16522 (re-search-backward org-ts-regexp0 nil t)
16523 (looking-at (concat org-ts-regexp0 "\\] =>")))
16524 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16525 (save-window-excursion
16526 ;; Find closest clock to point, adjust the previous/next one in history
16527 (let* ((p (save-excursion (org-back-to-heading t)))
16528 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16529 (clfixnth
16530 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16531 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16532 (if (not clfixpos)
16533 (message "No clock to adjust")
16534 (save-excursion
16535 (org-goto-marker-or-bmk clfixpos)
16536 (org-show-subtree)
16537 (when (re-search-forward clrgx nil t)
16538 (goto-char (match-beginning 1))
16539 (let (org-clock-adjust-closest)
16540 (org-timestamp-change n org-ts-what updown))
16541 (message "Clock adjusted in %s for heading: %s"
16542 (file-name-nondirectory (buffer-file-name))
16543 (org-get-heading t t)))))))))
16544 ;; Try to recenter the calendar window, if any.
16545 (if (and org-calendar-follow-timestamp-change
16546 (get-buffer-window "*Calendar*" t)
16547 (memq org-ts-what '(day month year)))
16548 (org-recenter-calendar (time-to-days time))))))
16550 (defun org-modify-ts-extra (s pos n dm)
16551 "Change the different parts of the lead-time and repeat fields in timestamp."
16552 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16553 ng h m new rem)
16554 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16555 (cond
16556 ((or (org-pos-in-match-range pos 2)
16557 (org-pos-in-match-range pos 3))
16558 (setq m (string-to-number (match-string 3 s))
16559 h (string-to-number (match-string 2 s)))
16560 (if (org-pos-in-match-range pos 2)
16561 (setq h (+ h n))
16562 (setq n (* dm (org-no-warnings (signum n))))
16563 (when (not (= 0 (setq rem (% m dm))))
16564 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16565 (setq m (+ m n)))
16566 (if (< m 0) (setq m (+ m 60) h (1- h)))
16567 (if (> m 59) (setq m (- m 60) h (1+ h)))
16568 (setq h (min 24 (max 0 h)))
16569 (setq ng 1 new (format "-%02d:%02d" h m)))
16570 ((org-pos-in-match-range pos 6)
16571 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16572 ((org-pos-in-match-range pos 5)
16573 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16575 ((org-pos-in-match-range pos 9)
16576 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16577 ((org-pos-in-match-range pos 8)
16578 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16580 (when ng
16581 (setq s (concat
16582 (substring s 0 (match-beginning ng))
16584 (substring s (match-end ng))))))
16587 (defun org-recenter-calendar (date)
16588 "If the calendar is visible, recenter it to DATE."
16589 (let ((cwin (get-buffer-window "*Calendar*" t)))
16590 (when cwin
16591 (let ((calendar-move-hook nil))
16592 (with-selected-window cwin
16593 (calendar-goto-date (if (listp date) date
16594 (calendar-gregorian-from-absolute date))))))))
16596 (defun org-goto-calendar (&optional arg)
16597 "Go to the Emacs calendar at the current date.
16598 If there is a time stamp in the current line, go to that date.
16599 A prefix ARG can be used to force the current date."
16600 (interactive "P")
16601 (let ((tsr org-ts-regexp) diff
16602 (calendar-move-hook nil)
16603 (calendar-view-holidays-initially-flag nil)
16604 (calendar-view-diary-initially-flag nil))
16605 (if (or (org-at-timestamp-p)
16606 (save-excursion
16607 (beginning-of-line 1)
16608 (looking-at (concat ".*" tsr))))
16609 (let ((d1 (time-to-days (current-time)))
16610 (d2 (time-to-days
16611 (org-time-string-to-time (match-string 1)))))
16612 (setq diff (- d2 d1))))
16613 (calendar)
16614 (calendar-goto-today)
16615 (if (and diff (not arg)) (calendar-forward-day diff))))
16617 (defun org-get-date-from-calendar ()
16618 "Return a list (month day year) of date at point in calendar."
16619 (with-current-buffer "*Calendar*"
16620 (save-match-data
16621 (calendar-cursor-to-date))))
16623 (defun org-date-from-calendar ()
16624 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16625 If there is already a time stamp at the cursor position, update it."
16626 (interactive)
16627 (if (org-at-timestamp-p t)
16628 (org-timestamp-change 0 'calendar)
16629 (let ((cal-date (org-get-date-from-calendar)))
16630 (org-insert-time-stamp
16631 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16633 (defun org-minutes-to-hh:mm-string (m)
16634 "Compute H:MM from a number of minutes."
16635 (let ((h (/ m 60)))
16636 (setq m (- m (* 60 h)))
16637 (format org-time-clocksum-format h m)))
16639 (defun org-hh:mm-string-to-minutes (s)
16640 "Convert a string H:MM to a number of minutes.
16641 If the string is just a number, interpret it as minutes.
16642 In fact, the first hh:mm or number in the string will be taken,
16643 there can be extra stuff in the string.
16644 If no number is found, the return value is 0."
16645 (cond
16646 ((integerp s) s)
16647 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16648 (+ (* (string-to-number (match-string 1 s)) 60)
16649 (string-to-number (match-string 2 s))))
16650 ((string-match "\\([0-9]+\\)" s)
16651 (string-to-number (match-string 1 s)))
16652 (t 0)))
16654 (defcustom org-effort-durations
16655 `(("h" . 60)
16656 ("d" . ,(* 60 8))
16657 ("w" . ,(* 60 8 5))
16658 ("m" . ,(* 60 8 5 4))
16659 ("y" . ,(* 60 8 5 40)))
16660 "Conversion factor to minutes for an effort modifier.
16662 Each entry has the form (MODIFIER . MINUTES).
16664 In an effort string, a number followed by MODIFIER is multiplied
16665 by the specified number of MINUTES to obtain an effort in
16666 minutes.
16668 For example, if the value of this variable is ((\"hours\" . 60)), then an
16669 effort string \"2hours\" is equivalent to 120 minutes."
16670 :group 'org-agenda
16671 :version "24.1"
16672 :type '(alist :key-type (string :tag "Modifier")
16673 :value-type (number :tag "Minutes")))
16675 (defun org-duration-string-to-minutes (s &optional output-to-string)
16676 "Convert a duration string S to minutes.
16678 A bare number is interpreted as minutes, modifiers can be set by
16679 customizing `org-effort-durations' (which see).
16681 Entries containing a colon are interpreted as H:MM by
16682 `org-hh:mm-string-to-minutes'."
16683 (let ((result 0)
16684 (re (concat "\\([0-9.]+\\) *\\("
16685 (regexp-opt (mapcar 'car org-effort-durations))
16686 "\\)")))
16687 (while (string-match re s)
16688 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16689 (string-to-number (match-string 1 s))))
16690 (setq s (replace-match "" nil t s)))
16691 (setq result (floor result))
16692 (incf result (org-hh:mm-string-to-minutes s))
16693 (if output-to-string (number-to-string result) result)))
16695 ;;;; Files
16697 (defun org-save-all-org-buffers ()
16698 "Save all Org-mode buffers without user confirmation."
16699 (interactive)
16700 (message "Saving all Org-mode buffers...")
16701 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16702 (when (featurep 'org-id) (org-id-locations-save))
16703 (message "Saving all Org-mode buffers... done"))
16705 (defun org-revert-all-org-buffers ()
16706 "Revert all Org-mode buffers.
16707 Prompt for confirmation when there are unsaved changes.
16708 Be sure you know what you are doing before letting this function
16709 overwrite your changes.
16711 This function is useful in a setup where one tracks org files
16712 with a version control system, to revert on one machine after pulling
16713 changes from another. I believe the procedure must be like this:
16715 1. M-x org-save-all-org-buffers
16716 2. Pull changes from the other machine, resolve conflicts
16717 3. M-x org-revert-all-org-buffers"
16718 (interactive)
16719 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16720 (error "Abort"))
16721 (save-excursion
16722 (save-window-excursion
16723 (mapc
16724 (lambda (b)
16725 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16726 (with-current-buffer b buffer-file-name))
16727 (org-pop-to-buffer-same-window b)
16728 (revert-buffer t 'no-confirm)))
16729 (buffer-list))
16730 (when (and (featurep 'org-id) org-id-track-globally)
16731 (org-id-locations-load)))))
16733 ;;;; Agenda files
16735 ;;;###autoload
16736 (defun org-switchb (&optional arg)
16737 "Switch between Org buffers.
16738 With one prefix argument, restrict available buffers to files.
16739 With two prefix arguments, restrict available buffers to agenda files.
16741 Defaults to `iswitchb' for buffer name completion.
16742 Set `org-completion-use-ido' to make it use ido instead."
16743 (interactive "P")
16744 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16745 ((equal arg '(16)) (org-buffer-list 'agenda))
16746 (t (org-buffer-list))))
16747 (org-completion-use-iswitchb org-completion-use-iswitchb)
16748 (org-completion-use-ido org-completion-use-ido))
16749 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16750 (setq org-completion-use-iswitchb t))
16751 (org-pop-to-buffer-same-window
16752 (org-icompleting-read "Org buffer: "
16753 (mapcar 'list (mapcar 'buffer-name blist))
16754 nil t))))
16756 ;;; Define some older names previously used for this functionality
16757 ;;;###autoload
16758 (defalias 'org-ido-switchb 'org-switchb)
16759 ;;;###autoload
16760 (defalias 'org-iswitchb 'org-switchb)
16762 (defun org-buffer-list (&optional predicate exclude-tmp)
16763 "Return a list of Org buffers.
16764 PREDICATE can be `export', `files' or `agenda'.
16766 export restrict the list to Export buffers.
16767 files restrict the list to buffers visiting Org files.
16768 agenda restrict the list to buffers visiting agenda files.
16770 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16771 (let* ((bfn nil)
16772 (agenda-files (and (eq predicate 'agenda)
16773 (mapcar 'file-truename (org-agenda-files t))))
16774 (filter
16775 (cond
16776 ((eq predicate 'files)
16777 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16778 ((eq predicate 'export)
16779 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16780 ((eq predicate 'agenda)
16781 (lambda (b)
16782 (with-current-buffer b
16783 (and (derived-mode-p 'org-mode)
16784 (setq bfn (buffer-file-name b))
16785 (member (file-truename bfn) agenda-files)))))
16786 (t (lambda (b) (with-current-buffer b
16787 (or (derived-mode-p 'org-mode)
16788 (string-match "\*Org .*Export"
16789 (buffer-name b)))))))))
16790 (delq nil
16791 (mapcar
16792 (lambda(b)
16793 (if (and (funcall filter b)
16794 (or (not exclude-tmp)
16795 (not (string-match "tmp" (buffer-name b)))))
16797 nil))
16798 (buffer-list)))))
16800 (defun org-agenda-files (&optional unrestricted archives)
16801 "Get the list of agenda files.
16802 Optional UNRESTRICTED means return the full list even if a restriction
16803 is currently in place.
16804 When ARCHIVES is t, include all archive files that are really being
16805 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16806 `org-agenda-archives-mode' is t."
16807 (let ((files
16808 (cond
16809 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16810 ((stringp org-agenda-files) (org-read-agenda-file-list))
16811 ((listp org-agenda-files) org-agenda-files)
16812 (t (error "Invalid value of `org-agenda-files'")))))
16813 (setq files (apply 'append
16814 (mapcar (lambda (f)
16815 (if (file-directory-p f)
16816 (directory-files
16817 f t org-agenda-file-regexp)
16818 (list f)))
16819 files)))
16820 (when org-agenda-skip-unavailable-files
16821 (setq files (delq nil
16822 (mapcar (function
16823 (lambda (file)
16824 (and (file-readable-p file) file)))
16825 files))))
16826 (when (or (eq archives t)
16827 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16828 (setq files (org-add-archive-files files)))
16829 files))
16831 (defun org-agenda-file-p (&optional file)
16832 "Return non-nil, if FILE is an agenda file.
16833 If FILE is omitted, use the file associated with the current
16834 buffer."
16835 (member (or file (buffer-file-name))
16836 (org-agenda-files t)))
16838 (defun org-edit-agenda-file-list ()
16839 "Edit the list of agenda files.
16840 Depending on setup, this either uses customize to edit the variable
16841 `org-agenda-files', or it visits the file that is holding the list. In the
16842 latter case, the buffer is set up in a way that saving it automatically kills
16843 the buffer and restores the previous window configuration."
16844 (interactive)
16845 (if (stringp org-agenda-files)
16846 (let ((cw (current-window-configuration)))
16847 (find-file org-agenda-files)
16848 (org-set-local 'org-window-configuration cw)
16849 (org-add-hook 'after-save-hook
16850 (lambda ()
16851 (set-window-configuration
16852 (prog1 org-window-configuration
16853 (kill-buffer (current-buffer))))
16854 (org-install-agenda-files-menu)
16855 (message "New agenda file list installed"))
16856 nil 'local)
16857 (message "%s" (substitute-command-keys
16858 "Edit list and finish with \\[save-buffer]")))
16859 (customize-variable 'org-agenda-files)))
16861 (defun org-store-new-agenda-file-list (list)
16862 "Set new value for the agenda file list and save it correctly."
16863 (if (stringp org-agenda-files)
16864 (let ((fe (org-read-agenda-file-list t)) b u)
16865 (while (setq b (find-buffer-visiting org-agenda-files))
16866 (kill-buffer b))
16867 (with-temp-file org-agenda-files
16868 (insert
16869 (mapconcat
16870 (lambda (f) ;; Keep un-expanded entries.
16871 (if (setq u (assoc f fe))
16872 (cdr u)
16874 list "\n")
16875 "\n")))
16876 (let ((org-mode-hook nil) (org-inhibit-startup t)
16877 (org-insert-mode-line-in-empty-file nil))
16878 (setq org-agenda-files list)
16879 (customize-save-variable 'org-agenda-files org-agenda-files))))
16881 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16882 "Read the list of agenda files from a file.
16883 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16884 filenames, used by `org-store-new-agenda-file-list' to write back
16885 un-expanded file names."
16886 (when (file-directory-p org-agenda-files)
16887 (error "`org-agenda-files' cannot be a single directory"))
16888 (when (stringp org-agenda-files)
16889 (with-temp-buffer
16890 (insert-file-contents org-agenda-files)
16891 (mapcar
16892 (lambda (f)
16893 (let ((e (expand-file-name (substitute-in-file-name f)
16894 org-directory)))
16895 (if pair-with-expansion
16896 (cons e f)
16897 e)))
16898 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16900 ;;;###autoload
16901 (defun org-cycle-agenda-files ()
16902 "Cycle through the files in `org-agenda-files'.
16903 If the current buffer visits an agenda file, find the next one in the list.
16904 If the current buffer does not, find the first agenda file."
16905 (interactive)
16906 (let* ((fs (org-agenda-files t))
16907 (files (append fs (list (car fs))))
16908 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16909 file)
16910 (unless files (error "No agenda files"))
16911 (catch 'exit
16912 (while (setq file (pop files))
16913 (if (equal (file-truename file) tcf)
16914 (when (car files)
16915 (find-file (car files))
16916 (throw 'exit t))))
16917 (find-file (car fs)))
16918 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16920 (defun org-agenda-file-to-front (&optional to-end)
16921 "Move/add the current file to the top of the agenda file list.
16922 If the file is not present in the list, it is added to the front. If it is
16923 present, it is moved there. With optional argument TO-END, add/move to the
16924 end of the list."
16925 (interactive "P")
16926 (let ((org-agenda-skip-unavailable-files nil)
16927 (file-alist (mapcar (lambda (x)
16928 (cons (file-truename x) x))
16929 (org-agenda-files t)))
16930 (ctf (file-truename buffer-file-name))
16931 x had)
16932 (setq x (assoc ctf file-alist) had x)
16934 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16935 (if to-end
16936 (setq file-alist (append (delq x file-alist) (list x)))
16937 (setq file-alist (cons x (delq x file-alist))))
16938 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16939 (org-install-agenda-files-menu)
16940 (message "File %s to %s of agenda file list"
16941 (if had "moved" "added") (if to-end "end" "front"))))
16943 (defun org-remove-file (&optional file)
16944 "Remove current file from the list of files in variable `org-agenda-files'.
16945 These are the files which are being checked for agenda entries.
16946 Optional argument FILE means use this file instead of the current."
16947 (interactive)
16948 (let* ((org-agenda-skip-unavailable-files nil)
16949 (file (or file buffer-file-name))
16950 (true-file (file-truename file))
16951 (afile (abbreviate-file-name file))
16952 (files (delq nil (mapcar
16953 (lambda (x)
16954 (if (equal true-file
16955 (file-truename x))
16956 nil x))
16957 (org-agenda-files t)))))
16958 (if (not (= (length files) (length (org-agenda-files t))))
16959 (progn
16960 (org-store-new-agenda-file-list files)
16961 (org-install-agenda-files-menu)
16962 (message "Removed file: %s" afile))
16963 (message "File was not in list: %s (not removed)" afile))))
16965 (defun org-file-menu-entry (file)
16966 (vector file (list 'find-file file) t))
16968 (defun org-check-agenda-file (file)
16969 "Make sure FILE exists. If not, ask user what to do."
16970 (when (not (file-exists-p file))
16971 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16972 (abbreviate-file-name file))
16973 (let ((r (downcase (read-char-exclusive))))
16974 (cond
16975 ((equal r ?r)
16976 (org-remove-file file)
16977 (throw 'nextfile t))
16978 (t (error "Abort"))))))
16980 (defun org-get-agenda-file-buffer (file)
16981 "Get a buffer visiting FILE. If the buffer needs to be created, add
16982 it to the list of buffers which might be released later."
16983 (let ((buf (org-find-base-buffer-visiting file)))
16984 (if buf
16985 buf ; just return it
16986 ;; Make a new buffer and remember it
16987 (setq buf (find-file-noselect file))
16988 (if buf (push buf org-agenda-new-buffers))
16989 buf)))
16991 (defun org-release-buffers (blist)
16992 "Release all buffers in list, asking the user for confirmation when needed.
16993 When a buffer is unmodified, it is just killed. When modified, it is saved
16994 \(if the user agrees) and then killed."
16995 (let (buf file)
16996 (while (setq buf (pop blist))
16997 (setq file (buffer-file-name buf))
16998 (when (and (buffer-modified-p buf)
16999 file
17000 (y-or-n-p (format "Save file %s? " file)))
17001 (with-current-buffer buf (save-buffer)))
17002 (kill-buffer buf))))
17004 (defun org-prepare-agenda-buffers (files)
17005 "Create buffers for all agenda files, protect archived trees and comments."
17006 (interactive)
17007 (let ((pa '(:org-archived t))
17008 (pc '(:org-comment t))
17009 (pall '(:org-archived t :org-comment t))
17010 (inhibit-read-only t)
17011 (rea (concat ":" org-archive-tag ":"))
17012 bmp file re)
17013 (save-excursion
17014 (save-restriction
17015 (while (setq file (pop files))
17016 (catch 'nextfile
17017 (if (bufferp file)
17018 (set-buffer file)
17019 (org-check-agenda-file file)
17020 (set-buffer (org-get-agenda-file-buffer file)))
17021 (widen)
17022 (setq bmp (buffer-modified-p))
17023 (org-refresh-category-properties)
17024 (setq org-todo-keywords-for-agenda
17025 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17026 (setq org-done-keywords-for-agenda
17027 (append org-done-keywords-for-agenda org-done-keywords))
17028 (setq org-todo-keyword-alist-for-agenda
17029 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17030 (setq org-drawers-for-agenda
17031 (append org-drawers-for-agenda org-drawers))
17032 (setq org-tag-alist-for-agenda
17033 (append org-tag-alist-for-agenda org-tag-alist))
17035 (save-excursion
17036 (remove-text-properties (point-min) (point-max) pall)
17037 (when org-agenda-skip-archived-trees
17038 (goto-char (point-min))
17039 (while (re-search-forward rea nil t)
17040 (if (org-at-heading-p t)
17041 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17042 (goto-char (point-min))
17043 (setq re (format org-heading-keyword-regexp-format
17044 org-comment-string))
17045 (while (re-search-forward re nil t)
17046 (add-text-properties
17047 (match-beginning 0) (org-end-of-subtree t) pc)))
17048 (set-buffer-modified-p bmp)))))
17049 (setq org-todo-keywords-for-agenda
17050 (org-uniquify org-todo-keywords-for-agenda))
17051 (setq org-todo-keyword-alist-for-agenda
17052 (org-uniquify org-todo-keyword-alist-for-agenda)
17053 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17055 ;;;; Embedded LaTeX
17057 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17058 "Keymap for the minor `org-cdlatex-mode'.")
17060 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17061 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17062 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17063 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17064 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17066 (defvar org-cdlatex-texmathp-advice-is-done nil
17067 "Flag remembering if we have applied the advice to texmathp already.")
17069 (define-minor-mode org-cdlatex-mode
17070 "Toggle the minor `org-cdlatex-mode'.
17071 This mode supports entering LaTeX environment and math in LaTeX fragments
17072 in Org-mode.
17073 \\{org-cdlatex-mode-map}"
17074 nil " OCDL" nil
17075 (when org-cdlatex-mode
17076 (require 'cdlatex)
17077 (run-hooks 'cdlatex-mode-hook)
17078 (cdlatex-compute-tables))
17079 (unless org-cdlatex-texmathp-advice-is-done
17080 (setq org-cdlatex-texmathp-advice-is-done t)
17081 (defadvice texmathp (around org-math-always-on activate)
17082 "Always return t in org-mode buffers.
17083 This is because we want to insert math symbols without dollars even outside
17084 the LaTeX math segments. If Orgmode thinks that point is actually inside
17085 an embedded LaTeX fragment, let texmathp do its job.
17086 \\[org-cdlatex-mode-map]"
17087 (interactive)
17088 (let (p)
17089 (cond
17090 ((not (derived-mode-p 'org-mode)) ad-do-it)
17091 ((eq this-command 'cdlatex-math-symbol)
17092 (setq ad-return-value t
17093 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17095 (let ((p (org-inside-LaTeX-fragment-p)))
17096 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17097 (setq ad-return-value t
17098 texmathp-why '("Org-mode embedded math" . 0))
17099 (if p ad-do-it)))))))))
17101 (defun turn-on-org-cdlatex ()
17102 "Unconditionally turn on `org-cdlatex-mode'."
17103 (org-cdlatex-mode 1))
17105 (defun org-inside-LaTeX-fragment-p ()
17106 "Test if point is inside a LaTeX fragment.
17107 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17108 sequence appearing also before point.
17109 Even though the matchers for math are configurable, this function assumes
17110 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17111 delimiters are skipped when they have been removed by customization.
17112 The return value is nil, or a cons cell with the delimiter and the
17113 position of this delimiter.
17115 This function does a reasonably good job, but can locally be fooled by
17116 for example currency specifications. For example it will assume being in
17117 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17118 fragments that are properly closed, but during editing, we have to live
17119 with the uncertainty caused by missing closing delimiters. This function
17120 looks only before point, not after."
17121 (catch 'exit
17122 (let ((pos (point))
17123 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17124 (lim (progn
17125 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17126 (point)))
17127 dd-on str (start 0) m re)
17128 (goto-char pos)
17129 (when dodollar
17130 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17131 re (nth 1 (assoc "$" org-latex-regexps)))
17132 (while (string-match re str start)
17133 (cond
17134 ((= (match-end 0) (length str))
17135 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17136 ((= (match-end 0) (- (length str) 5))
17137 (throw 'exit nil))
17138 (t (setq start (match-end 0))))))
17139 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17140 (goto-char pos)
17141 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17142 (and (match-beginning 2) (throw 'exit nil))
17143 ;; count $$
17144 (while (re-search-backward "\\$\\$" lim t)
17145 (setq dd-on (not dd-on)))
17146 (goto-char pos)
17147 (if dd-on (cons "$$" m))))))
17149 (defun org-inside-latex-macro-p ()
17150 "Is point inside a LaTeX macro or its arguments?"
17151 (save-match-data
17152 (org-in-regexp
17153 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17155 (defun org-try-cdlatex-tab ()
17156 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17157 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17158 - inside a LaTeX fragment, or
17159 - after the first word in a line, where an abbreviation expansion could
17160 insert a LaTeX environment."
17161 (when org-cdlatex-mode
17162 (cond
17163 ;; Before any word on the line: No expansion possible.
17164 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17165 ;; Just after first word on the line: Expand it. Make sure it
17166 ;; cannot happen on headlines, though.
17167 ((save-excursion
17168 (skip-chars-backward "a-zA-Z0-9*")
17169 (skip-chars-backward " \t")
17170 (and (bolp) (not (org-at-heading-p))))
17171 (cdlatex-tab) t)
17172 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17174 (defun org-cdlatex-underscore-caret (&optional arg)
17175 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17176 Revert to the normal definition outside of these fragments."
17177 (interactive "P")
17178 (if (org-inside-LaTeX-fragment-p)
17179 (call-interactively 'cdlatex-sub-superscript)
17180 (let (org-cdlatex-mode)
17181 (call-interactively (key-binding (vector last-input-event))))))
17183 (defun org-cdlatex-math-modify (&optional arg)
17184 "Execute `cdlatex-math-modify' in LaTeX fragments.
17185 Revert to the normal definition outside of these fragments."
17186 (interactive "P")
17187 (if (org-inside-LaTeX-fragment-p)
17188 (call-interactively 'cdlatex-math-modify)
17189 (let (org-cdlatex-mode)
17190 (call-interactively (key-binding (vector last-input-event))))))
17192 (defvar org-latex-fragment-image-overlays nil
17193 "List of overlays carrying the images of latex fragments.")
17194 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17196 (defun org-remove-latex-fragment-image-overlays ()
17197 "Remove all overlays with LaTeX fragment images in current buffer."
17198 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17199 (setq org-latex-fragment-image-overlays nil))
17201 (defun org-preview-latex-fragment (&optional subtree)
17202 "Preview the LaTeX fragment at point, or all locally or globally.
17203 If the cursor is in a LaTeX fragment, create the image and overlay
17204 it over the source code. If there is no fragment at point, display
17205 all fragments in the current text, from one headline to the next. With
17206 prefix SUBTREE, display all fragments in the current subtree. With a
17207 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17208 the cursor is before the first headline,
17209 display all fragments in the buffer.
17210 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17211 (interactive "P")
17212 (unless buffer-file-name
17213 (error "Can't preview LaTeX fragment in a non-file buffer"))
17214 (org-remove-latex-fragment-image-overlays)
17215 (save-excursion
17216 (save-restriction
17217 (let (beg end at msg)
17218 (cond
17219 ((or (equal subtree '(16))
17220 (not (save-excursion
17221 (re-search-backward org-outline-regexp-bol nil t))))
17222 (setq beg (point-min) end (point-max)
17223 msg "Creating images for buffer...%s"))
17224 ((equal subtree '(4))
17225 (org-back-to-heading)
17226 (setq beg (point) end (org-end-of-subtree t)
17227 msg "Creating images for subtree...%s"))
17229 (if (setq at (org-inside-LaTeX-fragment-p))
17230 (goto-char (max (point-min) (- (cdr at) 2)))
17231 (org-back-to-heading))
17232 (setq beg (point) end (progn (outline-next-heading) (point))
17233 msg (if at "Creating image...%s"
17234 "Creating images for entry...%s"))))
17235 (message msg "")
17236 (narrow-to-region beg end)
17237 (goto-char beg)
17238 (org-format-latex
17239 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17240 (file-name-nondirectory
17241 buffer-file-name)))
17242 default-directory 'overlays msg at 'forbuffer
17243 org-latex-create-formula-image-program)
17244 (message msg "done. Use `C-c C-c' to remove images.")))))
17246 (defvar org-latex-regexps
17247 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17248 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17249 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17250 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17251 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17252 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17253 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17254 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17255 "Regular expressions for matching embedded LaTeX.")
17257 (defvar org-export-have-math nil) ;; dynamic scoping
17258 (defun org-format-latex (prefix &optional dir overlays msg at
17259 forbuffer processing-type)
17260 "Replace LaTeX fragments with links to an image, and produce images.
17261 Some of the options can be changed using the variable
17262 `org-format-latex-options'."
17263 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17264 (let* ((prefixnodir (file-name-nondirectory prefix))
17265 (absprefix (expand-file-name prefix dir))
17266 (todir (file-name-directory absprefix))
17267 (opt org-format-latex-options)
17268 (matchers (plist-get opt :matchers))
17269 (re-list org-latex-regexps)
17270 (org-format-latex-header-extra
17271 (plist-get (org-infile-export-plist) :latex-header-extra))
17272 (cnt 0) txt hash link beg end re e checkdir
17273 executables-checked string
17274 m n block-type block linkfile movefile ov)
17275 ;; Check the different regular expressions
17276 (while (setq e (pop re-list))
17277 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17278 block (if block-type "\n\n" ""))
17279 (when (member m matchers)
17280 (goto-char (point-min))
17281 (while (re-search-forward re nil t)
17282 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17283 (not (get-text-property (match-beginning n)
17284 'org-protected))
17285 (or (not overlays)
17286 (not (eq (get-char-property (match-beginning n)
17287 'org-overlay-type)
17288 'org-latex-overlay))))
17289 (setq org-export-have-math t)
17290 (cond
17291 ((eq processing-type 'verbatim)
17292 ;; Leave the text verbatim, just protect it
17293 (add-text-properties (match-beginning n) (match-end n)
17294 '(org-protected t)))
17295 ((eq processing-type 'mathjax)
17296 ;; Prepare for MathJax processing
17297 (setq string (match-string n))
17298 (if (member m '("$" "$1"))
17299 (save-excursion
17300 (delete-region (match-beginning n) (match-end n))
17301 (goto-char (match-beginning n))
17302 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17303 "\\)")
17304 '(org-protected t))))
17305 (add-text-properties (match-beginning n) (match-end n)
17306 '(org-protected t))))
17307 ((or (eq processing-type 'dvipng)
17308 (eq processing-type 'imagemagick))
17309 ;; Process to an image
17310 (setq txt (match-string n)
17311 beg (match-beginning n) end (match-end n)
17312 cnt (1+ cnt))
17313 (let (print-length print-level) ; make sure full list is printed
17314 (setq hash (sha1 (prin1-to-string
17315 (list org-format-latex-header
17316 org-format-latex-header-extra
17317 org-export-latex-default-packages-alist
17318 org-export-latex-packages-alist
17319 org-format-latex-options
17320 forbuffer txt)))
17321 linkfile (format "%s_%s.png" prefix hash)
17322 movefile (format "%s_%s.png" absprefix hash)))
17323 (setq link (concat block "[[file:" linkfile "]]" block))
17324 (if msg (message msg cnt))
17325 (goto-char beg)
17326 (unless checkdir ; make sure the directory exists
17327 (setq checkdir t)
17328 (or (file-directory-p todir) (make-directory todir t)))
17329 (cond
17330 ((eq processing-type 'dvipng)
17331 (unless executables-checked
17332 (org-check-external-command
17333 "latex" "needed to convert LaTeX fragments to images")
17334 (org-check-external-command
17335 "dvipng" "needed to convert LaTeX fragments to images")
17336 (setq executables-checked t))
17337 (unless (file-exists-p movefile)
17338 (org-create-formula-image-with-dvipng
17339 txt movefile opt forbuffer)))
17340 ((eq processing-type 'imagemagick)
17341 (unless executables-checked
17342 (org-check-external-command
17343 "convert" "you need to install imagemagick")
17344 (setq executables-checked t))
17345 (unless (file-exists-p movefile)
17346 (org-create-formula-image-with-imagemagick
17347 txt movefile opt forbuffer))))
17348 (if overlays
17349 (progn
17350 (mapc (lambda (o)
17351 (if (eq (overlay-get o 'org-overlay-type)
17352 'org-latex-overlay)
17353 (delete-overlay o)))
17354 (overlays-in beg end))
17355 (setq ov (make-overlay beg end))
17356 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17357 (if (featurep 'xemacs)
17358 (progn
17359 (overlay-put ov 'invisible t)
17360 (overlay-put
17361 ov 'end-glyph
17362 (make-glyph (vector 'png :file movefile))))
17363 (overlay-put
17364 ov 'display
17365 (list 'image :type 'png :file movefile :ascent 'center)))
17366 (push ov org-latex-fragment-image-overlays)
17367 (goto-char end))
17368 (delete-region beg end)
17369 (insert (org-add-props link
17370 (list 'org-latex-src
17371 (replace-regexp-in-string
17372 "\"" "" txt)
17373 'org-latex-src-embed-type
17374 (if block-type 'paragraph 'character))))))
17375 ((eq processing-type 'mathml)
17376 ;; Process to MathML
17377 (unless executables-checked
17378 (unless (save-match-data (org-format-latex-mathml-available-p))
17379 (error "LaTeX to MathML converter not configured"))
17380 (setq executables-checked t))
17381 (setq txt (match-string n)
17382 beg (match-beginning n) end (match-end n)
17383 cnt (1+ cnt))
17384 (if msg (message msg cnt))
17385 (goto-char beg)
17386 (delete-region beg end)
17387 (insert (org-format-latex-as-mathml
17388 txt block-type prefix dir)))
17390 (error "Unknown conversion type %s for latex fragments"
17391 processing-type)))))))))
17393 (defun org-create-math-formula (latex-frag &optional mathml-file)
17394 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17395 Use `org-latex-to-mathml-convert-command'. If the conversion is
17396 sucessful, return the portion between \"<math...> </math>\"
17397 elements otherwise return nil. When MATHML-FILE is specified,
17398 write the results in to that file. When invoked as an
17399 interactive command, prompt for LATEX-FRAG, with initial value
17400 set to the current active region and echo the results for user
17401 inspection."
17402 (interactive (list (let ((frag (when (region-active-p)
17403 (buffer-substring-no-properties
17404 (region-beginning) (region-end)))))
17405 (read-string "LaTeX Fragment: " frag nil frag))))
17406 (unless latex-frag (error "Invalid latex-frag"))
17407 (let* ((tmp-in-file (file-relative-name
17408 (make-temp-name (expand-file-name "ltxmathml-in"))))
17409 (ignore (write-region latex-frag nil tmp-in-file))
17410 (tmp-out-file (file-relative-name
17411 (make-temp-name (expand-file-name "ltxmathml-out"))))
17412 (cmd (format-spec
17413 org-latex-to-mathml-convert-command
17414 `((?j . ,(shell-quote-argument
17415 (expand-file-name org-latex-to-mathml-jar-file)))
17416 (?I . ,(shell-quote-argument tmp-in-file))
17417 (?o . ,(shell-quote-argument tmp-out-file)))))
17418 mathml shell-command-output)
17419 (when (org-called-interactively-p 'any)
17420 (unless (org-format-latex-mathml-available-p)
17421 (error "LaTeX to MathML converter not configured")))
17422 (message "Running %s" cmd)
17423 (setq shell-command-output (shell-command-to-string cmd))
17424 (setq mathml
17425 (when (file-readable-p tmp-out-file)
17426 (with-current-buffer (find-file-noselect tmp-out-file t)
17427 (goto-char (point-min))
17428 (when (re-search-forward
17429 (concat
17430 (regexp-quote
17431 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17432 "\\(.\\|\n\\)*"
17433 (regexp-quote "</math>")) nil t)
17434 (prog1 (match-string 0) (kill-buffer))))))
17435 (cond
17436 (mathml
17437 (setq mathml
17438 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17439 (when mathml-file
17440 (write-region mathml nil mathml-file))
17441 (when (org-called-interactively-p 'any)
17442 (message mathml)))
17443 ((message "LaTeX to MathML conversion failed")
17444 (message shell-command-output)))
17445 (delete-file tmp-in-file)
17446 (when (file-exists-p tmp-out-file)
17447 (delete-file tmp-out-file))
17448 mathml))
17450 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17451 prefix &optional dir)
17452 "Use `org-create-math-formula' but check local cache first."
17453 (let* ((absprefix (expand-file-name prefix dir))
17454 (print-length nil) (print-level nil)
17455 (formula-id (concat
17456 "formula-"
17457 (sha1
17458 (prin1-to-string
17459 (list latex-frag
17460 org-latex-to-mathml-convert-command)))))
17461 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17462 (formula-cache-dir (file-name-directory formula-cache)))
17464 (unless (file-directory-p formula-cache-dir)
17465 (make-directory formula-cache-dir t))
17467 (unless (file-exists-p formula-cache)
17468 (org-create-math-formula latex-frag formula-cache))
17470 (if (file-exists-p formula-cache)
17471 ;; Successful conversion. Return the link to MathML file.
17472 (org-add-props
17473 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17474 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17475 'org-latex-src-embed-type (if latex-frag-type
17476 'paragraph 'character)))
17477 ;; Failed conversion. Return the LaTeX fragment verbatim
17478 (add-text-properties
17479 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17480 latex-frag)))
17482 ;; This function borrows from Ganesh Swami's latex2png.el
17483 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17484 "This calls dvipng."
17485 (require 'org-latex)
17486 (let* ((tmpdir (if (featurep 'xemacs)
17487 (temp-directory)
17488 temporary-file-directory))
17489 (texfilebase (make-temp-name
17490 (expand-file-name "orgtex" tmpdir)))
17491 (texfile (concat texfilebase ".tex"))
17492 (dvifile (concat texfilebase ".dvi"))
17493 (pngfile (concat texfilebase ".png"))
17494 (fnh (if (featurep 'xemacs)
17495 (font-height (face-font 'default))
17496 (face-attribute 'default :height nil)))
17497 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17498 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17499 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17500 "Black"))
17501 (bg (or (plist-get options (if buffer :background :html-background))
17502 "Transparent")))
17503 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17504 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17505 (with-temp-file texfile
17506 (insert (org-splice-latex-header
17507 org-format-latex-header
17508 org-export-latex-default-packages-alist
17509 org-export-latex-packages-alist t
17510 org-format-latex-header-extra))
17511 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17512 (require 'org-latex)
17513 (org-export-latex-fix-inputenc))
17514 (let ((dir default-directory))
17515 (condition-case nil
17516 (progn
17517 (cd tmpdir)
17518 (call-process "latex" nil nil nil texfile))
17519 (error nil))
17520 (cd dir))
17521 (if (not (file-exists-p dvifile))
17522 (progn (message "Failed to create dvi file from %s" texfile) nil)
17523 (condition-case nil
17524 (if (featurep 'xemacs)
17525 (call-process "dvipng" nil nil nil
17526 "-fg" fg "-bg" bg
17527 "-T" "tight"
17528 "-o" pngfile
17529 dvifile)
17530 (call-process "dvipng" nil nil nil
17531 "-fg" fg "-bg" bg
17532 "-D" dpi
17533 ;;"-x" scale "-y" scale
17534 "-T" "tight"
17535 "-o" pngfile
17536 dvifile))
17537 (error nil))
17538 (if (not (file-exists-p pngfile))
17539 (if org-format-latex-signal-error
17540 (error "Failed to create png file from %s" texfile)
17541 (message "Failed to create png file from %s" texfile)
17542 nil)
17543 ;; Use the requested file name and clean up
17544 (copy-file pngfile tofile 'replace)
17545 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17546 (if (file-exists-p (concat texfilebase e))
17547 (delete-file (concat texfilebase e))))
17548 pngfile))))
17550 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17551 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17552 "This calls convert, which is included into imagemagick."
17553 (require 'org-latex)
17554 (let* ((tmpdir (if (featurep 'xemacs)
17555 (temp-directory)
17556 temporary-file-directory))
17557 (texfilebase (make-temp-name
17558 (expand-file-name "orgtex" tmpdir)))
17559 (texfile (concat texfilebase ".tex"))
17560 (pdffile (concat texfilebase ".pdf"))
17561 (pngfile (concat texfilebase ".png"))
17562 (fnh (if (featurep 'xemacs)
17563 (font-height (face-font 'default))
17564 (face-attribute 'default :height nil)))
17565 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17566 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17567 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17568 "black"))
17569 (bg (or (plist-get options (if buffer :background :html-background))
17570 "white")))
17571 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17572 (setq fg (org-latex-color-format fg)))
17573 (if (eq bg 'default) (setq bg (org-latex-color :background))
17574 (setq bg (org-latex-color-format
17575 (if (string= bg "Transparent")(setq bg "white")))))
17576 (with-temp-file texfile
17577 (insert (org-splice-latex-header
17578 org-format-latex-header
17579 org-export-latex-default-packages-alist
17580 org-export-latex-packages-alist t
17581 org-format-latex-header-extra))
17582 (insert "\n\\begin{document}\n"
17583 "\\definecolor{fg}{rgb}{" fg "}\n"
17584 "\\definecolor{bg}{rgb}{" bg "}\n"
17585 "\n\\pagecolor{bg}\n"
17586 "\n{\\color{fg}\n"
17587 string
17588 "\n}\n"
17589 "\n\\end{document}\n" )
17590 (require 'org-latex)
17591 (org-export-latex-fix-inputenc))
17592 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17593 (condition-case nil
17594 (progn
17595 (cd tmpdir)
17596 (setq cmds org-latex-to-pdf-process)
17597 (while cmds
17598 (setq latex-frags-cmds (pop cmds))
17599 (if (listp latex-frags-cmds)
17600 (setq cmds nil)
17601 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17602 (while latex-frags-cmds
17603 (setq cmd (pop latex-frags-cmds))
17604 (while (string-match "%b" cmd)
17605 (setq cmd (replace-match
17606 (save-match-data
17607 (shell-quote-argument texfile))
17608 t t cmd)))
17609 (while (string-match "%f" cmd)
17610 (setq cmd (replace-match
17611 (save-match-data
17612 (shell-quote-argument (file-name-nondirectory texfile)))
17613 t t cmd)))
17614 (while (string-match "%o" cmd)
17615 (setq cmd (replace-match
17616 (save-match-data
17617 (shell-quote-argument (file-name-directory texfile)))
17618 t t cmd)))
17619 (setq cmd (split-string cmd))
17620 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17621 (error nil))
17622 (cd dir))
17623 (if (not (file-exists-p pdffile))
17624 (progn (message "Failed to create pdf file from %s" texfile) nil)
17625 (condition-case nil
17626 (if (featurep 'xemacs)
17627 (call-process "convert" nil nil nil
17628 "-density" "96"
17629 "-trim"
17630 "-antialias"
17631 pdffile
17632 "-quality" "100"
17633 ;; "-sharpen" "0x1.0"
17634 pngfile)
17635 (call-process "convert" nil nil nil
17636 "-density" dpi
17637 "-trim"
17638 "-antialias"
17639 pdffile
17640 "-quality" "100"
17641 ; "-sharpen" "0x1.0"
17642 pngfile))
17643 (error nil))
17644 (if (not (file-exists-p pngfile))
17645 (if org-format-latex-signal-error
17646 (error "Failed to create png file from %s" texfile)
17647 (message "Failed to create png file from %s" texfile)
17648 nil)
17649 ;; Use the requested file name and clean up
17650 (copy-file pngfile tofile 'replace)
17651 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17652 (if (file-exists-p (concat texfilebase e))
17653 (delete-file (concat texfilebase e))))
17654 pngfile))))
17656 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17657 "Fill a LaTeX header template TPL.
17658 In the template, the following place holders will be recognized:
17660 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17661 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17662 [PACKAGES] \\usepackage statements for PKG
17663 [NO-PACKAGES] do not include PKG
17664 [EXTRA] the string EXTRA
17665 [NO-EXTRA] do not include EXTRA
17667 For backward compatibility, if both the positive and the negative place
17668 holder is missing, the positive one (without the \"NO-\") will be
17669 assumed to be present at the end of the template.
17670 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17671 EXTRA is a string.
17672 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17673 (let (rpl (end ""))
17674 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17675 (setq rpl (if (or (match-end 1) (not def-pkg))
17676 "" (org-latex-packages-to-string def-pkg snippets-p t))
17677 tpl (replace-match rpl t t tpl))
17678 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17680 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17681 (setq rpl (if (or (match-end 1) (not pkg))
17682 "" (org-latex-packages-to-string pkg snippets-p t))
17683 tpl (replace-match rpl t t tpl))
17684 (if pkg (setq end
17685 (concat end "\n"
17686 (org-latex-packages-to-string pkg snippets-p)))))
17688 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17689 (setq rpl (if (or (match-end 1) (not extra))
17690 "" (concat extra "\n"))
17691 tpl (replace-match rpl t t tpl))
17692 (if (and extra (string-match "\\S-" extra))
17693 (setq end (concat end "\n" extra))))
17695 (if (string-match "\\S-" end)
17696 (concat tpl "\n" end)
17697 tpl)))
17699 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17700 "Turn an alist of packages into a string with the \\usepackage macros."
17701 (setq pkg (mapconcat (lambda(p)
17702 (cond
17703 ((stringp p) p)
17704 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17705 (format "%% Package %s omitted" (cadr p)))
17706 ((equal "" (car p))
17707 (format "\\usepackage{%s}" (cadr p)))
17709 (format "\\usepackage[%s]{%s}"
17710 (car p) (cadr p)))))
17712 "\n"))
17713 (if newline (concat pkg "\n") pkg))
17715 (defun org-dvipng-color (attr)
17716 "Return a RGB color specification for dvipng."
17717 (apply 'format "rgb %s %s %s"
17718 (mapcar 'org-normalize-color
17719 (if (featurep 'xemacs)
17720 (color-rgb-components
17721 (face-property 'default
17722 (cond ((eq attr :foreground) 'foreground)
17723 ((eq attr :background) 'background))))
17724 (color-values (face-attribute 'default attr nil))))))
17726 (defun org-latex-color (attr)
17727 "Return a RGB color for the LaTeX color package."
17728 (apply 'format "%s,%s,%s"
17729 (mapcar 'org-normalize-color
17730 (if (featurep 'xemacs)
17731 (color-rgb-components
17732 (face-property 'default
17733 (cond ((eq attr :foreground) 'foreground)
17734 ((eq attr :background) 'background))))
17735 (color-values (face-attribute 'default attr nil))))))
17737 (defun org-latex-color-format (color-name)
17738 "Convert COLOR-NAME to a RGB color value."
17739 (apply 'format "%s,%s,%s"
17740 (mapcar 'org-normalize-color
17741 (color-values color-name))))
17743 (defun org-normalize-color (value)
17744 "Return string to be used as color value for an RGB component."
17745 (format "%g" (/ value 65535.0)))
17747 ;; Image display
17750 (defvar org-inline-image-overlays nil)
17751 (make-variable-buffer-local 'org-inline-image-overlays)
17753 (defun org-toggle-inline-images (&optional include-linked)
17754 "Toggle the display of inline images.
17755 INCLUDE-LINKED is passed to `org-display-inline-images'."
17756 (interactive "P")
17757 (if org-inline-image-overlays
17758 (progn
17759 (org-remove-inline-images)
17760 (message "Inline image display turned off"))
17761 (org-display-inline-images include-linked)
17762 (if org-inline-image-overlays
17763 (message "%d images displayed inline"
17764 (length org-inline-image-overlays))
17765 (message "No images to display inline"))))
17767 (defun org-redisplay-inline-images ()
17768 "Refresh the display of inline images."
17769 (interactive)
17770 (if (not org-inline-image-overlays)
17771 (org-toggle-inline-images)
17772 (org-toggle-inline-images)
17773 (org-toggle-inline-images)))
17775 (defun org-display-inline-images (&optional include-linked refresh beg end)
17776 "Display inline images.
17777 Normally only links without a description part are inlined, because this
17778 is how it will work for export. When INCLUDE-LINKED is set, also links
17779 with a description part will be inlined. This can be nice for a quick
17780 look at those images, but it does not reflect what exported files will look
17781 like.
17782 When REFRESH is set, refresh existing images between BEG and END.
17783 This will create new image displays only if necessary.
17784 BEG and END default to the buffer boundaries."
17785 (interactive "P")
17786 (unless refresh
17787 (org-remove-inline-images)
17788 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17789 (save-excursion
17790 (save-restriction
17791 (widen)
17792 (setq beg (or beg (point-min)) end (or end (point-max)))
17793 (goto-char beg)
17794 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17795 (substring (org-image-file-name-regexp) 0 -2)
17796 "\\)\\]" (if include-linked "" "\\]")))
17797 old file ov img)
17798 (while (re-search-forward re end t)
17799 (setq old (get-char-property-and-overlay (match-beginning 1)
17800 'org-image-overlay))
17801 (setq file (expand-file-name
17802 (concat (or (match-string 3) "") (match-string 4))))
17803 (when (file-exists-p file)
17804 (if (and (car-safe old) refresh)
17805 (image-refresh (overlay-get (cdr old) 'display))
17806 (setq img (save-match-data (create-image file)))
17807 (when img
17808 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17809 (overlay-put ov 'display img)
17810 (overlay-put ov 'face 'default)
17811 (overlay-put ov 'org-image-overlay t)
17812 (overlay-put ov 'modification-hooks
17813 (list 'org-display-inline-modification-hook))
17814 (push ov org-inline-image-overlays)))))))))
17816 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17817 "Remove inline-display overlay if a corresponding region is modified."
17818 (let ((inhibit-modification-hooks t))
17819 (when (and ov after)
17820 (delete ov org-inline-image-overlays)
17821 (delete-overlay ov))))
17823 (defun org-remove-inline-images ()
17824 "Remove inline display of images."
17825 (interactive)
17826 (mapc 'delete-overlay org-inline-image-overlays)
17827 (setq org-inline-image-overlays nil))
17829 ;;;; Key bindings
17831 ;; Outline functions from `outline-mode-prefix-map'
17832 ;; that can be remapped in Org:
17833 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17834 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17835 (define-key org-mode-map [remap outline-forward-same-level]
17836 'org-forward-heading-same-level)
17837 (define-key org-mode-map [remap outline-backward-same-level]
17838 'org-backward-heading-same-level)
17839 (define-key org-mode-map [remap show-branches]
17840 'org-kill-note-or-show-branches)
17841 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17842 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17843 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17845 ;; Outline functions from `outline-mode-prefix-map' that can not
17846 ;; be remapped in Org:
17848 ;; - the column "key binding" shows whether the Outline function is still
17849 ;; available in Org mode on the same key that it has been bound to in
17850 ;; Outline mode:
17851 ;; - "overridden": key used for a different functionality in Org mode
17852 ;; - else: key still bound to the same Outline function in Org mode
17854 ;; | Outline function | key binding | Org replacement |
17855 ;; |------------------------------------+-------------+-----------------------|
17856 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17857 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17858 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17859 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17860 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17861 ;; | `show-entry' | overridden | no replacement |
17862 ;; | `show-children' | `C-c C-i' | visibility cycling |
17863 ;; | `show-branches' | `C-c C-k' | still same function |
17864 ;; | `show-subtree' | overridden | visibility cycling |
17865 ;; | `show-all' | overridden | no replacement |
17866 ;; | `hide-subtree' | overridden | visibility cycling |
17867 ;; | `hide-body' | overridden | no replacement |
17868 ;; | `hide-entry' | overridden | visibility cycling |
17869 ;; | `hide-leaves' | overridden | no replacement |
17870 ;; | `hide-sublevels' | overridden | no replacement |
17871 ;; | `hide-other' | overridden | no replacement |
17873 ;; Make `C-c C-x' a prefix key
17874 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17876 ;; TAB key with modifiers
17877 (org-defkey org-mode-map "\C-i" 'org-cycle)
17878 (org-defkey org-mode-map [(tab)] 'org-cycle)
17879 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17880 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17881 ;; The following line is necessary under Suse GNU/Linux
17882 (unless (featurep 'xemacs)
17883 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17884 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17885 (define-key org-mode-map [backtab] 'org-shifttab)
17887 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17888 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17889 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17891 ;; Cursor keys with modifiers
17892 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17893 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17894 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17895 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17897 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17898 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17899 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17900 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17902 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17903 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17904 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17905 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17907 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17908 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17909 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17910 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17912 ;; Babel keys
17913 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17914 (mapc (lambda (pair)
17915 (define-key org-babel-map (car pair) (cdr pair)))
17916 org-babel-key-bindings)
17918 ;;; Extra keys for tty access.
17919 ;; We only set them when really needed because otherwise the
17920 ;; menus don't show the simple keys
17922 (when (or org-use-extra-keys
17923 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17924 (not window-system))
17925 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17926 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17927 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17928 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17929 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17930 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17931 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17932 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17933 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17934 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17935 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17936 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17937 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17938 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17939 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17940 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17941 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17942 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17943 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17944 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17945 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17946 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17947 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17948 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17949 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17950 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17951 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17952 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17954 ;; All the other keys
17956 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17957 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17958 (if (boundp 'narrow-map)
17959 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17960 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17961 (if (boundp 'narrow-map)
17962 (org-defkey narrow-map "b" 'org-narrow-to-block)
17963 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17964 (if (boundp 'narrow-map)
17965 (org-defkey narrow-map "e" 'org-narrow-to-element)
17966 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17967 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17968 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17969 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17970 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17971 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17972 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17973 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17974 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17975 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17976 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17977 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17978 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17979 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17980 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17981 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17982 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17983 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17984 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17985 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17986 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17987 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17988 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17989 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17990 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17991 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17992 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17993 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17994 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17995 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17996 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17997 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17998 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17999 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18000 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18001 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18002 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18003 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18004 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18005 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18006 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18007 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18008 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18009 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18010 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18011 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18012 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18013 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18014 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18015 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18016 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18017 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18018 (org-defkey org-mode-map "\C-c^" 'org-sort)
18019 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18020 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18021 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18022 (org-defkey org-mode-map "\C-m" 'org-return)
18023 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18024 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18025 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18026 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18027 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18028 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18029 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18030 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18031 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18032 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18033 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18034 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18035 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18036 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18037 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18038 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18039 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18040 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18041 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18042 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18043 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18044 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18045 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18047 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18048 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18049 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18050 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18052 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18053 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18054 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18055 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18056 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18057 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18058 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18059 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18060 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18061 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18062 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18063 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18064 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18065 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18066 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18067 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18068 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18069 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18070 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18071 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18072 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18073 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18075 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18076 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18077 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18078 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18079 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18081 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18083 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18085 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18086 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18088 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18091 (when (featurep 'xemacs)
18092 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18095 (defconst org-speed-commands-default
18097 ("Outline Navigation")
18098 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18099 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18100 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18101 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18102 ("u" . (org-speed-move-safe 'outline-up-heading))
18103 ("j" . org-goto)
18104 ("g" . (org-refile t))
18105 ("Outline Visibility")
18106 ("c" . org-cycle)
18107 ("C" . org-shifttab)
18108 (" " . org-display-outline-path)
18109 (":" . org-columns)
18110 ("Outline Structure Editing")
18111 ("U" . org-shiftmetaup)
18112 ("D" . org-shiftmetadown)
18113 ("r" . org-metaright)
18114 ("l" . org-metaleft)
18115 ("R" . org-shiftmetaright)
18116 ("L" . org-shiftmetaleft)
18117 ("i" . (progn (forward-char 1) (call-interactively
18118 'org-insert-heading-respect-content)))
18119 ("^" . org-sort)
18120 ("w" . org-refile)
18121 ("a" . org-archive-subtree-default-with-confirmation)
18122 ("." . org-mark-subtree)
18123 ("#" . org-toggle-comment)
18124 ("Clock Commands")
18125 ("I" . org-clock-in)
18126 ("O" . org-clock-out)
18127 ("Meta Data Editing")
18128 ("t" . org-todo)
18129 ("0" . (org-priority ?\ ))
18130 ("1" . (org-priority ?A))
18131 ("2" . (org-priority ?B))
18132 ("3" . (org-priority ?C))
18133 (";" . org-set-tags-command)
18134 ("e" . org-set-effort)
18135 ("E" . org-inc-effort)
18136 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18137 (org-entry-put (point) "APPT_WARNTIME" m)))
18138 ("Agenda Views etc")
18139 ("v" . org-agenda)
18140 ("/" . org-sparse-tree)
18141 ("Misc")
18142 ("o" . org-open-at-point)
18143 ("?" . org-speed-command-help)
18144 ("<" . (org-agenda-set-restriction-lock 'subtree))
18145 (">" . (org-agenda-remove-restriction-lock))
18147 "The default speed commands.")
18149 (defun org-print-speed-command (e)
18150 (if (> (length (car e)) 1)
18151 (progn
18152 (princ "\n")
18153 (princ (car e))
18154 (princ "\n")
18155 (princ (make-string (length (car e)) ?-))
18156 (princ "\n"))
18157 (princ (car e))
18158 (princ " ")
18159 (if (symbolp (cdr e))
18160 (princ (symbol-name (cdr e)))
18161 (prin1 (cdr e)))
18162 (princ "\n")))
18164 (defun org-speed-command-help ()
18165 "Show the available speed commands."
18166 (interactive)
18167 (if (not org-use-speed-commands)
18168 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18169 (with-output-to-temp-buffer "*Help*"
18170 (princ "User-defined Speed commands\n===========================\n")
18171 (mapc 'org-print-speed-command org-speed-commands-user)
18172 (princ "\n")
18173 (princ "Built-in Speed commands\n=======================\n")
18174 (mapc 'org-print-speed-command org-speed-commands-default))
18175 (with-current-buffer "*Help*"
18176 (setq truncate-lines t))))
18178 (defun org-speed-move-safe (cmd)
18179 "Execute CMD, but make sure that the cursor always ends up in a headline.
18180 If not, return to the original position and throw an error."
18181 (interactive)
18182 (let ((pos (point)))
18183 (call-interactively cmd)
18184 (unless (and (bolp) (org-at-heading-p))
18185 (goto-char pos)
18186 (error "Boundary reached while executing %s" cmd))))
18188 (defvar org-self-insert-command-undo-counter 0)
18190 (defvar org-table-auto-blank-field) ; defined in org-table.el
18191 (defvar org-speed-command nil)
18193 (defun org-speed-command-default-hook (keys)
18194 "Hook for activating single-letter speed commands.
18195 `org-speed-commands-default' specifies a minimal command set.
18196 Use `org-speed-commands-user' for further customization."
18197 (when (or (and (bolp) (looking-at org-outline-regexp))
18198 (and (functionp org-use-speed-commands)
18199 (funcall org-use-speed-commands)))
18200 (cdr (assoc keys (append org-speed-commands-user
18201 org-speed-commands-default)))))
18203 (defun org-babel-speed-command-hook (keys)
18204 "Hook for activating single-letter code block commands."
18205 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18206 (cdr (assoc keys org-babel-key-bindings))))
18208 (defcustom org-speed-command-hook
18209 '(org-speed-command-default-hook org-babel-speed-command-hook)
18210 "Hook for activating speed commands at strategic locations.
18211 Hook functions are called in sequence until a valid handler is
18212 found.
18214 Each hook takes a single argument, a user-pressed command key
18215 which is also a `self-insert-command' from the global map.
18217 Within the hook, examine the cursor position and the command key
18218 and return nil or a valid handler as appropriate. Handler could
18219 be one of an interactive command, a function, or a form.
18221 Set `org-use-speed-commands' to non-nil value to enable this
18222 hook. The default setting is `org-speed-command-default-hook'."
18223 :group 'org-structure
18224 :version "24.1"
18225 :type 'hook)
18227 (defun org-self-insert-command (N)
18228 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18229 If the cursor is in a table looking at whitespace, the whitespace is
18230 overwritten, and the table is not marked as requiring realignment."
18231 (interactive "p")
18232 (org-check-before-invisible-edit 'insert)
18233 (cond
18234 ((and org-use-speed-commands
18235 (setq org-speed-command
18236 (run-hook-with-args-until-success
18237 'org-speed-command-hook (this-command-keys))))
18238 (cond
18239 ((commandp org-speed-command)
18240 (setq this-command org-speed-command)
18241 (call-interactively org-speed-command))
18242 ((functionp org-speed-command)
18243 (funcall org-speed-command))
18244 ((and org-speed-command (listp org-speed-command))
18245 (eval org-speed-command))
18246 (t (let (org-use-speed-commands)
18247 (call-interactively 'org-self-insert-command)))))
18248 ((and
18249 (org-table-p)
18250 (progn
18251 ;; check if we blank the field, and if that triggers align
18252 (and (featurep 'org-table) org-table-auto-blank-field
18253 (member last-command
18254 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18255 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18256 ;; got extra space, this field does not determine column width
18257 (let (org-table-may-need-update) (org-table-blank-field))
18258 ;; no extra space, this field may determine column width
18259 (org-table-blank-field)))
18261 (eq N 1)
18262 (looking-at "[^|\n]* |"))
18263 (let (org-table-may-need-update)
18264 (goto-char (1- (match-end 0)))
18265 (backward-delete-char 1)
18266 (goto-char (match-beginning 0))
18267 (self-insert-command N)))
18269 (setq org-table-may-need-update t)
18270 (self-insert-command N)
18271 (org-fix-tags-on-the-fly)
18272 (if org-self-insert-cluster-for-undo
18273 (if (not (eq last-command 'org-self-insert-command))
18274 (setq org-self-insert-command-undo-counter 1)
18275 (if (>= org-self-insert-command-undo-counter 20)
18276 (setq org-self-insert-command-undo-counter 1)
18277 (and (> org-self-insert-command-undo-counter 0)
18278 buffer-undo-list (listp buffer-undo-list)
18279 (not (cadr buffer-undo-list)) ; remove nil entry
18280 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18281 (setq org-self-insert-command-undo-counter
18282 (1+ org-self-insert-command-undo-counter))))))))
18284 (defun org-check-before-invisible-edit (kind)
18285 "Check is editing if kind KIND would be dangerous with invisible text around.
18286 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18287 ;; First, try to get out of here as quickly as possible, to reduce overhead
18288 (if (and org-catch-invisible-edits
18289 (or (not (boundp 'visible-mode)) (not visible-mode))
18290 (or (get-char-property (point) 'invisible)
18291 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18292 ;; OK, we need to take a closer look
18293 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18294 (invisible-before-point (if (bobp) nil (get-char-property
18295 (1- (point)) 'invisible)))
18296 (border-and-ok-direction
18298 ;; Check if we are acting predictably before invisible text
18299 (and invisible-at-point (not invisible-before-point)
18300 (memq kind '(insert delete-backward)))
18301 ;; Check if we are acting predictably after invisible text
18302 ;; This works not well, and I have turned it off. It seems
18303 ;; better to always show and stop after invisible text.
18304 ;; (and (not invisible-at-point) invisible-before-point
18305 ;; (memq kind '(insert delete)))
18307 (when (or (memq invisible-at-point '(outline org-hide-block t))
18308 (memq invisible-before-point '(outline org-hide-block t)))
18309 (if (eq org-catch-invisible-edits 'error)
18310 (error "Editing in invisible areas is prohibited - make visible first"))
18311 (if (and org-custom-properties-overlays
18312 (y-or-n-p "Display invisible properties in this buffer? "))
18313 (org-toggle-custom-properties-visibility)
18314 ;; Make the area visible
18315 (save-excursion
18316 (if invisible-before-point
18317 (goto-char (previous-single-char-property-change
18318 (point) 'invisible)))
18319 (org-cycle))
18320 (cond
18321 ((eq org-catch-invisible-edits 'show)
18322 ;; That's it, we do the edit after showing
18323 (message
18324 "Unfolding invisible region around point before editing")
18325 (sit-for 1))
18326 ((and (eq org-catch-invisible-edits 'smart)
18327 border-and-ok-direction)
18328 (message "Unfolding invisible region around point before editing"))
18330 ;; Don't do the edit, make the user repeat it in full visibility
18331 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18333 (defun org-fix-tags-on-the-fly ()
18334 (when (and (equal (char-after (point-at-bol)) ?*)
18335 (org-at-heading-p))
18336 (org-align-tags-here org-tags-column)))
18338 (defun org-delete-backward-char (N)
18339 "Like `delete-backward-char', insert whitespace at field end in tables.
18340 When deleting backwards, in tables this function will insert whitespace in
18341 front of the next \"|\" separator, to keep the table aligned. The table will
18342 still be marked for re-alignment if the field did fill the entire column,
18343 because, in this case the deletion might narrow the column."
18344 (interactive "p")
18345 (org-check-before-invisible-edit 'delete-backward)
18346 (if (and (org-table-p)
18347 (eq N 1)
18348 (string-match "|" (buffer-substring (point-at-bol) (point)))
18349 (looking-at ".*?|"))
18350 (let ((pos (point))
18351 (noalign (looking-at "[^|\n\r]* |"))
18352 (c org-table-may-need-update))
18353 (backward-delete-char N)
18354 (if (not overwrite-mode)
18355 (progn
18356 (skip-chars-forward "^|")
18357 (insert " ")
18358 (goto-char (1- pos))))
18359 ;; noalign: if there were two spaces at the end, this field
18360 ;; does not determine the width of the column.
18361 (if noalign (setq org-table-may-need-update c)))
18362 (backward-delete-char N)
18363 (org-fix-tags-on-the-fly)))
18365 (defun org-delete-char (N)
18366 "Like `delete-char', but insert whitespace at field end in tables.
18367 When deleting characters, in tables this function will insert whitespace in
18368 front of the next \"|\" separator, to keep the table aligned. The table will
18369 still be marked for re-alignment if the field did fill the entire column,
18370 because, in this case the deletion might narrow the column."
18371 (interactive "p")
18372 (org-check-before-invisible-edit 'delete)
18373 (if (and (org-table-p)
18374 (not (bolp))
18375 (not (= (char-after) ?|))
18376 (eq N 1))
18377 (if (looking-at ".*?|")
18378 (let ((pos (point))
18379 (noalign (looking-at "[^|\n\r]* |"))
18380 (c org-table-may-need-update))
18381 (replace-match (concat
18382 (substring (match-string 0) 1 -1)
18383 " |"))
18384 (goto-char pos)
18385 ;; noalign: if there were two spaces at the end, this field
18386 ;; does not determine the width of the column.
18387 (if noalign (setq org-table-may-need-update c)))
18388 (delete-char N))
18389 (delete-char N)
18390 (org-fix-tags-on-the-fly)))
18392 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18393 (put 'org-self-insert-command 'delete-selection t)
18394 (put 'orgtbl-self-insert-command 'delete-selection t)
18395 (put 'org-delete-char 'delete-selection 'supersede)
18396 (put 'org-delete-backward-char 'delete-selection 'supersede)
18397 (put 'org-yank 'delete-selection 'yank)
18399 ;; Make `flyspell-mode' delay after some commands
18400 (put 'org-self-insert-command 'flyspell-delayed t)
18401 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18402 (put 'org-delete-char 'flyspell-delayed t)
18403 (put 'org-delete-backward-char 'flyspell-delayed t)
18405 ;; Make pabbrev-mode expand after org-mode commands
18406 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18407 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18409 ;; How to do this: Measure non-white length of current string
18410 ;; If equal to column width, we should realign.
18412 (defun org-remap (map &rest commands)
18413 "In MAP, remap the functions given in COMMANDS.
18414 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18415 (let (new old)
18416 (while commands
18417 (setq old (pop commands) new (pop commands))
18418 (if (fboundp 'command-remapping)
18419 (org-defkey map (vector 'remap old) new)
18420 (substitute-key-definition old new map global-map)))))
18422 (when (eq org-enable-table-editor 'optimized)
18423 ;; If the user wants maximum table support, we need to hijack
18424 ;; some standard editing functions
18425 (org-remap org-mode-map
18426 'self-insert-command 'org-self-insert-command
18427 'delete-char 'org-delete-char
18428 'delete-backward-char 'org-delete-backward-char)
18429 (org-defkey org-mode-map "|" 'org-force-self-insert))
18431 (defvar org-ctrl-c-ctrl-c-hook nil
18432 "Hook for functions attaching themselves to `C-c C-c'.
18434 This can be used to add additional functionality to the C-c C-c
18435 key which executes context-dependent commands. This hook is run
18436 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18437 run after the last test.
18439 Each function will be called with no arguments. The function
18440 must check if the context is appropriate for it to act. If yes,
18441 it should do its thing and then return a non-nil value. If the
18442 context is wrong, just do nothing and return nil.")
18444 (defvar org-ctrl-c-ctrl-c-final-hook nil
18445 "Hook for functions attaching themselves to `C-c C-c'.
18447 This can be used to add additional functionality to the C-c C-c
18448 key which executes context-dependent commands. This hook is run
18449 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18450 before the first test.
18452 Each function will be called with no arguments. The function
18453 must check if the context is appropriate for it to act. If yes,
18454 it should do its thing and then return a non-nil value. If the
18455 context is wrong, just do nothing and return nil.")
18457 (defvar org-tab-first-hook nil
18458 "Hook for functions to attach themselves to TAB.
18459 See `org-ctrl-c-ctrl-c-hook' for more information.
18460 This hook runs as the first action when TAB is pressed, even before
18461 `org-cycle' messes around with the `outline-regexp' to cater for
18462 inline tasks and plain list item folding.
18463 If any function in this hook returns t, any other actions that
18464 would have been caused by TAB (such as table field motion or visibility
18465 cycling) will not occur.")
18467 (defvar org-tab-after-check-for-table-hook nil
18468 "Hook for functions to attach themselves to TAB.
18469 See `org-ctrl-c-ctrl-c-hook' for more information.
18470 This hook runs after it has been established that the cursor is not in a
18471 table, but before checking if the cursor is in a headline or if global cycling
18472 should be done.
18473 If any function in this hook returns t, not other actions like visibility
18474 cycling will be done.")
18476 (defvar org-tab-after-check-for-cycling-hook nil
18477 "Hook for functions to attach themselves to TAB.
18478 See `org-ctrl-c-ctrl-c-hook' for more information.
18479 This hook runs after it has been established that not table field motion and
18480 not visibility should be done because of current context. This is probably
18481 the place where a package like yasnippets can hook in.")
18483 (defvar org-tab-before-tab-emulation-hook nil
18484 "Hook for functions to attach themselves to TAB.
18485 See `org-ctrl-c-ctrl-c-hook' for more information.
18486 This hook runs after every other options for TAB have been exhausted, but
18487 before indentation and \t insertion takes place.")
18489 (defvar org-metaleft-hook nil
18490 "Hook for functions attaching themselves to `M-left'.
18491 See `org-ctrl-c-ctrl-c-hook' for more information.")
18492 (defvar org-metaright-hook nil
18493 "Hook for functions attaching themselves to `M-right'.
18494 See `org-ctrl-c-ctrl-c-hook' for more information.")
18495 (defvar org-metaup-hook nil
18496 "Hook for functions attaching themselves to `M-up'.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.")
18498 (defvar org-metadown-hook nil
18499 "Hook for functions attaching themselves to `M-down'.
18500 See `org-ctrl-c-ctrl-c-hook' for more information.")
18501 (defvar org-shiftmetaleft-hook nil
18502 "Hook for functions attaching themselves to `M-S-left'.
18503 See `org-ctrl-c-ctrl-c-hook' for more information.")
18504 (defvar org-shiftmetaright-hook nil
18505 "Hook for functions attaching themselves to `M-S-right'.
18506 See `org-ctrl-c-ctrl-c-hook' for more information.")
18507 (defvar org-shiftmetaup-hook nil
18508 "Hook for functions attaching themselves to `M-S-up'.
18509 See `org-ctrl-c-ctrl-c-hook' for more information.")
18510 (defvar org-shiftmetadown-hook nil
18511 "Hook for functions attaching themselves to `M-S-down'.
18512 See `org-ctrl-c-ctrl-c-hook' for more information.")
18513 (defvar org-metareturn-hook nil
18514 "Hook for functions attaching themselves to `M-RET'.
18515 See `org-ctrl-c-ctrl-c-hook' for more information.")
18516 (defvar org-shiftup-hook nil
18517 "Hook for functions attaching themselves to `S-up'.
18518 See `org-ctrl-c-ctrl-c-hook' for more information.")
18519 (defvar org-shiftup-final-hook nil
18520 "Hook for functions attaching themselves to `S-up'.
18521 This one runs after all other options except shift-select have been excluded.
18522 See `org-ctrl-c-ctrl-c-hook' for more information.")
18523 (defvar org-shiftdown-hook nil
18524 "Hook for functions attaching themselves to `S-down'.
18525 See `org-ctrl-c-ctrl-c-hook' for more information.")
18526 (defvar org-shiftdown-final-hook nil
18527 "Hook for functions attaching themselves to `S-down'.
18528 This one runs after all other options except shift-select have been excluded.
18529 See `org-ctrl-c-ctrl-c-hook' for more information.")
18530 (defvar org-shiftleft-hook nil
18531 "Hook for functions attaching themselves to `S-left'.
18532 See `org-ctrl-c-ctrl-c-hook' for more information.")
18533 (defvar org-shiftleft-final-hook nil
18534 "Hook for functions attaching themselves to `S-left'.
18535 This one runs after all other options except shift-select have been excluded.
18536 See `org-ctrl-c-ctrl-c-hook' for more information.")
18537 (defvar org-shiftright-hook nil
18538 "Hook for functions attaching themselves to `S-right'.
18539 See `org-ctrl-c-ctrl-c-hook' for more information.")
18540 (defvar org-shiftright-final-hook nil
18541 "Hook for functions attaching themselves to `S-right'.
18542 This one runs after all other options except shift-select have been excluded.
18543 See `org-ctrl-c-ctrl-c-hook' for more information.")
18545 (defun org-modifier-cursor-error ()
18546 "Throw an error, a modified cursor command was applied in wrong context."
18547 (error "This command is active in special context like tables, headlines or items"))
18549 (defun org-shiftselect-error ()
18550 "Throw an error because Shift-Cursor command was applied in wrong context."
18551 (if (and (boundp 'shift-select-mode) shift-select-mode)
18552 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18553 (error "This command works only in special context like headlines or timestamps")))
18555 (defun org-call-for-shift-select (cmd)
18556 (let ((this-command-keys-shift-translated t))
18557 (call-interactively cmd)))
18559 (defun org-shifttab (&optional arg)
18560 "Global visibility cycling or move to previous table field.
18561 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18562 on context.
18563 See the individual commands for more information."
18564 (interactive "P")
18565 (cond
18566 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18567 ((integerp arg)
18568 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18569 (message "Content view to level: %d" arg)
18570 (org-content (prefix-numeric-value arg2))
18571 (setq org-cycle-global-status 'overview)))
18572 (t (call-interactively 'org-global-cycle))))
18574 (defun org-shiftmetaleft ()
18575 "Promote subtree or delete table column.
18576 Calls `org-promote-subtree', `org-outdent-item-tree', or
18577 `org-table-delete-column', depending on context. See the
18578 individual commands for more information."
18579 (interactive)
18580 (cond
18581 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18582 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18583 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18584 ((if (not (org-region-active-p)) (org-at-item-p)
18585 (save-excursion (goto-char (region-beginning))
18586 (org-at-item-p)))
18587 (call-interactively 'org-outdent-item-tree))
18588 (t (org-modifier-cursor-error))))
18590 (defun org-shiftmetaright ()
18591 "Demote subtree or insert table column.
18592 Calls `org-demote-subtree', `org-indent-item-tree', or
18593 `org-table-insert-column', depending on context. See the
18594 individual commands for more information."
18595 (interactive)
18596 (cond
18597 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18598 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18599 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18600 ((if (not (org-region-active-p)) (org-at-item-p)
18601 (save-excursion (goto-char (region-beginning))
18602 (org-at-item-p)))
18603 (call-interactively 'org-indent-item-tree))
18604 (t (org-modifier-cursor-error))))
18606 (defun org-shiftmetaup (&optional arg)
18607 "Move subtree up or kill table row.
18608 Calls `org-move-subtree-up' or `org-table-kill-row' or
18609 `org-move-item-up' or `org-timestamp-up', depending on context.
18610 See the individual commands for more information."
18611 (interactive "P")
18612 (cond
18613 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18614 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18615 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18616 ((org-at-item-p) (call-interactively 'org-move-item-up))
18617 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18618 (call-interactively 'org-timestamp-up)))
18619 (t (org-modifier-cursor-error))))
18621 (defun org-shiftmetadown (&optional arg)
18622 "Move subtree down or insert table row.
18623 Calls `org-move-subtree-down' or `org-table-insert-row' or
18624 `org-move-item-down' or `org-timestamp-up', depending on context.
18625 See the individual commands for more information."
18626 (interactive "P")
18627 (cond
18628 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18629 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18630 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18631 ((org-at-item-p) (call-interactively 'org-move-item-down))
18632 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18633 (call-interactively 'org-timestamp-down)))
18634 (t (org-modifier-cursor-error))))
18636 (defsubst org-hidden-tree-error ()
18637 (error
18638 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18640 (defun org-metaleft (&optional arg)
18641 "Promote heading or move table column to left.
18642 Calls `org-do-promote' or `org-table-move-column', depending on context.
18643 With no specific context, calls the Emacs default `backward-word'.
18644 See the individual commands for more information."
18645 (interactive "P")
18646 (cond
18647 ((run-hook-with-args-until-success 'org-metaleft-hook))
18648 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18649 ((org-with-limited-levels
18650 (or (org-at-heading-p)
18651 (and (org-region-active-p)
18652 (save-excursion
18653 (goto-char (region-beginning))
18654 (org-at-heading-p)))))
18655 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18656 (call-interactively 'org-do-promote))
18657 ;; At an inline task.
18658 ((org-at-heading-p)
18659 (call-interactively 'org-inlinetask-promote))
18660 ((or (org-at-item-p)
18661 (and (org-region-active-p)
18662 (save-excursion
18663 (goto-char (region-beginning))
18664 (org-at-item-p))))
18665 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18666 (call-interactively 'org-outdent-item))
18667 (t (call-interactively 'backward-word))))
18669 (defun org-metaright (&optional arg)
18670 "Demote a subtree, a list item or move table column to right.
18671 In front of a drawer or a block keyword, indent it correctly.
18672 With no specific context, calls the Emacs default `forward-word'.
18673 See the individual commands for more information."
18674 (interactive "P")
18675 (cond
18676 ((run-hook-with-args-until-success 'org-metaright-hook))
18677 ((org-at-table-p) (call-interactively 'org-table-move-column))
18678 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18679 ((org-at-block-p) (call-interactively 'org-indent-block))
18680 ((org-with-limited-levels
18681 (or (org-at-heading-p)
18682 (and (org-region-active-p)
18683 (save-excursion
18684 (goto-char (region-beginning))
18685 (org-at-heading-p)))))
18686 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18687 (call-interactively 'org-do-demote))
18688 ;; At an inline task.
18689 ((org-at-heading-p)
18690 (call-interactively 'org-inlinetask-demote))
18691 ((or (org-at-item-p)
18692 (and (org-region-active-p)
18693 (save-excursion
18694 (goto-char (region-beginning))
18695 (org-at-item-p))))
18696 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18697 (call-interactively 'org-indent-item))
18698 (t (call-interactively 'forward-word))))
18700 (defun org-check-for-hidden (what)
18701 "Check if there are hidden headlines/items in the current visual line.
18702 WHAT can be either `headlines' or `items'. If the current line is
18703 an outline or item heading and it has a folded subtree below it,
18704 this function returns t, nil otherwise."
18705 (let ((re (cond
18706 ((eq what 'headlines) org-outline-regexp-bol)
18707 ((eq what 'items) (org-item-beginning-re))
18708 (t (error "This should not happen"))))
18709 beg end)
18710 (save-excursion
18711 (catch 'exit
18712 (unless (org-region-active-p)
18713 (setq beg (point-at-bol))
18714 (beginning-of-line 2)
18715 (while (and (not (eobp)) ;; this is like `next-line'
18716 (get-char-property (1- (point)) 'invisible))
18717 (beginning-of-line 2))
18718 (setq end (point))
18719 (goto-char beg)
18720 (goto-char (point-at-eol))
18721 (setq end (max end (point)))
18722 (while (re-search-forward re end t)
18723 (if (get-char-property (match-beginning 0) 'invisible)
18724 (throw 'exit t))))
18725 nil))))
18727 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18728 (declare-function org-element-type "org-element" (element))
18729 (declare-function org-element-contents "org-element" (element))
18730 (declare-function org-element-property "org-element" (property element))
18731 (declare-function org-element-paragraph-parser "org-element" (limit))
18732 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18733 (declare-function org-element-up "org-element" ())
18734 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18735 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18736 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18737 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18739 (defun org-metaup (&optional arg)
18740 "Move subtree up or move table row up.
18741 Calls `org-move-subtree-up' or `org-table-move-row' or
18742 `org-move-item-up', depending on context. See the individual commands
18743 for more information."
18744 (interactive "P")
18745 (cond
18746 ((run-hook-with-args-until-success 'org-metaup-hook))
18747 ((org-region-active-p)
18748 (let* ((a (min (region-beginning) (region-end)))
18749 (b (1- (max (region-beginning) (region-end))))
18750 (c (save-excursion (goto-char a)
18751 (move-beginning-of-line 0)))
18752 (d (save-excursion (goto-char a)
18753 (move-end-of-line 0) (point))))
18754 (transpose-regions a b c d)
18755 (goto-char c)))
18756 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18757 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18758 ((org-at-item-p) (call-interactively 'org-move-item-up))
18759 (t (org-drag-element-backward))))
18761 (defun org-metadown (&optional arg)
18762 "Move subtree down or move table row down.
18763 Calls `org-move-subtree-down' or `org-table-move-row' or
18764 `org-move-item-down', depending on context. See the individual
18765 commands for more information."
18766 (interactive "P")
18767 (cond
18768 ((run-hook-with-args-until-success 'org-metadown-hook))
18769 ((org-region-active-p)
18770 (let* ((a (min (region-beginning) (region-end)))
18771 (b (max (region-beginning) (region-end)))
18772 (c (save-excursion (goto-char b)
18773 (move-beginning-of-line 1)))
18774 (d (save-excursion (goto-char b)
18775 (move-end-of-line 1) (1+ (point)))))
18776 (transpose-regions a b c d)
18777 (goto-char d)))
18778 ((org-at-table-p) (call-interactively 'org-table-move-row))
18779 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18780 ((org-at-item-p) (call-interactively 'org-move-item-down))
18781 (t (org-drag-element-forward))))
18783 (defun org-shiftup (&optional arg)
18784 "Increase item in timestamp or increase priority of current headline.
18785 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18786 depending on context. See the individual commands for more information."
18787 (interactive "P")
18788 (cond
18789 ((run-hook-with-args-until-success 'org-shiftup-hook))
18790 ((and org-support-shift-select (org-region-active-p))
18791 (org-call-for-shift-select 'previous-line))
18792 ((org-at-timestamp-p t)
18793 (call-interactively (if org-edit-timestamp-down-means-later
18794 'org-timestamp-down 'org-timestamp-up)))
18795 ((and (not (eq org-support-shift-select 'always))
18796 org-enable-priority-commands
18797 (org-at-heading-p))
18798 (call-interactively 'org-priority-up))
18799 ((and (not org-support-shift-select) (org-at-item-p))
18800 (call-interactively 'org-previous-item))
18801 ((org-clocktable-try-shift 'up arg))
18802 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18803 (org-support-shift-select
18804 (org-call-for-shift-select 'previous-line))
18805 (t (org-shiftselect-error))))
18807 (defun org-shiftdown (&optional arg)
18808 "Decrease item in timestamp or decrease priority of current headline.
18809 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18810 depending on context. See the individual commands for more information."
18811 (interactive "P")
18812 (cond
18813 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18814 ((and org-support-shift-select (org-region-active-p))
18815 (org-call-for-shift-select 'next-line))
18816 ((org-at-timestamp-p t)
18817 (call-interactively (if org-edit-timestamp-down-means-later
18818 'org-timestamp-up 'org-timestamp-down)))
18819 ((and (not (eq org-support-shift-select 'always))
18820 org-enable-priority-commands
18821 (org-at-heading-p))
18822 (call-interactively 'org-priority-down))
18823 ((and (not org-support-shift-select) (org-at-item-p))
18824 (call-interactively 'org-next-item))
18825 ((org-clocktable-try-shift 'down arg))
18826 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18827 (org-support-shift-select
18828 (org-call-for-shift-select 'next-line))
18829 (t (org-shiftselect-error))))
18831 (defun org-shiftright (&optional arg)
18832 "Cycle the thing at point or in the current line, depending on context.
18833 Depending on context, this does one of the following:
18835 - switch a timestamp at point one day into the future
18836 - on a headline, switch to the next TODO keyword.
18837 - on an item, switch entire list to the next bullet type
18838 - on a property line, switch to the next allowed value
18839 - on a clocktable definition line, move time block into the future"
18840 (interactive "P")
18841 (cond
18842 ((run-hook-with-args-until-success 'org-shiftright-hook))
18843 ((and org-support-shift-select (org-region-active-p))
18844 (org-call-for-shift-select 'forward-char))
18845 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18846 ((and (not (eq org-support-shift-select 'always))
18847 (org-at-heading-p))
18848 (let ((org-inhibit-logging
18849 (not org-treat-S-cursor-todo-selection-as-state-change))
18850 (org-inhibit-blocking
18851 (not org-treat-S-cursor-todo-selection-as-state-change)))
18852 (org-call-with-arg 'org-todo 'right)))
18853 ((or (and org-support-shift-select
18854 (not (eq org-support-shift-select 'always))
18855 (org-at-item-bullet-p))
18856 (and (not org-support-shift-select) (org-at-item-p)))
18857 (org-call-with-arg 'org-cycle-list-bullet nil))
18858 ((and (not (eq org-support-shift-select 'always))
18859 (org-at-property-p))
18860 (call-interactively 'org-property-next-allowed-value))
18861 ((org-clocktable-try-shift 'right arg))
18862 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18863 (org-support-shift-select
18864 (org-call-for-shift-select 'forward-char))
18865 (t (org-shiftselect-error))))
18867 (defun org-shiftleft (&optional arg)
18868 "Cycle the thing at point or in the current line, depending on context.
18869 Depending on context, this does one of the following:
18871 - switch a timestamp at point one day into the past
18872 - on a headline, switch to the previous TODO keyword.
18873 - on an item, switch entire list to the previous bullet type
18874 - on a property line, switch to the previous allowed value
18875 - on a clocktable definition line, move time block into the past"
18876 (interactive "P")
18877 (cond
18878 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18879 ((and org-support-shift-select (org-region-active-p))
18880 (org-call-for-shift-select 'backward-char))
18881 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18882 ((and (not (eq org-support-shift-select 'always))
18883 (org-at-heading-p))
18884 (let ((org-inhibit-logging
18885 (not org-treat-S-cursor-todo-selection-as-state-change))
18886 (org-inhibit-blocking
18887 (not org-treat-S-cursor-todo-selection-as-state-change)))
18888 (org-call-with-arg 'org-todo 'left)))
18889 ((or (and org-support-shift-select
18890 (not (eq org-support-shift-select 'always))
18891 (org-at-item-bullet-p))
18892 (and (not org-support-shift-select) (org-at-item-p)))
18893 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18894 ((and (not (eq org-support-shift-select 'always))
18895 (org-at-property-p))
18896 (call-interactively 'org-property-previous-allowed-value))
18897 ((org-clocktable-try-shift 'left arg))
18898 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18899 (org-support-shift-select
18900 (org-call-for-shift-select 'backward-char))
18901 (t (org-shiftselect-error))))
18903 (defun org-shiftcontrolright ()
18904 "Switch to next TODO set."
18905 (interactive)
18906 (cond
18907 ((and org-support-shift-select (org-region-active-p))
18908 (org-call-for-shift-select 'forward-word))
18909 ((and (not (eq org-support-shift-select 'always))
18910 (org-at-heading-p))
18911 (org-call-with-arg 'org-todo 'nextset))
18912 (org-support-shift-select
18913 (org-call-for-shift-select 'forward-word))
18914 (t (org-shiftselect-error))))
18916 (defun org-shiftcontrolleft ()
18917 "Switch to previous TODO set."
18918 (interactive)
18919 (cond
18920 ((and org-support-shift-select (org-region-active-p))
18921 (org-call-for-shift-select 'backward-word))
18922 ((and (not (eq org-support-shift-select 'always))
18923 (org-at-heading-p))
18924 (org-call-with-arg 'org-todo 'previousset))
18925 (org-support-shift-select
18926 (org-call-for-shift-select 'backward-word))
18927 (t (org-shiftselect-error))))
18929 (defun org-shiftcontrolup ()
18930 "Change timestamps synchronously up in CLOCK log lines."
18931 (interactive)
18932 (cond ((and (not org-support-shift-select)
18933 (org-at-clock-log-p)
18934 (org-at-timestamp-p t))
18935 (org-clock-timestamps-up))
18936 (t (org-shiftselect-error))))
18938 (defun org-shiftcontroldown ()
18939 "Change timestamps synchronously down in CLOCK log lines."
18940 (interactive)
18941 (cond ((and (not org-support-shift-select)
18942 (org-at-clock-log-p)
18943 (org-at-timestamp-p t))
18944 (org-clock-timestamps-down))
18945 (t (org-shiftselect-error))))
18947 (defun org-ctrl-c-ret ()
18948 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18949 (interactive)
18950 (cond
18951 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18952 (t (call-interactively 'org-insert-heading))))
18954 (defun org-find-visible ()
18955 (let ((s (point)))
18956 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18957 (get-char-property s 'invisible)))
18959 (defun org-find-invisible ()
18960 (let ((s (point)))
18961 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18962 (not (get-char-property s 'invisible))))
18965 (defun org-copy-visible (beg end)
18966 "Copy the visible parts of the region."
18967 (interactive "r")
18968 (let (snippets s)
18969 (save-excursion
18970 (save-restriction
18971 (narrow-to-region beg end)
18972 (setq s (goto-char (point-min)))
18973 (while (not (= (point) (point-max)))
18974 (goto-char (org-find-invisible))
18975 (push (buffer-substring s (point)) snippets)
18976 (setq s (goto-char (org-find-visible))))))
18977 (kill-new (apply 'concat (nreverse snippets)))))
18979 (defun org-copy-special ()
18980 "Copy region in table or copy current subtree.
18981 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18982 See the individual commands for more information."
18983 (interactive)
18984 (call-interactively
18985 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18987 (defun org-cut-special ()
18988 "Cut region in table or cut current subtree.
18989 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18990 See the individual commands for more information."
18991 (interactive)
18992 (call-interactively
18993 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18995 (defun org-paste-special (arg)
18996 "Paste rectangular region into table, or past subtree relative to level.
18997 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18998 See the individual commands for more information."
18999 (interactive "P")
19000 (if (org-at-table-p)
19001 (org-table-paste-rectangle)
19002 (org-paste-subtree arg)))
19004 (defun org-edit-special (&optional arg)
19005 "Call a special editor for the stuff at point.
19006 When at a table, call the formula editor with `org-table-edit-formulas'.
19007 When at the first line of an src example, call `org-edit-src-code'.
19008 When in an #+include line, visit the include file. Otherwise call
19009 `ffap' to visit the file at point."
19010 (interactive)
19011 ;; possibly prep session before editing source
19012 (when arg
19013 (let* ((info (org-babel-get-src-block-info))
19014 (lang (nth 0 info))
19015 (params (nth 2 info))
19016 (session (cdr (assoc :session params))))
19017 (when (and info session) ;; we are in a source-code block with a session
19018 (funcall
19019 (intern (concat "org-babel-prep-session:" lang)) session params))))
19020 (cond ;; proceed with `org-edit-special'
19021 ((save-excursion
19022 (beginning-of-line 1)
19023 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19024 (find-file (org-trim (match-string 1))))
19025 ((org-edit-src-code))
19026 ((org-edit-fixed-width-region))
19027 ((org-at-table.el-p)
19028 (org-edit-src-code))
19029 ((or (org-at-table-p)
19030 (save-excursion
19031 (beginning-of-line 1)
19032 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19033 (call-interactively 'org-table-edit-formulas))
19034 (t (call-interactively 'ffap))))
19036 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19037 (defun org-ctrl-c-ctrl-c (&optional arg)
19038 "Set tags in headline, or update according to changed information at point.
19040 This command does many different things, depending on context:
19042 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19043 this is what we do.
19045 - If the cursor is on a statistics cookie, update it.
19047 - If the cursor is in a headline, prompt for tags and insert them
19048 into the current line, aligned to `org-tags-column'. When called
19049 with prefix arg, realign all tags in the current buffer.
19051 - If the cursor is in one of the special #+KEYWORD lines, this
19052 triggers scanning the buffer for these lines and updating the
19053 information.
19055 - If the cursor is inside a table, realign the table. This command
19056 works even if the automatic table editor has been turned off.
19058 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19059 the entire table.
19061 - If the cursor is at a footnote reference or definition, jump to
19062 the corresponding definition or references, respectively.
19064 - If the cursor is a the beginning of a dynamic block, update it.
19066 - If the current buffer is a capture buffer, close note and file it.
19068 - If the cursor is on a <<<target>>>, update radio targets and
19069 corresponding links in this buffer.
19071 - If the cursor is on a numbered item in a plain list, renumber the
19072 ordered list.
19074 - If the cursor is on a checkbox, toggle it.
19076 - If the cursor is on a code block, evaluate it. The variable
19077 `org-confirm-babel-evaluate' can be used to control prompting
19078 before code block evaluation, by default every code block
19079 evaluation requires confirmation. Code block evaluation can be
19080 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19081 (interactive "P")
19082 (let ((org-enable-table-editor t))
19083 (cond
19084 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19085 org-occur-highlights
19086 org-latex-fragment-image-overlays)
19087 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19088 (org-remove-occur-highlights)
19089 (org-remove-latex-fragment-image-overlays)
19090 (message "Temporary highlights/overlays removed from current buffer"))
19091 ((and (local-variable-p 'org-finish-function (current-buffer))
19092 (fboundp org-finish-function))
19093 (funcall org-finish-function))
19094 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19095 ((org-in-regexp org-ts-regexp-both)
19096 (org-timestamp-change 0 'day))
19097 ((or (looking-at org-property-start-re)
19098 (org-at-property-p))
19099 (call-interactively 'org-property-action))
19100 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19101 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19102 (or (org-at-heading-p) (org-at-item-p)))
19103 (call-interactively 'org-update-statistics-cookies))
19104 ((org-at-heading-p) (call-interactively 'org-set-tags))
19105 ((org-at-table.el-p)
19106 (message "Use C-c ' to edit table.el tables"))
19107 ((org-at-table-p)
19108 (org-table-maybe-eval-formula)
19109 (if arg
19110 (call-interactively 'org-table-recalculate)
19111 (org-table-maybe-recalculate-line))
19112 (call-interactively 'org-table-align)
19113 (orgtbl-send-table 'maybe))
19114 ((or (org-footnote-at-reference-p)
19115 (org-footnote-at-definition-p))
19116 (call-interactively 'org-footnote-action))
19117 ((org-at-item-checkbox-p)
19118 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19119 ;; list only if at top item.
19120 (let* ((cbox (match-string 1))
19121 (struct (org-list-struct))
19122 (old-struct (copy-tree struct))
19123 (parents (org-list-parents-alist struct))
19124 (orderedp (org-entry-get nil "ORDERED"))
19125 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19126 block-item)
19127 ;; Use a light version of `org-toggle-checkbox' to avoid
19128 ;; computing list structure twice.
19129 (let ((new-box (cond
19130 ((equal arg '(16)) "[-]")
19131 ((equal arg '(4)) nil)
19132 ((equal "[X]" cbox) "[ ]")
19133 (t "[X]"))))
19134 (if (and firstp arg)
19135 ;; If at first item of sub-list, remove check-box from
19136 ;; every item at the same level.
19137 (mapc
19138 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19139 (org-list-get-all-items
19140 (point-at-bol) struct (org-list-prevs-alist struct)))
19141 (org-list-set-checkbox (point-at-bol) struct new-box)))
19142 ;; Replicate `org-list-write-struct', while grabbing a return
19143 ;; value from `org-list-struct-fix-box'.
19144 (org-list-struct-fix-ind struct parents 2)
19145 (org-list-struct-fix-item-end struct)
19146 (let ((prevs (org-list-prevs-alist struct)))
19147 (org-list-struct-fix-bul struct prevs)
19148 (org-list-struct-fix-ind struct parents)
19149 (setq block-item
19150 (org-list-struct-fix-box struct parents prevs orderedp)))
19151 (org-list-struct-apply-struct struct old-struct)
19152 (org-update-checkbox-count-maybe)
19153 (when block-item
19154 (message
19155 "Checkboxes were removed due to unchecked box at line %d"
19156 (org-current-line block-item)))
19157 (when firstp (org-list-send-list 'maybe))))
19158 ((org-at-item-p)
19159 ;; Cursor at an item: repair list. Do checkbox related actions
19160 ;; only if function was called with an argument. Send list only
19161 ;; if at top item.
19162 (let* ((struct (org-list-struct))
19163 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19164 old-struct)
19165 (when arg
19166 (setq old-struct (copy-tree struct))
19167 (if firstp
19168 ;; If at first item of sub-list, add check-box to every
19169 ;; item at the same level.
19170 (mapc
19171 (lambda (pos)
19172 (unless (org-list-get-checkbox pos struct)
19173 (org-list-set-checkbox pos struct "[ ]")))
19174 (org-list-get-all-items
19175 (point-at-bol) struct (org-list-prevs-alist struct)))
19176 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19177 (org-list-write-struct
19178 struct (org-list-parents-alist struct) old-struct)
19179 (when arg (org-update-checkbox-count-maybe))
19180 (when firstp (org-list-send-list 'maybe))))
19181 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19182 ;; Dynamic block
19183 (beginning-of-line 1)
19184 (save-excursion (org-update-dblock)))
19185 ((save-excursion
19186 (let ((case-fold-search t))
19187 (beginning-of-line 1)
19188 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19189 (cond
19190 ((or (equal (match-string 1) "TBLFM")
19191 (equal (match-string 1) "tblfm"))
19192 ;; Recalculate the table before this line
19193 (save-excursion
19194 (beginning-of-line 1)
19195 (skip-chars-backward " \r\n\t")
19196 (if (org-at-table-p)
19197 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19199 (let ((org-inhibit-startup-visibility-stuff t)
19200 (org-startup-align-all-tables nil))
19201 (when (boundp 'org-table-coordinate-overlays)
19202 (mapc 'delete-overlay org-table-coordinate-overlays)
19203 (setq org-table-coordinate-overlays nil))
19204 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19205 (message "Local setup has been refreshed"))))
19206 ((org-clock-update-time-maybe))
19208 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19209 (error "C-c C-c can do nothing useful at this location"))))))
19211 (defun org-mode-restart ()
19212 "Restart Org-mode, to scan again for special lines.
19213 Also updates the keyword regular expressions."
19214 (interactive)
19215 (org-mode)
19216 (message "Org-mode restarted"))
19218 (defun org-kill-note-or-show-branches ()
19219 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19220 (interactive)
19221 (if (not org-finish-function)
19222 (progn
19223 (hide-subtree)
19224 (call-interactively 'show-branches))
19225 (let ((org-note-abort t))
19226 (funcall org-finish-function))))
19228 (defun org-return (&optional indent)
19229 "Goto next table row or insert a newline.
19230 Calls `org-table-next-row' or `newline', depending on context.
19231 See the individual commands for more information."
19232 (interactive)
19233 (let (org-ts-what)
19234 (cond
19235 ((or (bobp) (org-in-src-block-p))
19236 (if indent (newline-and-indent) (newline)))
19237 ((org-at-table-p)
19238 (org-table-justify-field-maybe)
19239 (call-interactively 'org-table-next-row))
19240 ;; when `newline-and-indent' is called within a list, make sure
19241 ;; text moved stays inside the item.
19242 ((and (org-in-item-p) indent)
19243 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19244 (progn
19245 (save-match-data (newline))
19246 (org-indent-line-to (length (match-string 0))))
19247 (let ((ind (org-get-indentation)))
19248 (newline)
19249 (if (org-looking-back org-list-end-re)
19250 (org-indent-line)
19251 (org-indent-line-to ind)))))
19252 ((and org-return-follows-link
19253 (org-at-timestamp-p t)
19254 (not (eq org-ts-what 'after)))
19255 (org-follow-timestamp-link))
19256 ((and org-return-follows-link
19257 (let ((tprop (get-text-property (point) 'face)))
19258 (or (eq tprop 'org-link)
19259 (and (listp tprop) (memq 'org-link tprop)))))
19260 (call-interactively 'org-open-at-point))
19261 ((and (org-at-heading-p)
19262 (looking-at
19263 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19264 (org-show-entry)
19265 (end-of-line 1)
19266 (newline))
19267 (t (if indent (newline-and-indent) (newline))))))
19269 (defun org-return-indent ()
19270 "Goto next table row or insert a newline and indent.
19271 Calls `org-table-next-row' or `newline-and-indent', depending on
19272 context. See the individual commands for more information."
19273 (interactive)
19274 (org-return t))
19276 (defun org-ctrl-c-star ()
19277 "Compute table, or change heading status of lines.
19278 Calls `org-table-recalculate' or `org-toggle-heading',
19279 depending on context."
19280 (interactive)
19281 (cond
19282 ((org-at-table-p)
19283 (call-interactively 'org-table-recalculate))
19285 ;; Convert all lines in region to list items
19286 (call-interactively 'org-toggle-heading))))
19288 (defun org-ctrl-c-minus ()
19289 "Insert separator line in table or modify bullet status of line.
19290 Also turns a plain line or a region of lines into list items.
19291 Calls `org-table-insert-hline', `org-toggle-item', or
19292 `org-cycle-list-bullet', depending on context."
19293 (interactive)
19294 (cond
19295 ((org-at-table-p)
19296 (call-interactively 'org-table-insert-hline))
19297 ((org-region-active-p)
19298 (call-interactively 'org-toggle-item))
19299 ((org-in-item-p)
19300 (call-interactively 'org-cycle-list-bullet))
19302 (call-interactively 'org-toggle-item))))
19304 (defun org-toggle-item (arg)
19305 "Convert headings or normal lines to items, items to normal lines.
19306 If there is no active region, only the current line is considered.
19308 If the first non blank line in the region is an headline, convert
19309 all headlines to items, shifting text accordingly.
19311 If it is an item, convert all items to normal lines.
19313 If it is normal text, change region into an item. With a prefix
19314 argument ARG, change each line in region into an item."
19315 (interactive "P")
19316 (let ((shift-text
19317 (function
19318 ;; Shift text in current section to IND, from point to END.
19319 ;; The function leaves point to END line.
19320 (lambda (ind end)
19321 (let ((min-i 1000) (end (copy-marker end)))
19322 ;; First determine the minimum indentation (MIN-I) of
19323 ;; the text.
19324 (save-excursion
19325 (catch 'exit
19326 (while (< (point) end)
19327 (let ((i (org-get-indentation)))
19328 (cond
19329 ;; Skip blank lines and inline tasks.
19330 ((looking-at "^[ \t]*$"))
19331 ((looking-at org-outline-regexp-bol))
19332 ;; We can't find less than 0 indentation.
19333 ((zerop i) (throw 'exit (setq min-i 0)))
19334 ((< i min-i) (setq min-i i))))
19335 (forward-line))))
19336 ;; Then indent each line so that a line indented to
19337 ;; MIN-I becomes indented to IND. Ignore blank lines
19338 ;; and inline tasks in the process.
19339 (let ((delta (- ind min-i)))
19340 (while (< (point) end)
19341 (unless (or (looking-at "^[ \t]*$")
19342 (looking-at org-outline-regexp-bol))
19343 (org-indent-line-to (+ (org-get-indentation) delta)))
19344 (forward-line)))))))
19345 (skip-blanks
19346 (function
19347 ;; Return beginning of first non-blank line, starting from
19348 ;; line at POS.
19349 (lambda (pos)
19350 (save-excursion
19351 (goto-char pos)
19352 (skip-chars-forward " \r\t\n")
19353 (point-at-bol)))))
19354 beg end)
19355 ;; Determine boundaries of changes.
19356 (if (org-region-active-p)
19357 (setq beg (funcall skip-blanks (region-beginning))
19358 end (copy-marker (region-end)))
19359 (setq beg (funcall skip-blanks (point-at-bol))
19360 end (copy-marker (point-at-eol))))
19361 ;; Depending on the starting line, choose an action on the text
19362 ;; between BEG and END.
19363 (org-with-limited-levels
19364 (save-excursion
19365 (goto-char beg)
19366 (cond
19367 ;; Case 1. Start at an item: de-itemize. Note that it only
19368 ;; happens when a region is active: `org-ctrl-c-minus'
19369 ;; would call `org-cycle-list-bullet' otherwise.
19370 ((org-at-item-p)
19371 (while (< (point) end)
19372 (when (org-at-item-p)
19373 (skip-chars-forward " \t")
19374 (delete-region (point) (match-end 0)))
19375 (forward-line)))
19376 ;; Case 2. Start at an heading: convert to items.
19377 ((org-at-heading-p)
19378 (let* ((bul (org-list-bullet-string "-"))
19379 (bul-len (length bul))
19380 ;; Indentation of the first heading. It should be
19381 ;; relative to the indentation of its parent, if any.
19382 (start-ind (save-excursion
19383 (cond
19384 ((not org-adapt-indentation) 0)
19385 ((not (outline-previous-heading)) 0)
19386 (t (length (match-string 0))))))
19387 ;; Level of first heading. Further headings will be
19388 ;; compared to it to determine hierarchy in the list.
19389 (ref-level (org-reduced-level (org-outline-level))))
19390 (while (< (point) end)
19391 (let* ((level (org-reduced-level (org-outline-level)))
19392 (delta (max 0 (- level ref-level))))
19393 ;; If current headline is less indented than the first
19394 ;; one, set it as reference, in order to preserve
19395 ;; subtrees.
19396 (when (< level ref-level) (setq ref-level level))
19397 (replace-match bul t t)
19398 (org-indent-line-to (+ start-ind (* delta bul-len)))
19399 ;; Ensure all text down to END (or SECTION-END) belongs
19400 ;; to the newly created item.
19401 (let ((section-end (save-excursion
19402 (or (outline-next-heading) (point)))))
19403 (forward-line)
19404 (funcall shift-text
19405 (+ start-ind (* (1+ delta) bul-len))
19406 (min end section-end)))))))
19407 ;; Case 3. Normal line with ARG: turn each non-item line into
19408 ;; an item.
19409 (arg
19410 (while (< (point) end)
19411 (unless (or (org-at-heading-p) (org-at-item-p))
19412 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19413 (replace-match
19414 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19415 (forward-line)))
19416 ;; Case 4. Normal line without ARG: make the first line of
19417 ;; region an item, and shift indentation of others
19418 ;; lines to set them as item's body.
19419 (t (let* ((bul (org-list-bullet-string "-"))
19420 (bul-len (length bul))
19421 (ref-ind (org-get-indentation)))
19422 (skip-chars-forward " \t")
19423 (insert bul)
19424 (forward-line)
19425 (while (< (point) end)
19426 ;; Ensure that lines less indented than first one
19427 ;; still get included in item body.
19428 (funcall shift-text
19429 (+ ref-ind bul-len)
19430 (min end (save-excursion (or (outline-next-heading)
19431 (point)))))
19432 (forward-line)))))))))
19434 (defun org-toggle-heading (&optional nstars)
19435 "Convert headings to normal text, or items or text to headings.
19436 If there is no active region, only the current line is considered.
19438 With a \\[universal-argument] prefix, convert the whole list at
19439 point into heading.
19441 In a region:
19443 - If the first non blank line is an headline, remove the stars
19444 from all headlines in the region.
19446 - If it is a normal line turn each and every normal line (i.e. not an
19447 heading or an item) in the region into a heading.
19449 - If it is a plain list item, turn all plain list items into headings.
19451 When converting a line into a heading, the number of stars is chosen
19452 such that the lines become children of the current entry. However,
19453 when a prefix argument is given, its value determines the number of
19454 stars to add."
19455 (interactive "P")
19456 (let ((skip-blanks
19457 (function
19458 ;; Return beginning of first non-blank line, starting from
19459 ;; line at POS.
19460 (lambda (pos)
19461 (save-excursion
19462 (goto-char pos)
19463 (while (org-at-comment-p) (forward-line))
19464 (skip-chars-forward " \r\t\n")
19465 (point-at-bol)))))
19466 beg end toggled)
19467 ;; Determine boundaries of changes. If a universal prefix has
19468 ;; been given, put the list in a region. If region ends at a bol,
19469 ;; do not consider the last line to be in the region.
19471 (when (and current-prefix-arg (org-at-item-p))
19472 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19473 (org-mark-element))
19475 (if (org-region-active-p)
19476 (setq beg (funcall skip-blanks (region-beginning))
19477 end (copy-marker (save-excursion
19478 (goto-char (region-end))
19479 (if (bolp) (point) (point-at-eol)))))
19480 (setq beg (funcall skip-blanks (point-at-bol))
19481 end (copy-marker (point-at-eol))))
19482 ;; Ensure inline tasks don't count as headings.
19483 (org-with-limited-levels
19484 (save-excursion
19485 (goto-char beg)
19486 (cond
19487 ;; Case 1. Started at an heading: de-star headings.
19488 ((org-at-heading-p)
19489 (while (< (point) end)
19490 (when (org-at-heading-p t)
19491 (looking-at org-outline-regexp) (replace-match "")
19492 (setq toggled t))
19493 (forward-line)))
19494 ;; Case 2. Started at an item: change items into headlines.
19495 ;; One star will be added by `org-list-to-subtree'.
19496 ((org-at-item-p)
19497 (let* ((stars (make-string
19498 (if nstars
19499 ;; subtract the star that will be added again by
19500 ;; `org-list-to-subtree'
19501 (1- (prefix-numeric-value current-prefix-arg))
19502 (or (org-current-level) 0))
19503 ?*))
19504 (add-stars
19505 (cond (nstars "") ; stars from prefix only
19506 ((equal stars "") "") ; before first heading
19507 (org-odd-levels-only "*") ; inside heading, odd
19508 (t "")))) ; inside heading, oddeven
19509 (while (< (point) end)
19510 (when (org-at-item-p)
19511 ;; Pay attention to cases when region ends before list.
19512 (let* ((struct (org-list-struct))
19513 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19514 (save-restriction
19515 (narrow-to-region (point) list-end)
19516 (insert
19517 (org-list-to-subtree
19518 (org-list-parse-list t)
19519 '(:istart (concat stars add-stars (funcall get-stars depth))
19520 :icount (concat stars add-stars (funcall get-stars depth)))))))
19521 (setq toggled t))
19522 (forward-line))))
19523 ;; Case 3. Started at normal text: make every line an heading,
19524 ;; skipping headlines and items.
19525 (t (let* ((stars (make-string
19526 (if nstars
19527 (prefix-numeric-value current-prefix-arg)
19528 (or (org-current-level) 0))
19529 ?*))
19530 (add-stars
19531 (cond (nstars "") ; stars from prefix only
19532 ((equal stars "") "*") ; before first heading
19533 (org-odd-levels-only "**") ; inside heading, odd
19534 (t "*"))) ; inside heading, oddeven
19535 (rpl (concat stars add-stars " ")))
19536 (while (< (point) end)
19537 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19538 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19539 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19540 (forward-line)))))))
19541 (unless toggled (message "Cannot toggle heading from here"))))
19543 (defun org-meta-return (&optional arg)
19544 "Insert a new heading or wrap a region in a table.
19545 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19546 See the individual commands for more information."
19547 (interactive "P")
19548 (cond
19549 ((run-hook-with-args-until-success 'org-metareturn-hook))
19550 ((or (org-at-drawer-p) (org-at-property-p))
19551 (newline-and-indent))
19552 ((org-at-table-p)
19553 (call-interactively 'org-table-wrap-region))
19554 (t (call-interactively 'org-insert-heading))))
19556 ;;; Menu entries
19558 ;; Define the Org-mode menus
19559 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19560 '("Tbl"
19561 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19562 ["Next Field" org-cycle (org-at-table-p)]
19563 ["Previous Field" org-shifttab (org-at-table-p)]
19564 ["Next Row" org-return (org-at-table-p)]
19565 "--"
19566 ["Blank Field" org-table-blank-field (org-at-table-p)]
19567 ["Edit Field" org-table-edit-field (org-at-table-p)]
19568 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19569 "--"
19570 ("Column"
19571 ["Move Column Left" org-metaleft (org-at-table-p)]
19572 ["Move Column Right" org-metaright (org-at-table-p)]
19573 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19574 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19575 ("Row"
19576 ["Move Row Up" org-metaup (org-at-table-p)]
19577 ["Move Row Down" org-metadown (org-at-table-p)]
19578 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19579 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19580 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19581 "--"
19582 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19583 ("Rectangle"
19584 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19585 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19586 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19587 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19588 "--"
19589 ("Calculate"
19590 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19591 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19592 ["Edit Formulas" org-edit-special (org-at-table-p)]
19593 "--"
19594 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19595 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19596 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19597 "--"
19598 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19599 "--"
19600 ["Sum Column/Rectangle" org-table-sum
19601 (or (org-at-table-p) (org-region-active-p))]
19602 ["Which Column?" org-table-current-column (org-at-table-p)])
19603 ["Debug Formulas"
19604 org-table-toggle-formula-debugger
19605 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19606 ["Show Col/Row Numbers"
19607 org-table-toggle-coordinate-overlays
19608 :style toggle
19609 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19610 "--"
19611 ["Create" org-table-create (and (not (org-at-table-p))
19612 org-enable-table-editor)]
19613 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19614 ["Import from File" org-table-import (not (org-at-table-p))]
19615 ["Export to File" org-table-export (org-at-table-p)]
19616 "--"
19617 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19619 (easy-menu-define org-org-menu org-mode-map "Org menu"
19620 '("Org"
19621 ("Show/Hide"
19622 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19623 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19624 ["Sparse Tree..." org-sparse-tree t]
19625 ["Reveal Context" org-reveal t]
19626 ["Show All" show-all t]
19627 "--"
19628 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19629 "--"
19630 ["New Heading" org-insert-heading t]
19631 ("Navigate Headings"
19632 ["Up" outline-up-heading t]
19633 ["Next" outline-next-visible-heading t]
19634 ["Previous" outline-previous-visible-heading t]
19635 ["Next Same Level" outline-forward-same-level t]
19636 ["Previous Same Level" outline-backward-same-level t]
19637 "--"
19638 ["Jump" org-goto t])
19639 ("Edit Structure"
19640 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19641 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19642 "--"
19643 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19644 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19645 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19646 "--"
19647 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19648 "--"
19649 ["Copy visible text" org-copy-visible t]
19650 "--"
19651 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19652 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19653 ["Demote Heading" org-metaright (not (org-at-table-p))]
19654 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19655 "--"
19656 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19657 "--"
19658 ["Convert to odd levels" org-convert-to-odd-levels t]
19659 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19660 ("Editing"
19661 ["Emphasis..." org-emphasize t]
19662 ["Edit Source Example" org-edit-special t]
19663 "--"
19664 ["Footnote new/jump" org-footnote-action t]
19665 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19666 ("Archive"
19667 ["Archive (default method)" org-archive-subtree-default t]
19668 "--"
19669 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19670 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19671 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19673 "--"
19674 ("Hyperlinks"
19675 ["Store Link (Global)" org-store-link t]
19676 ["Find existing link to here" org-occur-link-in-agenda-files t]
19677 ["Insert Link" org-insert-link t]
19678 ["Follow Link" org-open-at-point t]
19679 "--"
19680 ["Next link" org-next-link t]
19681 ["Previous link" org-previous-link t]
19682 "--"
19683 ["Descriptive Links"
19684 org-toggle-link-display
19685 :style radio
19686 :selected org-descriptive-links
19688 ["Literal Links"
19689 org-toggle-link-display
19690 :style radio
19691 :selected (not org-descriptive-links)])
19692 "--"
19693 ("TODO Lists"
19694 ["TODO/DONE/-" org-todo t]
19695 ("Select keyword"
19696 ["Next keyword" org-shiftright (org-at-heading-p)]
19697 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19698 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19699 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19700 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19701 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19702 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19703 "--"
19704 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19705 :selected org-enforce-todo-dependencies :style toggle :active t]
19706 "Settings for tree at point"
19707 ["Do Children sequentially" org-toggle-ordered-property :style radio
19708 :selected (org-entry-get nil "ORDERED")
19709 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19710 ["Do Children parallel" org-toggle-ordered-property :style radio
19711 :selected (not (org-entry-get nil "ORDERED"))
19712 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19713 "--"
19714 ["Set Priority" org-priority t]
19715 ["Priority Up" org-shiftup t]
19716 ["Priority Down" org-shiftdown t]
19717 "--"
19718 ["Get news from all feeds" org-feed-update-all t]
19719 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19720 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19721 ("TAGS and Properties"
19722 ["Set Tags" org-set-tags-command t]
19723 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19724 "--"
19725 ["Set property" org-set-property t]
19726 ["Column view of properties" org-columns t]
19727 ["Insert Column View DBlock" org-insert-columns-dblock t])
19728 ("Dates and Scheduling"
19729 ["Timestamp" org-time-stamp t]
19730 ["Timestamp (inactive)" org-time-stamp-inactive t]
19731 ("Change Date"
19732 ["1 Day Later" org-shiftright t]
19733 ["1 Day Earlier" org-shiftleft t]
19734 ["1 ... Later" org-shiftup t]
19735 ["1 ... Earlier" org-shiftdown t])
19736 ["Compute Time Range" org-evaluate-time-range t]
19737 ["Schedule Item" org-schedule t]
19738 ["Deadline" org-deadline t]
19739 "--"
19740 ["Custom time format" org-toggle-time-stamp-overlays
19741 :style radio :selected org-display-custom-times]
19742 "--"
19743 ["Goto Calendar" org-goto-calendar t]
19744 ["Date from Calendar" org-date-from-calendar t]
19745 "--"
19746 ["Start/Restart Timer" org-timer-start t]
19747 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19748 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19749 ["Insert Timer String" org-timer t]
19750 ["Insert Timer Item" org-timer-item t])
19751 ("Logging work"
19752 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19753 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19754 ["Clock out" org-clock-out t]
19755 ["Clock cancel" org-clock-cancel t]
19756 "--"
19757 ["Mark as default task" org-clock-mark-default-task t]
19758 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19759 ["Goto running clock" org-clock-goto t]
19760 "--"
19761 ["Display times" org-clock-display t]
19762 ["Create clock table" org-clock-report t]
19763 "--"
19764 ["Record DONE time"
19765 (progn (setq org-log-done (not org-log-done))
19766 (message "Switching to %s will %s record a timestamp"
19767 (car org-done-keywords)
19768 (if org-log-done "automatically" "not")))
19769 :style toggle :selected org-log-done])
19770 "--"
19771 ["Agenda Command..." org-agenda t]
19772 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19773 ("File List for Agenda")
19774 ("Special views current file"
19775 ["TODO Tree" org-show-todo-tree t]
19776 ["Check Deadlines" org-check-deadlines t]
19777 ["Timeline" org-timeline t]
19778 ["Tags/Property tree" org-match-sparse-tree t])
19779 "--"
19780 ["Export/Publish..." org-export t]
19781 ("LaTeX"
19782 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19783 :selected org-cdlatex-mode]
19784 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19785 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19786 ["Modify math symbol" org-cdlatex-math-modify
19787 (org-inside-LaTeX-fragment-p)]
19788 ["Insert citation" org-reftex-citation t]
19789 "--"
19790 ["Template for BEAMER" (progn (require 'org-beamer)
19791 (org-insert-beamer-options-template)) t])
19792 "--"
19793 ("MobileOrg"
19794 ["Push Files and Views" org-mobile-push t]
19795 ["Get Captured and Flagged" org-mobile-pull t]
19796 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19797 "--"
19798 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19799 "--"
19800 ("Documentation"
19801 ["Show Version" org-version t]
19802 ["Info Documentation" org-info t])
19803 ("Customize"
19804 ["Browse Org Group" org-customize t]
19805 "--"
19806 ["Expand This Menu" org-create-customize-menu
19807 (fboundp 'customize-menu-create)])
19808 ["Send bug report" org-submit-bug-report t]
19809 "--"
19810 ("Refresh/Reload"
19811 ["Refresh setup current buffer" org-mode-restart t]
19812 ["Reload Org (after update)" org-reload t]
19813 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19816 (defun org-info (&optional node)
19817 "Read documentation for Org-mode in the info system.
19818 With optional NODE, go directly to that node."
19819 (interactive)
19820 (info (format "(org)%s" (or node ""))))
19822 ;;;###autoload
19823 (defun org-submit-bug-report ()
19824 "Submit a bug report on Org-mode via mail.
19826 Don't hesitate to report any problems or inaccurate documentation.
19828 If you don't have setup sending mail from (X)Emacs, please copy the
19829 output buffer into your mail program, as it gives us important
19830 information about your Org-mode version and configuration."
19831 (interactive)
19832 (require 'reporter)
19833 (org-load-modules-maybe)
19834 (org-require-autoloaded-modules)
19835 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19836 (reporter-submit-bug-report
19837 "emacs-orgmode@gnu.org"
19838 (org-version nil 'full)
19839 (let (list)
19840 (save-window-excursion
19841 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19842 (delete-other-windows)
19843 (erase-buffer)
19844 (insert "You are about to submit a bug report to the Org-mode mailing list.
19846 We would like to add your full Org-mode and Outline configuration to the
19847 bug report. This greatly simplifies the work of the maintainer and
19848 other experts on the mailing list.
19850 HOWEVER, some variables you have customized may contain private
19851 information. The names of customers, colleagues, or friends, might
19852 appear in the form of file names, tags, todo states, or search strings.
19853 If you answer yes to the prompt, you might want to check and remove
19854 such private information before sending the email.")
19855 (add-text-properties (point-min) (point-max) '(face org-warning))
19856 (when (yes-or-no-p "Include your Org-mode configuration ")
19857 (mapatoms
19858 (lambda (v)
19859 (and (boundp v)
19860 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19861 (or (and (symbol-value v)
19862 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19863 (and
19864 (get v 'custom-type) (get v 'standard-value)
19865 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19866 (push v list)))))
19867 (kill-buffer (get-buffer "*Warn about privacy*"))
19868 list))
19869 nil nil
19870 "Remember to cover the basics, that is, what you expected to happen and
19871 what in fact did happen. You don't know how to make a good report? See
19873 http://orgmode.org/manual/Feedback.html#Feedback
19875 Your bug report will be posted to the Org-mode mailing list.
19876 ------------------------------------------------------------------------")
19877 (save-excursion
19878 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19879 (replace-match "\\1Bug: \\3 [\\2]")))))
19882 (defun org-install-agenda-files-menu ()
19883 (let ((bl (buffer-list)))
19884 (save-excursion
19885 (while bl
19886 (set-buffer (pop bl))
19887 (if (derived-mode-p 'org-mode) (setq bl nil)))
19888 (when (derived-mode-p 'org-mode)
19889 (easy-menu-change
19890 '("Org") "File List for Agenda"
19891 (append
19892 (list
19893 ["Edit File List" (org-edit-agenda-file-list) t]
19894 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19895 ["Remove Current File from List" org-remove-file t]
19896 ["Cycle through agenda files" org-cycle-agenda-files t]
19897 ["Occur in all agenda files" org-occur-in-agenda-files t]
19898 "--")
19899 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19901 ;;;; Documentation
19903 ;;;###autoload
19904 (defun org-require-autoloaded-modules ()
19905 (interactive)
19906 (mapc 'require
19907 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19908 org-docbook org-exp org-html org-icalendar
19909 org-id org-latex
19910 org-publish org-remember org-table
19911 org-timer org-xoxo)))
19913 ;;;###autoload
19914 (defun org-reload (&optional uncompiled)
19915 "Reload all org lisp files.
19916 With prefix arg UNCOMPILED, load the uncompiled versions."
19917 (interactive "P")
19918 (require 'find-func)
19919 (let* ((file-re "^org\\(-.*\\)?\\.el")
19920 (dir-org (file-name-directory (org-find-library-dir "org")))
19921 (dir-org-contrib (ignore-errors
19922 (file-name-directory
19923 (org-find-library-dir "org-contribdir"))))
19924 (babel-files
19925 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19926 (append (list nil "comint" "eval" "exp" "keys"
19927 "lob" "ref" "table" "tangle")
19928 (delq nil
19929 (mapcar
19930 (lambda (lang)
19931 (when (cdr lang) (symbol-name (car lang))))
19932 org-babel-load-languages)))))
19933 (files
19934 (append babel-files
19935 (and dir-org-contrib
19936 (directory-files dir-org-contrib t file-re))
19937 (directory-files dir-org t file-re)))
19938 (remove-re (concat (if (featurep 'xemacs)
19939 "org-colview" "org-colview-xemacs")
19940 "\\'")))
19941 (setq files (mapcar 'file-name-sans-extension files))
19942 (setq files (mapcar
19943 (lambda (x) (if (string-match remove-re x) nil x))
19944 files))
19945 (setq files (delq nil files))
19946 (mapc
19947 (lambda (f)
19948 (when (featurep (intern (file-name-nondirectory f)))
19949 (if (and (not uncompiled)
19950 (file-exists-p (concat f ".elc")))
19951 (load (concat f ".elc") nil nil 'nosuffix)
19952 (load (concat f ".el") nil nil 'nosuffix))))
19953 files)
19954 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19955 (org-version nil 'full 'message))
19957 ;;;###autoload
19958 (defun org-customize ()
19959 "Call the customize function with org as argument."
19960 (interactive)
19961 (org-load-modules-maybe)
19962 (org-require-autoloaded-modules)
19963 (customize-browse 'org))
19965 (defun org-create-customize-menu ()
19966 "Create a full customization menu for Org-mode, insert it into the menu."
19967 (interactive)
19968 (org-load-modules-maybe)
19969 (org-require-autoloaded-modules)
19970 (if (fboundp 'customize-menu-create)
19971 (progn
19972 (easy-menu-change
19973 '("Org") "Customize"
19974 `(["Browse Org group" org-customize t]
19975 "--"
19976 ,(customize-menu-create 'org)
19977 ["Set" Custom-set t]
19978 ["Save" Custom-save t]
19979 ["Reset to Current" Custom-reset-current t]
19980 ["Reset to Saved" Custom-reset-saved t]
19981 ["Reset to Standard Settings" Custom-reset-standard t]))
19982 (message "\"Org\"-menu now contains full customization menu"))
19983 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19985 ;;;; Miscellaneous stuff
19987 ;;; Generally useful functions
19989 (defun org-get-at-bol (property)
19990 "Get text property PROPERTY at beginning of line."
19991 (get-text-property (point-at-bol) property))
19993 (defun org-find-text-property-in-string (prop s)
19994 "Return the first non-nil value of property PROP in string S."
19995 (or (get-text-property 0 prop s)
19996 (get-text-property (or (next-single-property-change 0 prop s) 0)
19997 prop s)))
19999 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20000 "Display the given MESSAGE as a warning."
20001 (if (fboundp 'display-warning)
20002 (display-warning 'org message
20003 (if (featurep 'xemacs) 'warning :warning))
20004 (let ((buf (get-buffer-create "*Org warnings*")))
20005 (with-current-buffer buf
20006 (goto-char (point-max))
20007 (insert "Warning (Org): " message)
20008 (unless (bolp)
20009 (newline)))
20010 (display-buffer buf)
20011 (sit-for 0))))
20013 (defun org-eval (form)
20014 "Eval FORM and return result."
20015 (condition-case error
20016 (eval form)
20017 (error (format "%%![Error: %s]" error))))
20019 (defun org-in-clocktable-p ()
20020 "Check if the cursor is in a clocktable."
20021 (let ((pos (point)) start)
20022 (save-excursion
20023 (end-of-line 1)
20024 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20025 (setq start (match-beginning 0))
20026 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20027 (>= (match-end 0) pos)
20028 start))))
20030 (defun org-in-commented-line ()
20031 "Is point in a line starting with `#'?"
20032 (equal (char-after (point-at-bol)) ?#))
20034 (defun org-in-indented-comment-line ()
20035 "Is point in a line starting with `#' after some white space?"
20036 (save-excursion
20037 (save-match-data
20038 (goto-char (point-at-bol))
20039 (looking-at "[ \t]*#"))))
20041 (defun org-in-verbatim-emphasis ()
20042 (save-match-data
20043 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20045 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20046 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20047 (if (and marker (marker-buffer marker)
20048 (buffer-live-p (marker-buffer marker)))
20049 (progn
20050 (org-pop-to-buffer-same-window (marker-buffer marker))
20051 (if (or (> marker (point-max)) (< marker (point-min)))
20052 (widen))
20053 (goto-char marker)
20054 (org-show-context 'org-goto))
20055 (if bookmark
20056 (bookmark-jump bookmark)
20057 (error "Cannot find location"))))
20059 (defun org-quote-csv-field (s)
20060 "Quote field for inclusion in CSV material."
20061 (if (string-match "[\",]" s)
20062 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20065 (defun org-force-self-insert (N)
20066 "Needed to enforce self-insert under remapping."
20067 (interactive "p")
20068 (self-insert-command N))
20070 (defun org-string-width (s)
20071 "Compute width of string, ignoring invisible characters.
20072 This ignores character with invisibility property `org-link', and also
20073 characters with property `org-cwidth', because these will become invisible
20074 upon the next fontification round."
20075 (let (b l)
20076 (when (or (eq t buffer-invisibility-spec)
20077 (assq 'org-link buffer-invisibility-spec))
20078 (while (setq b (text-property-any 0 (length s)
20079 'invisible 'org-link s))
20080 (setq s (concat (substring s 0 b)
20081 (substring s (or (next-single-property-change
20082 b 'invisible s) (length s)))))))
20083 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20084 (setq s (concat (substring s 0 b)
20085 (substring s (or (next-single-property-change
20086 b 'org-cwidth s) (length s))))))
20087 (setq l (string-width s) b -1)
20088 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20089 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20092 (defun org-shorten-string (s maxlength)
20093 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20094 If the string is shorter or has length MAXLENGTH, just return the
20095 original string. If it is longer, the functions finds a space in the
20096 string, breaks this string off at that locations and adds three dots
20097 as ellipsis. Including the ellipsis, the string will not be longer
20098 than MAXLENGTH. If finding a good breaking point in the string does
20099 not work, the string is just chopped off in the middle of a word
20100 if necessary."
20101 (if (<= (length s) maxlength)
20103 (let* ((n (max (- maxlength 4) 1))
20104 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20105 (if (string-match re s)
20106 (concat (match-string 1 s) "...")
20107 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20109 (defun org-get-indentation (&optional line)
20110 "Get the indentation of the current line, interpreting tabs.
20111 When LINE is given, assume it represents a line and compute its indentation."
20112 (if line
20113 (if (string-match "^ *" (org-remove-tabs line))
20114 (match-end 0))
20115 (save-excursion
20116 (beginning-of-line 1)
20117 (skip-chars-forward " \t")
20118 (current-column))))
20120 (defun org-get-string-indentation (s)
20121 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20122 (let ((n -1) (i 0) (w tab-width) c)
20123 (catch 'exit
20124 (while (< (setq n (1+ n)) (length s))
20125 (setq c (aref s n))
20126 (cond ((= c ?\ ) (setq i (1+ i)))
20127 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20128 (t (throw 'exit t)))))
20131 (defun org-remove-tabs (s &optional width)
20132 "Replace tabulators in S with spaces.
20133 Assumes that s is a single line, starting in column 0."
20134 (setq width (or width tab-width))
20135 (while (string-match "\t" s)
20136 (setq s (replace-match
20137 (make-string
20138 (- (* width (/ (+ (match-beginning 0) width) width))
20139 (match-beginning 0)) ?\ )
20140 t t s)))
20143 (defun org-fix-indentation (line ind)
20144 "Fix indentation in LINE.
20145 IND is a cons cell with target and minimum indentation.
20146 If the current indentation in LINE is smaller than the minimum,
20147 leave it alone. If it is larger than ind, set it to the target."
20148 (let* ((l (org-remove-tabs line))
20149 (i (org-get-indentation l))
20150 (i1 (car ind)) (i2 (cdr ind)))
20151 (if (>= i i2) (setq l (substring line i2)))
20152 (if (> i1 0)
20153 (concat (make-string i1 ?\ ) l)
20154 l)))
20156 (defun org-remove-indentation (code &optional n)
20157 "Remove the maximum common indentation from the lines in CODE.
20158 N may optionally be the number of spaces to remove."
20159 (with-temp-buffer
20160 (insert code)
20161 (org-do-remove-indentation n)
20162 (buffer-string)))
20164 (defun org-do-remove-indentation (&optional n)
20165 "Remove the maximum common indentation from the buffer."
20166 (untabify (point-min) (point-max))
20167 (let ((min 10000) re)
20168 (if n
20169 (setq min n)
20170 (goto-char (point-min))
20171 (while (re-search-forward "^ *[^ \n]" nil t)
20172 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20173 (unless (or (= min 0) (= min 10000))
20174 (setq re (format "^ \\{%d\\}" min))
20175 (goto-char (point-min))
20176 (while (re-search-forward re nil t)
20177 (replace-match "")
20178 (end-of-line 1))
20179 min)))
20181 (defun org-fill-template (template alist)
20182 "Find each %key of ALIST in TEMPLATE and replace it."
20183 (let ((case-fold-search nil)
20184 entry key value)
20185 (setq alist (sort (copy-sequence alist)
20186 (lambda (a b) (< (length (car a)) (length (car b))))))
20187 (while (setq entry (pop alist))
20188 (setq template
20189 (replace-regexp-in-string
20190 (concat "%" (regexp-quote (car entry)))
20191 (or (cdr entry) "") template t t)))
20192 template))
20194 (defun org-base-buffer (buffer)
20195 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20196 (if (not buffer)
20197 buffer
20198 (or (buffer-base-buffer buffer)
20199 buffer)))
20201 (defun org-trim (s)
20202 "Remove whitespace at beginning and end of string."
20203 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20204 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20207 (defun org-wrap (string &optional width lines)
20208 "Wrap string to either a number of lines, or a width in characters.
20209 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20210 that costs. If there is a word longer than WIDTH, the text is actually
20211 wrapped to the length of that word.
20212 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20213 many lines, whatever width that takes.
20214 The return value is a list of lines, without newlines at the end."
20215 (let* ((words (org-split-string string "[ \t\n]+"))
20216 (maxword (apply 'max (mapcar 'org-string-width words)))
20217 w ll)
20218 (cond (width
20219 (org-do-wrap words (max maxword width)))
20220 (lines
20221 (setq w maxword)
20222 (setq ll (org-do-wrap words maxword))
20223 (if (<= (length ll) lines)
20225 (setq ll words)
20226 (while (> (length ll) lines)
20227 (setq w (1+ w))
20228 (setq ll (org-do-wrap words w)))
20229 ll))
20230 (t (error "Cannot wrap this")))))
20232 (defun org-do-wrap (words width)
20233 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20234 (let (lines line)
20235 (while words
20236 (setq line (pop words))
20237 (while (and words (< (+ (length line) (length (car words))) width))
20238 (setq line (concat line " " (pop words))))
20239 (setq lines (push line lines)))
20240 (nreverse lines)))
20242 (defun org-split-string (string &optional separators)
20243 "Splits STRING into substrings at SEPARATORS.
20244 No empty strings are returned if there are matches at the beginning
20245 and end of string."
20246 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20247 (start 0)
20248 notfirst
20249 (list nil))
20250 (while (and (string-match rexp string
20251 (if (and notfirst
20252 (= start (match-beginning 0))
20253 (< start (length string)))
20254 (1+ start) start))
20255 (< (match-beginning 0) (length string)))
20256 (setq notfirst t)
20257 (or (eq (match-beginning 0) 0)
20258 (and (eq (match-beginning 0) (match-end 0))
20259 (eq (match-beginning 0) start))
20260 (setq list
20261 (cons (substring string start (match-beginning 0))
20262 list)))
20263 (setq start (match-end 0)))
20264 (or (eq start (length string))
20265 (setq list
20266 (cons (substring string start)
20267 list)))
20268 (nreverse list)))
20270 (defun org-quote-vert (s)
20271 "Replace \"|\" with \"\\vert\"."
20272 (while (string-match "|" s)
20273 (setq s (replace-match "\\vert" t t s)))
20276 (defun org-uuidgen-p (s)
20277 "Is S an ID created by UUIDGEN?"
20278 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20280 (defun org-in-src-block-p nil
20281 "Whether point is in a code source block."
20282 (let (ov)
20283 (when (setq ov (overlays-at (point)))
20284 (memq 'org-block-background
20285 (overlay-properties
20286 (car ov))))))
20288 (defun org-context ()
20289 "Return a list of contexts of the current cursor position.
20290 If several contexts apply, all are returned.
20291 Each context entry is a list with a symbol naming the context, and
20292 two positions indicating start and end of the context. Possible
20293 contexts are:
20295 :headline anywhere in a headline
20296 :headline-stars on the leading stars in a headline
20297 :todo-keyword on a TODO keyword (including DONE) in a headline
20298 :tags on the TAGS in a headline
20299 :priority on the priority cookie in a headline
20300 :item on the first line of a plain list item
20301 :item-bullet on the bullet/number of a plain list item
20302 :checkbox on the checkbox in a plain list item
20303 :table in an org-mode table
20304 :table-special on a special filed in a table
20305 :table-table in a table.el table
20306 :clocktable in a clocktable
20307 :src-block in a source block
20308 :link on a hyperlink
20309 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20310 :target on a <<target>>
20311 :radio-target on a <<<radio-target>>>
20312 :latex-fragment on a LaTeX fragment
20313 :latex-preview on a LaTeX fragment with overlaid preview image
20315 This function expects the position to be visible because it uses font-lock
20316 faces as a help to recognize the following contexts: :table-special, :link,
20317 and :keyword."
20318 (let* ((f (get-text-property (point) 'face))
20319 (faces (if (listp f) f (list f)))
20320 (case-fold-search t)
20321 (p (point)) clist o)
20322 ;; First the large context
20323 (cond
20324 ((org-at-heading-p t)
20325 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20326 (when (progn
20327 (beginning-of-line 1)
20328 (looking-at org-todo-line-tags-regexp))
20329 (push (org-point-in-group p 1 :headline-stars) clist)
20330 (push (org-point-in-group p 2 :todo-keyword) clist)
20331 (push (org-point-in-group p 4 :tags) clist))
20332 (goto-char p)
20333 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20334 (if (looking-at "\\[#[A-Z0-9]\\]")
20335 (push (org-point-in-group p 0 :priority) clist)))
20337 ((org-at-item-p)
20338 (push (org-point-in-group p 2 :item-bullet) clist)
20339 (push (list :item (point-at-bol)
20340 (save-excursion (org-end-of-item) (point)))
20341 clist)
20342 (and (org-at-item-checkbox-p)
20343 (push (org-point-in-group p 0 :checkbox) clist)))
20345 ((org-at-table-p)
20346 (push (list :table (org-table-begin) (org-table-end)) clist)
20347 (if (memq 'org-formula faces)
20348 (push (list :table-special
20349 (previous-single-property-change p 'face)
20350 (next-single-property-change p 'face)) clist)))
20351 ((org-at-table-p 'any)
20352 (push (list :table-table) clist)))
20353 (goto-char p)
20355 ;; New the "medium" contexts: clocktables, source blocks
20356 (cond ((org-in-clocktable-p)
20357 (push (list :clocktable
20358 (and (or (looking-at "#\\+BEGIN: clocktable")
20359 (search-backward "#+BEGIN: clocktable" nil t))
20360 (match-beginning 0))
20361 (and (re-search-forward "#\\+END:?" nil t)
20362 (match-end 0))) clist))
20363 ((org-in-src-block-p)
20364 (push (list :src-block
20365 (and (or (looking-at "#\\+BEGIN_SRC")
20366 (search-backward "#+BEGIN_SRC" nil t))
20367 (match-beginning 0))
20368 (and (search-forward "#+END_SRC" nil t)
20369 (match-beginning 0))) clist)))
20370 (goto-char p)
20372 ;; Now the small context
20373 (cond
20374 ((org-at-timestamp-p)
20375 (push (org-point-in-group p 0 :timestamp) clist))
20376 ((memq 'org-link faces)
20377 (push (list :link
20378 (previous-single-property-change p 'face)
20379 (next-single-property-change p 'face)) clist))
20380 ((memq 'org-special-keyword faces)
20381 (push (list :keyword
20382 (previous-single-property-change p 'face)
20383 (next-single-property-change p 'face)) clist))
20384 ((org-at-target-p)
20385 (push (org-point-in-group p 0 :target) clist)
20386 (goto-char (1- (match-beginning 0)))
20387 (if (looking-at org-radio-target-regexp)
20388 (push (org-point-in-group p 0 :radio-target) clist))
20389 (goto-char p))
20390 ((setq o (car (delq nil
20391 (mapcar
20392 (lambda (x)
20393 (if (memq x org-latex-fragment-image-overlays) x))
20394 (overlays-at (point))))))
20395 (push (list :latex-fragment
20396 (overlay-start o) (overlay-end o)) clist)
20397 (push (list :latex-preview
20398 (overlay-start o) (overlay-end o)) clist))
20399 ((org-inside-LaTeX-fragment-p)
20400 ;; FIXME: positions wrong.
20401 (push (list :latex-fragment (point) (point)) clist)))
20403 (setq clist (nreverse (delq nil clist)))
20404 clist))
20406 ;; FIXME: Compare with at-regexp-p Do we need both?
20407 (defun org-in-regexp (re &optional nlines visually)
20408 "Check if point is inside a match of regexp.
20409 Normally only the current line is checked, but you can include NLINES extra
20410 lines both before and after point into the search.
20411 If VISUALLY is set, require that the cursor is not after the match but
20412 really on, so that the block visually is on the match."
20413 (catch 'exit
20414 (let ((pos (point))
20415 (eol (point-at-eol (+ 1 (or nlines 0))))
20416 (inc (if visually 1 0)))
20417 (save-excursion
20418 (beginning-of-line (- 1 (or nlines 0)))
20419 (while (re-search-forward re eol t)
20420 (if (and (<= (match-beginning 0) pos)
20421 (>= (+ inc (match-end 0)) pos))
20422 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20424 (defun org-at-regexp-p (regexp)
20425 "Is point inside a match of REGEXP in the current line?"
20426 (catch 'exit
20427 (save-excursion
20428 (let ((pos (point)) (end (point-at-eol)))
20429 (beginning-of-line 1)
20430 (while (re-search-forward regexp end t)
20431 (if (and (<= (match-beginning 0) pos)
20432 (>= (match-end 0) pos))
20433 (throw 'exit t)))
20434 nil))))
20436 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20437 "Non-nil when point is between matches of START-RE and END-RE.
20439 Also return a non-nil value when point is on one of the matches.
20441 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20442 buffer positions. Default values are the positions of headlines
20443 surrounding the point.
20445 The functions returns a cons cell whose car (resp. cdr) is the
20446 position before START-RE (resp. after END-RE)."
20447 (save-match-data
20448 (let ((pos (point))
20449 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20450 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20451 beg end)
20452 (save-excursion
20453 ;; Point is on a block when on START-RE or if START-RE can be
20454 ;; found before it...
20455 (and (or (org-at-regexp-p start-re)
20456 (re-search-backward start-re limit-up t))
20457 (setq beg (match-beginning 0))
20458 ;; ... and END-RE after it...
20459 (goto-char (match-end 0))
20460 (re-search-forward end-re limit-down t)
20461 (> (setq end (match-end 0)) pos)
20462 ;; ... without another START-RE in-between.
20463 (goto-char (match-beginning 0))
20464 (not (re-search-backward start-re (1+ beg) t))
20465 ;; Return value.
20466 (cons beg end))))))
20468 (defun org-in-block-p (names)
20469 "Non-nil when point belongs to a block whose name belongs to NAMES.
20471 NAMES is a list of strings containing names of blocks.
20473 Return first block name matched, or nil. Beware that in case of
20474 nested blocks, the returned name may not belong to the closest
20475 block from point."
20476 (save-match-data
20477 (catch 'exit
20478 (let ((case-fold-search t)
20479 (lim-up (save-excursion (outline-previous-heading)))
20480 (lim-down (save-excursion (outline-next-heading))))
20481 (mapc (lambda (name)
20482 (let ((n (regexp-quote name)))
20483 (when (org-between-regexps-p
20484 (concat "^[ \t]*#\\+begin_" n)
20485 (concat "^[ \t]*#\\+end_" n)
20486 lim-up lim-down)
20487 (throw 'exit n))))
20488 names))
20489 nil)))
20491 (defun org-occur-in-agenda-files (regexp &optional nlines)
20492 "Call `multi-occur' with buffers for all agenda files."
20493 (interactive "sOrg-files matching: \np")
20494 (let* ((files (org-agenda-files))
20495 (tnames (mapcar 'file-truename files))
20496 (extra org-agenda-text-search-extra-files)
20498 (when (eq (car extra) 'agenda-archives)
20499 (setq extra (cdr extra))
20500 (setq files (org-add-archive-files files)))
20501 (while (setq f (pop extra))
20502 (unless (member (file-truename f) tnames)
20503 (add-to-list 'files f 'append)
20504 (add-to-list 'tnames (file-truename f) 'append)))
20505 (multi-occur
20506 (mapcar (lambda (x)
20507 (with-current-buffer
20508 (or (get-file-buffer x) (find-file-noselect x))
20509 (widen)
20510 (current-buffer)))
20511 files)
20512 regexp)))
20514 (if (boundp 'occur-mode-find-occurrence-hook)
20515 ;; Emacs 23
20516 (add-hook 'occur-mode-find-occurrence-hook
20517 (lambda ()
20518 (when (derived-mode-p 'org-mode)
20519 (org-reveal))))
20520 ;; Emacs 22
20521 (defadvice occur-mode-goto-occurrence
20522 (after org-occur-reveal activate)
20523 (and (derived-mode-p 'org-mode) (org-reveal)))
20524 (defadvice occur-mode-goto-occurrence-other-window
20525 (after org-occur-reveal activate)
20526 (and (derived-mode-p 'org-mode) (org-reveal)))
20527 (defadvice occur-mode-display-occurrence
20528 (after org-occur-reveal activate)
20529 (when (derived-mode-p 'org-mode)
20530 (let ((pos (occur-mode-find-occurrence)))
20531 (with-current-buffer (marker-buffer pos)
20532 (save-excursion
20533 (goto-char pos)
20534 (org-reveal)))))))
20536 (defun org-occur-link-in-agenda-files ()
20537 "Create a link and search for it in the agendas.
20538 The link is not stored in `org-stored-links', it is just created
20539 for the search purpose."
20540 (interactive)
20541 (let ((link (condition-case nil
20542 (org-store-link nil)
20543 (error "Unable to create a link to here"))))
20544 (org-occur-in-agenda-files (regexp-quote link))))
20546 (defun org-uniquify (list)
20547 "Remove duplicate elements from LIST."
20548 (let (res)
20549 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20550 res))
20552 (defun org-delete-all (elts list)
20553 "Remove all elements in ELTS from LIST."
20554 (while elts
20555 (setq list (delete (pop elts) list)))
20556 list)
20558 (defun org-count (cl-item cl-seq)
20559 "Count the number of occurrences of ITEM in SEQ.
20560 Taken from `count' in cl-seq.el with all keyword arguments removed."
20561 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20562 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20563 (while (< cl-start cl-end)
20564 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20565 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20566 (setq cl-start (1+ cl-start)))
20567 cl-count))
20569 (defun org-remove-if (predicate seq)
20570 "Remove everything from SEQ that fulfills PREDICATE."
20571 (let (res e)
20572 (while seq
20573 (setq e (pop seq))
20574 (if (not (funcall predicate e)) (push e res)))
20575 (nreverse res)))
20577 (defun org-remove-if-not (predicate seq)
20578 "Remove everything from SEQ that does not fulfill PREDICATE."
20579 (let (res e)
20580 (while seq
20581 (setq e (pop seq))
20582 (if (funcall predicate e) (push e res)))
20583 (nreverse res)))
20585 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20586 "Reduce two-argument FUNCTION across SEQ.
20587 Taken from `reduce' in cl-seq.el with all keyword arguments but
20588 \":initial-value\" removed."
20589 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20590 (cadr (memq :initial-value cl-keys)))
20591 (cl-seq (pop cl-seq))
20592 (t (funcall cl-func)))))
20593 (while cl-seq
20594 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20595 cl-accum))
20597 (defun org-back-over-empty-lines ()
20598 "Move backwards over whitespace, to the beginning of the first empty line.
20599 Returns the number of empty lines passed."
20600 (let ((pos (point)))
20601 (if (cdr (assoc 'heading org-blank-before-new-entry))
20602 (skip-chars-backward " \t\n\r")
20603 (unless (eobp)
20604 (forward-line -1)))
20605 (beginning-of-line 2)
20606 (goto-char (min (point) pos))
20607 (count-lines (point) pos)))
20609 (defun org-skip-whitespace ()
20610 (skip-chars-forward " \t\n\r"))
20612 (defun org-point-in-group (point group &optional context)
20613 "Check if POINT is in match-group GROUP.
20614 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20615 match. If the match group does not exist or point is not inside it,
20616 return nil."
20617 (and (match-beginning group)
20618 (>= point (match-beginning group))
20619 (<= point (match-end group))
20620 (if context
20621 (list context (match-beginning group) (match-end group))
20622 t)))
20624 (defun org-switch-to-buffer-other-window (&rest args)
20625 "Switch to buffer in a second window on the current frame.
20626 In particular, do not allow pop-up frames.
20627 Returns the newly created buffer."
20628 (let (pop-up-frames special-display-buffer-names special-display-regexps
20629 special-display-function)
20630 (apply 'switch-to-buffer-other-window args)))
20632 (defun org-combine-plists (&rest plists)
20633 "Create a single property list from all plists in PLISTS.
20634 The process starts by copying the first list, and then setting properties
20635 from the other lists. Settings in the last list are the most significant
20636 ones and overrule settings in the other lists."
20637 (let ((rtn (copy-sequence (pop plists)))
20638 p v ls)
20639 (while plists
20640 (setq ls (pop plists))
20641 (while ls
20642 (setq p (pop ls) v (pop ls))
20643 (setq rtn (plist-put rtn p v))))
20644 rtn))
20646 (defun org-replace-escapes (string table)
20647 "Replace %-escapes in STRING with values in TABLE.
20648 TABLE is an association list with keys like \"%a\" and string values.
20649 The sequences in STRING may contain normal field width and padding information,
20650 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20651 so values can contain further %-escapes if they are define later in TABLE."
20652 (let ((tbl (copy-alist table))
20653 (case-fold-search nil)
20654 (pchg 0)
20655 e re rpl)
20656 (while (setq e (pop tbl))
20657 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20658 (when (and (cdr e) (string-match re (cdr e)))
20659 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20660 (safe "SREF"))
20661 (add-text-properties 0 3 (list 'sref sref) safe)
20662 (setcdr e (replace-match safe t t (cdr e)))))
20663 (while (string-match re string)
20664 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20665 (cdr e)))
20666 (setq string (replace-match rpl t t string))))
20667 (while (setq pchg (next-property-change pchg string))
20668 (let ((sref (get-text-property pchg 'sref string)))
20669 (when (and sref (string-match "SREF" string pchg))
20670 (setq string (replace-match sref t t string)))))
20671 string))
20673 (defun org-sublist (list start end)
20674 "Return a section of LIST, from START to END.
20675 Counting starts at 1."
20676 (let (rtn (c start))
20677 (setq list (nthcdr (1- start) list))
20678 (while (and list (<= c end))
20679 (push (pop list) rtn)
20680 (setq c (1+ c)))
20681 (nreverse rtn)))
20683 (defun org-find-base-buffer-visiting (file)
20684 "Like `find-buffer-visiting' but always return the base buffer and
20685 not an indirect buffer."
20686 (let ((buf (or (get-file-buffer file)
20687 (find-buffer-visiting file))))
20688 (if buf
20689 (or (buffer-base-buffer buf) buf)
20690 nil)))
20692 (defun org-image-file-name-regexp (&optional extensions)
20693 "Return regexp matching the file names of images.
20694 If EXTENSIONS is given, only match these."
20695 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20696 (image-file-name-regexp)
20697 (let ((image-file-name-extensions
20698 (or extensions
20699 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20700 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20701 (concat "\\."
20702 (regexp-opt (nconc (mapcar 'upcase
20703 image-file-name-extensions)
20704 image-file-name-extensions)
20706 "\\'"))))
20708 (defun org-file-image-p (file &optional extensions)
20709 "Return non-nil if FILE is an image."
20710 (save-match-data
20711 (string-match (org-image-file-name-regexp extensions) file)))
20713 (defun org-get-cursor-date ()
20714 "Return the date at cursor in as a time.
20715 This works in the calendar and in the agenda, anywhere else it just
20716 returns the current time."
20717 (let (date day defd)
20718 (cond
20719 ((eq major-mode 'calendar-mode)
20720 (setq date (calendar-cursor-to-date)
20721 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20722 ((eq major-mode 'org-agenda-mode)
20723 (setq day (get-text-property (point) 'day))
20724 (if day
20725 (setq date (calendar-gregorian-from-absolute day)
20726 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20727 (nth 2 date))))))
20728 (or defd (current-time))))
20730 (defvar org-agenda-action-marker (make-marker)
20731 "Marker pointing to the entry for the next agenda action.")
20733 (defun org-mark-entry-for-agenda-action ()
20734 "Mark the current entry as target of an agenda action.
20735 Agenda actions are actions executed from the agenda with the key `k',
20736 which make use of the date at the cursor."
20737 (interactive)
20738 (move-marker org-agenda-action-marker
20739 (save-excursion (org-back-to-heading t) (point))
20740 (current-buffer))
20741 (message
20742 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20744 (defun org-mark-subtree (&optional up)
20745 "Mark the current subtree.
20746 This puts point at the start of the current subtree, and mark at
20747 the end. If a numeric prefix UP is given, move up into the
20748 hierarchy of headlines by UP levels before marking the subtree."
20749 (interactive "P")
20750 (org-with-limited-levels
20751 (cond ((org-at-heading-p) (beginning-of-line))
20752 ((org-before-first-heading-p) (error "Not in a subtree"))
20753 (t (outline-previous-visible-heading 1))))
20754 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20755 (org-mark-element))
20757 ;;; Indentation
20759 (defun org-indent-line ()
20760 "Indent line depending on context."
20761 (interactive)
20762 (let* ((pos (point))
20763 (itemp (org-at-item-p))
20764 (case-fold-search t)
20765 (org-drawer-regexp (or org-drawer-regexp "\000"))
20766 (inline-task-p (and (featurep 'org-inlinetask)
20767 (org-inlinetask-in-task-p)))
20768 (inline-re (and inline-task-p
20769 (org-inlinetask-outline-regexp)))
20770 column)
20771 (if (and orgstruct-is-++ (eq pos (point)))
20772 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20773 (indent-according-to-mode))
20774 (beginning-of-line 1)
20775 (cond
20776 ;; Headings
20777 ((looking-at org-outline-regexp) (setq column 0))
20778 ;; Included files
20779 ((looking-at "#\\+include:") (setq column 0))
20780 ;; Footnote definition
20781 ((looking-at org-footnote-definition-re) (setq column 0))
20782 ;; Literal examples
20783 ((looking-at "[ \t]*:\\( \\|$\\)")
20784 (setq column (org-get-indentation))) ; do nothing
20785 ;; Lists
20786 ((ignore-errors (goto-char (org-in-item-p)))
20787 (setq column (if itemp
20788 (org-get-indentation)
20789 (org-list-item-body-column (point))))
20790 (goto-char pos))
20791 ;; Drawers
20792 ((and (looking-at "[ \t]*:END:")
20793 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20794 (save-excursion
20795 (goto-char (1- (match-beginning 1)))
20796 (setq column (current-column))))
20797 ;; Special blocks
20798 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20799 (save-excursion
20800 (re-search-backward
20801 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20802 (setq column (org-get-indentation (match-string 0))))
20803 ((and (not (looking-at "[ \t]*#\\+begin_"))
20804 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20805 (save-excursion
20806 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20807 (setq column
20808 (cond ((equal (downcase (match-string 1)) "src")
20809 ;; src blocks: let `org-edit-src-exit' handle them
20810 (org-get-indentation))
20811 ((equal (downcase (match-string 1)) "example")
20812 (max (org-get-indentation)
20813 (org-get-indentation (match-string 0))))
20815 (org-get-indentation (match-string 0))))))
20816 ;; This line has nothing special, look at the previous relevant
20817 ;; line to compute indentation
20819 (beginning-of-line 0)
20820 (while (and (not (bobp))
20821 (not (looking-at org-drawer-regexp))
20822 ;; When point started in an inline task, do not move
20823 ;; above task starting line.
20824 (not (and inline-task-p (looking-at inline-re)))
20825 ;; Skip drawers, blocks, empty lines, verbatim,
20826 ;; comments, tables, footnotes definitions, lists,
20827 ;; inline tasks.
20828 (or (and (looking-at "[ \t]*:END:")
20829 (re-search-backward org-drawer-regexp nil t))
20830 (and (looking-at "[ \t]*#\\+end_")
20831 (re-search-backward "[ \t]*#\\+begin_"nil t))
20832 (looking-at "[ \t]*[\n:#|]")
20833 (looking-at org-footnote-definition-re)
20834 (and (ignore-errors (goto-char (org-in-item-p)))
20835 (goto-char
20836 (org-list-get-top-point (org-list-struct))))
20837 (and (not inline-task-p)
20838 (featurep 'org-inlinetask)
20839 (org-inlinetask-in-task-p)
20840 (or (org-inlinetask-goto-beginning) t))))
20841 (beginning-of-line 0))
20842 (cond
20843 ;; There was an heading above.
20844 ((looking-at "\\*+[ \t]+")
20845 (if (not org-adapt-indentation)
20846 (setq column 0)
20847 (goto-char (match-end 0))
20848 (setq column (current-column))))
20849 ;; A drawer had started and is unfinished
20850 ((looking-at org-drawer-regexp)
20851 (goto-char (1- (match-beginning 1)))
20852 (setq column (current-column)))
20853 ;; Else, nothing noticeable found: get indentation and go on.
20854 (t (setq column (org-get-indentation))))))
20855 ;; Now apply indentation and move cursor accordingly
20856 (goto-char pos)
20857 (if (<= (current-column) (current-indentation))
20858 (org-indent-line-to column)
20859 (save-excursion (org-indent-line-to column)))
20860 ;; Special polishing for properties, see `org-property-format'
20861 (setq column (current-column))
20862 (beginning-of-line 1)
20863 (if (looking-at
20864 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20865 (replace-match (concat (match-string 1)
20866 (format org-property-format
20867 (match-string 2) (match-string 3)))
20868 t t))
20869 (org-move-to-column column))))
20871 (defun org-indent-drawer ()
20872 "Indent the drawer at point."
20873 (interactive)
20874 (let ((p (point))
20875 (e (and (save-excursion (re-search-forward ":END:" nil t))
20876 (match-end 0)))
20877 (folded
20878 (save-excursion
20879 (end-of-line)
20880 (when (overlays-at (point))
20881 (member 'invisible (overlay-properties
20882 (car (overlays-at (point)))))))))
20883 (when folded (org-cycle))
20884 (indent-for-tab-command)
20885 (while (and (move-beginning-of-line 2) (< (point) e))
20886 (indent-for-tab-command))
20887 (goto-char p)
20888 (when folded (org-cycle)))
20889 (message "Drawer at point indented"))
20891 (defun org-indent-block ()
20892 "Indent the block at point."
20893 (interactive)
20894 (let ((p (point))
20895 (case-fold-search t)
20896 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20897 (match-end 0)))
20898 (folded
20899 (save-excursion
20900 (end-of-line)
20901 (when (overlays-at (point))
20902 (member 'invisible (overlay-properties
20903 (car (overlays-at (point)))))))))
20904 (when folded (org-cycle))
20905 (indent-for-tab-command)
20906 (while (and (move-beginning-of-line 2) (< (point) e))
20907 (indent-for-tab-command))
20908 (goto-char p)
20909 (when folded (org-cycle)))
20910 (message "Block at point indented"))
20912 (defun org-indent-region (start end)
20913 "Indent region."
20914 (interactive "r")
20915 (save-excursion
20916 (let ((line-end (org-current-line end)))
20917 (goto-char start)
20918 (while (< (org-current-line) line-end)
20919 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20920 (t (call-interactively 'org-indent-line)))
20921 (move-beginning-of-line 2)))))
20924 ;;; Filling
20926 ;; We use our own fill-paragraph and auto-fill functions. These
20927 ;; functions will shadow `fill-prefix' (computed internally with
20928 ;; `org-fill-context-prefix') and pass through to
20929 ;; `fill-region-as-paragraph' and `do-auto-fill' as appropriate.
20931 (defun org-set-autofill-regexps ()
20932 (interactive)
20933 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20934 ;; Prevent auto-fill from inserting unwanted new items.
20935 (when (boundp 'fill-nobreak-predicate)
20936 (org-set-local
20937 'fill-nobreak-predicate
20938 (org-uniquify
20939 (append fill-nobreak-predicate
20940 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20941 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20942 (org-set-local 'align-mode-rules-list
20943 '((org-in-buffer-settings
20944 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20945 (modes . '(org-mode))))))
20947 (defun org-fill-item-nobreak-p ()
20948 "Non-nil when a line break at point would insert a new item."
20949 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20951 (defun org-fill-line-break-nobreak-p ()
20952 "Non-nil when a line break at point would create an Org line break."
20953 (save-excursion
20954 (skip-chars-backward "[ \t]")
20955 (skip-chars-backward "\\\\")
20956 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20958 (declare-function message-in-body-p "message" ())
20959 (defvar org-element--affiliated-re) ; From org-element.el
20960 (defun org-fill-context-prefix (p)
20961 "Compute a fill prefix for the line at point P.
20962 Return fill prefix, as a string, or nil if current line isn't
20963 meant to be filled."
20964 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20965 ;; FIXME: Prevent an error for users who forgot to make autoloads?
20966 ;; See also `org-fill-paragraph', which has the same.
20967 (require 'org-element)
20968 ;; FIXME: This is really the job of orgstruct++-mode
20969 (save-excursion
20970 (goto-char p)
20971 (beginning-of-line)
20972 (let* ((element (org-element-at-point))
20973 (type (org-element-type element))
20974 (post-affiliated
20975 (progn
20976 (goto-char (org-element-property :begin element))
20977 (while (looking-at org-element--affiliated-re) (forward-line))
20978 (point))))
20979 (unless (< p post-affiliated)
20980 (case type
20981 (comment (looking-at "[ \t]*# ?") (match-string 0))
20982 (footnote-definition "")
20983 ((item plain-list)
20984 (make-string (org-list-item-body-column
20985 (org-element-property :begin element))
20986 ? ))
20987 (paragraph
20988 ;; Fill prefix is usually the same as the current line,
20989 ;; except if the paragraph is at the beginning of an item.
20990 (let ((parent (org-element-property :parent element)))
20991 (cond ((eq (org-element-type parent) 'item)
20992 (make-string (org-list-item-body-column
20993 (org-element-property :begin parent))
20994 ? ))
20995 ((looking-at "\\s-+") (match-string 0))
20996 (t ""))))
20997 ((comment-block verse-block)
20998 ;; Only fill contents if P is within block boundaries.
20999 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21000 (forward-line)
21001 (point)))
21002 (cend (save-excursion
21003 (goto-char (org-element-property :end element))
21004 (skip-chars-backward " \r\t\n")
21005 (line-beginning-position))))
21006 (when (and (>= p cbeg) (< p cend))
21007 (if (looking-at "\\s-+") (match-string 0) ""))))))))))
21009 (defvar org-element-all-objects) ; From org-element.el
21010 (defun org-fill-paragraph (&optional justify)
21011 "Fill element at point, when applicable.
21013 This function only applies to comment blocks, comments, example
21014 blocks, paragraphs and verse blocks. Also, as a special case,
21015 re-align table when point is at one.
21017 If JUSTIFY is non-nil (interactively, with prefix argument),
21018 justify as well. If `sentence-end-double-space' is non-nil, then
21019 period followed by one space does not end a sentence, so don't
21020 break a line there. The variable `fill-column' controls the
21021 width for filling.
21023 For convenience, when point is at a plain list, an item or
21024 a footnote definition, try to fill the first paragraph within."
21025 ;; Falls back on message-fill-paragraph when necessary
21026 (interactive)
21027 (if (and (derived-mode-p 'message-mode)
21028 (or (not (message-in-body-p))
21029 (save-excursion (move-beginning-of-line 1)
21030 (looking-at "^>+ "))))
21031 (let ((fill-paragraph-function (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21032 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21033 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21034 (paragraph-separate (cadadr (assoc 'paragraph-separate org-fb-vars))))
21035 (fill-paragraph))
21036 (save-excursion
21037 ;; Move to end of line in order to get the first paragraph within
21038 ;; a plain list or a footnote definition.
21039 (end-of-line)
21040 (let ((element (org-element-at-point)))
21041 ;; First check if point is in a blank line at the beginning of the
21042 ;; buffer. In that case, ignore filling.
21043 (if (< (point) (org-element-property :begin element)) t
21044 (case (org-element-type element)
21045 ;; Align Org tables, leave table.el tables as-is.
21046 (table-row (org-table-align) t)
21047 (table
21048 (when (eq (org-element-property :type element) 'org)
21049 (org-table-align))
21051 ;; Elements that may contain `line-break' type objects.
21052 ((paragraph verse-block)
21053 (let ((beg (org-element-property :contents-begin element))
21054 (end (org-element-property :contents-end element))
21055 (type (org-element-type element)))
21056 ;; Do nothing if point is at an affiliated keyword or at
21057 ;; verse block markers.
21058 (if (or (< (point) beg)
21059 (and (eq type 'verse-block) (>= (point) end)))
21061 ;; At a verse block, first narrow to current "paragraph"
21062 ;; and set current element to that paragraph.
21063 (save-restriction
21064 (when (eq type 'verse-block)
21065 (narrow-to-region beg end)
21066 (save-excursion
21067 (let ((bol-pos (point-at-bol)))
21068 (re-search-backward "^[ \t]*$" nil 'm)
21069 (unless (or (bobp) (= (point-at-bol) bol-pos))
21070 (forward-line))
21071 (setq element (org-element-paragraph-parser end)
21072 beg (org-element-property :contents-begin element)
21073 end (org-element-property
21074 :contents-end element)))))
21075 ;; Fill paragraph, taking line breaks into consideration.
21076 ;; For that, slice the paragraph using line breaks as
21077 ;; separators, and fill the parts in reverse order to
21078 ;; avoid messing with markers.
21079 (save-excursion
21080 (goto-char end)
21081 (mapc
21082 (lambda (pos)
21083 (let ((fill-prefix (org-fill-context-prefix pos)))
21084 (fill-region-as-paragraph pos (point) justify))
21085 (goto-char pos))
21086 ;; Find the list of ending positions for line breaks
21087 ;; in the current paragraph. Add paragraph beginning
21088 ;; to include first slice.
21089 (nreverse
21090 (cons beg
21091 (org-element-map
21092 (org-element--parse-objects
21093 beg end nil org-element-all-objects)
21094 'line-break
21095 (lambda (lb) (org-element-property :end lb))))))))
21096 t)))
21097 ;; Contents of `comment-block' type elements should be filled as
21098 ;; plain text.
21099 (comment-block
21100 (let ((fill-prefix (org-fill-context-prefix (point))))
21101 (save-excursion
21102 (fill-region-as-paragraph
21103 (progn
21104 (goto-char (org-element-property :begin element))
21105 (while (looking-at org-element--affiliated-re) (forward-line))
21106 (forward-line)
21107 (point))
21108 (progn
21109 (goto-char (org-element-property :end element))
21110 (skip-chars-backward " \r\t\n")
21111 (line-beginning-position))
21112 justify))) t)
21113 ;; Fill comments, indented or not.
21114 (comment
21115 (let ((fill-prefix (org-fill-context-prefix (point))))
21116 (save-excursion
21117 (fill-region-as-paragraph
21118 (progn
21119 (goto-char (org-element-property :begin element))
21120 (while (looking-at org-element--affiliated-re) (forward-line))
21121 (point))
21122 (progn
21123 (goto-char (org-element-property :end element))
21124 (skip-chars-backward " \r\t\n")
21125 (line-end-position))))))
21126 ;; Ignore every other element.
21127 (otherwise t)))))))
21129 (defun org-auto-fill-function ()
21130 "Auto-fill function."
21131 ;; Check if auto-filling is meaningful before computing fill prefix.
21132 (let ((fc (current-fill-column)))
21133 (when (and fc (> (current-column) fc))
21134 (let ((fill-prefix (org-fill-context-prefix (point))))
21135 (when fill-prefix (do-auto-fill))))))
21138 ;;; Comments
21140 ;; Since difference between comments and keywords is subtle, we cannot
21141 ;; trust `comment-only-p' when applying `comment-dwim'. Hence, both
21142 ;; `comment-region-function' and `uncomment-region-function' point to
21143 ;; `org-comment-or-uncomment-region', which can tell when region only
21144 ;; contains comments or not.
21146 (defun org-insert-comment ()
21147 "Insert an empty comment above current line.
21148 If the line is empty, insert comment at its beginning."
21149 (beginning-of-line)
21150 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21151 (org-indent-line)
21152 (insert "# "))
21154 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21155 "Comment or uncomment each non-blank line in the region.
21156 Uncomment each non-blank line between BEG and END if it only
21157 contains commented lines. Otherwise, comment them."
21158 (save-excursion
21159 (goto-char beg)
21160 (skip-chars-forward " \r\t\n" end)
21161 (beginning-of-line)
21162 (let ((uncommentp
21163 ;; UNCOMMENTP is non-nil when every non blank line between
21164 ;; BEG and END is a comment.
21165 (save-excursion
21166 (while (progn (and (not (eobp))
21167 (let ((element (org-element-at-point)))
21168 (and (eq (org-element-type element) 'comment)
21169 (goto-char (org-element-property
21170 :end element)))))))
21171 (>= (point) end)))
21172 ;; Remove or adding comment markers is going to change end
21173 ;; position so make it a marker.
21174 (end (copy-marker end)))
21175 (while (< (point) end)
21176 (unless (looking-at "\\s-*$")
21177 (if (not uncommentp) (progn (back-to-indentation) (insert "# "))
21178 ;; Only comments and blank lines in region: uncomment it.
21179 (looking-at "[ \t]*\\(# ?\\)")
21180 (replace-match "" nil nil nil 1)))
21181 (forward-line))
21182 (set-marker end nil))))
21185 ;;; Other stuff.
21187 (defun org-toggle-fixed-width-section (arg)
21188 "Toggle the fixed-width export.
21189 If there is no active region, the QUOTE keyword at the current headline is
21190 inserted or removed. When present, it causes the text between this headline
21191 and the next to be exported as fixed-width text, and unmodified.
21192 If there is an active region, this command adds or removes a colon as the
21193 first character of this line. If the first character of a line is a colon,
21194 this line is also exported in fixed-width font."
21195 (interactive "P")
21196 (let* ((cc 0)
21197 (regionp (org-region-active-p))
21198 (beg (if regionp (region-beginning) (point)))
21199 (end (if regionp (region-end)))
21200 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21201 (case-fold-search nil)
21202 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21203 off)
21204 (if regionp
21205 (save-excursion
21206 (goto-char beg)
21207 (setq cc (current-column))
21208 (beginning-of-line 1)
21209 (setq off (looking-at re))
21210 (while (> nlines 0)
21211 (setq nlines (1- nlines))
21212 (beginning-of-line 1)
21213 (cond
21214 (arg
21215 (org-move-to-column cc t)
21216 (insert ": \n")
21217 (forward-line -1))
21218 ((and off (looking-at re))
21219 (replace-match "" t t nil 1))
21220 ((not off) (org-move-to-column cc t) (insert ": ")))
21221 (forward-line 1)))
21222 (save-excursion
21223 (org-back-to-heading)
21224 (cond
21225 ((looking-at (format org-heading-keyword-regexp-format
21226 org-quote-string))
21227 (goto-char (match-end 1))
21228 (looking-at (concat " +" org-quote-string))
21229 (replace-match "" t t)
21230 (when (eolp) (insert " ")))
21231 ((looking-at org-outline-regexp)
21232 (goto-char (match-end 0))
21233 (insert org-quote-string " ")))))))
21235 (defun org-reftex-citation ()
21236 "Use reftex-citation to insert a citation into the buffer.
21237 This looks for a line like
21239 #+BIBLIOGRAPHY: foo plain option:-d
21241 and derives from it that foo.bib is the bibliography file relevant
21242 for this document. It then installs the necessary environment for RefTeX
21243 to work in this buffer and calls `reftex-citation' to insert a citation
21244 into the buffer.
21246 Export of such citations to both LaTeX and HTML is handled by the contributed
21247 package org-exp-bibtex by Taru Karttunen."
21248 (interactive)
21249 (let ((reftex-docstruct-symbol 'rds)
21250 (reftex-cite-format "\\cite{%l}")
21251 rds bib)
21252 (save-excursion
21253 (save-restriction
21254 (widen)
21255 (let ((case-fold-search t)
21256 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21257 (if (not (save-excursion
21258 (or (re-search-forward re nil t)
21259 (re-search-backward re nil t))))
21260 (error "No bibliography defined in file")
21261 (setq bib (concat (match-string 1) ".bib")
21262 rds (list (list 'bib bib)))))))
21263 (call-interactively 'reftex-citation)))
21265 ;;;; Functions extending outline functionality
21267 (defun org-beginning-of-line (&optional arg)
21268 "Go to the beginning of the current line. If that is invisible, continue
21269 to a visible line beginning. This makes the function of C-a more intuitive.
21270 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21271 first attempt, and only move to after the tags when the cursor is already
21272 beyond the end of the headline."
21273 (interactive "P")
21274 (let ((pos (point))
21275 (special (if (consp org-special-ctrl-a/e)
21276 (car org-special-ctrl-a/e)
21277 org-special-ctrl-a/e))
21278 refpos)
21279 (if (org-bound-and-true-p line-move-visual)
21280 (beginning-of-visual-line 1)
21281 (beginning-of-line 1))
21282 (if (and arg (fboundp 'move-beginning-of-line))
21283 (call-interactively 'move-beginning-of-line)
21284 (if (bobp)
21286 (backward-char 1)
21287 (if (org-truely-invisible-p)
21288 (while (and (not (bobp)) (org-truely-invisible-p))
21289 (backward-char 1)
21290 (beginning-of-line 1))
21291 (forward-char 1))))
21292 (when special
21293 (cond
21294 ((and (looking-at org-complex-heading-regexp)
21295 (= (char-after (match-end 1)) ?\ ))
21296 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21297 (point-at-eol)))
21298 (goto-char
21299 (if (eq special t)
21300 (cond ((> pos refpos) refpos)
21301 ((= pos (point)) refpos)
21302 (t (point)))
21303 (cond ((> pos (point)) (point))
21304 ((not (eq last-command this-command)) (point))
21305 (t refpos)))))
21306 ((org-at-item-p)
21307 ;; Being at an item and not looking at an the item means point
21308 ;; was previously moved to beginning of a visual line, which
21309 ;; doesn't contain the item. Therefore, do nothing special,
21310 ;; just stay here.
21311 (when (looking-at org-list-full-item-re)
21312 ;; Set special position at first white space character after
21313 ;; bullet, and check-box, if any.
21314 (let ((after-bullet
21315 (let ((box (match-end 3)))
21316 (if (not box) (match-end 1)
21317 (let ((after (char-after box)))
21318 (if (and after (= after ? )) (1+ box) box))))))
21319 ;; Special case: Move point to special position when
21320 ;; currently after it or at beginning of line.
21321 (if (eq special t)
21322 (when (or (> pos after-bullet) (= (point) pos))
21323 (goto-char after-bullet))
21324 ;; Reversed case: Move point to special position when
21325 ;; point was already at beginning of line and command is
21326 ;; repeated.
21327 (when (and (= (point) pos) (eq last-command this-command))
21328 (goto-char after-bullet))))))))
21329 (org-no-warnings
21330 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21332 (defun org-end-of-line (&optional arg)
21333 "Go to the end of the line.
21334 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21335 first attempt, and only move to after the tags when the cursor is already
21336 beyond the end of the headline."
21337 (interactive "P")
21338 (let ((special (if (consp org-special-ctrl-a/e)
21339 (cdr org-special-ctrl-a/e)
21340 org-special-ctrl-a/e)))
21341 (cond
21342 ((or (not special) arg
21343 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21344 (call-interactively
21345 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21346 ((fboundp 'move-end-of-line) 'move-end-of-line)
21347 (t 'end-of-line))))
21348 ((org-at-heading-p)
21349 (let ((pos (point)))
21350 (beginning-of-line 1)
21351 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21352 (if (eq special t)
21353 (if (or (< pos (match-beginning 1))
21354 (= pos (match-end 0)))
21355 (goto-char (match-beginning 1))
21356 (goto-char (match-end 0)))
21357 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21358 (goto-char (match-end 0))
21359 (goto-char (match-beginning 1))))
21360 (call-interactively (if (fboundp 'move-end-of-line)
21361 'move-end-of-line
21362 'end-of-line)))))
21363 ((org-at-drawer-p)
21364 (move-end-of-line 1)
21365 (when (overlays-at (1- (point))) (backward-char 1)))
21366 ;; At an item: Move before any hidden text.
21367 (t (call-interactively
21368 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21369 ((fboundp 'move-end-of-line) 'move-end-of-line)
21370 (t 'end-of-line)))))
21371 (org-no-warnings
21372 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21374 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21375 (define-key org-mode-map "\C-e" 'org-end-of-line)
21377 (defun org-backward-sentence (&optional arg)
21378 "Go to beginning of sentence, or beginning of table field.
21379 This will call `backward-sentence' or `org-table-beginning-of-field',
21380 depending on context."
21381 (interactive "P")
21382 (cond
21383 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21384 (t (call-interactively 'backward-sentence))))
21386 (defun org-forward-sentence (&optional arg)
21387 "Go to end of sentence, or end of table field.
21388 This will call `forward-sentence' or `org-table-end-of-field',
21389 depending on context."
21390 (interactive "P")
21391 (cond
21392 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21393 (t (call-interactively 'forward-sentence))))
21395 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21396 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21398 (defun org-kill-line (&optional arg)
21399 "Kill line, to tags or end of line."
21400 (interactive "P")
21401 (cond
21402 ((or (not org-special-ctrl-k)
21403 (bolp)
21404 (not (org-at-heading-p)))
21405 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21406 org-ctrl-k-protect-subtree)
21407 (if (or (eq org-ctrl-k-protect-subtree 'error)
21408 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21409 (error "C-k aborted - would kill hidden subtree")))
21410 (call-interactively
21411 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21412 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21413 (kill-region (point) (match-beginning 1))
21414 (org-set-tags nil t))
21415 (t (kill-region (point) (point-at-eol)))))
21417 (define-key org-mode-map "\C-k" 'org-kill-line)
21419 (defun org-yank (&optional arg)
21420 "Yank. If the kill is a subtree, treat it specially.
21421 This command will look at the current kill and check if is a single
21422 subtree, or a series of subtrees[1]. If it passes the test, and if the
21423 cursor is at the beginning of a line or after the stars of a currently
21424 empty headline, then the yank is handled specially. How exactly depends
21425 on the value of the following variables, both set by default.
21427 org-yank-folded-subtrees
21428 When set, the subtree(s) will be folded after insertion, but only
21429 if doing so would now swallow text after the yanked text.
21431 org-yank-adjusted-subtrees
21432 When set, the subtree will be promoted or demoted in order to
21433 fit into the local outline tree structure, which means that the level
21434 will be adjusted so that it becomes the smaller one of the two
21435 *visible* surrounding headings.
21437 Any prefix to this command will cause `yank' to be called directly with
21438 no special treatment. In particular, a simple \\[universal-argument] prefix \
21439 will just
21440 plainly yank the text as it is.
21442 \[1] The test checks if the first non-white line is a heading
21443 and if there are no other headings with fewer stars."
21444 (interactive "P")
21445 (org-yank-generic 'yank arg))
21447 (defun org-yank-generic (command arg)
21448 "Perform some yank-like command.
21450 This function implements the behavior described in the `org-yank'
21451 documentation. However, it has been generalized to work for any
21452 interactive command with similar behavior."
21454 ;; pretend to be command COMMAND
21455 (setq this-command command)
21457 (if arg
21458 (call-interactively command)
21460 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21461 (and (org-kill-is-subtree-p)
21462 (or (bolp)
21463 (and (looking-at "[ \t]*$")
21464 (string-match
21465 "\\`\\*+\\'"
21466 (buffer-substring (point-at-bol) (point)))))))
21467 swallowp)
21468 (cond
21469 ((and subtreep org-yank-folded-subtrees)
21470 (let ((beg (point))
21471 end)
21472 (if (and subtreep org-yank-adjusted-subtrees)
21473 (org-paste-subtree nil nil 'for-yank)
21474 (call-interactively command))
21476 (setq end (point))
21477 (goto-char beg)
21478 (when (and (bolp) subtreep
21479 (not (setq swallowp
21480 (org-yank-folding-would-swallow-text beg end))))
21481 (org-with-limited-levels
21482 (or (looking-at org-outline-regexp)
21483 (re-search-forward org-outline-regexp-bol end t))
21484 (while (and (< (point) end) (looking-at org-outline-regexp))
21485 (hide-subtree)
21486 (org-cycle-show-empty-lines 'folded)
21487 (condition-case nil
21488 (outline-forward-same-level 1)
21489 (error (goto-char end))))))
21490 (when swallowp
21491 (message
21492 "Inserted text not folded because that would swallow text"))
21494 (goto-char end)
21495 (skip-chars-forward " \t\n\r")
21496 (beginning-of-line 1)
21497 (push-mark beg 'nomsg)))
21498 ((and subtreep org-yank-adjusted-subtrees)
21499 (let ((beg (point-at-bol)))
21500 (org-paste-subtree nil nil 'for-yank)
21501 (push-mark beg 'nomsg)))
21503 (call-interactively command))))))
21505 (defun org-yank-folding-would-swallow-text (beg end)
21506 "Would hide-subtree at BEG swallow any text after END?"
21507 (let (level)
21508 (org-with-limited-levels
21509 (save-excursion
21510 (goto-char beg)
21511 (when (or (looking-at org-outline-regexp)
21512 (re-search-forward org-outline-regexp-bol end t))
21513 (setq level (org-outline-level)))
21514 (goto-char end)
21515 (skip-chars-forward " \t\r\n\v\f")
21516 (if (or (eobp)
21517 (and (bolp) (looking-at org-outline-regexp)
21518 (<= (org-outline-level) level)))
21519 nil ; Nothing would be swallowed
21520 t))))) ; something would swallow
21522 (define-key org-mode-map "\C-y" 'org-yank)
21524 (defun org-truely-invisible-p ()
21525 "Check if point is at a character currently not visible.
21526 This version does not only check the character property, but also
21527 `visible-mode'."
21528 ;; Early versions of noutline don't have `outline-invisible-p'.
21529 (if (org-bound-and-true-p visible-mode)
21531 (outline-invisible-p)))
21533 (defun org-invisible-p2 ()
21534 "Check if point is at a character currently not visible."
21535 (save-excursion
21536 (if (and (eolp) (not (bobp))) (backward-char 1))
21537 ;; Early versions of noutline don't have `outline-invisible-p'.
21538 (outline-invisible-p)))
21540 (defun org-back-to-heading (&optional invisible-ok)
21541 "Call `outline-back-to-heading', but provide a better error message."
21542 (condition-case nil
21543 (outline-back-to-heading invisible-ok)
21544 (error (error "Before first headline at position %d in buffer %s"
21545 (point) (current-buffer)))))
21547 (defun org-beginning-of-defun ()
21548 "Go to the beginning of the subtree, i.e. back to the heading."
21549 (org-back-to-heading))
21550 (defun org-end-of-defun ()
21551 "Go to the end of the subtree."
21552 (org-end-of-subtree nil t))
21554 (defun org-before-first-heading-p ()
21555 "Before first heading?"
21556 (save-excursion
21557 (end-of-line)
21558 (null (re-search-backward org-outline-regexp-bol nil t))))
21560 (defun org-at-heading-p (&optional ignored)
21561 (outline-on-heading-p t))
21562 ;; Compatibility alias with Org versions < 7.8.03
21563 (defalias 'org-on-heading-p 'org-at-heading-p)
21565 (defun org-at-comment-p nil
21566 "Is cursor in a line starting with a # character?"
21567 (save-excursion
21568 (beginning-of-line)
21569 (looking-at "^#")))
21571 (defun org-at-drawer-p nil
21572 "Is cursor at a drawer keyword?"
21573 (save-excursion
21574 (move-beginning-of-line 1)
21575 (looking-at org-drawer-regexp)))
21577 (defun org-at-block-p nil
21578 "Is cursor at a block keyword?"
21579 (save-excursion
21580 (move-beginning-of-line 1)
21581 (looking-at org-block-regexp)))
21583 (defun org-point-at-end-of-empty-headline ()
21584 "If point is at the end of an empty headline, return t, else nil.
21585 If the heading only contains a TODO keyword, it is still still considered
21586 empty."
21587 (and (looking-at "[ \t]*$")
21588 (when org-todo-line-regexp
21589 (save-excursion
21590 (beginning-of-line 1)
21591 (let ((case-fold-search nil))
21592 (looking-at org-todo-line-regexp)
21593 (string= (match-string 3) ""))))))
21595 (defun org-at-heading-or-item-p ()
21596 (or (org-at-heading-p) (org-at-item-p)))
21598 (defun org-at-target-p ()
21599 (or (org-in-regexp org-radio-target-regexp)
21600 (org-in-regexp org-target-regexp)))
21601 ;; Compatibility alias with Org versions < 7.8.03
21602 (defalias 'org-on-target-p 'org-at-target-p)
21604 (defun org-up-heading-all (arg)
21605 "Move to the heading line of which the present line is a subheading.
21606 This function considers both visible and invisible heading lines.
21607 With argument, move up ARG levels."
21608 (if (fboundp 'outline-up-heading-all)
21609 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21610 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21612 (defun org-up-heading-safe ()
21613 "Move to the heading line of which the present line is a subheading.
21614 This version will not throw an error. It will return the level of the
21615 headline found, or nil if no higher level is found.
21617 Also, this function will be a lot faster than `outline-up-heading',
21618 because it relies on stars being the outline starters. This can really
21619 make a significant difference in outlines with very many siblings."
21620 (let (start-level re)
21621 (org-back-to-heading t)
21622 (setq start-level (funcall outline-level))
21623 (if (equal start-level 1)
21625 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21626 (if (re-search-backward re nil t)
21627 (funcall outline-level)))))
21629 (defun org-first-sibling-p ()
21630 "Is this heading the first child of its parents?"
21631 (interactive)
21632 (let ((re org-outline-regexp-bol)
21633 level l)
21634 (unless (org-at-heading-p t)
21635 (error "Not at a heading"))
21636 (setq level (funcall outline-level))
21637 (save-excursion
21638 (if (not (re-search-backward re nil t))
21640 (setq l (funcall outline-level))
21641 (< l level)))))
21643 (defun org-goto-sibling (&optional previous)
21644 "Goto the next sibling, even if it is invisible.
21645 When PREVIOUS is set, go to the previous sibling instead. Returns t
21646 when a sibling was found. When none is found, return nil and don't
21647 move point."
21648 (let ((fun (if previous 're-search-backward 're-search-forward))
21649 (pos (point))
21650 (re org-outline-regexp-bol)
21651 level l)
21652 (when (condition-case nil (org-back-to-heading t) (error nil))
21653 (setq level (funcall outline-level))
21654 (catch 'exit
21655 (or previous (forward-char 1))
21656 (while (funcall fun re nil t)
21657 (setq l (funcall outline-level))
21658 (when (< l level) (goto-char pos) (throw 'exit nil))
21659 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21660 (goto-char pos)
21661 nil))))
21663 (defun org-show-siblings ()
21664 "Show all siblings of the current headline."
21665 (save-excursion
21666 (while (org-goto-sibling) (org-flag-heading nil)))
21667 (save-excursion
21668 (while (org-goto-sibling 'previous)
21669 (org-flag-heading nil))))
21671 (defun org-goto-first-child ()
21672 "Goto the first child, even if it is invisible.
21673 Return t when a child was found. Otherwise don't move point and
21674 return nil."
21675 (let (level (pos (point)) (re org-outline-regexp-bol))
21676 (when (condition-case nil (org-back-to-heading t) (error nil))
21677 (setq level (outline-level))
21678 (forward-char 1)
21679 (if (and (re-search-forward re nil t) (> (outline-level) level))
21680 (progn (goto-char (match-beginning 0)) t)
21681 (goto-char pos) nil))))
21683 (defun org-show-hidden-entry ()
21684 "Show an entry where even the heading is hidden."
21685 (save-excursion
21686 (org-show-entry)))
21688 (defun org-flag-heading (flag &optional entry)
21689 "Flag the current heading. FLAG non-nil means make invisible.
21690 When ENTRY is non-nil, show the entire entry."
21691 (save-excursion
21692 (org-back-to-heading t)
21693 ;; Check if we should show the entire entry
21694 (if entry
21695 (progn
21696 (org-show-entry)
21697 (save-excursion
21698 (and (outline-next-heading)
21699 (org-flag-heading nil))))
21700 (outline-flag-region (max (point-min) (1- (point)))
21701 (save-excursion (outline-end-of-heading) (point))
21702 flag))))
21704 (defun org-get-next-sibling ()
21705 "Move to next heading of the same level, and return point.
21706 If there is no such heading, return nil.
21707 This is like outline-next-sibling, but invisible headings are ok."
21708 (let ((level (funcall outline-level)))
21709 (outline-next-heading)
21710 (while (and (not (eobp)) (> (funcall outline-level) level))
21711 (outline-next-heading))
21712 (if (or (eobp) (< (funcall outline-level) level))
21714 (point))))
21716 (defun org-get-last-sibling ()
21717 "Move to previous heading of the same level, and return point.
21718 If there is no such heading, return nil."
21719 (let ((opoint (point))
21720 (level (funcall outline-level)))
21721 (outline-previous-heading)
21722 (when (and (/= (point) opoint) (outline-on-heading-p t))
21723 (while (and (> (funcall outline-level) level)
21724 (not (bobp)))
21725 (outline-previous-heading))
21726 (if (< (funcall outline-level) level)
21728 (point)))))
21730 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21731 ;; This contains an exact copy of the original function, but it uses
21732 ;; `org-back-to-heading', to make it work also in invisible
21733 ;; trees. And is uses an invisible-OK argument.
21734 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21735 ;; Furthermore, when used inside Org, finding the end of a large subtree
21736 ;; with many children and grandchildren etc, this can be much faster
21737 ;; than the outline version.
21738 (org-back-to-heading invisible-OK)
21739 (let ((first t)
21740 (level (funcall outline-level)))
21741 (if (and (derived-mode-p 'org-mode) (< level 1000))
21742 ;; A true heading (not a plain list item), in Org-mode
21743 ;; This means we can easily find the end by looking
21744 ;; only for the right number of stars. Using a regexp to do
21745 ;; this is so much faster than using a Lisp loop.
21746 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21747 (forward-char 1)
21748 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21749 ;; something else, do it the slow way
21750 (while (and (not (eobp))
21751 (or first (> (funcall outline-level) level)))
21752 (setq first nil)
21753 (outline-next-heading)))
21754 (unless to-heading
21755 (if (memq (preceding-char) '(?\n ?\^M))
21756 (progn
21757 ;; Go to end of line before heading
21758 (forward-char -1)
21759 (if (memq (preceding-char) '(?\n ?\^M))
21760 ;; leave blank line before heading
21761 (forward-char -1))))))
21762 (point))
21764 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21765 "Use Org version in org-mode, for dramatic speed-up."
21766 (if (derived-mode-p 'org-mode)
21767 (progn
21768 (org-end-of-subtree nil t)
21769 (unless (eobp) (backward-char 1)))
21770 ad-do-it))
21772 (defun org-end-of-meta-data-and-drawers ()
21773 "Jump to the first text after meta data and drawers in the current entry.
21774 This will move over empty lines, lines with planning time stamps,
21775 clocking lines, and drawers."
21776 (org-back-to-heading t)
21777 (let ((end (save-excursion (outline-next-heading) (point)))
21778 (re (concat "\\(" org-drawer-regexp "\\)"
21779 "\\|" "[ \t]*" org-keyword-time-regexp)))
21780 (forward-line 1)
21781 (while (re-search-forward re end t)
21782 (if (not (match-end 1))
21783 ;; empty or planning line
21784 (forward-line 1)
21785 ;; a drawer, find the end
21786 (re-search-forward "^[ \t]*:END:" end 'move)
21787 (forward-line 1)))
21788 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21789 (point)))
21791 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21792 "Move forward to the arg'th subheading at same level as this one.
21793 Stop at the first and last subheadings of a superior heading.
21794 Normally this only looks at visible headings, but when INVISIBLE-OK is
21795 non-nil it will also look at invisible ones."
21796 (interactive "p")
21797 (org-back-to-heading invisible-ok)
21798 (org-at-heading-p)
21799 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21800 (re (format "^\\*\\{1,%d\\} " level))
21802 (forward-char 1)
21803 (while (> arg 0)
21804 (while (and (re-search-forward re nil 'move)
21805 (setq l (- (match-end 0) (match-beginning 0) 1))
21806 (= l level)
21807 (not invisible-ok)
21808 (progn (backward-char 1) (outline-invisible-p)))
21809 (if (< l level) (setq arg 1)))
21810 (setq arg (1- arg)))
21811 (beginning-of-line 1)))
21813 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21814 "Move backward to the arg'th subheading at same level as this one.
21815 Stop at the first and last subheadings of a superior heading."
21816 (interactive "p")
21817 (org-back-to-heading)
21818 (org-at-heading-p)
21819 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21820 (re (format "^\\*\\{1,%d\\} " level))
21822 (while (> arg 0)
21823 (while (and (re-search-backward re nil 'move)
21824 (setq l (- (match-end 0) (match-beginning 0) 1))
21825 (= l level)
21826 (not invisible-ok)
21827 (outline-invisible-p))
21828 (if (< l level) (setq arg 1)))
21829 (setq arg (1- arg)))))
21831 ;;;###autoload
21832 (defun org-forward-element ()
21833 "Move forward by one element.
21834 Move to the next element at the same level, when possible."
21835 (interactive)
21836 (cond ((eobp) (error "Cannot move further down"))
21837 ((org-with-limited-levels (org-at-heading-p))
21838 (let ((origin (point)))
21839 (org-forward-heading-same-level 1)
21840 (unless (org-with-limited-levels (org-at-heading-p))
21841 (goto-char origin)
21842 (error "Cannot move further down"))))
21844 (let* ((elem (org-element-at-point))
21845 (end (org-element-property :end elem))
21846 (parent (org-element-property :parent elem)))
21847 (if (and parent (= (org-element-property :contents-end parent) end))
21848 (goto-char (org-element-property :end parent))
21849 (goto-char end))))))
21851 ;;;###autoload
21852 (defun org-backward-element ()
21853 "Move backward by one element.
21854 Move to the previous element at the same level, when possible."
21855 (interactive)
21856 (if (org-with-limited-levels (org-at-heading-p))
21857 ;; At an headline, move to the previous one, if any, or stay
21858 ;; here.
21859 (let ((origin (point)))
21860 (org-backward-heading-same-level 1)
21861 (unless (org-with-limited-levels (org-at-heading-p))
21862 (goto-char origin)
21863 (error "Cannot move further up")))
21864 (let* ((trail (org-element-at-point 'keep-trail))
21865 (elem (car trail))
21866 (prev-elem (nth 1 trail))
21867 (beg (org-element-property :begin elem)))
21868 (cond
21869 ;; Move to beginning of current element if point isn't there
21870 ;; already.
21871 ((/= (point) beg) (goto-char beg))
21872 ((not prev-elem) (error "Cannot move further up"))
21873 (t (goto-char (org-element-property :begin prev-elem)))))))
21875 ;;;###autoload
21876 (defun org-up-element ()
21877 "Move to upper element."
21878 (interactive)
21879 (if (org-with-limited-levels (org-at-heading-p))
21880 (unless (org-up-heading-safe) (error "No surrounding element"))
21881 (let* ((elem (org-element-at-point))
21882 (parent (org-element-property :parent elem)))
21883 (if parent (goto-char (org-element-property :begin parent))
21884 (if (org-with-limited-levels (org-before-first-heading-p))
21885 (error "No surrounding element")
21886 (org-with-limited-levels (org-back-to-heading)))))))
21888 ;;;###autoload
21889 (defvar org-element-greater-elements)
21890 (defun org-down-element ()
21891 "Move to inner element."
21892 (interactive)
21893 (let ((element (org-element-at-point)))
21894 (cond
21895 ((memq (org-element-type element) '(plain-list table))
21896 (goto-char (org-element-property :contents-begin element))
21897 (forward-char))
21898 ((memq (org-element-type element) org-element-greater-elements)
21899 ;; If contents are hidden, first disclose them.
21900 (when (org-element-property :hiddenp element) (org-cycle))
21901 (goto-char (or (org-element-property :contents-begin element)
21902 (error "No content for this element"))))
21903 (t (error "No inner element")))))
21905 ;;;###autoload
21906 (defun org-drag-element-backward ()
21907 "Move backward element at point."
21908 (interactive)
21909 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21910 (let* ((trail (org-element-at-point 'keep-trail))
21911 (elem (car trail))
21912 (prev-elem (nth 1 trail)))
21913 ;; Error out if no previous element or previous element is
21914 ;; a parent of the current one.
21915 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21916 (error "Cannot drag element backward")
21917 (let ((pos (point)))
21918 (org-element-swap-A-B prev-elem elem)
21919 (goto-char (+ (org-element-property :begin prev-elem)
21920 (- pos (org-element-property :begin elem)))))))))
21922 ;;;###autoload
21923 (defun org-drag-element-forward ()
21924 "Move forward element at point."
21925 (interactive)
21926 (let* ((pos (point))
21927 (elem (org-element-at-point)))
21928 (when (= (point-max) (org-element-property :end elem))
21929 (error "Cannot drag element forward"))
21930 (goto-char (org-element-property :end elem))
21931 (let ((next-elem (org-element-at-point)))
21932 (when (or (org-element-nested-p elem next-elem)
21933 (and (eq (org-element-type next-elem) 'headline)
21934 (not (eq (org-element-type elem) 'headline))))
21935 (goto-char pos)
21936 (error "Cannot drag element forward"))
21937 ;; Compute new position of point: it's shifted by NEXT-ELEM
21938 ;; body's length (without final blanks) and by the length of
21939 ;; blanks between ELEM and NEXT-ELEM.
21940 (let ((size-next (- (save-excursion
21941 (goto-char (org-element-property :end next-elem))
21942 (skip-chars-backward " \r\t\n")
21943 (forward-line)
21944 ;; Small correction if buffer doesn't end
21945 ;; with a newline character.
21946 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21947 (org-element-property :begin next-elem)))
21948 (size-blank (- (org-element-property :end elem)
21949 (save-excursion
21950 (goto-char (org-element-property :end elem))
21951 (skip-chars-backward " \r\t\n")
21952 (forward-line)
21953 (point)))))
21954 (org-element-swap-A-B elem next-elem)
21955 (goto-char (+ pos size-next size-blank))))))
21957 ;;;###autoload
21958 (defun org-mark-element ()
21959 "Put point at beginning of this element, mark at end.
21961 Interactively, if this command is repeated or (in Transient Mark
21962 mode) if the mark is active, it marks the next element after the
21963 ones already marked."
21964 (interactive)
21965 (let (deactivate-mark)
21966 (if (or (and (eq last-command this-command) (mark t))
21967 (and transient-mark-mode mark-active))
21968 (set-mark
21969 (save-excursion
21970 (goto-char (mark))
21971 (goto-char (org-element-property :end (org-element-at-point)))))
21972 (let ((element (org-element-at-point)))
21973 (end-of-line)
21974 (push-mark (org-element-property :end element) t t)
21975 (goto-char (org-element-property :begin element))))))
21977 ;;;###autoload
21978 (defun org-narrow-to-element ()
21979 "Narrow buffer to current element."
21980 (interactive)
21981 (let ((elem (org-element-at-point)))
21982 (cond
21983 ((eq (car elem) 'headline)
21984 (narrow-to-region
21985 (org-element-property :begin elem)
21986 (org-element-property :end elem)))
21987 ((memq (car elem) org-element-greater-elements)
21988 (narrow-to-region
21989 (org-element-property :contents-begin elem)
21990 (org-element-property :contents-end elem)))
21992 (narrow-to-region
21993 (org-element-property :begin elem)
21994 (org-element-property :end elem))))))
21996 ;;;###autoload
21997 (defun org-transpose-element ()
21998 "Transpose current and previous elements, keeping blank lines between.
21999 Point is moved after both elements."
22000 (interactive)
22001 (org-skip-whitespace)
22002 (let ((end (org-element-property :end (org-element-at-point))))
22003 (org-drag-element-backward)
22004 (goto-char end)))
22006 ;;;###autoload
22007 (defun org-unindent-buffer ()
22008 "Un-indent the visible part of the buffer.
22009 Relative indentation (between items, inside blocks, etc.) isn't
22010 modified."
22011 (interactive)
22012 (unless (eq major-mode 'org-mode)
22013 (error "Cannot un-indent a buffer not in Org mode"))
22014 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22015 unindent-tree ; For byte-compiler.
22016 (unindent-tree
22017 (function
22018 (lambda (contents)
22019 (mapc
22020 (lambda (element)
22021 (if (memq (org-element-type element) '(headline section))
22022 (funcall unindent-tree (org-element-contents element))
22023 (save-excursion
22024 (save-restriction
22025 (narrow-to-region
22026 (org-element-property :begin element)
22027 (org-element-property :end element))
22028 (org-do-remove-indentation)))))
22029 (reverse contents))))))
22030 (funcall unindent-tree (org-element-contents parse-tree))))
22032 (defun org-show-subtree ()
22033 "Show everything after this heading at deeper levels."
22034 (interactive)
22035 (outline-flag-region
22036 (point)
22037 (save-excursion
22038 (org-end-of-subtree t t))
22039 nil))
22041 (defun org-show-entry ()
22042 "Show the body directly following this heading.
22043 Show the heading too, if it is currently invisible."
22044 (interactive)
22045 (save-excursion
22046 (condition-case nil
22047 (progn
22048 (org-back-to-heading t)
22049 (outline-flag-region
22050 (max (point-min) (1- (point)))
22051 (save-excursion
22052 (if (re-search-forward
22053 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22054 (match-beginning 1)
22055 (point-max)))
22056 nil)
22057 (org-cycle-hide-drawers 'children))
22058 (error nil))))
22060 (defun org-make-options-regexp (kwds &optional extra)
22061 "Make a regular expression for keyword lines."
22062 (concat
22064 "#?[ \t]*\\+\\("
22065 (mapconcat 'regexp-quote kwds "\\|")
22066 (if extra (concat "\\|" extra))
22067 "\\):[ \t]*"
22068 "\\(.*\\)"))
22070 ;; Make isearch reveal the necessary context
22071 (defun org-isearch-end ()
22072 "Reveal context after isearch exits."
22073 (when isearch-success ; only if search was successful
22074 (if (featurep 'xemacs)
22075 ;; Under XEmacs, the hook is run in the correct place,
22076 ;; we directly show the context.
22077 (org-show-context 'isearch)
22078 ;; In Emacs the hook runs *before* restoring the overlays.
22079 ;; So we have to use a one-time post-command-hook to do this.
22080 ;; (Emacs 22 has a special variable, see function `org-mode')
22081 (unless (and (boundp 'isearch-mode-end-hook-quit)
22082 isearch-mode-end-hook-quit)
22083 ;; Only when the isearch was not quitted.
22084 (org-add-hook 'post-command-hook 'org-isearch-post-command
22085 'append 'local)))))
22087 (defun org-isearch-post-command ()
22088 "Remove self from hook, and show context."
22089 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22090 (org-show-context 'isearch))
22093 ;;;; Integration with and fixes for other packages
22095 ;;; Imenu support
22097 (defvar org-imenu-markers nil
22098 "All markers currently used by Imenu.")
22099 (make-variable-buffer-local 'org-imenu-markers)
22101 (defun org-imenu-new-marker (&optional pos)
22102 "Return a new marker for use by Imenu, and remember the marker."
22103 (let ((m (make-marker)))
22104 (move-marker m (or pos (point)))
22105 (push m org-imenu-markers)
22108 (defun org-imenu-get-tree ()
22109 "Produce the index for Imenu."
22110 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22111 (setq org-imenu-markers nil)
22112 (let* ((n org-imenu-depth)
22113 (re (concat "^" (org-get-limited-outline-regexp)))
22114 (subs (make-vector (1+ n) nil))
22115 (last-level 0)
22116 m level head)
22117 (save-excursion
22118 (save-restriction
22119 (widen)
22120 (goto-char (point-max))
22121 (while (re-search-backward re nil t)
22122 (setq level (org-reduced-level (funcall outline-level)))
22123 (when (and (<= level n)
22124 (looking-at org-complex-heading-regexp))
22125 (setq head (org-link-display-format
22126 (org-match-string-no-properties 4))
22127 m (org-imenu-new-marker))
22128 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22129 (if (>= level last-level)
22130 (push (cons head m) (aref subs level))
22131 (push (cons head (aref subs (1+ level))) (aref subs level))
22132 (loop for i from (1+ level) to n do (aset subs i nil)))
22133 (setq last-level level)))))
22134 (aref subs 1)))
22136 (eval-after-load "imenu"
22137 '(progn
22138 (add-hook 'imenu-after-jump-hook
22139 (lambda ()
22140 (if (derived-mode-p 'org-mode)
22141 (org-show-context 'org-goto))))))
22143 (defun org-link-display-format (link)
22144 "Replace a link with either the description, or the link target
22145 if no description is present"
22146 (save-match-data
22147 (if (string-match org-bracket-link-analytic-regexp link)
22148 (replace-match (if (match-end 5)
22149 (match-string 5 link)
22150 (concat (match-string 1 link)
22151 (match-string 3 link)))
22152 nil t link)
22153 link)))
22155 (defun org-toggle-link-display ()
22156 "Toggle the literal or descriptive display of links."
22157 (interactive)
22158 (if org-descriptive-links
22159 (progn (org-remove-from-invisibility-spec '(org-link))
22160 (org-restart-font-lock)
22161 (setq org-descriptive-links nil))
22162 (progn (add-to-invisibility-spec '(org-link))
22163 (org-restart-font-lock)
22164 (setq org-descriptive-links t))))
22166 ;; Speedbar support
22168 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22169 "Overlay marking the agenda restriction line in speedbar.")
22170 (overlay-put org-speedbar-restriction-lock-overlay
22171 'face 'org-agenda-restriction-lock)
22172 (overlay-put org-speedbar-restriction-lock-overlay
22173 'help-echo "Agendas are currently limited to this item.")
22174 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22176 (defun org-speedbar-set-agenda-restriction ()
22177 "Restrict future agenda commands to the location at point in speedbar.
22178 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22179 (interactive)
22180 (require 'org-agenda)
22181 (let (p m tp np dir txt)
22182 (cond
22183 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22184 'org-imenu t))
22185 (setq m (get-text-property p 'org-imenu-marker))
22186 (with-current-buffer (marker-buffer m)
22187 (goto-char m)
22188 (org-agenda-set-restriction-lock 'subtree)))
22189 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22190 'speedbar-function 'speedbar-find-file))
22191 (setq tp (previous-single-property-change
22192 (1+ p) 'speedbar-function)
22193 np (next-single-property-change
22194 tp 'speedbar-function)
22195 dir (speedbar-line-directory)
22196 txt (buffer-substring-no-properties (or tp (point-min))
22197 (or np (point-max))))
22198 (with-current-buffer (find-file-noselect
22199 (let ((default-directory dir))
22200 (expand-file-name txt)))
22201 (unless (derived-mode-p 'org-mode)
22202 (error "Cannot restrict to non-Org-mode file"))
22203 (org-agenda-set-restriction-lock 'file)))
22204 (t (error "Don't know how to restrict Org-mode's agenda")))
22205 (move-overlay org-speedbar-restriction-lock-overlay
22206 (point-at-bol) (point-at-eol))
22207 (setq current-prefix-arg nil)
22208 (org-agenda-maybe-redo)))
22210 (eval-after-load "speedbar"
22211 '(progn
22212 (speedbar-add-supported-extension ".org")
22213 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22214 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22215 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22216 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22217 (add-hook 'speedbar-visiting-tag-hook
22218 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22220 ;;; Fixes and Hacks for problems with other packages
22222 ;; Make flyspell not check words in links, to not mess up our keymap
22223 (defun org-mode-flyspell-verify ()
22224 "Don't let flyspell put overlays at active buttons, or on
22225 {todo,all-time,additional-option-like}-keywords."
22226 (let ((pos (max (1- (point)) (point-min)))
22227 (word (thing-at-point 'word)))
22228 (and (not (get-text-property pos 'keymap))
22229 (not (get-text-property pos 'org-no-flyspell))
22230 (not (member word org-todo-keywords-1))
22231 (not (member word org-all-time-keywords))
22232 (not (member word org-options-keywords))
22233 (not (member word (mapcar 'car org-startup-options)))
22234 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22236 (defun org-remove-flyspell-overlays-in (beg end)
22237 "Remove flyspell overlays in region."
22238 (and (org-bound-and-true-p flyspell-mode)
22239 (fboundp 'flyspell-delete-region-overlays)
22240 (flyspell-delete-region-overlays beg end))
22241 (add-text-properties beg end '(org-no-flyspell t)))
22243 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22244 (eval-after-load "bookmark"
22245 '(if (boundp 'bookmark-after-jump-hook)
22246 ;; We can use the hook
22247 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22248 ;; Hook not available, use advice
22249 (defadvice bookmark-jump (after org-make-visible activate)
22250 "Make the position visible."
22251 (org-bookmark-jump-unhide))))
22253 ;; Make sure saveplace shows the location if it was hidden
22254 (eval-after-load "saveplace"
22255 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22256 "Make the position visible."
22257 (org-bookmark-jump-unhide)))
22259 ;; Make sure ecb shows the location if it was hidden
22260 (eval-after-load "ecb"
22261 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22262 "Make hierarchy visible when jumping into location from ECB tree buffer."
22263 (if (derived-mode-p 'org-mode)
22264 (org-show-context))))
22266 (defun org-bookmark-jump-unhide ()
22267 "Unhide the current position, to show the bookmark location."
22268 (and (derived-mode-p 'org-mode)
22269 (or (outline-invisible-p)
22270 (save-excursion (goto-char (max (point-min) (1- (point))))
22271 (outline-invisible-p)))
22272 (org-show-context 'bookmark-jump)))
22274 ;; Make session.el ignore our circular variable
22275 (eval-after-load "session"
22276 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22278 ;;;; Experimental code
22280 (defun org-closed-in-range ()
22281 "Sparse tree of items closed in a certain time range.
22282 Still experimental, may disappear in the future."
22283 (interactive)
22284 ;; Get the time interval from the user.
22285 (let* ((time1 (org-float-time
22286 (org-read-date nil 'to-time nil "Starting date: ")))
22287 (time2 (org-float-time
22288 (org-read-date nil 'to-time nil "End date:")))
22289 ;; callback function
22290 (callback (lambda ()
22291 (let ((time
22292 (org-float-time
22293 (apply 'encode-time
22294 (org-parse-time-string
22295 (match-string 1))))))
22296 ;; check if time in interval
22297 (and (>= time time1) (<= time time2))))))
22298 ;; make tree, check each match with the callback
22299 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22301 ;;;; Finish up
22303 (provide 'org)
22305 (run-hooks 'org-load-hook)
22307 ;;; org.el ends here