Auto-commit of loaddefs files.
[emacs.git] / lisp / org / org.el
blob9409feca178ee8d6d4db30a788f7ef625f46a35a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 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 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (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)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search.
1223 When nil, you can use these keybindings to navigate the buffer:
1225 q Quit the org-goto interface
1226 n Go to the next visible heading
1227 p Go to the previous visible heading
1228 f Go one heading forward on same level
1229 b Go one heading backward on same level
1230 u Go one heading up"
1231 :group 'org-edit-structure
1232 :type 'boolean)
1234 (defgroup org-sparse-trees nil
1235 "Options concerning sparse trees in Org-mode."
1236 :tag "Org Sparse Trees"
1237 :group 'org-structure)
1239 (defcustom org-highlight-sparse-tree-matches t
1240 "Non-nil means highlight all matches that define a sparse tree.
1241 The highlights will automatically disappear the next time the buffer is
1242 changed by an edit command."
1243 :group 'org-sparse-trees
1244 :type 'boolean)
1246 (defcustom org-remove-highlights-with-change t
1247 "Non-nil means any change to the buffer will remove temporary highlights.
1248 Such highlights are created by `org-occur' and `org-clock-display'.
1249 When nil, `C-c C-c needs to be used to get rid of the highlights.
1250 The highlights created by `org-preview-latex-fragment' always need
1251 `C-c C-c' to be removed."
1252 :group 'org-sparse-trees
1253 :group 'org-time
1254 :type 'boolean)
1257 (defcustom org-occur-hook '(org-first-headline-recenter)
1258 "Hook that is run after `org-occur' has constructed a sparse tree.
1259 This can be used to recenter the window to show as much of the structure
1260 as possible."
1261 :group 'org-sparse-trees
1262 :type 'hook)
1264 (defgroup org-imenu-and-speedbar nil
1265 "Options concerning imenu and speedbar in Org-mode."
1266 :tag "Org Imenu and Speedbar"
1267 :group 'org-structure)
1269 (defcustom org-imenu-depth 2
1270 "The maximum level for Imenu access to Org-mode headlines.
1271 This also applied for speedbar access."
1272 :group 'org-imenu-and-speedbar
1273 :type 'integer)
1275 (defgroup org-table nil
1276 "Options concerning tables in Org-mode."
1277 :tag "Org Table"
1278 :group 'org)
1280 (defcustom org-enable-table-editor 'optimized
1281 "Non-nil means lines starting with \"|\" are handled by the table editor.
1282 When nil, such lines will be treated like ordinary lines.
1284 When equal to the symbol `optimized', the table editor will be optimized to
1285 do the following:
1286 - Automatic overwrite mode in front of whitespace in table fields.
1287 This makes the structure of the table stay in tact as long as the edited
1288 field does not exceed the column width.
1289 - Minimize the number of realigns. Normally, the table is aligned each time
1290 TAB or RET are pressed to move to another field. With optimization this
1291 happens only if changes to a field might have changed the column width.
1292 Optimization requires replacing the functions `self-insert-command',
1293 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1294 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1295 very good at guessing when a re-align will be necessary, but you can always
1296 force one with \\[org-ctrl-c-ctrl-c].
1298 If you would like to use the optimized version in Org-mode, but the
1299 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1301 This variable can be used to turn on and off the table editor during a session,
1302 but in order to toggle optimization, a restart is required.
1304 See also the variable `org-table-auto-blank-field'."
1305 :group 'org-table
1306 :type '(choice
1307 (const :tag "off" nil)
1308 (const :tag "on" t)
1309 (const :tag "on, optimized" optimized)))
1311 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1312 (version<= emacs-version "24.1"))
1313 "Non-nil means cluster self-insert commands for undo when possible.
1314 If this is set, then, like in the Emacs command loop, 20 consecutive
1315 characters will be undone together.
1316 This is configurable, because there is some impact on typing performance."
1317 :group 'org-table
1318 :type 'boolean)
1320 (defcustom org-table-tab-recognizes-table.el t
1321 "Non-nil means TAB will automatically notice a table.el table.
1322 When it sees such a table, it moves point into it and - if necessary -
1323 calls `table-recognize-table'."
1324 :group 'org-table-editing
1325 :type 'boolean)
1327 (defgroup org-link nil
1328 "Options concerning links in Org-mode."
1329 :tag "Org Link"
1330 :group 'org)
1332 (defvar org-link-abbrev-alist-local nil
1333 "Buffer-local version of `org-link-abbrev-alist', which see.
1334 The value of this is taken from the #+LINK lines.")
1335 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1337 (defcustom org-link-abbrev-alist nil
1338 "Alist of link abbreviations.
1339 The car of each element is a string, to be replaced at the start of a link.
1340 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1341 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1343 [[linkkey:tag][description]]
1345 The 'linkkey' must be a word word, starting with a letter, followed
1346 by letters, numbers, '-' or '_'.
1348 If REPLACE is a string, the tag will simply be appended to create the link.
1349 If the string contains \"%s\", the tag will be inserted there. If the string
1350 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1351 at that point (see the function `url-hexify-string'). If the string contains
1352 the specifier \"%(my-function)\", then the custom function `my-function' will
1353 be invoked: this function takes the tag as its only argument and must return
1354 a string.
1356 REPLACE may also be a function that will be called with the tag as the
1357 only argument to create the link, which should be returned as a string.
1359 See the manual for examples."
1360 :group 'org-link
1361 :type '(repeat
1362 (cons
1363 (string :tag "Protocol")
1364 (choice
1365 (string :tag "Format")
1366 (function)))))
1368 (defcustom org-descriptive-links t
1369 "Non-nil means Org will display descriptive links.
1370 E.g. [[http://orgmode.org][Org website]] will be displayed as
1371 \"Org Website\", hiding the link itself and just displaying its
1372 description. When set to `nil', Org will display the full links
1373 literally.
1375 You can interactively set the value of this variable by calling
1376 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1377 :group 'org-link
1378 :type 'boolean)
1380 (defcustom org-link-file-path-type 'adaptive
1381 "How the path name in file links should be stored.
1382 Valid values are:
1384 relative Relative to the current directory, i.e. the directory of the file
1385 into which the link is being inserted.
1386 absolute Absolute path, if possible with ~ for home directory.
1387 noabbrev Absolute path, no abbreviation of home directory.
1388 adaptive Use relative path for files in the current directory and sub-
1389 directories of it. For other files, use an absolute path."
1390 :group 'org-link
1391 :type '(choice
1392 (const relative)
1393 (const absolute)
1394 (const noabbrev)
1395 (const adaptive)))
1397 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1398 "Types of links that should be activated in Org-mode files.
1399 This is a list of symbols, each leading to the activation of a certain link
1400 type. In principle, it does not hurt to turn on most link types - there may
1401 be a small gain when turning off unused link types. The types are:
1403 bracket The recommended [[link][description]] or [[link]] links with hiding.
1404 angle Links in angular brackets that may contain whitespace like
1405 <bbdb:Carsten Dominik>.
1406 plain Plain links in normal text, no whitespace, like http://google.com.
1407 radio Text that is matched by a radio target, see manual for details.
1408 tag Tag settings in a headline (link to tag search).
1409 date Time stamps (link to calendar).
1410 footnote Footnote labels.
1412 Changing this variable requires a restart of Emacs to become effective."
1413 :group 'org-link
1414 :type '(set :greedy t
1415 (const :tag "Double bracket links" bracket)
1416 (const :tag "Angular bracket links" angle)
1417 (const :tag "Plain text links" plain)
1418 (const :tag "Radio target matches" radio)
1419 (const :tag "Tags" tag)
1420 (const :tag "Timestamps" date)
1421 (const :tag "Footnotes" footnote)))
1423 (defcustom org-make-link-description-function nil
1424 "Function to use for generating link descriptions from links.
1425 When nil, the link location will be used. This function must take
1426 two parameters: the first one is the link, the second one is the
1427 description generated by `org-insert-link'. The function should
1428 return the description to use."
1429 :group 'org-link
1430 :type 'function)
1432 (defgroup org-link-store nil
1433 "Options concerning storing links in Org-mode."
1434 :tag "Org Store Link"
1435 :group 'org-link)
1437 (defcustom org-url-hexify-p t
1438 "When non-nil, hexify URL when creating a link."
1439 :type 'boolean
1440 :version "24.3"
1441 :group 'org-link-store)
1443 (defcustom org-email-link-description-format "Email %c: %.30s"
1444 "Format of the description part of a link to an email or usenet message.
1445 The following %-escapes will be replaced by corresponding information:
1447 %F full \"From\" field
1448 %f name, taken from \"From\" field, address if no name
1449 %T full \"To\" field
1450 %t first name in \"To\" field, address if no name
1451 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1452 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1453 %s subject
1454 %d date
1455 %m message-id.
1457 You may use normal field width specification between the % and the letter.
1458 This is for example useful to limit the length of the subject.
1460 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1461 :group 'org-link-store
1462 :type 'string)
1464 (defcustom org-from-is-user-regexp
1465 (let (r1 r2)
1466 (when (and user-mail-address (not (string= user-mail-address "")))
1467 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1468 (when (and user-full-name (not (string= user-full-name "")))
1469 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1470 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1471 "Regexp matched against the \"From:\" header of an email or usenet message.
1472 It should match if the message is from the user him/herself."
1473 :group 'org-link-store
1474 :type 'regexp)
1476 (defcustom org-context-in-file-links t
1477 "Non-nil means file links from `org-store-link' contain context.
1478 A search string will be added to the file name with :: as separator and
1479 used to find the context when the link is activated by the command
1480 `org-open-at-point'. When this option is t, the entire active region
1481 will be placed in the search string of the file link. If set to a
1482 positive integer, only the first n lines of context will be stored.
1484 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1485 negates this setting for the duration of the command."
1486 :group 'org-link-store
1487 :type '(choice boolean integer))
1489 (defcustom org-keep-stored-link-after-insertion nil
1490 "Non-nil means keep link in list for entire session.
1492 The command `org-store-link' adds a link pointing to the current
1493 location to an internal list. These links accumulate during a session.
1494 The command `org-insert-link' can be used to insert links into any
1495 Org-mode file (offering completion for all stored links). When this
1496 option is nil, every link which has been inserted once using \\[org-insert-link]
1497 will be removed from the list, to make completing the unused links
1498 more efficient."
1499 :group 'org-link-store
1500 :type 'boolean)
1502 (defgroup org-link-follow nil
1503 "Options concerning following links in Org-mode."
1504 :tag "Org Follow Link"
1505 :group 'org-link)
1507 (defcustom org-link-translation-function nil
1508 "Function to translate links with different syntax to Org syntax.
1509 This can be used to translate links created for example by the Planner
1510 or emacs-wiki packages to Org syntax.
1511 The function must accept two parameters, a TYPE containing the link
1512 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1513 which is everything after the link protocol. It should return a cons
1514 with possibly modified values of type and path.
1515 Org contains a function for this, so if you set this variable to
1516 `org-translate-link-from-planner', you should be able follow many
1517 links created by planner."
1518 :group 'org-link-follow
1519 :type 'function)
1521 (defcustom org-follow-link-hook nil
1522 "Hook that is run after a link has been followed."
1523 :group 'org-link-follow
1524 :type 'hook)
1526 (defcustom org-tab-follows-link nil
1527 "Non-nil means on links TAB will follow the link.
1528 Needs to be set before org.el is loaded.
1529 This really should not be used, it does not make sense, and the
1530 implementation is bad."
1531 :group 'org-link-follow
1532 :type 'boolean)
1534 (defcustom org-return-follows-link nil
1535 "Non-nil means on links RET will follow the link."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mouse-1-follows-link
1540 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1541 "Non-nil means mouse-1 on a link will follow the link.
1542 A longer mouse click will still set point. Does not work on XEmacs.
1543 Needs to be set before org.el is loaded."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-mark-ring-length 4
1548 "Number of different positions to be recorded in the ring.
1549 Changing this requires a restart of Emacs to work correctly."
1550 :group 'org-link-follow
1551 :type 'integer)
1553 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1554 "Non-nil means internal links in Org files must exactly match a headline.
1555 When nil, the link search tries to match a phrase with all words
1556 in the search text."
1557 :group 'org-link-follow
1558 :version "24.1"
1559 :type '(choice
1560 (const :tag "Use fuzzy text search" nil)
1561 (const :tag "Match only exact headline" t)
1562 (const :tag "Match exact headline or query to create it"
1563 query-to-create)))
1565 (defcustom org-link-frame-setup
1566 '((vm . vm-visit-folder-other-frame)
1567 (vm-imap . vm-visit-imap-folder-other-frame)
1568 (gnus . org-gnus-no-new-news)
1569 (file . find-file-other-window)
1570 (wl . wl-other-frame))
1571 "Setup the frame configuration for following links.
1572 When following a link with Emacs, it may often be useful to display
1573 this link in another window or frame. This variable can be used to
1574 set this up for the different types of links.
1575 For VM, use any of
1576 `vm-visit-folder'
1577 `vm-visit-folder-other-window'
1578 `vm-visit-folder-other-frame'
1579 For Gnus, use any of
1580 `gnus'
1581 `gnus-other-frame'
1582 `org-gnus-no-new-news'
1583 For FILE, use any of
1584 `find-file'
1585 `find-file-other-window'
1586 `find-file-other-frame'
1587 For Wanderlust use any of
1588 `wl'
1589 `wl-other-frame'
1590 For the calendar, use the variable `calendar-setup'.
1591 For BBDB, it is currently only possible to display the matches in
1592 another window."
1593 :group 'org-link-follow
1594 :type '(list
1595 (cons (const vm)
1596 (choice
1597 (const vm-visit-folder)
1598 (const vm-visit-folder-other-window)
1599 (const vm-visit-folder-other-frame)))
1600 (cons (const gnus)
1601 (choice
1602 (const gnus)
1603 (const gnus-other-frame)
1604 (const org-gnus-no-new-news)))
1605 (cons (const file)
1606 (choice
1607 (const find-file)
1608 (const find-file-other-window)
1609 (const find-file-other-frame)))
1610 (cons (const wl)
1611 (choice
1612 (const wl)
1613 (const wl-other-frame)))))
1615 (defcustom org-display-internal-link-with-indirect-buffer nil
1616 "Non-nil means use indirect buffer to display infile links.
1617 Activating internal links (from one location in a file to another location
1618 in the same file) normally just jumps to the location. When the link is
1619 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1620 is displayed in
1621 another window. When this option is set, the other window actually displays
1622 an indirect buffer clone of the current buffer, to avoid any visibility
1623 changes to the current buffer."
1624 :group 'org-link-follow
1625 :type 'boolean)
1627 (defcustom org-open-non-existing-files nil
1628 "Non-nil means `org-open-file' will open non-existing files.
1629 When nil, an error will be generated.
1630 This variable applies only to external applications because they
1631 might choke on non-existing files. If the link is to a file that
1632 will be opened in Emacs, the variable is ignored."
1633 :group 'org-link-follow
1634 :type 'boolean)
1636 (defcustom org-open-directory-means-index-dot-org nil
1637 "Non-nil means a link to a directory really means to index.org.
1638 When nil, following a directory link will run dired or open a finder/explorer
1639 window on that directory."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1644 "Function and arguments to call for following mailto links.
1645 This is a list with the first element being a Lisp function, and the
1646 remaining elements being arguments to the function. In string arguments,
1647 %a will be replaced by the address, and %s will be replaced by the subject
1648 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1649 :group 'org-link-follow
1650 :type '(choice
1651 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1652 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1653 (const :tag "message-mail" (message-mail "%a" "%s"))
1654 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1656 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing shell links.
1658 Shell links can be dangerous: just think about a link
1660 [[shell:rm -rf ~/*][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-shell-link-not-regexp ""
1677 "A regexp to skip confirmation for shell links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1683 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1684 Elisp links can be dangerous: just think about a link
1686 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1688 This link would show up in your Org-mode document as \"Google Search\",
1689 but really it would remove your entire home directory.
1690 Therefore we advise against setting this variable to nil.
1691 Just change it to `y-or-n-p' if you want to confirm with a
1692 single keystroke rather than having to type \"yes\"."
1693 :group 'org-link-follow
1694 :type '(choice
1695 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1696 (const :tag "with y-or-n (faster)" y-or-n-p)
1697 (const :tag "no confirmation (dangerous)" nil)))
1698 (put 'org-confirm-shell-link-function
1699 'safe-local-variable
1700 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1702 (defcustom org-confirm-elisp-link-not-regexp ""
1703 "A regexp to skip confirmation for Elisp links."
1704 :group 'org-link-follow
1705 :version "24.1"
1706 :type 'regexp)
1708 (defconst org-file-apps-defaults-gnu
1709 '((remote . emacs)
1710 (system . mailcap)
1711 (t . mailcap))
1712 "Default file applications on a UNIX or GNU/Linux system.
1713 See `org-file-apps'.")
1715 (defconst org-file-apps-defaults-macosx
1716 '((remote . emacs)
1717 (t . "open %s")
1718 (system . "open %s")
1719 ("ps.gz" . "gv %s")
1720 ("eps.gz" . "gv %s")
1721 ("dvi" . "xdvi %s")
1722 ("fig" . "xfig %s"))
1723 "Default file applications on a MacOS X system.
1724 The system \"open\" is known as a default, but we use X11 applications
1725 for some files for which the OS does not have a good default.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-windowsnt
1729 (list
1730 '(remote . emacs)
1731 (cons t
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file))
1736 (cons 'system
1737 (list (if (featurep 'xemacs)
1738 'mswindows-shell-execute
1739 'w32-shell-execute)
1740 "open" 'file)))
1741 "Default file applications on a Windows NT system.
1742 The system \"open\" is used for most files.
1743 See `org-file-apps'.")
1745 (defcustom org-file-apps
1747 (auto-mode . emacs)
1748 ("\\.mm\\'" . default)
1749 ("\\.x?html?\\'" . default)
1750 ("\\.pdf\\'" . default)
1752 "External applications for opening `file:path' items in a document.
1753 Org-mode uses system defaults for different file types, but
1754 you can use this variable to set the application for a given file
1755 extension. The entries in this list are cons cells where the car identifies
1756 files and the cdr the corresponding command. Possible values for the
1757 file identifier are
1758 \"string\" A string as a file identifier can be interpreted in different
1759 ways, depending on its contents:
1761 - Alphanumeric characters only:
1762 Match links with this file extension.
1763 Example: (\"pdf\" . \"evince %s\")
1764 to open PDFs with evince.
1766 - Regular expression: Match links where the
1767 filename matches the regexp. If you want to
1768 use groups here, use shy groups.
1770 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1771 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1772 to open *.html and *.xhtml with firefox.
1774 - Regular expression which contains (non-shy) groups:
1775 Match links where the whole link, including \"::\", and
1776 anything after that, matches the regexp.
1777 In a custom command string, %1, %2, etc. are replaced with
1778 the parts of the link that were matched by the groups.
1779 For backwards compatibility, if a command string is given
1780 that does not use any of the group matches, this case is
1781 handled identically to the second one (i.e. match against
1782 file name only).
1783 In a custom lisp form, you can access the group matches with
1784 (match-string n link).
1786 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1787 to open [[file:document.pdf::5]] with evince at page 5.
1789 `directory' Matches a directory
1790 `remote' Matches a remote file, accessible through tramp or efs.
1791 Remote files most likely should be visited through Emacs
1792 because external applications cannot handle such paths.
1793 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1794 so all files Emacs knows how to handle. Using this with
1795 command `emacs' will open most files in Emacs. Beware that this
1796 will also open html files inside Emacs, unless you add
1797 (\"html\" . default) to the list as well.
1798 t Default for files not matched by any of the other options.
1799 `system' The system command to open files, like `open' on Windows
1800 and Mac OS X, and mailcap under GNU/Linux. This is the command
1801 that will be selected if you call `C-c C-o' with a double
1802 \\[universal-argument] \\[universal-argument] prefix.
1804 Possible values for the command are:
1805 `emacs' The file will be visited by the current Emacs process.
1806 `default' Use the default application for this file type, which is the
1807 association for t in the list, most likely in the system-specific
1808 part.
1809 This can be used to overrule an unwanted setting in the
1810 system-specific variable.
1811 `system' Use the system command for opening files, like \"open\".
1812 This command is specified by the entry whose car is `system'.
1813 Most likely, the system-specific version of this variable
1814 does define this command, but you can overrule/replace it
1815 here.
1816 string A command to be executed by a shell; %s will be replaced
1817 by the path to the file.
1818 sexp A Lisp form which will be evaluated. The file path will
1819 be available in the Lisp variable `file'.
1820 For more examples, see the system specific constants
1821 `org-file-apps-defaults-macosx'
1822 `org-file-apps-defaults-windowsnt'
1823 `org-file-apps-defaults-gnu'."
1824 :group 'org-link-follow
1825 :type '(repeat
1826 (cons (choice :value ""
1827 (string :tag "Extension")
1828 (const :tag "System command to open files" system)
1829 (const :tag "Default for unrecognized files" t)
1830 (const :tag "Remote file" remote)
1831 (const :tag "Links to a directory" directory)
1832 (const :tag "Any files that have Emacs modes"
1833 auto-mode))
1834 (choice :value ""
1835 (const :tag "Visit with Emacs" emacs)
1836 (const :tag "Use default" default)
1837 (const :tag "Use the system command" system)
1838 (string :tag "Command")
1839 (sexp :tag "Lisp form")))))
1841 (defcustom org-doi-server-url "http://dx.doi.org/"
1842 "The URL of the DOI server."
1843 :type 'string
1844 :version "24.3"
1845 :group 'org-link-follow)
1847 (defgroup org-refile nil
1848 "Options concerning refiling entries in Org-mode."
1849 :tag "Org Refile"
1850 :group 'org)
1852 (defcustom org-directory "~/org"
1853 "Directory with org files.
1854 This is just a default location to look for Org files. There is no need
1855 at all to put your files into this directory. It is only used in the
1856 following situations:
1858 1. When a capture template specifies a target file that is not an
1859 absolute path. The path will then be interpreted relative to
1860 `org-directory'
1861 2. When a capture note is filed away in an interactive way (when exiting the
1862 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1863 with `org-directory' as the default path."
1864 :group 'org-refile
1865 :group 'org-remember
1866 :group 'org-capture
1867 :type 'directory)
1869 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1870 "Default target for storing notes.
1871 Used as a fall back file for org-remember.el and org-capture.el, for
1872 templates that do not specify a target file."
1873 :group 'org-refile
1874 :group 'org-remember
1875 :group 'org-capture
1876 :type '(choice
1877 (const :tag "Default from remember-data-file" nil)
1878 file))
1880 (defcustom org-goto-interface 'outline
1881 "The default interface to be used for `org-goto'.
1882 Allowed values are:
1883 outline The interface shows an outline of the relevant file
1884 and the correct heading is found by moving through
1885 the outline or by searching with incremental search.
1886 outline-path-completion Headlines in the current buffer are offered via
1887 completion. This is the interface also used by
1888 the refile command."
1889 :group 'org-refile
1890 :type '(choice
1891 (const :tag "Outline" outline)
1892 (const :tag "Outline-path-completion" outline-path-completion)))
1894 (defcustom org-goto-max-level 5
1895 "Maximum target level when running `org-goto' with refile interface."
1896 :group 'org-refile
1897 :type 'integer)
1899 (defcustom org-reverse-note-order nil
1900 "Non-nil means store new notes at the beginning of a file or entry.
1901 When nil, new notes will be filed to the end of a file or entry.
1902 This can also be a list with cons cells of regular expressions that
1903 are matched against file names, and values."
1904 :group 'org-remember
1905 :group 'org-capture
1906 :group 'org-refile
1907 :type '(choice
1908 (const :tag "Reverse always" t)
1909 (const :tag "Reverse never" nil)
1910 (repeat :tag "By file name regexp"
1911 (cons regexp boolean))))
1913 (defcustom org-log-refile nil
1914 "Information to record when a task is refiled.
1916 Possible values are:
1918 nil Don't add anything
1919 time Add a time stamp to the task
1920 note Prompt for a note and add it with template `org-log-note-headings'
1922 This option can also be set with on a per-file-basis with
1924 #+STARTUP: nologrefile
1925 #+STARTUP: logrefile
1926 #+STARTUP: lognoterefile
1928 You can have local logging settings for a subtree by setting the LOGGING
1929 property to one or more of these keywords.
1931 When bulk-refiling from the agenda, the value `note' is forbidden and
1932 will temporarily be changed to `time'."
1933 :group 'org-refile
1934 :group 'org-progress
1935 :version "24.1"
1936 :type '(choice
1937 (const :tag "No logging" nil)
1938 (const :tag "Record timestamp" time)
1939 (const :tag "Record timestamp with note." note)))
1941 (defcustom org-refile-targets nil
1942 "Targets for refiling entries with \\[org-refile].
1943 This is a list of cons cells. Each cell contains:
1944 - a specification of the files to be considered, either a list of files,
1945 or a symbol whose function or variable value will be used to retrieve
1946 a file name or a list of file names. If you use `org-agenda-files' for
1947 that, all agenda files will be scanned for targets. Nil means consider
1948 headings in the current buffer.
1949 - A specification of how to find candidate refile targets. This may be
1950 any of:
1951 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1952 This tag has to be present in all target headlines, inheritance will
1953 not be considered.
1954 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1955 todo keyword.
1956 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1957 headlines that are refiling targets.
1958 - a cons cell (:level . N). Any headline of level N is considered a target.
1959 Note that, when `org-odd-levels-only' is set, level corresponds to
1960 order in hierarchy, not to the number of stars.
1961 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1962 Note that, when `org-odd-levels-only' is set, level corresponds to
1963 order in hierarchy, not to the number of stars.
1965 Each element of this list generates a set of possible targets.
1966 The union of these sets is presented (with completion) to
1967 the user by `org-refile'.
1969 You can set the variable `org-refile-target-verify-function' to a function
1970 to verify each headline found by the simple criteria above.
1972 When this variable is nil, all top-level headlines in the current buffer
1973 are used, equivalent to the value `((nil . (:level . 1))'."
1974 :group 'org-refile
1975 :type '(repeat
1976 (cons
1977 (choice :value org-agenda-files
1978 (const :tag "All agenda files" org-agenda-files)
1979 (const :tag "Current buffer" nil)
1980 (function) (variable) (file))
1981 (choice :tag "Identify target headline by"
1982 (cons :tag "Specific tag" (const :value :tag) (string))
1983 (cons :tag "TODO keyword" (const :value :todo) (string))
1984 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1985 (cons :tag "Level number" (const :value :level) (integer))
1986 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1988 (defcustom org-refile-target-verify-function nil
1989 "Function to verify if the headline at point should be a refile target.
1990 The function will be called without arguments, with point at the
1991 beginning of the headline. It should return t and leave point
1992 where it is if the headline is a valid target for refiling.
1994 If the target should not be selected, the function must return nil.
1995 In addition to this, it may move point to a place from where the search
1996 should be continued. For example, the function may decide that the entire
1997 subtree of the current entry should be excluded and move point to the end
1998 of the subtree."
1999 :group 'org-refile
2000 :type 'function)
2002 (defcustom org-refile-use-cache nil
2003 "Non-nil means cache refile targets to speed up the process.
2004 The cache for a particular file will be updated automatically when
2005 the buffer has been killed, or when any of the marker used for flagging
2006 refile targets no longer points at a live buffer.
2007 If you have added new entries to a buffer that might themselves be targets,
2008 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2009 find that easier, `C-u C-u C-u C-c C-w'."
2010 :group 'org-refile
2011 :version "24.1"
2012 :type 'boolean)
2014 (defcustom org-refile-use-outline-path nil
2015 "Non-nil means provide refile targets as paths.
2016 So a level 3 headline will be available as level1/level2/level3.
2018 When the value is `file', also include the file name (without directory)
2019 into the path. In this case, you can also stop the completion after
2020 the file name, to get entries inserted as top level in the file.
2022 When `full-file-path', include the full file path."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Not" nil)
2026 (const :tag "Yes" t)
2027 (const :tag "Start with file name" file)
2028 (const :tag "Start with full file path" full-file-path)))
2030 (defcustom org-outline-path-complete-in-steps t
2031 "Non-nil means complete the outline path in hierarchical steps.
2032 When Org-mode uses the refile interface to select an outline path
2033 \(see variable `org-refile-use-outline-path'), the completion of
2034 the path can be done is a single go, or if can be done in steps down
2035 the headline hierarchy. Going in steps is probably the best if you
2036 do not use a special completion package like `ido' or `icicles'.
2037 However, when using these packages, going in one step can be very
2038 fast, while still showing the whole path to the entry."
2039 :group 'org-refile
2040 :type 'boolean)
2042 (defcustom org-refile-allow-creating-parent-nodes nil
2043 "Non-nil means allow to create new nodes as refile targets.
2044 New nodes are then created by adding \"/new node name\" to the completion
2045 of an existing node. When the value of this variable is `confirm',
2046 new node creation must be confirmed by the user (recommended)
2047 When nil, the completion must match an existing entry.
2049 Note that, if the new heading is not seen by the criteria
2050 listed in `org-refile-targets', multiple instances of the same
2051 heading would be created by trying again to file under the new
2052 heading."
2053 :group 'org-refile
2054 :type '(choice
2055 (const :tag "Never" nil)
2056 (const :tag "Always" t)
2057 (const :tag "Prompt for confirmation" confirm)))
2059 (defcustom org-refile-active-region-within-subtree nil
2060 "Non-nil means also refile active region within a subtree.
2062 By default `org-refile' doesn't allow refiling regions if they
2063 don't contain a set of subtrees, but it might be convenient to
2064 do so sometimes: in that case, the first line of the region is
2065 converted to a headline before refiling."
2066 :group 'org-refile
2067 :version "24.1"
2068 :type 'boolean)
2070 (defgroup org-todo nil
2071 "Options concerning TODO items in Org-mode."
2072 :tag "Org TODO"
2073 :group 'org)
2075 (defgroup org-progress nil
2076 "Options concerning Progress logging in Org-mode."
2077 :tag "Org Progress"
2078 :group 'org-time)
2080 (defvar org-todo-interpretation-widgets
2081 '((:tag "Sequence (cycling hits every state)" sequence)
2082 (:tag "Type (cycling directly to DONE)" type))
2083 "The available interpretation symbols for customizing `org-todo-keywords'.
2084 Interested libraries should add to this list.")
2086 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2087 "List of TODO entry keyword sequences and their interpretation.
2088 \\<org-mode-map>This is a list of sequences.
2090 Each sequence starts with a symbol, either `sequence' or `type',
2091 indicating if the keywords should be interpreted as a sequence of
2092 action steps, or as different types of TODO items. The first
2093 keywords are states requiring action - these states will select a headline
2094 for inclusion into the global TODO list Org-mode produces. If one of
2095 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2096 signify that no further action is necessary. If \"|\" is not found,
2097 the last keyword is treated as the only DONE state of the sequence.
2099 The command \\[org-todo] cycles an entry through these states, and one
2100 additional state where no keyword is present. For details about this
2101 cycling, see the manual.
2103 TODO keywords and interpretation can also be set on a per-file basis with
2104 the special #+SEQ_TODO and #+TYP_TODO lines.
2106 Each keyword can optionally specify a character for fast state selection
2107 \(in combination with the variable `org-use-fast-todo-selection')
2108 and specifiers for state change logging, using the same syntax that
2109 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2110 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2111 indicates to record a time stamp each time this state is selected.
2113 Each keyword may also specify if a timestamp or a note should be
2114 recorded when entering or leaving the state, by adding additional
2115 characters in the parenthesis after the keyword. This looks like this:
2116 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2117 record only the time of the state change. With X and Y being either
2118 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2119 Y when leaving the state if and only if the *target* state does not
2120 define X. You may omit any of the fast-selection key or X or /Y,
2121 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2123 For backward compatibility, this variable may also be just a list
2124 of keywords. In this case the interpretation (sequence or type) will be
2125 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2126 :group 'org-todo
2127 :group 'org-keywords
2128 :type '(choice
2129 (repeat :tag "Old syntax, just keywords"
2130 (string :tag "Keyword"))
2131 (repeat :tag "New syntax"
2132 (cons
2133 (choice
2134 :tag "Interpretation"
2135 ;;Quick and dirty way to see
2136 ;;`org-todo-interpretations'. This takes the
2137 ;;place of item arguments
2138 :convert-widget
2139 (lambda (widget)
2140 (widget-put widget
2141 :args (mapcar
2142 #'(lambda (x)
2143 (widget-convert
2144 (cons 'const x)))
2145 org-todo-interpretation-widgets))
2146 widget))
2147 (repeat
2148 (string :tag "Keyword"))))))
2150 (defvar org-todo-keywords-1 nil
2151 "All TODO and DONE keywords active in a buffer.")
2152 (make-variable-buffer-local 'org-todo-keywords-1)
2153 (defvar org-todo-keywords-for-agenda nil)
2154 (defvar org-done-keywords-for-agenda nil)
2155 (defvar org-drawers-for-agenda nil)
2156 (defvar org-todo-keyword-alist-for-agenda nil)
2157 (defvar org-tag-alist-for-agenda nil)
2158 (defvar org-agenda-contributing-files nil)
2159 (defvar org-not-done-keywords nil)
2160 (make-variable-buffer-local 'org-not-done-keywords)
2161 (defvar org-done-keywords nil)
2162 (make-variable-buffer-local 'org-done-keywords)
2163 (defvar org-todo-heads nil)
2164 (make-variable-buffer-local 'org-todo-heads)
2165 (defvar org-todo-sets nil)
2166 (make-variable-buffer-local 'org-todo-sets)
2167 (defvar org-todo-log-states nil)
2168 (make-variable-buffer-local 'org-todo-log-states)
2169 (defvar org-todo-kwd-alist nil)
2170 (make-variable-buffer-local 'org-todo-kwd-alist)
2171 (defvar org-todo-key-alist nil)
2172 (make-variable-buffer-local 'org-todo-key-alist)
2173 (defvar org-todo-key-trigger nil)
2174 (make-variable-buffer-local 'org-todo-key-trigger)
2176 (defcustom org-todo-interpretation 'sequence
2177 "Controls how TODO keywords are interpreted.
2178 This variable is in principle obsolete and is only used for
2179 backward compatibility, if the interpretation of todo keywords is
2180 not given already in `org-todo-keywords'. See that variable for
2181 more information."
2182 :group 'org-todo
2183 :group 'org-keywords
2184 :type '(choice (const sequence)
2185 (const type)))
2187 (defcustom org-use-fast-todo-selection t
2188 "Non-nil means use the fast todo selection scheme with C-c C-t.
2189 This variable describes if and under what circumstances the cycling
2190 mechanism for TODO keywords will be replaced by a single-key, direct
2191 selection scheme.
2193 When nil, fast selection is never used.
2195 When the symbol `prefix', it will be used when `org-todo' is called
2196 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2197 `C-u t' in an agenda buffer.
2199 When t, fast selection is used by default. In this case, the prefix
2200 argument forces cycling instead.
2202 In all cases, the special interface is only used if access keys have
2203 actually been assigned by the user, i.e. if keywords in the configuration
2204 are followed by a letter in parenthesis, like TODO(t)."
2205 :group 'org-todo
2206 :type '(choice
2207 (const :tag "Never" nil)
2208 (const :tag "By default" t)
2209 (const :tag "Only with C-u C-c C-t" prefix)))
2211 (defcustom org-provide-todo-statistics t
2212 "Non-nil means update todo statistics after insert and toggle.
2213 ALL-HEADLINES means update todo statistics by including headlines
2214 with no TODO keyword as well, counting them as not done.
2215 A list of TODO keywords means the same, but skip keywords that are
2216 not in this list.
2218 When this is set, todo statistics is updated in the parent of the
2219 current entry each time a todo state is changed."
2220 :group 'org-todo
2221 :type '(choice
2222 (const :tag "Yes, only for TODO entries" t)
2223 (const :tag "Yes, including all entries" 'all-headlines)
2224 (repeat :tag "Yes, for TODOs in this list"
2225 (string :tag "TODO keyword"))
2226 (other :tag "No TODO statistics" nil)))
2228 (defcustom org-hierarchical-todo-statistics t
2229 "Non-nil means TODO statistics covers just direct children.
2230 When nil, all entries in the subtree are considered.
2231 This has only an effect if `org-provide-todo-statistics' is set.
2232 To set this to nil for only a single subtree, use a COOKIE_DATA
2233 property and include the word \"recursive\" into the value."
2234 :group 'org-todo
2235 :type 'boolean)
2237 (defcustom org-after-todo-state-change-hook nil
2238 "Hook which is run after the state of a TODO item was changed.
2239 The new state (a string with a TODO keyword, or nil) is available in the
2240 Lisp variable `org-state'."
2241 :group 'org-todo
2242 :type 'hook)
2244 (defvar org-blocker-hook nil
2245 "Hook for functions that are allowed to block a state change.
2247 Functions in this hook should not modify the buffer.
2248 Each function gets as its single argument a property list,
2249 see `org-trigger-hook' for more information about this list.
2251 If any of the functions in this hook returns nil, the state change
2252 is blocked.")
2254 (defvar org-trigger-hook nil
2255 "Hook for functions that are triggered by a state change.
2257 Each function gets as its single argument a property list with at
2258 least the following elements:
2260 (:type type-of-change :position pos-at-entry-start
2261 :from old-state :to new-state)
2263 Depending on the type, more properties may be present.
2265 This mechanism is currently implemented for:
2267 TODO state changes
2268 ------------------
2269 :type todo-state-change
2270 :from previous state (keyword as a string), or nil, or a symbol
2271 'todo' or 'done', to indicate the general type of state.
2272 :to new state, like in :from")
2274 (defcustom org-enforce-todo-dependencies nil
2275 "Non-nil means undone TODO entries will block switching the parent to DONE.
2276 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2277 be blocked if any prior sibling is not yet done.
2278 Finally, if the parent is blocked because of ordered siblings of its own,
2279 the child will also be blocked."
2280 :set (lambda (var val)
2281 (set var val)
2282 (if val
2283 (add-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)
2285 (remove-hook 'org-blocker-hook
2286 'org-block-todo-from-children-or-siblings-or-parent)))
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-enforce-todo-checkbox-dependencies nil
2291 "Non-nil means unchecked boxes will block switching the parent to DONE.
2292 When this is nil, checkboxes have no influence on switching TODO states.
2293 When non-nil, you first need to check off all check boxes before the TODO
2294 entry can be switched to DONE.
2295 This variable needs to be set before org.el is loaded, and you need to
2296 restart Emacs after a change to make the change effective. The only way
2297 to change is while Emacs is running is through the customize interface."
2298 :set (lambda (var val)
2299 (set var val)
2300 (if val
2301 (add-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)
2303 (remove-hook 'org-blocker-hook
2304 'org-block-todo-from-checkboxes)))
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-insert-todo-heading-as-state-change nil
2309 "Non-nil means inserting a TODO heading is treated as state change.
2310 So when the command \\[org-insert-todo-heading] is used, state change
2311 logging will apply if appropriate. When nil, the new TODO item will
2312 be inserted directly, and no logging will take place."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2317 "Non-nil means switching TODO states with S-cursor counts as state change.
2318 This is the default behavior. However, setting this to nil allows a
2319 convenient way to select a TODO state and bypass any logging associated
2320 with that."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-todo-state-tags-triggers nil
2325 "Tag changes that should be triggered by TODO state changes.
2326 This is a list. Each entry is
2328 (state-change (tag . flag) .......)
2330 State-change can be a string with a state, and empty string to indicate the
2331 state that has no TODO keyword, or it can be one of the symbols `todo'
2332 or `done', meaning any not-done or done state, respectively."
2333 :group 'org-todo
2334 :group 'org-tags
2335 :type '(repeat
2336 (cons (choice :tag "When changing to"
2337 (const :tag "Not-done state" todo)
2338 (const :tag "Done state" done)
2339 (string :tag "State"))
2340 (repeat
2341 (cons :tag "Tag action"
2342 (string :tag "Tag")
2343 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2345 (defcustom org-log-done nil
2346 "Information to record when a task moves to the DONE state.
2348 Possible values are:
2350 nil Don't add anything, just change the keyword
2351 time Add a time stamp to the task
2352 note Prompt for a note and add it with template `org-log-note-headings'
2354 This option can also be set with on a per-file-basis with
2356 #+STARTUP: nologdone
2357 #+STARTUP: logdone
2358 #+STARTUP: lognotedone
2360 You can have local logging settings for a subtree by setting the LOGGING
2361 property to one or more of these keywords."
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record CLOSED timestamp" time)
2367 (const :tag "Record CLOSED timestamp with note." note)))
2369 ;; Normalize old uses of org-log-done.
2370 (cond
2371 ((eq org-log-done t) (setq org-log-done 'time))
2372 ((and (listp org-log-done) (memq 'done org-log-done))
2373 (setq org-log-done 'note)))
2375 (defcustom org-log-reschedule nil
2376 "Information to record when the scheduling date of a tasks is modified.
2378 Possible values are:
2380 nil Don't add anything, just change the date
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologreschedule
2387 #+STARTUP: logreschedule
2388 #+STARTUP: lognotereschedule"
2389 :group 'org-todo
2390 :group 'org-progress
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-log-redeadline nil
2397 "Information to record when the deadline date of a tasks is modified.
2399 Possible values are:
2401 nil Don't add anything, just change the date
2402 time Add a time stamp to the task
2403 note Prompt for a note and add it with template `org-log-note-headings'
2405 This option can also be set with on a per-file-basis with
2407 #+STARTUP: nologredeadline
2408 #+STARTUP: logredeadline
2409 #+STARTUP: lognoteredeadline
2411 You can have local logging settings for a subtree by setting the LOGGING
2412 property to one or more of these keywords."
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-note-clock-out nil
2421 "Non-nil means record a note when clocking out of an item.
2422 This can also be configured on a per-file basis by adding one of
2423 the following lines anywhere in the buffer:
2425 #+STARTUP: lognoteclock-out
2426 #+STARTUP: nolognoteclock-out"
2427 :group 'org-todo
2428 :group 'org-progress
2429 :type 'boolean)
2431 (defcustom org-log-done-with-time t
2432 "Non-nil means the CLOSED time stamp will contain date and time.
2433 When nil, only the date will be recorded."
2434 :group 'org-progress
2435 :type 'boolean)
2437 (defcustom org-log-note-headings
2438 '((done . "CLOSING NOTE %t")
2439 (state . "State %-12s from %-12S %t")
2440 (note . "Note taken on %t")
2441 (reschedule . "Rescheduled from %S on %t")
2442 (delschedule . "Not scheduled, was %S on %t")
2443 (redeadline . "New deadline from %S on %t")
2444 (deldeadline . "Removed deadline, was %S on %t")
2445 (refile . "Refiled on %t")
2446 (clock-out . ""))
2447 "Headings for notes added to entries.
2448 The value is an alist, with the car being a symbol indicating the note
2449 context, and the cdr is the heading to be used. The heading may also be the
2450 empty string.
2451 %t in the heading will be replaced by a time stamp.
2452 %T will be an active time stamp instead the default inactive one
2453 %d will be replaced by a short-format time stamp.
2454 %D will be replaced by an active short-format time stamp.
2455 %s will be replaced by the new TODO state, in double quotes.
2456 %S will be replaced by the old TODO state, in double quotes.
2457 %u will be replaced by the user name.
2458 %U will be replaced by the full user name.
2460 In fact, it is not a good idea to change the `state' entry, because
2461 agenda log mode depends on the format of these entries."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(list :greedy t
2465 (cons (const :tag "Heading when closing an item" done) string)
2466 (cons (const :tag
2467 "Heading when changing todo state (todo sequence only)"
2468 state) string)
2469 (cons (const :tag "Heading when just taking a note" note) string)
2470 (cons (const :tag "Heading when clocking out" clock-out) string)
2471 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2472 (cons (const :tag "Heading when rescheduling" reschedule) string)
2473 (cons (const :tag "Heading when changing deadline" redeadline) string)
2474 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2475 (cons (const :tag "Heading when refiling" refile) string)))
2477 (unless (assq 'note org-log-note-headings)
2478 (push '(note . "%t") org-log-note-headings))
2480 (defcustom org-log-into-drawer nil
2481 "Non-nil means insert state change notes and time stamps into a drawer.
2482 When nil, state changes notes will be inserted after the headline and
2483 any scheduling and clock lines, but not inside a drawer.
2485 The value of this variable should be the name of the drawer to use.
2486 LOGBOOK is proposed as the default drawer for this purpose, you can
2487 also set this to a string to define the drawer of your choice.
2489 A value of t is also allowed, representing \"LOGBOOK\".
2491 If this variable is set, `org-log-state-notes-insert-after-drawers'
2492 will be ignored.
2494 You can set the property LOG_INTO_DRAWER to overrule this setting for
2495 a subtree."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "Not into a drawer" nil)
2500 (const :tag "LOGBOOK" t)
2501 (string :tag "Other")))
2503 (if (fboundp 'defvaralias)
2504 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2506 (defun org-log-into-drawer ()
2507 "Return the value of `org-log-into-drawer', but let properties overrule.
2508 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2509 used instead of the default value."
2510 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2511 (cond
2512 ((not p) org-log-into-drawer)
2513 ((equal p "nil") nil)
2514 ((equal p "t") "LOGBOOK")
2515 (t p))))
2517 (defcustom org-log-state-notes-insert-after-drawers nil
2518 "Non-nil means insert state change notes after any drawers in entry.
2519 Only the drawers that *immediately* follow the headline and the
2520 deadline/scheduled line are skipped.
2521 When nil, insert notes right after the heading and perhaps the line
2522 with deadline/scheduling if present.
2524 This variable will have no effect if `org-log-into-drawer' is
2525 set."
2526 :group 'org-todo
2527 :group 'org-progress
2528 :type 'boolean)
2530 (defcustom org-log-states-order-reversed t
2531 "Non-nil means the latest state note will be directly after heading.
2532 When nil, the state change notes will be ordered according to time."
2533 :group 'org-todo
2534 :group 'org-progress
2535 :type 'boolean)
2537 (defcustom org-todo-repeat-to-state nil
2538 "The TODO state to which a repeater should return the repeating task.
2539 By default this is the first task in a TODO sequence, or the previous state
2540 in a TODO_TYP set. But you can specify another task here.
2541 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2542 :group 'org-todo
2543 :version "24.1"
2544 :type '(choice (const :tag "Head of sequence" nil)
2545 (string :tag "Specific state")))
2547 (defcustom org-log-repeat 'time
2548 "Non-nil means record moving through the DONE state when triggering repeat.
2549 An auto-repeating task is immediately switched back to TODO when
2550 marked DONE. If you are not logging state changes (by adding \"@\"
2551 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2552 record a closing note, there will be no record of the task moving
2553 through DONE. This variable forces taking a note anyway.
2555 nil Don't force a record
2556 time Record a time stamp
2557 note Prompt for a note and add it with template `org-log-note-headings'
2559 This option can also be set with on a per-file-basis with
2561 #+STARTUP: nologrepeat
2562 #+STARTUP: logrepeat
2563 #+STARTUP: lognoterepeat
2565 You can have local logging settings for a subtree by setting the LOGGING
2566 property to one or more of these keywords."
2567 :group 'org-todo
2568 :group 'org-progress
2569 :type '(choice
2570 (const :tag "Don't force a record" nil)
2571 (const :tag "Force recording the DONE state" time)
2572 (const :tag "Force recording a note with the DONE state" note)))
2575 (defgroup org-priorities nil
2576 "Priorities in Org-mode."
2577 :tag "Org Priorities"
2578 :group 'org-todo)
2580 (defcustom org-enable-priority-commands t
2581 "Non-nil means priority commands are active.
2582 When nil, these commands will be disabled, so that you never accidentally
2583 set a priority."
2584 :group 'org-priorities
2585 :type 'boolean)
2587 (defcustom org-highest-priority ?A
2588 "The highest priority of TODO items. A character like ?A, ?B etc.
2589 Must have a smaller ASCII number than `org-lowest-priority'."
2590 :group 'org-priorities
2591 :type 'character)
2593 (defcustom org-lowest-priority ?C
2594 "The lowest priority of TODO items. A character like ?A, ?B etc.
2595 Must have a larger ASCII number than `org-highest-priority'."
2596 :group 'org-priorities
2597 :type 'character)
2599 (defcustom org-default-priority ?B
2600 "The default priority of TODO items.
2601 This is the priority an item gets if no explicit priority is given.
2602 When starting to cycle on an empty priority the first step in the cycle
2603 depends on `org-priority-start-cycle-with-default'. The resulting first
2604 step priority must not exceed the range from `org-highest-priority' to
2605 `org-lowest-priority' which means that `org-default-priority' has to be
2606 in this range exclusive or inclusive the range boundaries. Else the
2607 first step refuses to set the default and the second will fall back
2608 to (depending on the command used) the highest or lowest priority."
2609 :group 'org-priorities
2610 :type 'character)
2612 (defcustom org-priority-start-cycle-with-default t
2613 "Non-nil means start with default priority when starting to cycle.
2614 When this is nil, the first step in the cycle will be (depending on the
2615 command used) one higher or lower than the default priority.
2616 See also `org-default-priority'."
2617 :group 'org-priorities
2618 :type 'boolean)
2620 (defcustom org-get-priority-function nil
2621 "Function to extract the priority from a string.
2622 The string is normally the headline. If this is nil Org computes the
2623 priority from the priority cookie like [#A] in the headline. It returns
2624 an integer, increasing by 1000 for each priority level.
2625 The user can set a different function here, which should take a string
2626 as an argument and return the numeric priority."
2627 :group 'org-priorities
2628 :version "24.1"
2629 :type 'function)
2631 (defgroup org-time nil
2632 "Options concerning time stamps and deadlines in Org-mode."
2633 :tag "Org Time"
2634 :group 'org)
2636 (defcustom org-insert-labeled-timestamps-at-point nil
2637 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2638 When nil, these labeled time stamps are forces into the second line of an
2639 entry, just after the headline. When scheduling from the global TODO list,
2640 the time stamp will always be forced into the second line."
2641 :group 'org-time
2642 :type 'boolean)
2644 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2645 "Formats for `format-time-string' which are used for time stamps.
2646 It is not recommended to change this constant.")
2648 (defcustom org-time-stamp-rounding-minutes '(0 5)
2649 "Number of minutes to round time stamps to.
2650 These are two values, the first applies when first creating a time stamp.
2651 The second applies when changing it with the commands `S-up' and `S-down'.
2652 When changing the time stamp, this means that it will change in steps
2653 of N minutes, as given by the second value.
2655 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2656 numbers should be factors of 60, so for example 5, 10, 15.
2658 When this is larger than 1, you can still force an exact time stamp by using
2659 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2660 and by using a prefix arg to `S-up/down' to specify the exact number
2661 of minutes to shift."
2662 :group 'org-time
2663 :get #'(lambda (var) ; Make sure both elements are there
2664 (if (integerp (default-value var))
2665 (list (default-value var) 5)
2666 (default-value var)))
2667 :type '(list
2668 (integer :tag "when inserting times")
2669 (integer :tag "when modifying times")))
2671 ;; Normalize old customizations of this variable.
2672 (when (integerp org-time-stamp-rounding-minutes)
2673 (setq org-time-stamp-rounding-minutes
2674 (list org-time-stamp-rounding-minutes
2675 org-time-stamp-rounding-minutes)))
2677 (defcustom org-display-custom-times nil
2678 "Non-nil means overlay custom formats over all time stamps.
2679 The formats are defined through the variable `org-time-stamp-custom-formats'.
2680 To turn this on on a per-file basis, insert anywhere in the file:
2681 #+STARTUP: customtime"
2682 :group 'org-time
2683 :set 'set-default
2684 :type 'sexp)
2685 (make-variable-buffer-local 'org-display-custom-times)
2687 (defcustom org-time-stamp-custom-formats
2688 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2689 "Custom formats for time stamps. See `format-time-string' for the syntax.
2690 These are overlaid over the default ISO format if the variable
2691 `org-display-custom-times' is set. Time like %H:%M should be at the
2692 end of the second format. The custom formats are also honored by export
2693 commands, if custom time display is turned on at the time of export."
2694 :group 'org-time
2695 :type 'sexp)
2697 (defun org-time-stamp-format (&optional long inactive)
2698 "Get the right format for a time string."
2699 (let ((f (if long (cdr org-time-stamp-formats)
2700 (car org-time-stamp-formats))))
2701 (if inactive
2702 (concat "[" (substring f 1 -1) "]")
2703 f)))
2705 (defcustom org-time-clocksum-format "%d:%02d"
2706 "The format string used when creating CLOCKSUM lines.
2707 This is also used when org-mode generates a time duration."
2708 :group 'org-time
2709 :type 'string)
2711 (defcustom org-time-clocksum-use-fractional nil
2712 "If non-nil, \\[org-clock-display] uses fractional times.
2713 org-mode generates a time duration."
2714 :group 'org-time
2715 :type 'boolean)
2717 (defcustom org-time-clocksum-fractional-format "%.2f"
2718 "The format string used when creating CLOCKSUM lines, or when
2719 org-mode generates a time duration."
2720 :group 'org-time
2721 :type 'string)
2723 (defcustom org-deadline-warning-days 14
2724 "No. of days before expiration during which a deadline becomes active.
2725 This variable governs the display in sparse trees and in the agenda.
2726 When 0 or negative, it means use this number (the absolute value of it)
2727 even if a deadline has a different individual lead time specified.
2729 Custom commands can set this variable in the options section."
2730 :group 'org-time
2731 :group 'org-agenda-daily/weekly
2732 :type 'integer)
2734 (defcustom org-read-date-prefer-future t
2735 "Non-nil means assume future for incomplete date input from user.
2736 This affects the following situations:
2737 1. The user gives a month but not a year.
2738 For example, if it is April and you enter \"feb 2\", this will be read
2739 as Feb 2, *next* year. \"May 5\", however, will be this year.
2740 2. The user gives a day, but no month.
2741 For example, if today is the 15th, and you enter \"3\", Org-mode will
2742 read this as the third of *next* month. However, if you enter \"17\",
2743 it will be considered as *this* month.
2745 If you set this variable to the symbol `time', then also the following
2746 will work:
2748 3. If the user gives a time.
2749 If the time is before now, it will be interpreted as tomorrow.
2751 Currently none of this works for ISO week specifications.
2753 When this option is nil, the current day, month and year will always be
2754 used as defaults.
2756 See also `org-agenda-jump-prefer-future'."
2757 :group 'org-time
2758 :type '(choice
2759 (const :tag "Never" nil)
2760 (const :tag "Check month and day" t)
2761 (const :tag "Check month, day, and time" time)))
2763 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2764 "Should the agenda jump command prefer the future for incomplete dates?
2765 The default is to do the same as configured in `org-read-date-prefer-future'.
2766 But you can also set a deviating value here.
2767 This may t or nil, or the symbol `org-read-date-prefer-future'."
2768 :group 'org-agenda
2769 :group 'org-time
2770 :version "24.1"
2771 :type '(choice
2772 (const :tag "Use org-read-date-prefer-future"
2773 org-read-date-prefer-future)
2774 (const :tag "Never" nil)
2775 (const :tag "Always" t)))
2777 (defcustom org-read-date-force-compatible-dates t
2778 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2780 Depending on the system Emacs is running on, certain dates cannot
2781 be represented with the type used internally to represent time.
2782 Dates between 1970-1-1 and 2038-1-1 can always be represented
2783 correctly. Some systems allow for earlier dates, some for later,
2784 some for both. One way to find out it to insert any date into an
2785 Org buffer, putting the cursor on the year and hitting S-up and
2786 S-down to test the range.
2788 When this variable is set to t, the date/time prompt will not let
2789 you specify dates outside the 1970-2037 range, so it is certain that
2790 these dates will work in whatever version of Emacs you are
2791 running, and also that you can move a file from one Emacs implementation
2792 to another. WHenever Org is forcing the year for you, it will display
2793 a message and beep.
2795 When this variable is nil, Org will check if the date is
2796 representable in the specific Emacs implementation you are using.
2797 If not, it will force a year, usually the current year, and beep
2798 to remind you. Currently this setting is not recommended because
2799 the likelihood that you will open your Org files in an Emacs that
2800 has limited date range is not negligible.
2802 A workaround for this problem is to use diary sexp dates for time
2803 stamps outside of this range."
2804 :group 'org-time
2805 :version "24.1"
2806 :type 'boolean)
2808 (defcustom org-read-date-display-live t
2809 "Non-nil means display current interpretation of date prompt live.
2810 This display will be in an overlay, in the minibuffer."
2811 :group 'org-time
2812 :type 'boolean)
2814 (defcustom org-read-date-popup-calendar t
2815 "Non-nil means pop up a calendar when prompting for a date.
2816 In the calendar, the date can be selected with mouse-1. However, the
2817 minibuffer will also be active, and you can simply enter the date as well.
2818 When nil, only the minibuffer will be available."
2819 :group 'org-time
2820 :type 'boolean)
2821 (if (fboundp 'defvaralias)
2822 (defvaralias 'org-popup-calendar-for-date-prompt
2823 'org-read-date-popup-calendar))
2825 (defcustom org-read-date-minibuffer-setup-hook nil
2826 "Hook to be used to set up keys for the date/time interface.
2827 Add key definitions to `minibuffer-local-map', which will be a temporary
2828 copy."
2829 :group 'org-time
2830 :type 'hook)
2832 (defcustom org-extend-today-until 0
2833 "The hour when your day really ends. Must be an integer.
2834 This has influence for the following applications:
2835 - When switching the agenda to \"today\". It it is still earlier than
2836 the time given here, the day recognized as TODAY is actually yesterday.
2837 - When a date is read from the user and it is still before the time given
2838 here, the current date and time will be assumed to be yesterday, 23:59.
2839 Also, timestamps inserted in capture templates follow this rule.
2841 IMPORTANT: This is a feature whose implementation is and likely will
2842 remain incomplete. Really, it is only here because past midnight seems to
2843 be the favorite working time of John Wiegley :-)"
2844 :group 'org-time
2845 :type 'integer)
2847 (defcustom org-use-effective-time nil
2848 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2849 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2850 \"effective time\" of any timestamps between midnight and 8am will be
2851 23:59 of the previous day."
2852 :group 'org-time
2853 :version "24.1"
2854 :type 'boolean)
2856 (defcustom org-edit-timestamp-down-means-later nil
2857 "Non-nil means S-down will increase the time in a time stamp.
2858 When nil, S-up will increase."
2859 :group 'org-time
2860 :type 'boolean)
2862 (defcustom org-calendar-follow-timestamp-change t
2863 "Non-nil means make the calendar window follow timestamp changes.
2864 When a timestamp is modified and the calendar window is visible, it will be
2865 moved to the new date."
2866 :group 'org-time
2867 :type 'boolean)
2869 (defgroup org-tags nil
2870 "Options concerning tags in Org-mode."
2871 :tag "Org Tags"
2872 :group 'org)
2874 (defcustom org-tag-alist nil
2875 "List of tags allowed in Org-mode files.
2876 When this list is nil, Org-mode will base TAG input on what is already in the
2877 buffer.
2878 The value of this variable is an alist, the car of each entry must be a
2879 keyword as a string, the cdr may be a character that is used to select
2880 that tag through the fast-tag-selection interface.
2881 See the manual for details."
2882 :group 'org-tags
2883 :type '(repeat
2884 (choice
2885 (cons (string :tag "Tag name")
2886 (character :tag "Access char"))
2887 (list :tag "Start radio group"
2888 (const :startgroup)
2889 (option (string :tag "Group description")))
2890 (list :tag "End radio group"
2891 (const :endgroup)
2892 (option (string :tag "Group description")))
2893 (const :tag "New line" (:newline)))))
2895 (defcustom org-tag-persistent-alist nil
2896 "List of tags that will always appear in all Org-mode files.
2897 This is in addition to any in buffer settings or customizations
2898 of `org-tag-alist'.
2899 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2900 The value of this variable is an alist, the car of each entry must be a
2901 keyword as a string, the cdr may be a character that is used to select
2902 that tag through the fast-tag-selection interface.
2903 See the manual for details.
2904 To disable these tags on a per-file basis, insert anywhere in the file:
2905 #+STARTUP: noptag"
2906 :group 'org-tags
2907 :type '(repeat
2908 (choice
2909 (cons (string :tag "Tag name")
2910 (character :tag "Access char"))
2911 (const :tag "Start radio group" (:startgroup))
2912 (const :tag "End radio group" (:endgroup))
2913 (const :tag "New line" (:newline)))))
2915 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2916 "If non-nil, always offer completion for all tags of all agenda files.
2917 Instead of customizing this variable directly, you might want to
2918 set it locally for capture buffers, because there no list of
2919 tags in that file can be created dynamically (there are none).
2921 (add-hook 'org-capture-mode-hook
2922 (lambda ()
2923 (set (make-local-variable
2924 'org-complete-tags-always-offer-all-agenda-tags)
2925 t)))"
2926 :group 'org-tags
2927 :version "24.1"
2928 :type 'boolean)
2930 (defvar org-file-tags nil
2931 "List of tags that can be inherited by all entries in the file.
2932 The tags will be inherited if the variable `org-use-tag-inheritance'
2933 says they should be.
2934 This variable is populated from #+FILETAGS lines.")
2936 (defcustom org-use-fast-tag-selection 'auto
2937 "Non-nil means use fast tag selection scheme.
2938 This is a special interface to select and deselect tags with single keys.
2939 When nil, fast selection is never used.
2940 When the symbol `auto', fast selection is used if and only if selection
2941 characters for tags have been configured, either through the variable
2942 `org-tag-alist' or through a #+TAGS line in the buffer.
2943 When t, fast selection is always used and selection keys are assigned
2944 automatically if necessary."
2945 :group 'org-tags
2946 :type '(choice
2947 (const :tag "Always" t)
2948 (const :tag "Never" nil)
2949 (const :tag "When selection characters are configured" 'auto)))
2951 (defcustom org-fast-tag-selection-single-key nil
2952 "Non-nil means fast tag selection exits after first change.
2953 When nil, you have to press RET to exit it.
2954 During fast tag selection, you can toggle this flag with `C-c'.
2955 This variable can also have the value `expert'. In this case, the window
2956 displaying the tags menu is not even shown, until you press C-c again."
2957 :group 'org-tags
2958 :type '(choice
2959 (const :tag "No" nil)
2960 (const :tag "Yes" t)
2961 (const :tag "Expert" expert)))
2963 (defvar org-fast-tag-selection-include-todo nil
2964 "Non-nil means fast tags selection interface will also offer TODO states.
2965 This is an undocumented feature, you should not rely on it.")
2967 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2968 "The column to which tags should be indented in a headline.
2969 If this number is positive, it specifies the column. If it is negative,
2970 it means that the tags should be flushright to that column. For example,
2971 -80 works well for a normal 80 character screen.
2972 When 0, place tags directly after headline text, with only one space in
2973 between."
2974 :group 'org-tags
2975 :type 'integer)
2977 (defcustom org-auto-align-tags t
2978 "Non-nil keeps tags aligned when modifying headlines.
2979 Some operations (i.e. demoting) change the length of a headline and
2980 therefore shift the tags around. With this option turned on, after
2981 each such operation the tags are again aligned to `org-tags-column'."
2982 :group 'org-tags
2983 :type 'boolean)
2985 (defcustom org-use-tag-inheritance t
2986 "Non-nil means tags in levels apply also for sublevels.
2987 When nil, only the tags directly given in a specific line apply there.
2988 This may also be a list of tags that should be inherited, or a regexp that
2989 matches tags that should be inherited. Additional control is possible
2990 with the variable `org-tags-exclude-from-inheritance' which gives an
2991 explicit list of tags to be excluded from inheritance, even if the value of
2992 `org-use-tag-inheritance' would select it for inheritance.
2994 If this option is t, a match early-on in a tree can lead to a large
2995 number of matches in the subtree when constructing the agenda or creating
2996 a sparse tree. If you only want to see the first match in a tree during
2997 a search, check out the variable `org-tags-match-list-sublevels'."
2998 :group 'org-tags
2999 :type '(choice
3000 (const :tag "Not" nil)
3001 (const :tag "Always" t)
3002 (repeat :tag "Specific tags" (string :tag "Tag"))
3003 (regexp :tag "Tags matched by regexp")))
3005 (defcustom org-tags-exclude-from-inheritance nil
3006 "List of tags that should never be inherited.
3007 This is a way to exclude a few tags from inheritance. For way to do
3008 the opposite, to actively allow inheritance for selected tags,
3009 see the variable `org-use-tag-inheritance'."
3010 :group 'org-tags
3011 :type '(repeat (string :tag "Tag")))
3013 (defun org-tag-inherit-p (tag)
3014 "Check if TAG is one that should be inherited."
3015 (cond
3016 ((member tag org-tags-exclude-from-inheritance) nil)
3017 ((eq org-use-tag-inheritance t) t)
3018 ((not org-use-tag-inheritance) nil)
3019 ((stringp org-use-tag-inheritance)
3020 (string-match org-use-tag-inheritance tag))
3021 ((listp org-use-tag-inheritance)
3022 (member tag org-use-tag-inheritance))
3023 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3025 (defcustom org-tags-match-list-sublevels t
3026 "Non-nil means list also sublevels of headlines matching a search.
3027 This variable applies to tags/property searches, and also to stuck
3028 projects because this search is based on a tags match as well.
3030 When set to the symbol `indented', sublevels are indented with
3031 leading dots.
3033 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3034 the sublevels of a headline matching a tag search often also match
3035 the same search. Listing all of them can create very long lists.
3036 Setting this variable to nil causes subtrees of a match to be skipped.
3038 This variable is semi-obsolete and probably should always be true. It
3039 is better to limit inheritance to certain tags using the variables
3040 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No, don't list them" nil)
3044 (const :tag "Yes, do list them" t)
3045 (const :tag "List them, indented with leading dots" indented)))
3047 (defcustom org-tags-sort-function nil
3048 "When set, tags are sorted using this function as a comparator."
3049 :group 'org-tags
3050 :type '(choice
3051 (const :tag "No sorting" nil)
3052 (const :tag "Alphabetical" string<)
3053 (const :tag "Reverse alphabetical" string>)
3054 (function :tag "Custom function" nil)))
3056 (defvar org-tags-history nil
3057 "History of minibuffer reads for tags.")
3058 (defvar org-last-tags-completion-table nil
3059 "The last used completion table for tags.")
3060 (defvar org-after-tags-change-hook nil
3061 "Hook that is run after the tags in a line have changed.")
3063 (defgroup org-properties nil
3064 "Options concerning properties in Org-mode."
3065 :tag "Org Properties"
3066 :group 'org)
3068 (defcustom org-property-format "%-10s %s"
3069 "How property key/value pairs should be formatted by `indent-line'.
3070 When `indent-line' hits a property definition, it will format the line
3071 according to this format, mainly to make sure that the values are
3072 lined-up with respect to each other."
3073 :group 'org-properties
3074 :type 'string)
3076 (defcustom org-properties-postprocess-alist nil
3077 "Alist of properties and functions to adjust inserted values.
3078 Elements of this alist must be of the form
3080 ([string] [function])
3082 where [string] must be a property name and [function] must be a
3083 lambda expression: this lambda expression must take one argument,
3084 the value to adjust, and return the new value as a string.
3086 For example, this element will allow the property \"Remaining\"
3087 to be updated wrt the relation between the \"Effort\" property
3088 and the clock summary:
3090 ((\"Remaining\" (lambda(value)
3091 (let ((clocksum (org-clock-sum-current-item))
3092 (effort (org-duration-string-to-minutes
3093 (org-entry-get (point) \"Effort\"))))
3094 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3095 :group 'org-properties
3096 :version "24.1"
3097 :type '(alist :key-type (string :tag "Property")
3098 :value-type (function :tag "Function")))
3100 (defcustom org-use-property-inheritance nil
3101 "Non-nil means properties apply also for sublevels.
3103 This setting is chiefly used during property searches. Turning it on can
3104 cause significant overhead when doing a search, which is why it is not
3105 on by default.
3107 When nil, only the properties directly given in the current entry count.
3108 When t, every property is inherited. The value may also be a list of
3109 properties that should have inheritance, or a regular expression matching
3110 properties that should be inherited.
3112 However, note that some special properties use inheritance under special
3113 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3114 and the properties ending in \"_ALL\" when they are used as descriptor
3115 for valid values of a property.
3117 Note for programmers:
3118 When querying an entry with `org-entry-get', you can control if inheritance
3119 should be used. By default, `org-entry-get' looks only at the local
3120 properties. You can request inheritance by setting the inherit argument
3121 to t (to force inheritance) or to `selective' (to respect the setting
3122 in this variable)."
3123 :group 'org-properties
3124 :type '(choice
3125 (const :tag "Not" nil)
3126 (const :tag "Always" t)
3127 (repeat :tag "Specific properties" (string :tag "Property"))
3128 (regexp :tag "Properties matched by regexp")))
3130 (defun org-property-inherit-p (property)
3131 "Check if PROPERTY is one that should be inherited."
3132 (cond
3133 ((eq org-use-property-inheritance t) t)
3134 ((not org-use-property-inheritance) nil)
3135 ((stringp org-use-property-inheritance)
3136 (string-match org-use-property-inheritance property))
3137 ((listp org-use-property-inheritance)
3138 (member property org-use-property-inheritance))
3139 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3141 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3142 "The default column format, if no other format has been defined.
3143 This variable can be set on the per-file basis by inserting a line
3145 #+COLUMNS: %25ITEM ....."
3146 :group 'org-properties
3147 :type 'string)
3149 (defcustom org-columns-ellipses ".."
3150 "The ellipses to be used when a field in column view is truncated.
3151 When this is the empty string, as many characters as possible are shown,
3152 but then there will be no visual indication that the field has been truncated.
3153 When this is a string of length N, the last N characters of a truncated
3154 field are replaced by this string. If the column is narrower than the
3155 ellipses string, only part of the ellipses string will be shown."
3156 :group 'org-properties
3157 :type 'string)
3159 (defcustom org-columns-modify-value-for-display-function nil
3160 "Function that modifies values for display in column view.
3161 For example, it can be used to cut out a certain part from a time stamp.
3162 The function must take 2 arguments:
3164 column-title The title of the column (*not* the property name)
3165 value The value that should be modified.
3167 The function should return the value that should be displayed,
3168 or nil if the normal value should be used."
3169 :group 'org-properties
3170 :type 'function)
3172 (defcustom org-effort-property "Effort"
3173 "The property that is being used to keep track of effort estimates.
3174 Effort estimates given in this property need to have the format H:MM."
3175 :group 'org-properties
3176 :group 'org-progress
3177 :type '(string :tag "Property"))
3179 (defconst org-global-properties-fixed
3180 '(("VISIBILITY_ALL" . "folded children content all")
3181 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3182 "List of property/value pairs that can be inherited by any entry.
3184 These are fixed values, for the preset properties. The user variable
3185 that can be used to add to this list is `org-global-properties'.
3187 The entries in this list are cons cells where the car is a property
3188 name and cdr is a string with the value. If the value represents
3189 multiple items like an \"_ALL\" property, separate the items by
3190 spaces.")
3192 (defcustom org-global-properties nil
3193 "List of property/value pairs that can be inherited by any entry.
3195 This list will be combined with the constant `org-global-properties-fixed'.
3197 The entries in this list are cons cells where the car is a property
3198 name and cdr is a string with the value.
3200 You can set buffer-local values for the same purpose in the variable
3201 `org-file-properties' this by adding lines like
3203 #+PROPERTY: NAME VALUE"
3204 :group 'org-properties
3205 :type '(repeat
3206 (cons (string :tag "Property")
3207 (string :tag "Value"))))
3209 (defvar org-file-properties nil
3210 "List of property/value pairs that can be inherited by any entry.
3211 Valid for the current buffer.
3212 This variable is populated from #+PROPERTY lines.")
3213 (make-variable-buffer-local 'org-file-properties)
3215 (defgroup org-agenda nil
3216 "Options concerning agenda views in Org-mode."
3217 :tag "Org Agenda"
3218 :group 'org)
3220 (defvar org-category nil
3221 "Variable used by org files to set a category for agenda display.
3222 Such files should use a file variable to set it, for example
3224 # -*- mode: org; org-category: \"ELisp\"
3226 or contain a special line
3228 #+CATEGORY: ELisp
3230 If the file does not specify a category, then file's base name
3231 is used instead.")
3232 (make-variable-buffer-local 'org-category)
3233 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3235 (defcustom org-agenda-files nil
3236 "The files to be used for agenda display.
3237 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3238 \\[org-remove-file]. You can also use customize to edit the list.
3240 If an entry is a directory, all files in that directory that are matched by
3241 `org-agenda-file-regexp' will be part of the file list.
3243 If the value of the variable is not a list but a single file name, then
3244 the list of agenda files is actually stored and maintained in that file, one
3245 agenda file per line. In this file paths can be given relative to
3246 `org-directory'. Tilde expansion and environment variable substitution
3247 are also made."
3248 :group 'org-agenda
3249 :type '(choice
3250 (repeat :tag "List of files and directories" file)
3251 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3253 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3254 "Regular expression to match files for `org-agenda-files'.
3255 If any element in the list in that variable contains a directory instead
3256 of a normal file, all files in that directory that are matched by this
3257 regular expression will be included."
3258 :group 'org-agenda
3259 :type 'regexp)
3261 (defcustom org-agenda-text-search-extra-files nil
3262 "List of extra files to be searched by text search commands.
3263 These files will be search in addition to the agenda files by the
3264 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3265 Note that these files will only be searched for text search commands,
3266 not for the other agenda views like todo lists, tag searches or the weekly
3267 agenda. This variable is intended to list notes and possibly archive files
3268 that should also be searched by these two commands.
3269 In fact, if the first element in the list is the symbol `agenda-archives',
3270 than all archive files of all agenda files will be added to the search
3271 scope."
3272 :group 'org-agenda
3273 :type '(set :greedy t
3274 (const :tag "Agenda Archives" agenda-archives)
3275 (repeat :inline t (file))))
3277 (if (fboundp 'defvaralias)
3278 (defvaralias 'org-agenda-multi-occur-extra-files
3279 'org-agenda-text-search-extra-files))
3281 (defcustom org-agenda-skip-unavailable-files nil
3282 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3283 A nil value means to remove them, after a query, from the list."
3284 :group 'org-agenda
3285 :type 'boolean)
3287 (defcustom org-calendar-to-agenda-key [?c]
3288 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3289 The command `org-calendar-goto-agenda' will be bound to this key. The
3290 default is the character `c' because then `c' can be used to switch back and
3291 forth between agenda and calendar."
3292 :group 'org-agenda
3293 :type 'sexp)
3295 (defcustom org-calendar-insert-diary-entry-key [?i]
3296 "The key to be installed in `calendar-mode-map' for adding diary entries.
3297 This option is irrelevant until `org-agenda-diary-file' has been configured
3298 to point to an Org-mode file. When that is the case, the command
3299 `org-agenda-diary-entry' will be bound to the key given here, by default
3300 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3301 if you want to continue doing this, you need to change this to a different
3302 key."
3303 :group 'org-agenda
3304 :type 'sexp)
3306 (defcustom org-agenda-diary-file 'diary-file
3307 "File to which to add new entries with the `i' key in agenda and calendar.
3308 When this is the symbol `diary-file', the functionality in the Emacs
3309 calendar will be used to add entries to the `diary-file'. But when this
3310 points to a file, `org-agenda-diary-entry' will be used instead."
3311 :group 'org-agenda
3312 :type '(choice
3313 (const :tag "The standard Emacs diary file" diary-file)
3314 (file :tag "Special Org file diary entries")))
3316 (eval-after-load "calendar"
3317 '(progn
3318 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3319 'org-calendar-goto-agenda)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defcustom org-latex-create-formula-image-program 'dvipng
3394 "Program to convert LaTeX fragments with.
3396 dvipng Process the LaTeX fragments to dvi file, then convert
3397 dvi files to png files using dvipng.
3398 This will also include processing of non-math environments.
3399 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3400 to convert pdf files to png files"
3401 :group 'org-latex
3402 :version "24.1"
3403 :type '(choice
3404 (const :tag "dvipng" dvipng)
3405 (const :tag "imagemagick" imagemagick)))
3407 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3408 "Path to store latex preview images. A relative path here creates many
3409 directories relative to the processed org files paths. An absolute path
3410 puts all preview images at the same place."
3411 :group 'org-latex
3412 :version "24.3"
3413 :type 'string)
3415 (defun org-format-latex-mathml-available-p ()
3416 "Return t if `org-latex-to-mathml-convert-command' is usable."
3417 (save-match-data
3418 (when (and (boundp 'org-latex-to-mathml-convert-command)
3419 org-latex-to-mathml-convert-command)
3420 (let ((executable (car (split-string
3421 org-latex-to-mathml-convert-command))))
3422 (when (executable-find executable)
3423 (if (string-match
3424 "%j" org-latex-to-mathml-convert-command)
3425 (file-readable-p org-latex-to-mathml-jar-file)
3426 t))))))
3428 (defcustom org-format-latex-header "\\documentclass{article}
3429 \\usepackage[usenames]{color}
3430 \\usepackage{amsmath}
3431 \\usepackage[mathscr]{eucal}
3432 \\pagestyle{empty} % do not remove
3433 \[PACKAGES]
3434 \[DEFAULT-PACKAGES]
3435 % The settings below are copied from fullpage.sty
3436 \\setlength{\\textwidth}{\\paperwidth}
3437 \\addtolength{\\textwidth}{-3cm}
3438 \\setlength{\\oddsidemargin}{1.5cm}
3439 \\addtolength{\\oddsidemargin}{-2.54cm}
3440 \\setlength{\\evensidemargin}{\\oddsidemargin}
3441 \\setlength{\\textheight}{\\paperheight}
3442 \\addtolength{\\textheight}{-\\headheight}
3443 \\addtolength{\\textheight}{-\\headsep}
3444 \\addtolength{\\textheight}{-\\footskip}
3445 \\addtolength{\\textheight}{-3cm}
3446 \\setlength{\\topmargin}{1.5cm}
3447 \\addtolength{\\topmargin}{-2.54cm}"
3448 "The document header used for processing LaTeX fragments.
3449 It is imperative that this header make sure that no page number
3450 appears on the page. The package defined in the variables
3451 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3452 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3453 will be appended."
3454 :group 'org-latex
3455 :type 'string)
3457 (defvar org-format-latex-header-extra nil)
3459 (defun org-set-packages-alist (var val)
3460 "Set the packages alist and make sure it has 3 elements per entry."
3461 (set var (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 val)))
3467 (defun org-get-packages-alist (var)
3469 "Get the packages alist and make sure it has 3 elements per entry."
3470 (mapcar (lambda (x)
3471 (if (and (consp x) (= (length x) 2))
3472 (list (car x) (nth 1 x) t)
3474 (default-value var)))
3476 ;; The following variables are defined here because is it also used
3477 ;; when formatting latex fragments. Originally it was part of the
3478 ;; LaTeX exporter, which is why the name includes "export".
3479 (defcustom org-export-latex-default-packages-alist
3480 '(("AUTO" "inputenc" t)
3481 ("T1" "fontenc" t)
3482 ("" "fixltx2e" nil)
3483 ("" "graphicx" t)
3484 ("" "longtable" nil)
3485 ("" "float" nil)
3486 ("" "wrapfig" nil)
3487 ("" "soul" t)
3488 ("" "textcomp" t)
3489 ("" "marvosym" t)
3490 ("" "wasysym" t)
3491 ("" "latexsym" t)
3492 ("" "amssymb" t)
3493 ("" "hyperref" nil)
3494 "\\tolerance=1000"
3496 "Alist of default packages to be inserted in the header.
3497 Change this only if one of the packages here causes an incompatibility
3498 with another package you are using.
3499 The packages in this list are needed by one part or another of Org-mode
3500 to function properly.
3502 - inputenc, fontenc: for basic font and character selection
3503 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3504 for interpreting the entities in `org-entities'. You can skip some of these
3505 packages if you don't use any of the symbols in it.
3506 - graphicx: for including images
3507 - float, wrapfig: for figure placement
3508 - longtable: for long tables
3509 - hyperref: for cross references
3511 Therefore you should not modify this variable unless you know what you
3512 are doing. The one reason to change it anyway is that you might be loading
3513 some other package that conflicts with one of the default packages.
3514 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3515 If SNIPPET-FLAG is t, the package also needs to be included when
3516 compiling LaTeX snippets into images for inclusion into HTML."
3517 :group 'org-export-latex
3518 :set 'org-set-packages-alist
3519 :get 'org-get-packages-alist
3520 :version "24.1"
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3529 (defcustom org-export-latex-packages-alist nil
3530 "Alist of packages to be inserted in every LaTeX header.
3531 These will be inserted after `org-export-latex-default-packages-alist'.
3532 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3533 SNIPPET-FLAG, when t, indicates that this package is also needed when
3534 turning LaTeX snippets into images for inclusion into HTML.
3535 Make sure that you only list packages here which:
3536 - you want in every file
3537 - do not conflict with the default packages in
3538 `org-export-latex-default-packages-alist'
3539 - do not conflict with the setup in `org-format-latex-header'."
3540 :group 'org-export-latex
3541 :set 'org-set-packages-alist
3542 :get 'org-get-packages-alist
3543 :type '(repeat
3544 (choice
3545 (list :tag "options/package pair"
3546 (string :tag "options")
3547 (string :tag "package")
3548 (boolean :tag "Snippet"))
3549 (string :tag "A line of LaTeX"))))
3552 (defgroup org-appearance nil
3553 "Settings for Org-mode appearance."
3554 :tag "Org Appearance"
3555 :group 'org)
3557 (defcustom org-level-color-stars-only nil
3558 "Non-nil means fontify only the stars in each headline.
3559 When nil, the entire headline is fontified.
3560 Changing it requires restart of `font-lock-mode' to become effective
3561 also in regions already fontified."
3562 :group 'org-appearance
3563 :type 'boolean)
3565 (defcustom org-hide-leading-stars nil
3566 "Non-nil means hide the first N-1 stars in a headline.
3567 This works by using the face `org-hide' for these stars. This
3568 face is white for a light background, and black for a dark
3569 background. You may have to customize the face `org-hide' to
3570 make this work.
3571 Changing it requires restart of `font-lock-mode' to become effective
3572 also in regions already fontified.
3573 You may also set this on a per-file basis by adding one of the following
3574 lines to the buffer:
3576 #+STARTUP: hidestars
3577 #+STARTUP: showstars"
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hidden-keywords nil
3582 "List of symbols corresponding to keywords to be hidden the org buffer.
3583 For example, a value '(title) for this list will make the document's title
3584 appear in the buffer without the initial #+TITLE: keyword."
3585 :group 'org-appearance
3586 :version "24.1"
3587 :type '(set (const :tag "#+AUTHOR" author)
3588 (const :tag "#+DATE" date)
3589 (const :tag "#+EMAIL" email)
3590 (const :tag "#+TITLE" title)))
3592 (defcustom org-custom-properties nil
3593 "List of properties (as strings) with a special meaning.
3594 The default use of these custom properties is to let the user
3595 hide them with `org-toggle-custom-properties-visibility'."
3596 :group 'org-properties
3597 :group 'org-appearance
3598 :version "24.3"
3599 :type '(repeat (string :tag "Property Name")))
3601 (defcustom org-fontify-done-headline nil
3602 "Non-nil means change the face of a headline if it is marked DONE.
3603 Normally, only the TODO/DONE keyword indicates the state of a headline.
3604 When this is non-nil, the headline after the keyword is set to the
3605 `org-headline-done' as an additional indication."
3606 :group 'org-appearance
3607 :type 'boolean)
3609 (defcustom org-fontify-emphasized-text t
3610 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3611 Changing this variable requires a restart of Emacs to take effect."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-fontify-whole-heading-line nil
3616 "Non-nil means fontify the whole line for headings.
3617 This is useful when setting a background color for the
3618 org-level-* faces."
3619 :group 'org-appearance
3620 :type 'boolean)
3622 (defcustom org-highlight-latex-fragments-and-specials nil
3623 "Non-nil means fontify what is treated specially by the exporters."
3624 :group 'org-appearance
3625 :type 'boolean)
3627 (defcustom org-hide-emphasis-markers nil
3628 "Non-nil mean font-lock should hide the emphasis marker characters."
3629 :group 'org-appearance
3630 :type 'boolean)
3632 (defcustom org-pretty-entities nil
3633 "Non-nil means show entities as UTF8 characters.
3634 When nil, the \\name form remains in the buffer."
3635 :group 'org-appearance
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-pretty-entities-include-sub-superscripts t
3640 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3641 :group 'org-appearance
3642 :version "24.1"
3643 :type 'boolean)
3645 (defvar org-emph-re nil
3646 "Regular expression for matching emphasis.
3647 After a match, the match groups contain these elements:
3648 0 The match of the full regular expression, including the characters
3649 before and after the proper match
3650 1 The character before the proper match, or empty at beginning of line
3651 2 The proper match, including the leading and trailing markers
3652 3 The leading marker like * or /, indicating the type of highlighting
3653 4 The text between the emphasis markers, not including the markers
3654 5 The character after the match, empty at the end of a line")
3655 (defvar org-verbatim-re nil
3656 "Regular expression for matching verbatim text.")
3657 (defvar org-emphasis-regexp-components) ; defined just below
3658 (defvar org-emphasis-alist) ; defined just below
3659 (defun org-set-emph-re (var val)
3660 "Set variable and compute the emphasis regular expression."
3661 (set var val)
3662 (when (and (boundp 'org-emphasis-alist)
3663 (boundp 'org-emphasis-regexp-components)
3664 org-emphasis-alist org-emphasis-regexp-components)
3665 (let* ((e org-emphasis-regexp-components)
3666 (pre (car e))
3667 (post (nth 1 e))
3668 (border (nth 2 e))
3669 (body (nth 3 e))
3670 (nl (nth 4 e))
3671 (body1 (concat body "*?"))
3672 (markers (mapconcat 'car org-emphasis-alist ""))
3673 (vmarkers (mapconcat
3674 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3675 org-emphasis-alist "")))
3676 ;; make sure special characters appear at the right position in the class
3677 (if (string-match "\\^" markers)
3678 (setq markers (concat (replace-match "" t t markers) "^")))
3679 (if (string-match "-" markers)
3680 (setq markers (concat (replace-match "" t t markers) "-")))
3681 (if (string-match "\\^" vmarkers)
3682 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3683 (if (string-match "-" vmarkers)
3684 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3685 (if (> nl 0)
3686 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3687 (int-to-string nl) "\\}")))
3688 ;; Make the regexp
3689 (setq org-emph-re
3690 (concat "\\([" pre "]\\|^\\)"
3691 "\\("
3692 "\\([" markers "]\\)"
3693 "\\("
3694 "[^" border "]\\|"
3695 "[^" border "]"
3696 body1
3697 "[^" border "]"
3698 "\\)"
3699 "\\3\\)"
3700 "\\([" post "]\\|$\\)"))
3701 (setq org-verbatim-re
3702 (concat "\\([" pre "]\\|^\\)"
3703 "\\("
3704 "\\([" vmarkers "]\\)"
3705 "\\("
3706 "[^" border "]\\|"
3707 "[^" border "]"
3708 body1
3709 "[^" border "]"
3710 "\\)"
3711 "\\3\\)"
3712 "\\([" post "]\\|$\\)")))))
3714 (defcustom org-emphasis-regexp-components
3715 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3716 "Components used to build the regular expression for emphasis.
3717 This is a list with five entries. Terminology: In an emphasis string
3718 like \" *strong word* \", we call the initial space PREMATCH, the final
3719 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3720 and \"trong wor\" is the body. The different components in this variable
3721 specify what is allowed/forbidden in each part:
3723 pre Chars allowed as prematch. Beginning of line will be allowed too.
3724 post Chars allowed as postmatch. End of line will be allowed too.
3725 border The chars *forbidden* as border characters.
3726 body-regexp A regexp like \".\" to match a body character. Don't use
3727 non-shy groups here, and don't allow newline here.
3728 newline The maximum number of newlines allowed in an emphasis exp.
3730 Use customize to modify this, or restart Emacs after changing it."
3731 :group 'org-appearance
3732 :set 'org-set-emph-re
3733 :type '(list
3734 (sexp :tag "Allowed chars in pre ")
3735 (sexp :tag "Allowed chars in post ")
3736 (sexp :tag "Forbidden chars in border ")
3737 (sexp :tag "Regexp for body ")
3738 (integer :tag "number of newlines allowed")
3739 (option (boolean :tag "Please ignore this button"))))
3741 (defcustom org-emphasis-alist
3742 `(("*" bold "<b>" "</b>")
3743 ("/" italic "<i>" "</i>")
3744 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3745 ("=" org-code "<code>" "</code>" verbatim)
3746 ("~" org-verbatim "<code>" "</code>" verbatim)
3747 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3748 "<del>" "</del>")
3750 "Special syntax for emphasized text.
3751 Text starting and ending with a special character will be emphasized, for
3752 example *bold*, _underlined_ and /italic/. This variable sets the marker
3753 characters, the face to be used by font-lock for highlighting in Org-mode
3754 Emacs buffers, and the HTML tags to be used for this.
3755 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3756 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3757 Use customize to modify this, or restart Emacs after changing it."
3758 :group 'org-appearance
3759 :set 'org-set-emph-re
3760 :type '(repeat
3761 (list
3762 (string :tag "Marker character")
3763 (choice
3764 (face :tag "Font-lock-face")
3765 (plist :tag "Face property list"))
3766 (string :tag "HTML start tag")
3767 (string :tag "HTML end tag")
3768 (option (const verbatim)))))
3770 (defvar org-protecting-blocks
3771 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3772 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3773 This is needed for font-lock setup.")
3775 ;;; Miscellaneous options
3777 (defgroup org-completion nil
3778 "Completion in Org-mode."
3779 :tag "Org Completion"
3780 :group 'org)
3782 (defcustom org-completion-use-ido nil
3783 "Non-nil means use ido completion wherever possible.
3784 Note that `ido-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 See also `org-completion-use-iswitchb'."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-use-iswitchb nil
3792 "Non-nil means use iswitchb completion wherever possible.
3793 Note that `iswitchb-mode' must be active for this variable to be relevant.
3794 If you decide to turn this variable on, you might well want to turn off
3795 `org-outline-path-complete-in-steps'.
3796 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3797 :group 'org-completion
3798 :type 'boolean)
3800 (defcustom org-completion-fallback-command 'hippie-expand
3801 "The expansion command called by \\[pcomplete] in normal context.
3802 Normal means, no org-mode-specific context."
3803 :group 'org-completion
3804 :type 'function)
3806 ;;; Functions and variables from their packages
3807 ;; Declared here to avoid compiler warnings
3809 ;; XEmacs only
3810 (defvar outline-mode-menu-heading)
3811 (defvar outline-mode-menu-show)
3812 (defvar outline-mode-menu-hide)
3813 (defvar zmacs-regions) ; XEmacs regions
3815 ;; Emacs only
3816 (defvar mark-active)
3818 ;; Various packages
3819 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3820 (declare-function calendar-forward-day "cal-move" (arg))
3821 (declare-function calendar-goto-date "cal-move" (date))
3822 (declare-function calendar-goto-today "cal-move" ())
3823 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3824 (defvar calc-embedded-close-formula)
3825 (defvar calc-embedded-open-formula)
3826 (declare-function cdlatex-tab "ext:cdlatex" ())
3827 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3828 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3829 (defvar font-lock-unfontify-region-function)
3830 (declare-function iswitchb-read-buffer "iswitchb"
3831 (prompt &optional default require-match start matches-set))
3832 (defvar iswitchb-temp-buflist)
3833 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3834 (defvar org-agenda-tags-todo-honor-ignore-options)
3835 (declare-function org-agenda-skip "org-agenda" ())
3836 (declare-function
3837 org-agenda-format-item "org-agenda"
3838 (extra txt &optional category tags dotime noprefix remove-re habitp))
3839 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3840 (declare-function org-agenda-change-all-lines "org-agenda"
3841 (newhead hdmarker &optional fixface just-this))
3842 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3843 (declare-function org-agenda-maybe-redo "org-agenda" ())
3844 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3845 (beg end))
3846 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3847 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3848 "org-agenda" (&optional end))
3849 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3850 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3851 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3852 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3853 (declare-function org-indent-mode "org-indent" (&optional arg))
3854 (declare-function parse-time-string "parse-time" (string))
3855 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3856 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3857 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3858 (defvar remember-data-file)
3859 (defvar texmathp-why)
3860 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3861 (declare-function table--at-cell-p "table" (position &optional object at-column))
3863 (defvar w3m-current-url)
3864 (defvar w3m-current-title)
3866 (defvar org-latex-regexps)
3868 ;;; Autoload and prepare some org modules
3870 ;; Some table stuff that needs to be defined here, because it is used
3871 ;; by the functions setting up org-mode or checking for table context.
3873 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3874 "Detect an org-type or table-type table.")
3875 (defconst org-table-line-regexp "^[ \t]*|"
3876 "Detect an org-type table line.")
3877 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3878 "Detect an org-type table line.")
3879 (defconst org-table-hline-regexp "^[ \t]*|-"
3880 "Detect an org-type table hline.")
3881 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3882 "Detect a table-type table hline.")
3883 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3884 "Detect the first line outside a table when searching from within it.
3885 This works for both table types.")
3887 ;; Autoload the functions in org-table.el that are needed by functions here.
3889 (eval-and-compile
3890 (org-autoload "org-table"
3891 '(org-table-begin org-table-blank-field org-table-end)))
3893 ;;;###autoload
3894 (defun turn-on-orgtbl ()
3895 "Unconditionally turn on `orgtbl-mode'."
3896 (require 'org-table)
3897 (orgtbl-mode 1))
3899 (defun org-at-table-p (&optional table-type)
3900 "Return t if the cursor is inside an org-type table.
3901 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3902 (if org-enable-table-editor
3903 (save-excursion
3904 (beginning-of-line 1)
3905 (looking-at (if table-type org-table-any-line-regexp
3906 org-table-line-regexp)))
3907 nil))
3908 (defsubst org-table-p () (org-at-table-p))
3910 (defun org-at-table.el-p ()
3911 "Return t if and only if we are at a table.el table."
3912 (and (org-at-table-p 'any)
3913 (save-excursion
3914 (goto-char (org-table-begin 'any))
3915 (looking-at org-table1-hline-regexp))))
3916 (defun org-table-recognize-table.el ()
3917 "If there is a table.el table nearby, recognize it and move into it."
3918 (if org-table-tab-recognizes-table.el
3919 (if (org-at-table.el-p)
3920 (progn
3921 (beginning-of-line 1)
3922 (if (looking-at org-table-dataline-regexp)
3924 (if (looking-at org-table1-hline-regexp)
3925 (progn
3926 (beginning-of-line 2)
3927 (if (looking-at org-table-any-border-regexp)
3928 (beginning-of-line -1)))))
3929 (if (re-search-forward "|" (org-table-end t) t)
3930 (progn
3931 (require 'table)
3932 (if (table--at-cell-p (point))
3934 (message "recognizing table.el table...")
3935 (table-recognize-table)
3936 (message "recognizing table.el table...done")))
3937 (error "This should not happen"))
3939 nil)
3940 nil))
3942 (defun org-at-table-hline-p ()
3943 "Return t if the cursor is inside a hline in a table."
3944 (if org-enable-table-editor
3945 (save-excursion
3946 (beginning-of-line 1)
3947 (looking-at org-table-hline-regexp))
3948 nil))
3950 (defvar org-table-clean-did-remove-column nil)
3952 (defun org-table-map-tables (function &optional quietly)
3953 "Apply FUNCTION to the start of all tables in the buffer."
3954 (save-excursion
3955 (save-restriction
3956 (widen)
3957 (goto-char (point-min))
3958 (while (re-search-forward org-table-any-line-regexp nil t)
3959 (unless quietly
3960 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3961 (beginning-of-line 1)
3962 (when (and (looking-at org-table-line-regexp)
3963 ;; Exclude tables in src/example/verbatim/clocktable blocks
3964 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3965 (save-excursion (funcall function))
3966 (or (looking-at org-table-line-regexp)
3967 (forward-char 1)))
3968 (re-search-forward org-table-any-border-regexp nil 1))))
3969 (unless quietly (message "Mapping tables: done")))
3971 ;; Declare and autoload functions from org-exp.el & Co
3973 (declare-function org-default-export-plist "org-exp")
3974 (declare-function org-infile-export-plist "org-exp")
3975 (declare-function org-get-current-options "org-exp")
3977 ;; Declare and autoload functions from org-agenda.el
3979 (eval-and-compile
3980 (org-autoload "org-agenda"
3981 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3983 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3984 (declare-function org-clock-update-mode-line "org-clock" ())
3985 (declare-function org-resolve-clocks "org-clock"
3986 (&optional also-non-dangling-p prompt last-valid))
3987 (defvar org-clock-start-time)
3988 (defvar org-clock-marker (make-marker)
3989 "Marker recording the last clock-in.")
3990 (defvar org-clock-hd-marker (make-marker)
3991 "Marker recording the last clock-in, but the headline position.")
3992 (defvar org-clock-heading ""
3993 "The heading of the current clock entry.")
3994 (defun org-clock-is-active ()
3995 "Return non-nil if clock is currently running.
3996 The return value is actually the clock marker."
3997 (marker-buffer org-clock-marker))
3999 (eval-and-compile
4000 (org-autoload "org-clock" '(org-clock-remove-overlays
4001 org-clock-update-time-maybe
4002 org-clocktable-shift)))
4004 (defun org-check-running-clock ()
4005 "Check if the current buffer contains the running clock.
4006 If yes, offer to stop it and to save the buffer with the changes."
4007 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4008 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4009 (buffer-name))))
4010 (org-clock-out)
4011 (when (y-or-n-p "Save changed buffer?")
4012 (save-buffer))))
4014 (defun org-clocktable-try-shift (dir n)
4015 "Check if this line starts a clock table, if yes, shift the time block."
4016 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4017 (org-clocktable-shift dir n)))
4019 ;;;###autoload
4020 (defun org-clock-persistence-insinuate ()
4021 "Set up hooks for clock persistence."
4022 (require 'org-clock)
4023 (add-hook 'org-mode-hook 'org-clock-load)
4024 (add-hook 'kill-emacs-hook 'org-clock-save))
4026 ;; Define the variable already here, to make sure we have it.
4027 (defvar org-indent-mode nil
4028 "Non-nil if Org-Indent mode is enabled.
4029 Use the command `org-indent-mode' to change this variable.")
4031 ;; Autoload archiving code
4032 ;; The stuff that is needed for cycling and tags has to be defined here.
4034 (defgroup org-archive nil
4035 "Options concerning archiving in Org-mode."
4036 :tag "Org Archive"
4037 :group 'org-structure)
4039 (defcustom org-archive-location "%s_archive::"
4040 "The location where subtrees should be archived.
4042 The value of this variable is a string, consisting of two parts,
4043 separated by a double-colon. The first part is a filename and
4044 the second part is a headline.
4046 When the filename is omitted, archiving happens in the same file.
4047 %s in the filename will be replaced by the current file
4048 name (without the directory part). Archiving to a different file
4049 is useful to keep archived entries from contributing to the
4050 Org-mode Agenda.
4052 The archived entries will be filed as subtrees of the specified
4053 headline. When the headline is omitted, the subtrees are simply
4054 filed away at the end of the file, as top-level entries. Also in
4055 the heading you can use %s to represent the file name, this can be
4056 useful when using the same archive for a number of different files.
4058 Here are a few examples:
4059 \"%s_archive::\"
4060 If the current file is Projects.org, archive in file
4061 Projects.org_archive, as top-level trees. This is the default.
4063 \"::* Archived Tasks\"
4064 Archive in the current file, under the top-level headline
4065 \"* Archived Tasks\".
4067 \"~/org/archive.org::\"
4068 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4070 \"~/org/archive.org::* From %s\"
4071 Archive in file ~/org/archive.org (absolute path), under headlines
4072 \"From FILENAME\" where file name is the current file name.
4074 \"~/org/datetree.org::datetree/* Finished Tasks\"
4075 The \"datetree/\" string is special, signifying to archive
4076 items to the datetree. Items are placed in either the CLOSED
4077 date of the item, or the current date if there is no CLOSED date.
4078 The heading will be a subentry to the current date. There doesn't
4079 need to be a heading, but there always needs to be a slash after
4080 datetree. For example, to store archived items directly in the
4081 datetree, use \"~/org/datetree.org::datetree/\".
4083 \"basement::** Finished Tasks\"
4084 Archive in file ./basement (relative path), as level 3 trees
4085 below the level 2 heading \"** Finished Tasks\".
4087 You may set this option on a per-file basis by adding to the buffer a
4088 line like
4090 #+ARCHIVE: basement::** Finished Tasks
4092 You may also define it locally for a subtree by setting an ARCHIVE property
4093 in the entry. If such a property is found in an entry, or anywhere up
4094 the hierarchy, it will be used."
4095 :group 'org-archive
4096 :type 'string)
4098 (defcustom org-archive-tag "ARCHIVE"
4099 "The tag that marks a subtree as archived.
4100 An archived subtree does not open during visibility cycling, and does
4101 not contribute to the agenda listings.
4102 After changing this, font-lock must be restarted in the relevant buffers to
4103 get the proper fontification."
4104 :group 'org-archive
4105 :group 'org-keywords
4106 :type 'string)
4108 (defcustom org-agenda-skip-archived-trees t
4109 "Non-nil means the agenda will skip any items located in archived trees.
4110 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4111 variable is no longer recommended, you should leave it at the value t.
4112 Instead, use the key `v' to cycle the archives-mode in the agenda."
4113 :group 'org-archive
4114 :group 'org-agenda-skip
4115 :type 'boolean)
4117 (defcustom org-columns-skip-archived-trees t
4118 "Non-nil means ignore archived trees when creating column view."
4119 :group 'org-archive
4120 :group 'org-properties
4121 :type 'boolean)
4123 (defcustom org-cycle-open-archived-trees nil
4124 "Non-nil means `org-cycle' will open archived trees.
4125 An archived tree is a tree marked with the tag ARCHIVE.
4126 When nil, archived trees will stay folded. You can still open them with
4127 normal outline commands like `show-all', but not with the cycling commands."
4128 :group 'org-archive
4129 :group 'org-cycle
4130 :type 'boolean)
4132 (defcustom org-sparse-tree-open-archived-trees nil
4133 "Non-nil means sparse tree construction shows matches in archived trees.
4134 When nil, matches in these trees are highlighted, but the trees are kept in
4135 collapsed state."
4136 :group 'org-archive
4137 :group 'org-sparse-trees
4138 :type 'boolean)
4140 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4141 "The default date type when building a sparse tree.
4142 When this is nil, a date is a scheduled or a deadline timestamp.
4143 Otherwise, these types are allowed:
4145 all: all timestamps
4146 active: only active timestamps (<...>)
4147 inactive: only inactive timestamps (<...)
4148 scheduled: only scheduled timestamps
4149 deadline: only deadline timestamps"
4150 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4151 (const :tag "All timestamps" all)
4152 (const :tag "Only active timestamps" active)
4153 (const :tag "Only inactive timestamps" inactive)
4154 (const :tag "Only scheduled timestamps" scheduled)
4155 (const :tag "Only deadline timestamps" deadline))
4156 :version "24.3"
4157 :group 'org-sparse-trees)
4159 (defun org-cycle-hide-archived-subtrees (state)
4160 "Re-hide all archived subtrees after a visibility state change."
4161 (when (and (not org-cycle-open-archived-trees)
4162 (not (memq state '(overview folded))))
4163 (save-excursion
4164 (let* ((globalp (memq state '(contents all)))
4165 (beg (if globalp (point-min) (point)))
4166 (end (if globalp (point-max) (org-end-of-subtree t))))
4167 (org-hide-archived-subtrees beg end)
4168 (goto-char beg)
4169 (if (looking-at (concat ".*:" org-archive-tag ":"))
4170 (message "%s" (substitute-command-keys
4171 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4173 (defun org-force-cycle-archived ()
4174 "Cycle subtree even if it is archived."
4175 (interactive)
4176 (setq this-command 'org-cycle)
4177 (let ((org-cycle-open-archived-trees t))
4178 (call-interactively 'org-cycle)))
4180 (defun org-hide-archived-subtrees (beg end)
4181 "Re-hide all archived subtrees after a visibility state change."
4182 (save-excursion
4183 (let* ((re (concat ":" org-archive-tag ":")))
4184 (goto-char beg)
4185 (while (re-search-forward re end t)
4186 (when (org-at-heading-p)
4187 (org-flag-subtree t)
4188 (org-end-of-subtree t))))))
4190 (declare-function outline-end-of-heading "outline" ())
4191 (declare-function outline-flag-region "outline" (from to flag))
4192 (defun org-flag-subtree (flag)
4193 (save-excursion
4194 (org-back-to-heading t)
4195 (outline-end-of-heading)
4196 (outline-flag-region (point)
4197 (progn (org-end-of-subtree t) (point))
4198 flag)))
4200 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4202 (eval-and-compile
4203 (org-autoload "org-archive"
4204 '(org-add-archive-files)))
4206 ;; Autoload Column View Code
4208 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4209 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4210 (declare-function org-columns-compute "org-colview" (property))
4212 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4213 '(org-columns-number-to-string
4214 org-columns-get-format-and-top-level
4215 org-columns-compute
4216 org-columns-remove-overlays))
4218 ;; Autoload ID code
4220 (declare-function org-id-store-link "org-id")
4221 (declare-function org-id-locations-load "org-id")
4222 (declare-function org-id-locations-save "org-id")
4223 (defvar org-id-track-globally)
4224 (org-autoload "org-id"
4225 '(org-id-new
4226 org-id-copy
4227 org-id-get-with-outline-path-completion
4228 org-id-get-with-outline-drilling))
4230 ;;; Variables for pre-computed regular expressions, all buffer local
4232 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4233 "Matches first line of a hidden block.")
4234 (make-variable-buffer-local 'org-drawer-regexp)
4235 (defvar org-todo-regexp nil
4236 "Matches any of the TODO state keywords.")
4237 (make-variable-buffer-local 'org-todo-regexp)
4238 (defvar org-not-done-regexp nil
4239 "Matches any of the TODO state keywords except the last one.")
4240 (make-variable-buffer-local 'org-not-done-regexp)
4241 (defvar org-not-done-heading-regexp nil
4242 "Matches a TODO headline that is not done.")
4243 (make-variable-buffer-local 'org-not-done-regexp)
4244 (defvar org-todo-line-regexp nil
4245 "Matches a headline and puts TODO state into group 2 if present.")
4246 (make-variable-buffer-local 'org-todo-line-regexp)
4247 (defvar org-complex-heading-regexp nil
4248 "Matches a headline and puts everything into groups:
4249 group 1: the stars
4250 group 2: The todo keyword, maybe
4251 group 3: Priority cookie
4252 group 4: True headline
4253 group 5: Tags")
4254 (make-variable-buffer-local 'org-complex-heading-regexp)
4255 (defvar org-complex-heading-regexp-format nil
4256 "Printf format to make regexp to match an exact headline.
4257 This regexp will match the headline of any node which has the
4258 exact headline text that is put into the format, but may have any
4259 TODO state, priority and tags.")
4260 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4261 (defvar org-todo-line-tags-regexp nil
4262 "Matches a headline and puts TODO state into group 2 if present.
4263 Also put tags into group 4 if tags are present.")
4264 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4265 (defvar org-ds-keyword-length 12
4266 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4267 (make-variable-buffer-local 'org-ds-keyword-length)
4268 (defvar org-deadline-regexp nil
4269 "Matches the DEADLINE keyword.")
4270 (make-variable-buffer-local 'org-deadline-regexp)
4271 (defvar org-deadline-time-regexp nil
4272 "Matches the DEADLINE keyword together with a time stamp.")
4273 (make-variable-buffer-local 'org-deadline-time-regexp)
4274 (defvar org-deadline-line-regexp nil
4275 "Matches the DEADLINE keyword and the rest of the line.")
4276 (make-variable-buffer-local 'org-deadline-line-regexp)
4277 (defvar org-scheduled-regexp nil
4278 "Matches the SCHEDULED keyword.")
4279 (make-variable-buffer-local 'org-scheduled-regexp)
4280 (defvar org-scheduled-time-regexp nil
4281 "Matches the SCHEDULED keyword together with a time stamp.")
4282 (make-variable-buffer-local 'org-scheduled-time-regexp)
4283 (defvar org-closed-time-regexp nil
4284 "Matches the CLOSED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-closed-time-regexp)
4287 (defvar org-keyword-time-regexp nil
4288 "Matches any of the 4 keywords, together with the time stamp.")
4289 (make-variable-buffer-local 'org-keyword-time-regexp)
4290 (defvar org-keyword-time-not-clock-regexp nil
4291 "Matches any of the 3 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4293 (defvar org-maybe-keyword-time-regexp nil
4294 "Matches a timestamp, possibly preceded by a keyword.")
4295 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4296 (defvar org-all-time-keywords nil
4297 "List of time keywords.")
4298 (make-variable-buffer-local 'org-all-time-keywords)
4300 (defconst org-plain-time-of-day-regexp
4301 (concat
4302 "\\(\\<[012]?[0-9]"
4303 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4304 "\\(--?"
4305 "\\(\\<[012]?[0-9]"
4306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4307 "\\)?")
4308 "Regular expression to match a plain time or time range.
4309 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4310 groups carry important information:
4311 0 the full match
4312 1 the first time, range or not
4313 8 the second time, if it is a range.")
4315 (defconst org-plain-time-extension-regexp
4316 (concat
4317 "\\(\\<[012]?[0-9]"
4318 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4319 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4320 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4321 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4322 groups carry important information:
4323 0 the full match
4324 7 hours of duration
4325 9 minutes of duration")
4327 (defconst org-stamp-time-of-day-regexp
4328 (concat
4329 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4330 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4331 "\\(--?"
4332 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4333 "Regular expression to match a timestamp time or time range.
4334 After a match, the following groups carry important information:
4335 0 the full match
4336 1 date plus weekday, for back referencing to make sure both times are on the same day
4337 2 the first time, range or not
4338 4 the second time, if it is a range.")
4340 (defconst org-startup-options
4341 '(("fold" org-startup-folded t)
4342 ("overview" org-startup-folded t)
4343 ("nofold" org-startup-folded nil)
4344 ("showall" org-startup-folded nil)
4345 ("showeverything" org-startup-folded showeverything)
4346 ("content" org-startup-folded content)
4347 ("indent" org-startup-indented t)
4348 ("noindent" org-startup-indented nil)
4349 ("hidestars" org-hide-leading-stars t)
4350 ("showstars" org-hide-leading-stars nil)
4351 ("odd" org-odd-levels-only t)
4352 ("oddeven" org-odd-levels-only nil)
4353 ("align" org-startup-align-all-tables t)
4354 ("noalign" org-startup-align-all-tables nil)
4355 ("inlineimages" org-startup-with-inline-images t)
4356 ("noinlineimages" org-startup-with-inline-images nil)
4357 ("customtime" org-display-custom-times t)
4358 ("logdone" org-log-done time)
4359 ("lognotedone" org-log-done note)
4360 ("nologdone" org-log-done nil)
4361 ("lognoteclock-out" org-log-note-clock-out t)
4362 ("nolognoteclock-out" org-log-note-clock-out nil)
4363 ("logrepeat" org-log-repeat state)
4364 ("lognoterepeat" org-log-repeat note)
4365 ("nologrepeat" org-log-repeat nil)
4366 ("logreschedule" org-log-reschedule time)
4367 ("lognotereschedule" org-log-reschedule note)
4368 ("nologreschedule" org-log-reschedule nil)
4369 ("logredeadline" org-log-redeadline time)
4370 ("lognoteredeadline" org-log-redeadline note)
4371 ("nologredeadline" org-log-redeadline nil)
4372 ("logrefile" org-log-refile time)
4373 ("lognoterefile" org-log-refile note)
4374 ("nologrefile" org-log-refile nil)
4375 ("fninline" org-footnote-define-inline t)
4376 ("nofninline" org-footnote-define-inline nil)
4377 ("fnlocal" org-footnote-section nil)
4378 ("fnauto" org-footnote-auto-label t)
4379 ("fnprompt" org-footnote-auto-label nil)
4380 ("fnconfirm" org-footnote-auto-label confirm)
4381 ("fnplain" org-footnote-auto-label plain)
4382 ("fnadjust" org-footnote-auto-adjust t)
4383 ("nofnadjust" org-footnote-auto-adjust nil)
4384 ("constcgs" constants-unit-system cgs)
4385 ("constSI" constants-unit-system SI)
4386 ("noptag" org-tag-persistent-alist nil)
4387 ("hideblocks" org-hide-block-startup t)
4388 ("nohideblocks" org-hide-block-startup nil)
4389 ("beamer" org-startup-with-beamer-mode t)
4390 ("entitiespretty" org-pretty-entities t)
4391 ("entitiesplain" org-pretty-entities nil))
4392 "Variable associated with STARTUP options for org-mode.
4393 Each element is a list of three items: the startup options (as written
4394 in the #+STARTUP line), the corresponding variable, and the value to set
4395 this variable to if the option is found. An optional forth element PUSH
4396 means to push this value onto the list in the variable.")
4398 (defun org-update-property-plist (key val props)
4399 "Update PROPS with KEY and VAL."
4400 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4401 (key (if appending (substring key 0 (- (length key) 1)) key))
4402 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4403 (previous (cdr (assoc key props))))
4404 (if appending
4405 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4406 (cons (cons key val) remainder))))
4408 (defconst org-block-regexp
4409 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4410 "Regular expression for hiding blocks.")
4411 (defconst org-heading-keyword-regexp-format
4412 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4413 "Printf format for a regexp matching an headline with some keyword.
4414 This regexp will match the headline of any node which has the
4415 exact keyword that is put into the format. The keyword isn't in
4416 any group by default, but the stars and the body are.")
4417 (defconst org-heading-keyword-maybe-regexp-format
4418 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4419 "Printf format for a regexp matching an headline, possibly with some keyword.
4420 This regexp can match any headline with the specified keyword, or
4421 without a keyword. The keyword isn't in any group by default,
4422 but the stars and the body are.")
4424 (defun org-set-regexps-and-options ()
4425 "Precompute regular expressions for current buffer."
4426 (when (derived-mode-p 'org-mode)
4427 (org-set-local 'org-todo-kwd-alist nil)
4428 (org-set-local 'org-todo-key-alist nil)
4429 (org-set-local 'org-todo-key-trigger nil)
4430 (org-set-local 'org-todo-keywords-1 nil)
4431 (org-set-local 'org-done-keywords nil)
4432 (org-set-local 'org-todo-heads nil)
4433 (org-set-local 'org-todo-sets nil)
4434 (org-set-local 'org-todo-log-states nil)
4435 (org-set-local 'org-file-properties nil)
4436 (org-set-local 'org-file-tags nil)
4437 (let ((re (org-make-options-regexp
4438 '("CATEGORY" "TODO" "COLUMNS"
4439 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4440 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4441 "OPTIONS")
4442 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4443 (splitre "[ \t]+")
4444 (scripts org-use-sub-superscripts)
4445 kwds kws0 kwsa key log value cat arch tags const links hw dws
4446 tail sep kws1 prio props ftags drawers beamer-p
4447 ext-setup-or-nil setup-contents (start 0))
4448 (save-excursion
4449 (save-restriction
4450 (widen)
4451 (goto-char (point-min))
4452 (while (or (and ext-setup-or-nil
4453 (string-match re ext-setup-or-nil start)
4454 (setq start (match-end 0)))
4455 (and (setq ext-setup-or-nil nil start 0)
4456 (re-search-forward re nil t)))
4457 (setq key (upcase (match-string 1 ext-setup-or-nil))
4458 value (org-match-string-no-properties 2 ext-setup-or-nil))
4459 (if (stringp value) (setq value (org-trim value)))
4460 (cond
4461 ((equal key "CATEGORY")
4462 (setq cat value))
4463 ((member key '("SEQ_TODO" "TODO"))
4464 (push (cons 'sequence (org-split-string value splitre)) kwds))
4465 ((equal key "TYP_TODO")
4466 (push (cons 'type (org-split-string value splitre)) kwds))
4467 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4468 ;; general TODO-like setup
4469 (push (cons (intern (downcase (match-string 1 key)))
4470 (org-split-string value splitre)) kwds))
4471 ((equal key "TAGS")
4472 (setq tags (append tags (if tags '("\\n") nil)
4473 (org-split-string value splitre))))
4474 ((equal key "COLUMNS")
4475 (org-set-local 'org-columns-default-format value))
4476 ((equal key "LINK")
4477 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4478 (push (cons (match-string 1 value)
4479 (org-trim (match-string 2 value)))
4480 links)))
4481 ((equal key "PRIORITIES")
4482 (setq prio (org-split-string value " +")))
4483 ((equal key "PROPERTY")
4484 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4485 (setq props (org-update-property-plist (match-string 1 value)
4486 (match-string 2 value)
4487 props))))
4488 ((equal key "FILETAGS")
4489 (when (string-match "\\S-" value)
4490 (setq ftags
4491 (append
4492 ftags
4493 (apply 'append
4494 (mapcar (lambda (x) (org-split-string x ":"))
4495 (org-split-string value)))))))
4496 ((equal key "DRAWERS")
4497 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4498 ((equal key "CONSTANTS")
4499 (setq const (append const (org-split-string value splitre))))
4500 ((equal key "STARTUP")
4501 (let ((opts (org-split-string value splitre))
4502 l var val)
4503 (while (setq l (pop opts))
4504 (when (setq l (assoc l org-startup-options))
4505 (setq var (nth 1 l) val (nth 2 l))
4506 (if (not (nth 3 l))
4507 (set (make-local-variable var) val)
4508 (if (not (listp (symbol-value var)))
4509 (set (make-local-variable var) nil))
4510 (set (make-local-variable var) (symbol-value var))
4511 (add-to-list var val))))))
4512 ((equal key "ARCHIVE")
4513 (setq arch value)
4514 (remove-text-properties 0 (length arch)
4515 '(face t fontified t) arch))
4516 ((equal key "LATEX_CLASS")
4517 (setq beamer-p (equal value "beamer")))
4518 ((equal key "OPTIONS")
4519 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4520 (setq scripts (read (match-string 2 value)))))
4521 ((equal key "SETUPFILE")
4522 (setq setup-contents (org-file-contents
4523 (expand-file-name
4524 (org-remove-double-quotes value))
4525 'noerror))
4526 (if (not ext-setup-or-nil)
4527 (setq ext-setup-or-nil setup-contents start 0)
4528 (setq ext-setup-or-nil
4529 (concat (substring ext-setup-or-nil 0 start)
4530 "\n" setup-contents "\n"
4531 (substring ext-setup-or-nil start)))))))
4532 ;; search for property blocks
4533 (goto-char (point-min))
4534 (while (re-search-forward org-block-regexp nil t)
4535 (when (equal "PROPERTY" (upcase (match-string 1)))
4536 (setq value (replace-regexp-in-string
4537 "[\n\r]" " " (match-string 4)))
4538 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4539 (setq props (org-update-property-plist (match-string 1 value)
4540 (match-string 2 value)
4541 props)))))))
4542 (org-set-local 'org-use-sub-superscripts scripts)
4543 (when cat
4544 (org-set-local 'org-category (intern cat))
4545 (push (cons "CATEGORY" cat) props))
4546 (when prio
4547 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4548 (setq prio (mapcar 'string-to-char prio))
4549 (org-set-local 'org-highest-priority (nth 0 prio))
4550 (org-set-local 'org-lowest-priority (nth 1 prio))
4551 (org-set-local 'org-default-priority (nth 2 prio)))
4552 (and props (org-set-local 'org-file-properties (nreverse props)))
4553 (and ftags (org-set-local 'org-file-tags
4554 (mapcar 'org-add-prop-inherited ftags)))
4555 (and drawers (org-set-local 'org-drawers drawers))
4556 (and arch (org-set-local 'org-archive-location arch))
4557 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4558 ;; Process the TODO keywords
4559 (unless kwds
4560 ;; Use the global values as if they had been given locally.
4561 (setq kwds (default-value 'org-todo-keywords))
4562 (if (stringp (car kwds))
4563 (setq kwds (list (cons org-todo-interpretation
4564 (default-value 'org-todo-keywords)))))
4565 (setq kwds (reverse kwds)))
4566 (setq kwds (nreverse kwds))
4567 (let (inter kws kw)
4568 (while (setq kws (pop kwds))
4569 (let ((kws (or
4570 (run-hook-with-args-until-success
4571 'org-todo-setup-filter-hook kws)
4572 kws)))
4573 (setq inter (pop kws) sep (member "|" kws)
4574 kws0 (delete "|" (copy-sequence kws))
4575 kwsa nil
4576 kws1 (mapcar
4577 (lambda (x)
4578 ;; 1 2
4579 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4580 (progn
4581 (setq kw (match-string 1 x)
4582 key (and (match-end 2) (match-string 2 x))
4583 log (org-extract-log-state-settings x))
4584 (push (cons kw (and key (string-to-char key))) kwsa)
4585 (and log (push log org-todo-log-states))
4587 (error "Invalid TODO keyword %s" x)))
4588 kws0)
4589 kwsa (if kwsa (append '((:startgroup))
4590 (nreverse kwsa)
4591 '((:endgroup))))
4592 hw (car kws1)
4593 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4594 tail (list inter hw (car dws) (org-last dws))))
4595 (add-to-list 'org-todo-heads hw 'append)
4596 (push kws1 org-todo-sets)
4597 (setq org-done-keywords (append org-done-keywords dws nil))
4598 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4599 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4600 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4601 (setq org-todo-sets (nreverse org-todo-sets)
4602 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4603 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4604 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4605 ;; Process the constants
4606 (when const
4607 (let (e cst)
4608 (while (setq e (pop const))
4609 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4610 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4611 (setq org-table-formula-constants-local cst)))
4613 ;; Process the tags.
4614 (when tags
4615 (let (e tgs)
4616 (while (setq e (pop tags))
4617 (cond
4618 ((equal e "{") (push '(:startgroup) tgs))
4619 ((equal e "}") (push '(:endgroup) tgs))
4620 ((equal e "\\n") (push '(:newline) tgs))
4621 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4622 (push (cons (match-string 1 e)
4623 (string-to-char (match-string 2 e)))
4624 tgs))
4625 (t (push (list e) tgs))))
4626 (org-set-local 'org-tag-alist nil)
4627 (while (setq e (pop tgs))
4628 (or (and (stringp (car e))
4629 (assoc (car e) org-tag-alist))
4630 (push e org-tag-alist)))))
4632 ;; Compute the regular expressions and other local variables.
4633 ;; Using `org-outline-regexp-bol' would complicate them much,
4634 ;; because of the fixed white space at the end of that string.
4635 (if (not org-done-keywords)
4636 (setq org-done-keywords (and org-todo-keywords-1
4637 (list (org-last org-todo-keywords-1)))))
4638 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4639 (length org-scheduled-string)
4640 (length org-clock-string)
4641 (length org-closed-string)))
4642 org-drawer-regexp
4643 (concat "^[ \t]*:\\("
4644 (mapconcat 'regexp-quote org-drawers "\\|")
4645 "\\):[ \t]*$")
4646 org-not-done-keywords
4647 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4648 org-todo-regexp
4649 (concat "\\("
4650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4651 "\\)")
4652 org-not-done-regexp
4653 (concat "\\("
4654 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4655 "\\)")
4656 org-not-done-heading-regexp
4657 (format org-heading-keyword-regexp-format org-not-done-regexp)
4658 org-todo-line-regexp
4659 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4660 org-complex-heading-regexp
4661 (concat "^\\(\\*+\\)"
4662 "\\(?: +" org-todo-regexp "\\)?"
4663 "\\(?: +\\(\\[#.\\]\\)\\)?"
4664 "\\(?: +\\(.*?\\)\\)??"
4665 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4666 "[ \t]*$")
4667 org-complex-heading-regexp-format
4668 (concat "^\\(\\*+\\)"
4669 "\\(?: +" org-todo-regexp "\\)?"
4670 "\\(?: +\\(\\[#.\\]\\)\\)?"
4671 "\\(?: +"
4672 ;; Stats cookies can be stuck to body.
4673 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4674 "\\(%s\\)"
4675 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4676 "\\)"
4677 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4678 "[ \t]*$")
4679 org-todo-line-tags-regexp
4680 (concat "^\\(\\*+\\)"
4681 "\\(?: +" org-todo-regexp "\\)?"
4682 "\\(?: +\\(.*?\\)\\)??"
4683 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4684 "[ \t]*$")
4685 org-deadline-regexp (concat "\\<" org-deadline-string)
4686 org-deadline-time-regexp
4687 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4688 org-deadline-line-regexp
4689 (concat "\\<\\(" org-deadline-string "\\).*")
4690 org-scheduled-regexp
4691 (concat "\\<" org-scheduled-string)
4692 org-scheduled-time-regexp
4693 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4694 org-closed-time-regexp
4695 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4696 org-keyword-time-regexp
4697 (concat "\\<\\(" org-scheduled-string
4698 "\\|" org-deadline-string
4699 "\\|" org-closed-string
4700 "\\|" org-clock-string "\\)"
4701 " *[[<]\\([^]>]+\\)[]>]")
4702 org-keyword-time-not-clock-regexp
4703 (concat "\\<\\(" org-scheduled-string
4704 "\\|" org-deadline-string
4705 "\\|" org-closed-string
4706 "\\)"
4707 " *[[<]\\([^]>]+\\)[]>]")
4708 org-maybe-keyword-time-regexp
4709 (concat "\\(\\<\\(" org-scheduled-string
4710 "\\|" org-deadline-string
4711 "\\|" org-closed-string
4712 "\\|" org-clock-string "\\)\\)?"
4713 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4714 org-all-time-keywords
4715 (mapcar (lambda (w) (substring w 0 -1))
4716 (list org-scheduled-string org-deadline-string
4717 org-clock-string org-closed-string))
4719 (org-compute-latex-and-specials-regexp)
4720 (org-set-font-lock-defaults))))
4722 (defun org-file-contents (file &optional noerror)
4723 "Return the contents of FILE, as a string."
4724 (if (or (not file)
4725 (not (file-readable-p file)))
4726 (if noerror
4727 (progn
4728 (message "Cannot read file \"%s\"" file)
4729 (ding) (sit-for 2)
4731 (error "Cannot read file \"%s\"" file))
4732 (with-temp-buffer
4733 (insert-file-contents file)
4734 (buffer-string))))
4736 (defun org-extract-log-state-settings (x)
4737 "Extract the log state setting from a TODO keyword string.
4738 This will extract info from a string like \"WAIT(w@/!)\"."
4739 (let (kw key log1 log2)
4740 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log1 (and (match-end 3) (match-string 3 x))
4744 log2 (and (match-end 4) (match-string 4 x)))
4745 (and (or log1 log2)
4746 (list kw
4747 (and log1 (if (equal log1 "!") 'time 'note))
4748 (and log2 (if (equal log2 "!") 'time 'note)))))))
4750 (defun org-remove-keyword-keys (list)
4751 "Remove a pair of parenthesis at the end of each string in LIST."
4752 (mapcar (lambda (x)
4753 (if (string-match "(.*)$" x)
4754 (substring x 0 (match-beginning 0))
4756 list))
4758 (defun org-assign-fast-keys (alist)
4759 "Assign fast keys to a keyword-key alist.
4760 Respect keys that are already there."
4761 (let (new e (alt ?0))
4762 (while (setq e (pop alist))
4763 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4764 (cdr e)) ;; Key already assigned.
4765 (push e new)
4766 (let ((clist (string-to-list (downcase (car e))))
4767 (used (append new alist)))
4768 (when (= (car clist) ?@)
4769 (pop clist))
4770 (while (and clist (rassoc (car clist) used))
4771 (pop clist))
4772 (unless clist
4773 (while (rassoc alt used)
4774 (incf alt)))
4775 (push (cons (car e) (or (car clist) alt)) new))))
4776 (nreverse new)))
4778 ;;; Some variables used in various places
4780 (defvar org-window-configuration nil
4781 "Used in various places to store a window configuration.")
4782 (defvar org-selected-window nil
4783 "Used in various places to store a window configuration.")
4784 (defvar org-finish-function nil
4785 "Function to be called when `C-c C-c' is used.
4786 This is for getting out of special buffers like capture.")
4789 ;; FIXME: Occasionally check by commenting these, to make sure
4790 ;; no other functions uses these, forgetting to let-bind them.
4791 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4792 (defvar org-last-state)
4793 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4795 ;; Defined somewhere in this file, but used before definition.
4796 (defvar org-entities) ;; defined in org-entities.el
4797 (defvar org-struct-menu)
4798 (defvar org-org-menu)
4799 (defvar org-tbl-menu)
4801 ;;;; Define the Org-mode
4803 ;; We use a before-change function to check if a table might need
4804 ;; an update.
4805 (defvar org-table-may-need-update t
4806 "Indicates that a table might need an update.
4807 This variable is set by `org-before-change-function'.
4808 `org-table-align' sets it back to nil.")
4809 (defun org-before-change-function (beg end)
4810 "Every change indicates that a table might need an update."
4811 (setq org-table-may-need-update t))
4812 (defvar org-mode-map)
4813 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4814 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4815 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4816 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4818 (defvar org-table-buffer-is-an nil)
4820 (defvar bidi-paragraph-direction)
4821 (defvar buffer-face-mode-face)
4823 (require 'outline)
4824 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4825 (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"))
4826 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4828 ;; Other stuff we need.
4829 (require 'time-date)
4830 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4831 (require 'easymenu)
4832 (require 'overlay)
4834 (require 'org-macs)
4835 (require 'org-entities)
4836 ;; (require 'org-compat) moved higher up in the file before it is first used
4837 (require 'org-faces)
4838 (require 'org-list)
4839 (require 'org-pcomplete)
4840 (require 'org-src)
4841 (require 'org-footnote)
4843 ;; babel
4844 (require 'ob)
4845 (require 'ob-table)
4846 (require 'ob-lob)
4847 (require 'ob-ref)
4848 (require 'ob-tangle)
4849 (require 'ob-comint)
4850 (require 'ob-keys)
4852 ;;;###autoload
4853 (define-derived-mode org-mode outline-mode "Org"
4854 "Outline-based notes management and organizer, alias
4855 \"Carsten's outline-mode for keeping track of everything.\"
4857 Org-mode develops organizational tasks around a NOTES file which
4858 contains information about projects as plain text. Org-mode is
4859 implemented on top of outline-mode, which is ideal to keep the content
4860 of large files well structured. It supports ToDo items, deadlines and
4861 time stamps, which magically appear in the diary listing of the Emacs
4862 calendar. Tables are easily created with a built-in table editor.
4863 Plain text URL-like links connect to websites, emails (VM), Usenet
4864 messages (Gnus), BBDB entries, and any files related to the project.
4865 For printing and sharing of notes, an Org-mode file (or a part of it)
4866 can be exported as a structured ASCII or HTML file.
4868 The following commands are available:
4870 \\{org-mode-map}"
4872 ;; Get rid of Outline menus, they are not needed
4873 ;; Need to do this here because define-derived-mode sets up
4874 ;; the keymap so late. Still, it is a waste to call this each time
4875 ;; we switch another buffer into org-mode.
4876 (if (featurep 'xemacs)
4877 (when (boundp 'outline-mode-menu-heading)
4878 ;; Assume this is Greg's port, it uses easymenu
4879 (easy-menu-remove outline-mode-menu-heading)
4880 (easy-menu-remove outline-mode-menu-show)
4881 (easy-menu-remove outline-mode-menu-hide))
4882 (define-key org-mode-map [menu-bar headings] 'undefined)
4883 (define-key org-mode-map [menu-bar hide] 'undefined)
4884 (define-key org-mode-map [menu-bar show] 'undefined))
4886 (org-load-modules-maybe)
4887 (easy-menu-add org-org-menu)
4888 (easy-menu-add org-tbl-menu)
4889 (org-install-agenda-files-menu)
4890 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4891 (add-to-invisibility-spec '(org-cwidth))
4892 (add-to-invisibility-spec '(org-hide-block . t))
4893 (when (featurep 'xemacs)
4894 (org-set-local 'line-move-ignore-invisible t))
4895 (org-set-local 'outline-regexp org-outline-regexp)
4896 (org-set-local 'outline-level 'org-outline-level)
4897 (setq bidi-paragraph-direction 'left-to-right)
4898 (when (and org-ellipsis
4899 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4900 (fboundp 'make-glyph-code))
4901 (unless org-display-table
4902 (setq org-display-table (make-display-table)))
4903 (set-display-table-slot
4904 org-display-table 4
4905 (vconcat (mapcar
4906 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4907 org-ellipsis)))
4908 (if (stringp org-ellipsis) org-ellipsis "..."))))
4909 (setq buffer-display-table org-display-table))
4910 (org-set-regexps-and-options)
4911 (when (and org-tag-faces (not org-tags-special-faces-re))
4912 ;; tag faces set outside customize.... force initialization.
4913 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4914 ;; Calc embedded
4915 (org-set-local 'calc-embedded-open-mode "# ")
4916 (modify-syntax-entry ?@ "w")
4917 (if org-startup-truncated (setq truncate-lines t))
4918 (org-set-local 'font-lock-unfontify-region-function
4919 'org-unfontify-region)
4920 ;; Activate before-change-function
4921 (org-set-local 'org-table-may-need-update t)
4922 (org-add-hook 'before-change-functions 'org-before-change-function nil
4923 'local)
4924 ;; Check for running clock before killing a buffer
4925 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4926 ;; Indentation.
4927 (org-set-local 'indent-line-function 'org-indent-line)
4928 (org-set-local 'indent-region-function 'org-indent-region)
4929 ;; Initialize radio targets.
4930 (org-update-radio-target-regexp)
4931 ;; Filling and auto-filling.
4932 (org-setup-filling)
4933 ;; Comments.
4934 (org-setup-comments-handling)
4935 ;; Beginning/end of defun
4936 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4937 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4938 ;; Next error for sparse trees
4939 (org-set-local 'next-error-function 'org-occur-next-match)
4940 ;; Make sure dependence stuff works reliably, even for users who set it
4941 ;; too late :-(
4942 (if org-enforce-todo-dependencies
4943 (add-hook 'org-blocker-hook
4944 'org-block-todo-from-children-or-siblings-or-parent)
4945 (remove-hook 'org-blocker-hook
4946 'org-block-todo-from-children-or-siblings-or-parent))
4947 (if org-enforce-todo-checkbox-dependencies
4948 (add-hook 'org-blocker-hook
4949 'org-block-todo-from-checkboxes)
4950 (remove-hook 'org-blocker-hook
4951 'org-block-todo-from-checkboxes))
4953 ;; Align options lines
4954 (org-set-local
4955 'align-mode-rules-list
4956 '((org-in-buffer-settings
4957 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4958 (modes . '(org-mode)))))
4960 ;; Imenu
4961 (org-set-local 'imenu-create-index-function
4962 'org-imenu-get-tree)
4964 ;; Make isearch reveal context
4965 (if (or (featurep 'xemacs)
4966 (not (boundp 'outline-isearch-open-invisible-function)))
4967 ;; Emacs 21 and XEmacs make use of the hook
4968 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4969 ;; Emacs 22 deals with this through a special variable
4970 (org-set-local 'outline-isearch-open-invisible-function
4971 (lambda (&rest ignore) (org-show-context 'isearch))))
4973 ;; Turn on org-beamer-mode?
4974 (and org-startup-with-beamer-mode (org-beamer-mode))
4976 ;; Setup the pcomplete hooks
4977 (set (make-local-variable 'pcomplete-command-completion-function)
4978 'org-pcomplete-initial)
4979 (set (make-local-variable 'pcomplete-command-name-function)
4980 'org-command-at-point)
4981 (set (make-local-variable 'pcomplete-default-completion-function)
4982 'ignore)
4983 (set (make-local-variable 'pcomplete-parse-arguments-function)
4984 'org-parse-arguments)
4985 (set (make-local-variable 'pcomplete-termination-string) "")
4986 (when (>= emacs-major-version 23)
4987 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4989 ;; If empty file that did not turn on org-mode automatically, make it to.
4990 (if (and org-insert-mode-line-in-empty-file
4991 (org-called-interactively-p 'any)
4992 (= (point-min) (point-max)))
4993 (insert "# -*- mode: org -*-\n\n"))
4994 (unless org-inhibit-startup
4995 (when org-startup-align-all-tables
4996 (let ((bmp (buffer-modified-p)))
4997 (org-table-map-tables 'org-table-align 'quietly)
4998 (set-buffer-modified-p bmp)))
4999 (when org-startup-with-inline-images
5000 (org-display-inline-images))
5001 (when org-startup-indented
5002 (require 'org-indent)
5003 (org-indent-mode 1))
5004 (unless org-inhibit-startup-visibility-stuff
5005 (org-set-startup-visibility)))
5006 ;; Try to set org-hide correctly
5007 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5009 (when (fboundp 'abbrev-table-put)
5010 (abbrev-table-put org-mode-abbrev-table
5011 :parents (list text-mode-abbrev-table)))
5013 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5016 (defun org-find-invisible-foreground ()
5017 (let ((candidates (remove
5018 "unspecified-bg"
5019 (nconc
5020 (list (face-background 'default)
5021 (face-background 'org-default))
5022 (mapcar
5023 (lambda (alist)
5024 (when (boundp alist)
5025 (cdr (assoc 'background-color (symbol-value alist)))))
5026 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5027 (list (face-foreground 'org-hide))))))
5028 (car (remove nil candidates))))
5030 (defun org-current-time ()
5031 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5032 (if (> (car org-time-stamp-rounding-minutes) 1)
5033 (let ((r (car org-time-stamp-rounding-minutes))
5034 (time (decode-time)))
5035 (apply 'encode-time
5036 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5037 (nthcdr 2 time))))
5038 (current-time)))
5040 (defun org-today ()
5041 "Return today date, considering `org-extend-today-until'."
5042 (time-to-days
5043 (time-subtract (current-time)
5044 (list 0 (* 3600 org-extend-today-until) 0))))
5046 ;;;; Font-Lock stuff, including the activators
5048 (defvar org-mouse-map (make-sparse-keymap))
5049 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5050 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5051 (when org-mouse-1-follows-link
5052 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5053 (when org-tab-follows-link
5054 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5055 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5057 (require 'font-lock)
5059 (defconst org-non-link-chars "]\t\n\r<>")
5060 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5061 "shell" "elisp" "doi" "message"))
5062 (defvar org-link-types-re nil
5063 "Matches a link that has a url-like prefix like \"http:\"")
5064 (defvar org-link-re-with-space nil
5065 "Matches a link with spaces, optional angular brackets around it.")
5066 (defvar org-link-re-with-space2 nil
5067 "Matches a link with spaces, optional angular brackets around it.")
5068 (defvar org-link-re-with-space3 nil
5069 "Matches a link with spaces, only for internal part in bracket links.")
5070 (defvar org-angle-link-re nil
5071 "Matches link with angular brackets, spaces are allowed.")
5072 (defvar org-plain-link-re nil
5073 "Matches plain link, without spaces.")
5074 (defvar org-bracket-link-regexp nil
5075 "Matches a link in double brackets.")
5076 (defvar org-bracket-link-analytic-regexp nil
5077 "Regular expression used to analyze links.
5078 Here is what the match groups contain after a match:
5079 1: http:
5080 2: http
5081 3: path
5082 4: [desc]
5083 5: desc")
5084 (defvar org-bracket-link-analytic-regexp++ nil
5085 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5086 (defvar org-any-link-re nil
5087 "Regular expression matching any link.")
5089 (defcustom org-match-sexp-depth 3
5090 "Number of stacked braces for sub/superscript matching.
5091 This has to be set before loading org.el to be effective."
5092 :group 'org-export-translation ; ??????????????????????????/
5093 :type 'integer)
5095 (defun org-create-multibrace-regexp (left right n)
5096 "Create a regular expression which will match a balanced sexp.
5097 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5098 as single character strings.
5099 The regexp returned will match the entire expression including the
5100 delimiters. It will also define a single group which contains the
5101 match except for the outermost delimiters. The maximum depth of
5102 stacked delimiters is N. Escaping delimiters is not possible."
5103 (let* ((nothing (concat "[^" left right "]*?"))
5104 (or "\\|")
5105 (re nothing)
5106 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5107 (while (> n 1)
5108 (setq n (1- n)
5109 re (concat re or next)
5110 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5111 (concat left "\\(" re "\\)" right)))
5113 (defvar org-match-substring-regexp
5114 (concat
5115 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5116 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5117 "\\|"
5118 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5119 "\\|"
5120 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5121 "The regular expression matching a sub- or superscript.")
5123 (defvar org-match-substring-with-braces-regexp
5124 (concat
5125 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5126 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5127 "\\)")
5128 "The regular expression matching a sub- or superscript, forcing braces.")
5130 (defun org-make-link-regexps ()
5131 "Update the link regular expressions.
5132 This should be called after the variable `org-link-types' has changed."
5133 (setq org-link-types-re
5134 (concat
5135 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5136 org-link-re-with-space
5137 (concat
5138 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5139 "\\([^" org-non-link-chars " ]"
5140 "[^" org-non-link-chars "]*"
5141 "[^" org-non-link-chars " ]\\)>?")
5142 org-link-re-with-space2
5143 (concat
5144 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5145 "\\([^" org-non-link-chars " ]"
5146 "[^\t\n\r]*"
5147 "[^" org-non-link-chars " ]\\)>?")
5148 org-link-re-with-space3
5149 (concat
5150 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5151 "\\([^" org-non-link-chars " ]"
5152 "[^\t\n\r]*\\)")
5153 org-angle-link-re
5154 (concat
5155 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5156 "\\([^" org-non-link-chars " ]"
5157 "[^" org-non-link-chars "]*"
5158 "\\)>")
5159 org-plain-link-re
5160 (concat
5161 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5162 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5163 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5164 org-bracket-link-regexp
5165 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5166 org-bracket-link-analytic-regexp
5167 (concat
5168 "\\[\\["
5169 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5170 "\\([^]]+\\)"
5171 "\\]"
5172 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5173 "\\]")
5174 org-bracket-link-analytic-regexp++
5175 (concat
5176 "\\[\\["
5177 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5178 "\\([^]]+\\)"
5179 "\\]"
5180 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5181 "\\]")
5182 org-any-link-re
5183 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5184 org-angle-link-re "\\)\\|\\("
5185 org-plain-link-re "\\)")))
5187 (org-make-link-regexps)
5189 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5190 "Regular expression for fast time stamp matching.")
5191 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5192 "Regular expression for fast time stamp matching.")
5193 (defconst org-ts-regexp0
5194 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5195 "Regular expression matching time strings for analysis.
5196 This one does not require the space after the date, so it can be used
5197 on a string that terminates immediately after the date.")
5198 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5199 "Regular expression matching time strings for analysis.")
5200 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5201 "Regular expression matching time stamps, with groups.")
5202 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5203 "Regular expression matching time stamps (also [..]), with groups.")
5204 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5205 "Regular expression matching a time stamp range.")
5206 (defconst org-tr-regexp-both
5207 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5208 "Regular expression matching a time stamp range.")
5209 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5210 org-ts-regexp "\\)?")
5211 "Regular expression matching a time stamp or time stamp range.")
5212 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5213 org-ts-regexp-both "\\)?")
5214 "Regular expression matching a time stamp or time stamp range.
5215 The time stamps may be either active or inactive.")
5217 (defvar org-emph-face nil)
5219 (defun org-do-emphasis-faces (limit)
5220 "Run through the buffer and add overlays to emphasized strings."
5221 (let (rtn a)
5222 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5223 (if (not (= (char-after (match-beginning 3))
5224 (char-after (match-beginning 4))))
5225 (progn
5226 (setq rtn t)
5227 (setq a (assoc (match-string 3) org-emphasis-alist))
5228 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5229 'face
5230 (nth 1 a))
5231 (and (nth 4 a)
5232 (org-remove-flyspell-overlays-in
5233 (match-beginning 0) (match-end 0)))
5234 (add-text-properties (match-beginning 2) (match-end 2)
5235 '(font-lock-multiline t org-emphasis t))
5236 (when org-hide-emphasis-markers
5237 (add-text-properties (match-end 4) (match-beginning 5)
5238 '(invisible org-link))
5239 (add-text-properties (match-beginning 3) (match-end 3)
5240 '(invisible org-link)))))
5241 (backward-char 1))
5242 rtn))
5244 (defun org-emphasize (&optional char)
5245 "Insert or change an emphasis, i.e. a font like bold or italic.
5246 If there is an active region, change that region to a new emphasis.
5247 If there is no region, just insert the marker characters and position
5248 the cursor between them.
5249 CHAR should be either the marker character, or the first character of the
5250 HTML tag associated with that emphasis. If CHAR is a space, the means
5251 to remove the emphasis of the selected region.
5252 If char is not given (for example in an interactive call) it
5253 will be prompted for."
5254 (interactive)
5255 (let ((eal org-emphasis-alist) e det
5256 (erc org-emphasis-regexp-components)
5257 (prompt "")
5258 (string "") beg end move tag c s)
5259 (if (org-region-active-p)
5260 (setq beg (region-beginning) end (region-end)
5261 string (buffer-substring beg end))
5262 (setq move t))
5264 (while (setq e (pop eal))
5265 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5266 c (aref tag 0))
5267 (push (cons c (string-to-char (car e))) det)
5268 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5269 (substring tag 1)))))
5270 (setq det (nreverse det))
5271 (unless char
5272 (message "%s" (concat "Emphasis marker or tag:" prompt))
5273 (setq char (read-char-exclusive)))
5274 (setq char (or (cdr (assoc char det)) char))
5275 (if (equal char ?\ )
5276 (setq s "" move nil)
5277 (unless (assoc (char-to-string char) org-emphasis-alist)
5278 (error "No such emphasis marker: \"%c\"" char))
5279 (setq s (char-to-string char)))
5280 (while (and (> (length string) 1)
5281 (equal (substring string 0 1) (substring string -1))
5282 (assoc (substring string 0 1) org-emphasis-alist))
5283 (setq string (substring string 1 -1)))
5284 (setq string (concat s string s))
5285 (if beg (delete-region beg end))
5286 (unless (or (bolp)
5287 (string-match (concat "[" (nth 0 erc) "\n]")
5288 (char-to-string (char-before (point)))))
5289 (insert " "))
5290 (unless (or (eobp)
5291 (string-match (concat "[" (nth 1 erc) "\n]")
5292 (char-to-string (char-after (point)))))
5293 (insert " ") (backward-char 1))
5294 (insert string)
5295 (and move (backward-char 1))))
5297 (defconst org-nonsticky-props
5298 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5300 (defsubst org-rear-nonsticky-at (pos)
5301 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5303 (defun org-activate-plain-links (limit)
5304 "Run through the buffer and add overlays to links."
5305 (catch 'exit
5306 (let (f)
5307 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5308 (not (org-in-src-block-p)))
5309 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5310 (setq f (get-text-property (match-beginning 0) 'face))
5311 (unless (or (org-in-src-block-p)
5312 (eq f 'org-tag)
5313 (and (listp f) (memq 'org-tag f)))
5314 (add-text-properties (match-beginning 0) (match-end 0)
5315 (list 'mouse-face 'highlight
5316 'face 'org-link
5317 'keymap org-mouse-map))
5318 (org-rear-nonsticky-at (match-end 0)))
5319 t))))
5321 (defun org-activate-code (limit)
5322 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5323 (progn
5324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5325 (remove-text-properties (match-beginning 0) (match-end 0)
5326 '(display t invisible t intangible t))
5327 t)))
5329 (defcustom org-src-fontify-natively nil
5330 "When non-nil, fontify code in code blocks."
5331 :type 'boolean
5332 :version "24.1"
5333 :group 'org-appearance
5334 :group 'org-babel)
5336 (defcustom org-allow-promoting-top-level-subtree nil
5337 "When non-nil, allow promoting a top level subtree.
5338 The leading star of the top level headline will be replaced
5339 by a #."
5340 :type 'boolean
5341 :version "24.1"
5342 :group 'org-appearance)
5344 (defun org-fontify-meta-lines-and-blocks (limit)
5345 (condition-case nil
5346 (org-fontify-meta-lines-and-blocks-1 limit)
5347 (error (message "org-mode fontification error"))))
5349 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5350 "Fontify #+ lines and blocks, in the correct ways."
5351 (let ((case-fold-search t))
5352 (if (re-search-forward
5353 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5354 limit t)
5355 (let ((beg (match-beginning 0))
5356 (block-start (match-end 0))
5357 (block-end nil)
5358 (lang (match-string 7))
5359 (beg1 (line-beginning-position 2))
5360 (dc1 (downcase (match-string 2)))
5361 (dc3 (downcase (match-string 3)))
5362 end end1 quoting block-type ovl)
5363 (cond
5364 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5365 ;; a single line of backend-specific content
5366 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5367 (remove-text-properties (match-beginning 0) (match-end 0)
5368 '(display t invisible t intangible t))
5369 (add-text-properties (match-beginning 1) (match-end 3)
5370 '(font-lock-fontified t face org-meta-line))
5371 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5372 '(font-lock-fontified t face org-block))
5373 ; for backend-specific code
5375 ((and (match-end 4) (equal dc3 "+begin"))
5376 ;; Truly a block
5377 (setq block-type (downcase (match-string 5))
5378 quoting (member block-type org-protecting-blocks))
5379 (when (re-search-forward
5380 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5381 nil t) ;; on purpose, we look further than LIMIT
5382 (setq end (min (point-max) (match-end 0))
5383 end1 (min (point-max) (1- (match-beginning 0))))
5384 (setq block-end (match-beginning 0))
5385 (when quoting
5386 (remove-text-properties beg end
5387 '(display t invisible t intangible t)))
5388 (add-text-properties
5389 beg end
5390 '(font-lock-fontified t font-lock-multiline t))
5391 (add-text-properties beg beg1 '(face org-meta-line))
5392 (add-text-properties end1 (min (point-max) (1+ end))
5393 '(face org-meta-line)) ; for end_src
5394 (cond
5395 ((and lang (not (string= lang "")) org-src-fontify-natively)
5396 (org-src-font-lock-fontify-block lang block-start block-end)
5397 ;; remove old background overlays
5398 (mapc (lambda (ov)
5399 (if (eq (overlay-get ov 'face) 'org-block-background)
5400 (delete-overlay ov)))
5401 (overlays-at (/ (+ beg1 block-end) 2)))
5402 ;; add a background overlay
5403 (setq ovl (make-overlay beg1 block-end))
5404 (overlay-put ovl 'face 'org-block-background)
5405 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5406 (quoting
5407 (add-text-properties beg1 (min (point-max) (1+ end1))
5408 '(face org-block))) ; end of source block
5409 ((not org-fontify-quote-and-verse-blocks))
5410 ((string= block-type "quote")
5411 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5412 ((string= block-type "verse")
5413 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5414 (add-text-properties beg beg1 '(face org-block-begin-line))
5415 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5416 '(face org-block-end-line))
5418 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5419 (add-text-properties
5420 beg (match-end 3)
5421 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5422 '(font-lock-fontified t invisible t)
5423 '(font-lock-fontified t face org-document-info-keyword)))
5424 (add-text-properties
5425 (match-beginning 6) (1+ (match-end 6))
5426 (if (string-equal dc1 "+title:")
5427 '(font-lock-fontified t face org-document-title)
5428 '(font-lock-fontified t face org-document-info))))
5429 ((or (equal dc1 "+results")
5430 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5431 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5432 "+call:" "+header:" "+headers:" "+name:"))
5433 (and (match-end 4) (equal dc3 "+attr")))
5434 (add-text-properties
5435 beg (match-end 0)
5436 '(font-lock-fontified t face org-meta-line))
5438 ((member dc3 '(" " ""))
5439 (add-text-properties
5440 beg (match-end 0)
5441 '(font-lock-fontified t face font-lock-comment-face)))
5442 ((not (member (char-after beg) '(?\ ?\t)))
5443 ;; just any other in-buffer setting, but not indented
5444 (add-text-properties
5445 beg (match-end 0)
5446 '(font-lock-fontified t face org-meta-line))
5448 (t nil))))))
5450 (defun org-activate-angle-links (limit)
5451 "Run through the buffer and add overlays to links."
5452 (if (and (re-search-forward org-angle-link-re limit t)
5453 (not (org-in-src-block-p)))
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (add-text-properties (match-beginning 0) (match-end 0)
5457 (list 'mouse-face 'highlight
5458 'keymap org-mouse-map))
5459 (org-rear-nonsticky-at (match-end 0))
5460 t)))
5462 (defun org-activate-footnote-links (limit)
5463 "Run through the buffer and add overlays to footnotes."
5464 (let ((fn (org-footnote-next-reference-or-definition limit)))
5465 (when fn
5466 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5467 (org-remove-flyspell-overlays-in beg end)
5468 (add-text-properties beg end
5469 (list 'mouse-face 'highlight
5470 'keymap org-mouse-map
5471 'help-echo
5472 (if (= (point-at-bol) beg)
5473 "Footnote definition"
5474 "Footnote reference")
5475 'font-lock-fontified t
5476 'font-lock-multiline t
5477 'face 'org-footnote))))))
5479 (defun org-activate-bracket-links (limit)
5480 "Run through the buffer and add overlays to bracketed links."
5481 (if (and (re-search-forward org-bracket-link-regexp limit t)
5482 (not (org-in-src-block-p)))
5483 (let* ((help (concat "LINK: "
5484 (org-match-string-no-properties 1)))
5485 ;; FIXME: above we should remove the escapes.
5486 ;; but that requires another match, protecting match data,
5487 ;; a lot of overhead for font-lock.
5488 (ip (org-maybe-intangible
5489 (list 'invisible 'org-link
5490 'keymap org-mouse-map 'mouse-face 'highlight
5491 'font-lock-multiline t 'help-echo help)))
5492 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help)))
5494 ;; We need to remove the invisible property here. Table narrowing
5495 ;; may have made some of this invisible.
5496 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5497 (remove-text-properties (match-beginning 0) (match-end 0)
5498 '(invisible nil))
5499 (if (match-end 3)
5500 (progn
5501 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5502 (org-rear-nonsticky-at (match-beginning 3))
5503 (add-text-properties (match-beginning 3) (match-end 3) vp)
5504 (org-rear-nonsticky-at (match-end 3))
5505 (add-text-properties (match-end 3) (match-end 0) ip)
5506 (org-rear-nonsticky-at (match-end 0)))
5507 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5508 (org-rear-nonsticky-at (match-beginning 1))
5509 (add-text-properties (match-beginning 1) (match-end 1) vp)
5510 (org-rear-nonsticky-at (match-end 1))
5511 (add-text-properties (match-end 1) (match-end 0) ip)
5512 (org-rear-nonsticky-at (match-end 0)))
5513 t)))
5515 (defun org-activate-dates (limit)
5516 "Run through the buffer and add overlays to dates."
5517 (if (re-search-forward org-tsr-regexp-both limit t)
5518 (progn
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (add-text-properties (match-beginning 0) (match-end 0)
5521 (list 'mouse-face 'highlight
5522 'keymap org-mouse-map))
5523 (org-rear-nonsticky-at (match-end 0))
5524 (when org-display-custom-times
5525 (if (match-end 3)
5526 (org-display-custom-time (match-beginning 3) (match-end 3)))
5527 (org-display-custom-time (match-beginning 1) (match-end 1)))
5528 t)))
5530 (defvar org-target-link-regexp nil
5531 "Regular expression matching radio targets in plain text.")
5532 (make-variable-buffer-local 'org-target-link-regexp)
5533 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5534 "Regular expression matching a link target.")
5535 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5536 "Regular expression matching a radio target.")
5537 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5538 "Regular expression matching any target.")
5540 (defun org-activate-target-links (limit)
5541 "Run through the buffer and add overlays to target matches."
5542 (when org-target-link-regexp
5543 (let ((case-fold-search t))
5544 (if (re-search-forward org-target-link-regexp limit t)
5545 (progn
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (add-text-properties (match-beginning 0) (match-end 0)
5548 (list 'mouse-face 'highlight
5549 'keymap org-mouse-map
5550 'help-echo "Radio target link"
5551 'org-linked-text t))
5552 (org-rear-nonsticky-at (match-end 0))
5553 t)))))
5555 (defun org-update-radio-target-regexp ()
5556 "Find all radio targets in this file and update the regular expression."
5557 (interactive)
5558 (when (memq 'radio org-activate-links)
5559 (setq org-target-link-regexp
5560 (org-make-target-link-regexp (org-all-targets 'radio)))
5561 (org-restart-font-lock)))
5563 (defun org-hide-wide-columns (limit)
5564 (let (s e)
5565 (setq s (text-property-any (point) (or limit (point-max))
5566 'org-cwidth t))
5567 (when s
5568 (setq e (next-single-property-change s 'org-cwidth))
5569 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5570 (goto-char e)
5571 t)))
5573 (defvar org-latex-and-specials-regexp nil
5574 "Regular expression for highlighting export special stuff.")
5575 (defvar org-match-substring-regexp)
5576 (defvar org-match-substring-with-braces-regexp)
5578 ;; This should be with the exporter code, but we also use if for font-locking
5579 (defconst org-export-html-special-string-regexps
5580 '(("\\\\-" . "&shy;")
5581 ("---\\([^-]\\)" . "&mdash;\\1")
5582 ("--\\([^-]\\)" . "&ndash;\\1")
5583 ("\\.\\.\\." . "&hellip;"))
5584 "Regular expressions for special string conversion.")
5587 (defun org-compute-latex-and-specials-regexp ()
5588 "Compute regular expression for stuff treated specially by exporters."
5589 (if (not org-highlight-latex-fragments-and-specials)
5590 (org-set-local 'org-latex-and-specials-regexp nil)
5591 (require 'org-exp)
5592 (let*
5593 ((matchers (plist-get org-format-latex-options :matchers))
5594 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5595 org-latex-regexps)))
5596 (org-export-allow-BIND nil)
5597 (options (org-combine-plists (org-default-export-plist)
5598 (org-infile-export-plist)))
5599 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5600 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5601 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5602 (org-export-html-expand (plist-get options :expand-quoted-html))
5603 (org-export-with-special-strings (plist-get options :special-strings))
5604 (re-sub
5605 (cond
5606 ((equal org-export-with-sub-superscripts '{})
5607 (list org-match-substring-with-braces-regexp))
5608 (org-export-with-sub-superscripts
5609 (list org-match-substring-regexp))))
5610 (re-latex
5611 (if org-export-with-LaTeX-fragments
5612 (mapcar (lambda (x) (nth 1 x)) latexs)))
5613 (re-macros
5614 (if org-export-with-TeX-macros
5615 (list (concat "\\\\"
5616 (regexp-opt
5617 (append
5619 (delq nil
5620 (mapcar 'car-safe
5621 (append org-entities-user
5622 org-entities)))
5623 (if (boundp 'org-latex-entities)
5624 (mapcar (lambda (x)
5625 (or (car-safe x) x))
5626 org-latex-entities)
5627 nil))
5628 'words))) ; FIXME
5630 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5631 (re-special (if org-export-with-special-strings
5632 (mapcar (lambda (x) (car x))
5633 org-export-html-special-string-regexps)))
5634 (re-rest
5635 (delq nil
5636 (list
5637 (if org-export-html-expand "@<[^>\n]+>")
5638 ))))
5639 (org-set-local
5640 'org-latex-and-specials-regexp
5641 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5642 re-rest) "\\|")))))
5644 (defun org-do-latex-and-special-faces (limit)
5645 "Run through the buffer and add overlays to links."
5646 (when org-latex-and-specials-regexp
5647 (let (rtn d)
5648 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5649 limit t))
5650 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5651 'face))
5652 '(org-code org-verbatim underline)))
5653 (progn
5654 (setq rtn t
5655 d (cond ((member (char-after (1+ (match-beginning 0)))
5656 '(?_ ?^)) 1)
5657 (t 0)))
5658 (font-lock-prepend-text-property
5659 (+ d (match-beginning 0)) (match-end 0)
5660 'face 'org-latex-and-export-specials)
5661 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5662 '(font-lock-multiline t)))))
5663 rtn)))
5665 (defun org-restart-font-lock ()
5666 "Restart `font-lock-mode', to force refontification."
5667 (when (and (boundp 'font-lock-mode) font-lock-mode)
5668 (font-lock-mode -1)
5669 (font-lock-mode 1)))
5671 (defun org-all-targets (&optional radio)
5672 "Return a list of all targets in this file.
5673 With optional argument RADIO, only find radio targets."
5674 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5675 rtn)
5676 (save-excursion
5677 (goto-char (point-min))
5678 (while (re-search-forward re nil t)
5679 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5680 rtn)))
5682 (defun org-make-target-link-regexp (targets)
5683 "Make regular expression matching all strings in TARGETS.
5684 The regular expression finds the targets also if there is a line break
5685 between words."
5686 (and targets
5687 (concat
5688 "\\<\\("
5689 (mapconcat
5690 (lambda (x)
5691 (setq x (regexp-quote x))
5692 (while (string-match " +" x)
5693 (setq x (replace-match "\\s-+" t t x)))
5695 targets
5696 "\\|")
5697 "\\)\\>")))
5699 (defun org-activate-tags (limit)
5700 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5701 (progn
5702 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5703 (add-text-properties (match-beginning 1) (match-end 1)
5704 (list 'mouse-face 'highlight
5705 'keymap org-mouse-map))
5706 (org-rear-nonsticky-at (match-end 1))
5707 t)))
5709 (defun org-outline-level ()
5710 "Compute the outline level of the heading at point.
5711 This function assumes that the cursor is at the beginning of a line matched
5712 by `outline-regexp'. Otherwise it returns garbage.
5713 If this is called at a normal headline, the level is the number of stars.
5714 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5715 (save-excursion
5716 (looking-at org-outline-regexp)
5717 (1- (- (match-end 0) (match-beginning 0)))))
5719 (defvar org-font-lock-keywords nil)
5721 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5722 "Regular expression matching a property line.")
5724 (defvar org-font-lock-hook nil
5725 "Functions to be called for special font lock stuff.")
5727 (defvar org-font-lock-set-keywords-hook nil
5728 "Functions that can manipulate `org-font-lock-extra-keywords'.
5729 This is called after `org-font-lock-extra-keywords' is defined, but before
5730 it is installed to be used by font lock. This can be useful if something
5731 needs to be inserted at a specific position in the font-lock sequence.")
5733 (defun org-font-lock-hook (limit)
5734 "Run `org-font-lock-hook' within LIMIT."
5735 (run-hook-with-args 'org-font-lock-hook limit))
5737 (defun org-set-font-lock-defaults ()
5738 "Set font lock defaults for the current buffer."
5739 (let* ((em org-fontify-emphasized-text)
5740 (lk org-activate-links)
5741 (org-font-lock-extra-keywords
5742 (list
5743 ;; Call the hook
5744 '(org-font-lock-hook)
5745 ;; Headlines
5746 `(,(if org-fontify-whole-heading-line
5747 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5748 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5749 (1 (org-get-level-face 1))
5750 (2 (org-get-level-face 2))
5751 (3 (org-get-level-face 3)))
5752 ;; Table lines
5753 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5754 (1 'org-table t))
5755 ;; Table internals
5756 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5757 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5758 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5759 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5760 ;; Drawers
5761 (list org-drawer-regexp '(0 'org-special-keyword t))
5762 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5763 ;; Properties
5764 (list org-property-re
5765 '(1 'org-special-keyword t)
5766 '(3 'org-property-value t))
5767 ;; Links
5768 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5769 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5770 (if (memq 'plain lk) '(org-activate-plain-links))
5771 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5772 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5773 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5774 (if (memq 'footnote lk) '(org-activate-footnote-links))
5775 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5776 '(org-hide-wide-columns (0 nil append))
5777 ;; TODO keyword
5778 (list (format org-heading-keyword-regexp-format
5779 org-todo-regexp)
5780 '(2 (org-get-todo-face 2) t))
5781 ;; DONE
5782 (if org-fontify-done-headline
5783 (list (format org-heading-keyword-regexp-format
5784 (concat
5785 "\\(?:"
5786 (mapconcat 'regexp-quote org-done-keywords "\\|")
5787 "\\)"))
5788 '(2 'org-headline-done t))
5789 nil)
5790 ;; Priorities
5791 '(org-font-lock-add-priority-faces)
5792 ;; Tags
5793 '(org-font-lock-add-tag-faces)
5794 ;; Special keywords
5795 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5796 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5798 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5799 ;; Emphasis
5800 (if em
5801 (if (featurep 'xemacs)
5802 '(org-do-emphasis-faces (0 nil append))
5803 '(org-do-emphasis-faces)))
5804 ;; Checkboxes
5805 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5806 1 'org-checkbox prepend)
5807 (if (cdr (assq 'checkbox org-list-automatic-rules))
5808 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5809 (0 (org-get-checkbox-statistics-face) t)))
5810 ;; Description list items
5811 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5812 1 'org-list-dt prepend)
5813 ;; ARCHIVEd headings
5814 (list (concat
5815 org-outline-regexp-bol
5816 "\\(.*:" org-archive-tag ":.*\\)")
5817 '(1 'org-archived prepend))
5818 ;; Specials
5819 '(org-do-latex-and-special-faces)
5820 '(org-fontify-entities)
5821 '(org-raise-scripts)
5822 ;; Code
5823 '(org-activate-code (1 'org-code t))
5824 ;; COMMENT
5825 (list (format org-heading-keyword-regexp-format
5826 (concat "\\("
5827 org-comment-string "\\|" org-quote-string
5828 "\\)"))
5829 '(2 'org-special-keyword t))
5830 ;; Blocks and meta lines
5831 '(org-fontify-meta-lines-and-blocks)
5833 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5834 (run-hooks 'org-font-lock-set-keywords-hook)
5835 ;; Now set the full font-lock-keywords
5836 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5837 (org-set-local 'font-lock-defaults
5838 '(org-font-lock-keywords t nil nil backward-paragraph))
5839 (kill-local-variable 'font-lock-keywords) nil))
5841 (defun org-toggle-pretty-entities ()
5842 "Toggle the composition display of entities as UTF8 characters."
5843 (interactive)
5844 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5845 (org-restart-font-lock)
5846 (if org-pretty-entities
5847 (message "Entities are displayed as UTF8 characters")
5848 (save-restriction
5849 (widen)
5850 (org-decompose-region (point-min) (point-max))
5851 (message "Entities are displayed plain"))))
5853 (defvar org-custom-properties-overlays nil
5854 "List of overlays used for custom properties.")
5855 (make-variable-buffer-local 'org-custom-properties-overlays)
5857 (defun org-toggle-custom-properties-visibility ()
5858 "Display or hide properties in `org-custom-properties'."
5859 (interactive)
5860 (if org-custom-properties-overlays
5861 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5862 (setq org-custom-properties-overlays nil))
5863 (unless (not org-custom-properties)
5864 (save-excursion
5865 (save-restriction
5866 (widen)
5867 (goto-char (point-min))
5868 (while (re-search-forward org-property-re nil t)
5869 (mapc (lambda(p)
5870 (when (equal p (substring (match-string 1) 1 -1))
5871 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5872 (overlay-put o 'invisible t)
5873 (overlay-put o 'org-custom-property t)
5874 (push o org-custom-properties-overlays))))
5875 org-custom-properties)))))))
5877 (defun org-fontify-entities (limit)
5878 "Find an entity to fontify."
5879 (let (ee)
5880 (when org-pretty-entities
5881 (catch 'match
5882 (while (re-search-forward
5883 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5884 limit t)
5885 (if (and (not (org-in-indented-comment-line))
5886 (setq ee (org-entity-get (match-string 1)))
5887 (= (length (nth 6 ee)) 1))
5888 (let*
5889 ((end (if (equal (match-string 2) "{}")
5890 (match-end 2)
5891 (match-end 1))))
5892 (add-text-properties
5893 (match-beginning 0) end
5894 (list 'font-lock-fontified t))
5895 (compose-region (match-beginning 0) end
5896 (nth 6 ee) nil)
5897 (backward-char 1)
5898 (throw 'match t))))
5899 nil))))
5901 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5902 "Fontify string S like in Org-mode."
5903 (with-temp-buffer
5904 (insert s)
5905 (let ((org-odd-levels-only odd-levels))
5906 (org-mode)
5907 (font-lock-fontify-buffer)
5908 (buffer-string))))
5910 (defvar org-m nil)
5911 (defvar org-l nil)
5912 (defvar org-f nil)
5913 (defun org-get-level-face (n)
5914 "Get the right face for match N in font-lock matching of headlines."
5915 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5916 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5917 (if org-cycle-level-faces
5918 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5919 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5920 (cond
5921 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5922 ((eq n 2) org-f)
5923 (t (if org-level-color-stars-only nil org-f))))
5926 (defun org-get-todo-face (kwd)
5927 "Get the right face for a TODO keyword KWD.
5928 If KWD is a number, get the corresponding match group."
5929 (if (numberp kwd) (setq kwd (match-string kwd)))
5930 (or (org-face-from-face-or-color
5931 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5932 (and (member kwd org-done-keywords) 'org-done)
5933 'org-todo))
5935 (defun org-face-from-face-or-color (context inherit face-or-color)
5936 "Create a face list that inherits INHERIT, but sets the foreground color.
5937 When FACE-OR-COLOR is not a string, just return it."
5938 (if (stringp face-or-color)
5939 (list :inherit inherit
5940 (cdr (assoc context org-faces-easy-properties))
5941 face-or-color)
5942 face-or-color))
5944 (defun org-font-lock-add-tag-faces (limit)
5945 "Add the special tag faces."
5946 (when (and org-tag-faces org-tags-special-faces-re)
5947 (while (re-search-forward org-tags-special-faces-re limit t)
5948 (add-text-properties (match-beginning 1) (match-end 1)
5949 (list 'face (org-get-tag-face 1)
5950 'font-lock-fontified t))
5951 (backward-char 1))))
5953 (defun org-font-lock-add-priority-faces (limit)
5954 "Add the special priority faces."
5955 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5956 (when (save-match-data (org-at-heading-p))
5957 (add-text-properties
5958 (match-beginning 0) (match-end 0)
5959 (list 'face (or (org-face-from-face-or-color
5960 'priority 'org-special-keyword
5961 (cdr (assoc (char-after (match-beginning 1))
5962 org-priority-faces)))
5963 'org-special-keyword)
5964 'font-lock-fontified t)))))
5966 (defun org-get-tag-face (kwd)
5967 "Get the right face for a TODO keyword KWD.
5968 If KWD is a number, get the corresponding match group."
5969 (if (numberp kwd) (setq kwd (match-string kwd)))
5970 (or (org-face-from-face-or-color
5971 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5972 'org-tag))
5974 (defun org-unfontify-region (beg end &optional maybe_loudly)
5975 "Remove fontification and activation overlays from links."
5976 (font-lock-default-unfontify-region beg end)
5977 (let* ((buffer-undo-list t)
5978 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5979 (inhibit-modification-hooks t)
5980 deactivate-mark buffer-file-name buffer-file-truename)
5981 (org-decompose-region beg end)
5982 (remove-text-properties beg end
5983 '(mouse-face t keymap t org-linked-text t
5984 invisible t intangible t
5985 org-no-flyspell t org-emphasis t))
5986 (org-remove-font-lock-display-properties beg end)))
5988 (defconst org-script-display '(((raise -0.3) (height 0.7))
5989 ((raise 0.3) (height 0.7))
5990 ((raise -0.5))
5991 ((raise 0.5)))
5992 "Display properties for showing superscripts and subscripts.")
5994 (defun org-remove-font-lock-display-properties (beg end)
5995 "Remove specific display properties that have been added by font lock.
5996 The will remove the raise properties that are used to show superscripts
5997 and subscripts."
5998 (let (next prop)
5999 (while (< beg end)
6000 (setq next (next-single-property-change beg 'display nil end)
6001 prop (get-text-property beg 'display))
6002 (if (member prop org-script-display)
6003 (put-text-property beg next 'display nil))
6004 (setq beg next))))
6006 (defun org-raise-scripts (limit)
6007 "Add raise properties to sub/superscripts."
6008 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6009 (if (re-search-forward
6010 (if (eq org-use-sub-superscripts t)
6011 org-match-substring-regexp
6012 org-match-substring-with-braces-regexp)
6013 limit t)
6014 (let* ((pos (point)) table-p comment-p
6015 (mpos (match-beginning 3))
6016 (emph-p (get-text-property mpos 'org-emphasis))
6017 (link-p (get-text-property mpos 'mouse-face))
6018 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6019 (goto-char (point-at-bol))
6020 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6021 comment-p (org-looking-at-p "[ \t]*#"))
6022 (goto-char pos)
6023 ;; FIXME: Should we go back one character here, for a_b^c
6024 ;; (goto-char (1- pos)) ;????????????????????
6025 (if (or comment-p emph-p link-p keyw-p)
6027 (put-text-property (match-beginning 3) (match-end 0)
6028 'display
6029 (if (equal (char-after (match-beginning 2)) ?^)
6030 (nth (if table-p 3 1) org-script-display)
6031 (nth (if table-p 2 0) org-script-display)))
6032 (add-text-properties (match-beginning 2) (match-end 2)
6033 (list 'invisible t
6034 'org-dwidth t 'org-dwidth-n 1))
6035 (if (and (eq (char-after (match-beginning 3)) ?{)
6036 (eq (char-before (match-end 3)) ?}))
6037 (progn
6038 (add-text-properties
6039 (match-beginning 3) (1+ (match-beginning 3))
6040 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6041 (add-text-properties
6042 (1- (match-end 3)) (match-end 3)
6043 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6044 t)))))
6046 ;;;; Visibility cycling, including org-goto and indirect buffer
6048 ;;; Cycling
6050 (defvar org-cycle-global-status nil)
6051 (make-variable-buffer-local 'org-cycle-global-status)
6052 (defvar org-cycle-subtree-status nil)
6053 (make-variable-buffer-local 'org-cycle-subtree-status)
6055 (defvar org-inlinetask-min-level)
6057 ;;;###autoload
6058 (defun org-cycle (&optional arg)
6059 "TAB-action and visibility cycling for Org-mode.
6061 This is the command invoked in Org-mode by the TAB key. Its main purpose
6062 is outline visibility cycling, but it also invokes other actions
6063 in special contexts.
6065 - When this function is called with a prefix argument, rotate the entire
6066 buffer through 3 states (global cycling)
6067 1. OVERVIEW: Show only top-level headlines.
6068 2. CONTENTS: Show all headlines of all levels, but no body text.
6069 3. SHOW ALL: Show everything.
6070 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6071 determined by the variable `org-startup-folded', and by any VISIBILITY
6072 properties in the buffer.
6073 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6074 including any drawers.
6076 - When inside a table, re-align the table and move to the next field.
6078 - When point is at the beginning of a headline, rotate the subtree started
6079 by this line through 3 different states (local cycling)
6080 1. FOLDED: Only the main headline is shown.
6081 2. CHILDREN: The main headline and the direct children are shown.
6082 From this state, you can move to one of the children
6083 and zoom in further.
6084 3. SUBTREE: Show the entire subtree, including body text.
6085 If there is no subtree, switch directly from CHILDREN to FOLDED.
6087 - When point is at the beginning of an empty headline and the variable
6088 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6089 of the headline by demoting and promoting it to likely levels. This
6090 speeds up creation document structure by pressing TAB once or several
6091 times right after creating a new headline.
6093 - When there is a numeric prefix, go up to a heading with level ARG, do
6094 a `show-subtree' and return to the previous cursor position. If ARG
6095 is negative, go up that many levels.
6097 - When point is not at the beginning of a headline, execute the global
6098 binding for TAB, which is re-indenting the line. See the option
6099 `org-cycle-emulate-tab' for details.
6101 - Special case: if point is at the beginning of the buffer and there is
6102 no headline in line 1, this function will act as if called with prefix arg
6103 (C-u TAB, same as S-TAB) also when called without prefix arg.
6104 But only if also the variable `org-cycle-global-at-bob' is t."
6105 (interactive "P")
6106 (org-load-modules-maybe)
6107 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6108 (and org-cycle-level-after-item/entry-creation
6109 (or (org-cycle-level)
6110 (org-cycle-item-indentation))))
6111 (let* ((limit-level
6112 (or org-cycle-max-level
6113 (and (boundp 'org-inlinetask-min-level)
6114 org-inlinetask-min-level
6115 (1- org-inlinetask-min-level))))
6116 (nstars (and limit-level
6117 (if org-odd-levels-only
6118 (and limit-level (1- (* limit-level 2)))
6119 limit-level)))
6120 (org-outline-regexp
6121 (if (not (derived-mode-p 'org-mode))
6122 outline-regexp
6123 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6124 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6125 (not (looking-at org-outline-regexp))))
6126 (org-cycle-hook
6127 (if bob-special
6128 (delq 'org-optimize-window-after-visibility-change
6129 (copy-sequence org-cycle-hook))
6130 org-cycle-hook))
6131 (pos (point)))
6133 (if (or bob-special (equal arg '(4)))
6134 ;; special case: use global cycling
6135 (setq arg t))
6137 (cond
6139 ((equal arg '(16))
6140 (setq last-command 'dummy)
6141 (org-set-startup-visibility)
6142 (message "Startup visibility, plus VISIBILITY properties"))
6144 ((equal arg '(64))
6145 (show-all)
6146 (message "Entire buffer visible, including drawers"))
6148 ;; Table: enter it or move to the next field.
6149 ((org-at-table-p 'any)
6150 (if (org-at-table.el-p)
6151 (message "Use C-c ' to edit table.el tables")
6152 (if arg (org-table-edit-field t)
6153 (org-table-justify-field-maybe)
6154 (call-interactively 'org-table-next-field))))
6156 ((run-hook-with-args-until-success
6157 'org-tab-after-check-for-table-hook))
6159 ;; Global cycling: delegate to `org-cycle-internal-global'.
6160 ((eq arg t) (org-cycle-internal-global))
6162 ;; Drawers: delegate to `org-flag-drawer'.
6163 ((and org-drawers org-drawer-regexp
6164 (save-excursion
6165 (beginning-of-line 1)
6166 (looking-at org-drawer-regexp)))
6167 (org-flag-drawer ; toggle block visibility
6168 (not (get-char-property (match-end 0) 'invisible))))
6170 ;; Show-subtree, ARG levels up from here.
6171 ((integerp arg)
6172 (save-excursion
6173 (org-back-to-heading)
6174 (outline-up-heading (if (< arg 0) (- arg)
6175 (- (funcall outline-level) arg)))
6176 (org-show-subtree)))
6178 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6179 ((and (featurep 'org-inlinetask)
6180 (org-inlinetask-at-task-p)
6181 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6182 (org-inlinetask-toggle-visibility))
6184 ((org-try-cdlatex-tab))
6186 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6187 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6188 (save-excursion (beginning-of-line 1)
6189 (looking-at org-outline-regexp)))
6190 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6191 (org-cycle-internal-local))
6193 ;; From there: TAB emulation and template completion.
6194 (buffer-read-only (org-back-to-heading))
6196 ((run-hook-with-args-until-success
6197 'org-tab-after-check-for-cycling-hook))
6199 ((org-try-structure-completion))
6201 ((run-hook-with-args-until-success
6202 'org-tab-before-tab-emulation-hook))
6204 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6205 (or (not (bolp))
6206 (not (looking-at org-outline-regexp))))
6207 (call-interactively (global-key-binding "\t")))
6209 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6210 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6211 (or (and (eq org-cycle-emulate-tab 'white)
6212 (= (match-end 0) (point-at-eol)))
6213 (and (eq org-cycle-emulate-tab 'whitestart)
6214 (>= (match-end 0) pos))))
6216 (eq org-cycle-emulate-tab t))
6217 (call-interactively (global-key-binding "\t")))
6219 (t (save-excursion
6220 (org-back-to-heading)
6221 (org-cycle)))))))
6223 (defun org-cycle-internal-global ()
6224 "Do the global cycling action."
6225 ;; Hack to avoid display of messages for .org attachments in Gnus
6226 (let ((ga (string-match "\\*fontification" (buffer-name))))
6227 (cond
6228 ((and (eq last-command this-command)
6229 (eq org-cycle-global-status 'overview))
6230 ;; We just created the overview - now do table of contents
6231 ;; This can be slow in very large buffers, so indicate action
6232 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6233 (unless ga (message "CONTENTS..."))
6234 (org-content)
6235 (unless ga (message "CONTENTS...done"))
6236 (setq org-cycle-global-status 'contents)
6237 (run-hook-with-args 'org-cycle-hook 'contents))
6239 ((and (eq last-command this-command)
6240 (eq org-cycle-global-status 'contents))
6241 ;; We just showed the table of contents - now show everything
6242 (run-hook-with-args 'org-pre-cycle-hook 'all)
6243 (show-all)
6244 (unless ga (message "SHOW ALL"))
6245 (setq org-cycle-global-status 'all)
6246 (run-hook-with-args 'org-cycle-hook 'all))
6249 ;; Default action: go to overview
6250 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6251 (org-overview)
6252 (unless ga (message "OVERVIEW"))
6253 (setq org-cycle-global-status 'overview)
6254 (run-hook-with-args 'org-cycle-hook 'overview)))))
6256 (defun org-cycle-internal-local ()
6257 "Do the local cycling action."
6258 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6259 ;; First, determine end of headline (EOH), end of subtree or item
6260 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6261 (save-excursion
6262 (if (org-at-item-p)
6263 (progn
6264 (beginning-of-line)
6265 (setq struct (org-list-struct))
6266 (setq eoh (point-at-eol))
6267 (setq eos (org-list-get-item-end-before-blank (point) struct))
6268 (setq has-children (org-list-has-child-p (point) struct)))
6269 (org-back-to-heading)
6270 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6271 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6272 (setq has-children
6273 (or (save-excursion
6274 (let ((level (funcall outline-level)))
6275 (outline-next-heading)
6276 (and (org-at-heading-p t)
6277 (> (funcall outline-level) level))))
6278 (save-excursion
6279 (org-list-search-forward (org-item-beginning-re) eos t)))))
6280 ;; Determine end invisible part of buffer (EOL)
6281 (beginning-of-line 2)
6282 ;; XEmacs doesn't have `next-single-char-property-change'
6283 (if (featurep 'xemacs)
6284 (while (and (not (eobp)) ;; this is like `next-line'
6285 (get-char-property (1- (point)) 'invisible))
6286 (beginning-of-line 2))
6287 (while (and (not (eobp)) ;; this is like `next-line'
6288 (get-char-property (1- (point)) 'invisible))
6289 (goto-char (next-single-char-property-change (point) 'invisible))
6290 (and (eolp) (beginning-of-line 2))))
6291 (setq eol (point)))
6292 ;; Find out what to do next and set `this-command'
6293 (cond
6294 ((= eos eoh)
6295 ;; Nothing is hidden behind this heading
6296 (unless (org-before-first-heading-p)
6297 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6298 (message "EMPTY ENTRY")
6299 (setq org-cycle-subtree-status nil)
6300 (save-excursion
6301 (goto-char eos)
6302 (outline-next-heading)
6303 (if (outline-invisible-p) (org-flag-heading nil))))
6304 ((and (or (>= eol eos)
6305 (not (string-match "\\S-" (buffer-substring eol eos))))
6306 (or has-children
6307 (not (setq children-skipped
6308 org-cycle-skip-children-state-if-no-children))))
6309 ;; Entire subtree is hidden in one line: children view
6310 (unless (org-before-first-heading-p)
6311 (run-hook-with-args 'org-pre-cycle-hook 'children))
6312 (if (org-at-item-p)
6313 (org-list-set-item-visibility (point-at-bol) struct 'children)
6314 (org-show-entry)
6315 (org-with-limited-levels (show-children))
6316 ;; FIXME: This slows down the func way too much.
6317 ;; How keep drawers hidden in subtree anyway?
6318 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6319 ;; (org-cycle-hide-drawers 'subtree))
6321 ;; Fold every list in subtree to top-level items.
6322 (when (eq org-cycle-include-plain-lists 'integrate)
6323 (save-excursion
6324 (org-back-to-heading)
6325 (while (org-list-search-forward (org-item-beginning-re) eos t)
6326 (beginning-of-line 1)
6327 (let* ((struct (org-list-struct))
6328 (prevs (org-list-prevs-alist struct))
6329 (end (org-list-get-bottom-point struct)))
6330 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6331 (org-list-get-all-items (point) struct prevs))
6332 (goto-char end))))))
6333 (message "CHILDREN")
6334 (save-excursion
6335 (goto-char eos)
6336 (outline-next-heading)
6337 (if (outline-invisible-p) (org-flag-heading nil)))
6338 (setq org-cycle-subtree-status 'children)
6339 (unless (org-before-first-heading-p)
6340 (run-hook-with-args 'org-cycle-hook 'children)))
6341 ((or children-skipped
6342 (and (eq last-command this-command)
6343 (eq org-cycle-subtree-status 'children)))
6344 ;; We just showed the children, or no children are there,
6345 ;; now show everything.
6346 (unless (org-before-first-heading-p)
6347 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6348 (outline-flag-region eoh eos nil)
6349 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6350 (setq org-cycle-subtree-status 'subtree)
6351 (unless (org-before-first-heading-p)
6352 (run-hook-with-args 'org-cycle-hook 'subtree)))
6354 ;; Default action: hide the subtree.
6355 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6356 (outline-flag-region eoh eos t)
6357 (message "FOLDED")
6358 (setq org-cycle-subtree-status 'folded)
6359 (unless (org-before-first-heading-p)
6360 (run-hook-with-args 'org-cycle-hook 'folded))))))
6362 ;;;###autoload
6363 (defun org-global-cycle (&optional arg)
6364 "Cycle the global visibility. For details see `org-cycle'.
6365 With \\[universal-argument] prefix arg, switch to startup visibility.
6366 With a numeric prefix, show all headlines up to that level."
6367 (interactive "P")
6368 (let ((org-cycle-include-plain-lists
6369 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6370 (cond
6371 ((integerp arg)
6372 (show-all)
6373 (hide-sublevels arg)
6374 (setq org-cycle-global-status 'contents))
6375 ((equal arg '(4))
6376 (org-set-startup-visibility)
6377 (message "Startup visibility, plus VISIBILITY properties."))
6379 (org-cycle '(4))))))
6381 (defun org-set-startup-visibility ()
6382 "Set the visibility required by startup options and properties."
6383 (cond
6384 ((eq org-startup-folded t)
6385 (org-cycle '(4)))
6386 ((eq org-startup-folded 'content)
6387 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6388 (org-cycle '(4)) (org-cycle '(4)))))
6389 (unless (eq org-startup-folded 'showeverything)
6390 (if org-hide-block-startup (org-hide-block-all))
6391 (org-set-visibility-according-to-property 'no-cleanup)
6392 (org-cycle-hide-archived-subtrees 'all)
6393 (org-cycle-hide-drawers 'all)
6394 (org-cycle-show-empty-lines t)))
6396 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6397 "Switch subtree visibilities according to :VISIBILITY: property."
6398 (interactive)
6399 (let (org-show-entry-below state)
6400 (save-excursion
6401 (goto-char (point-min))
6402 (while (re-search-forward
6403 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6404 nil t)
6405 (setq state (match-string 1))
6406 (save-excursion
6407 (org-back-to-heading t)
6408 (hide-subtree)
6409 (org-reveal)
6410 (cond
6411 ((equal state '("fold" "folded"))
6412 (hide-subtree))
6413 ((equal state "children")
6414 (org-show-hidden-entry)
6415 (show-children))
6416 ((equal state "content")
6417 (save-excursion
6418 (save-restriction
6419 (org-narrow-to-subtree)
6420 (org-content))))
6421 ((member state '("all" "showall"))
6422 (show-subtree)))))
6423 (unless no-cleanup
6424 (org-cycle-hide-archived-subtrees 'all)
6425 (org-cycle-hide-drawers 'all)
6426 (org-cycle-show-empty-lines 'all)))))
6428 ;; This function uses outline-regexp instead of the more fundamental
6429 ;; org-outline-regexp so that org-cycle-global works outside of Org
6430 ;; buffers, where outline-regexp is needed.
6431 (defun org-overview ()
6432 "Switch to overview mode, showing only top-level headlines.
6433 Really, this shows all headlines with level equal or greater than the level
6434 of the first headline in the buffer. This is important, because if the
6435 first headline is not level one, then (hide-sublevels 1) gives confusing
6436 results."
6437 (interactive)
6438 (let ((level (save-excursion
6439 (goto-char (point-min))
6440 (if (re-search-forward (concat "^" outline-regexp) nil t)
6441 (progn
6442 (goto-char (match-beginning 0))
6443 (funcall outline-level))))))
6444 (and level (hide-sublevels level))))
6446 (defun org-content (&optional arg)
6447 "Show all headlines in the buffer, like a table of contents.
6448 With numerical argument N, show content up to level N."
6449 (interactive "P")
6450 (save-excursion
6451 ;; Visit all headings and show their offspring
6452 (and (integerp arg) (org-overview))
6453 (goto-char (point-max))
6454 (catch 'exit
6455 (while (and (progn (condition-case nil
6456 (outline-previous-visible-heading 1)
6457 (error (goto-char (point-min))))
6459 (looking-at org-outline-regexp))
6460 (if (integerp arg)
6461 (show-children (1- arg))
6462 (show-branches))
6463 (if (bobp) (throw 'exit nil))))))
6466 (defun org-optimize-window-after-visibility-change (state)
6467 "Adjust the window after a change in outline visibility.
6468 This function is the default value of the hook `org-cycle-hook'."
6469 (when (get-buffer-window (current-buffer))
6470 (cond
6471 ((eq state 'content) nil)
6472 ((eq state 'all) nil)
6473 ((eq state 'folded) nil)
6474 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6475 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6477 (defun org-remove-empty-overlays-at (pos)
6478 "Remove outline overlays that do not contain non-white stuff."
6479 (mapc
6480 (lambda (o)
6481 (and (eq 'outline (overlay-get o 'invisible))
6482 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6483 (overlay-end o))))
6484 (delete-overlay o)))
6485 (overlays-at pos)))
6487 (defun org-clean-visibility-after-subtree-move ()
6488 "Fix visibility issues after moving a subtree."
6489 ;; First, find a reasonable region to look at:
6490 ;; Start two siblings above, end three below
6491 (let* ((beg (save-excursion
6492 (and (org-get-last-sibling)
6493 (org-get-last-sibling))
6494 (point)))
6495 (end (save-excursion
6496 (and (org-get-next-sibling)
6497 (org-get-next-sibling)
6498 (org-get-next-sibling))
6499 (if (org-at-heading-p)
6500 (point-at-eol)
6501 (point))))
6502 (level (looking-at "\\*+"))
6503 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6504 (save-excursion
6505 (save-restriction
6506 (narrow-to-region beg end)
6507 (when re
6508 ;; Properly fold already folded siblings
6509 (goto-char (point-min))
6510 (while (re-search-forward re nil t)
6511 (if (and (not (outline-invisible-p))
6512 (save-excursion
6513 (goto-char (point-at-eol)) (outline-invisible-p)))
6514 (hide-entry))))
6515 (org-cycle-show-empty-lines 'overview)
6516 (org-cycle-hide-drawers 'overview)))))
6518 (defun org-cycle-show-empty-lines (state)
6519 "Show empty lines above all visible headlines.
6520 The region to be covered depends on STATE when called through
6521 `org-cycle-hook'. Lisp program can use t for STATE to get the
6522 entire buffer covered. Note that an empty line is only shown if there
6523 are at least `org-cycle-separator-lines' empty lines before the headline."
6524 (when (not (= org-cycle-separator-lines 0))
6525 (save-excursion
6526 (let* ((n (abs org-cycle-separator-lines))
6527 (re (cond
6528 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6529 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6530 (t (let ((ns (number-to-string (- n 2))))
6531 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6532 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6533 beg end b e)
6534 (cond
6535 ((memq state '(overview contents t))
6536 (setq beg (point-min) end (point-max)))
6537 ((memq state '(children folded))
6538 (setq beg (point) end (progn (org-end-of-subtree t t)
6539 (beginning-of-line 2)
6540 (point)))))
6541 (when beg
6542 (goto-char beg)
6543 (while (re-search-forward re end t)
6544 (unless (get-char-property (match-end 1) 'invisible)
6545 (setq e (match-end 1))
6546 (if (< org-cycle-separator-lines 0)
6547 (setq b (save-excursion
6548 (goto-char (match-beginning 0))
6549 (org-back-over-empty-lines)
6550 (if (save-excursion
6551 (goto-char (max (point-min) (1- (point))))
6552 (org-at-heading-p))
6553 (1- (point))
6554 (point))))
6555 (setq b (match-beginning 1)))
6556 (outline-flag-region b e nil)))))))
6557 ;; Never hide empty lines at the end of the file.
6558 (save-excursion
6559 (goto-char (point-max))
6560 (outline-previous-heading)
6561 (outline-end-of-heading)
6562 (if (and (looking-at "[ \t\n]+")
6563 (= (match-end 0) (point-max)))
6564 (outline-flag-region (point) (match-end 0) nil))))
6566 (defun org-show-empty-lines-in-parent ()
6567 "Move to the parent and re-show empty lines before visible headlines."
6568 (save-excursion
6569 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6570 (org-cycle-show-empty-lines context))))
6572 (defun org-files-list ()
6573 "Return `org-agenda-files' list, plus all open org-mode files.
6574 This is useful for operations that need to scan all of a user's
6575 open and agenda-wise Org files."
6576 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6577 (dolist (buf (buffer-list))
6578 (with-current-buffer buf
6579 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6580 (let ((file (expand-file-name (buffer-file-name))))
6581 (unless (member file files)
6582 (push file files))))))
6583 files))
6585 (defsubst org-entry-beginning-position ()
6586 "Return the beginning position of the current entry."
6587 (save-excursion (outline-back-to-heading t) (point)))
6589 (defsubst org-entry-end-position ()
6590 "Return the end position of the current entry."
6591 (save-excursion (outline-next-heading) (point)))
6593 (defun org-cycle-hide-drawers (state)
6594 "Re-hide all drawers after a visibility state change."
6595 (when (and (derived-mode-p 'org-mode)
6596 (not (memq state '(overview folded contents))))
6597 (save-excursion
6598 (let* ((globalp (memq state '(contents all)))
6599 (beg (if globalp (point-min) (point)))
6600 (end (if globalp (point-max)
6601 (if (eq state 'children)
6602 (save-excursion (outline-next-heading) (point))
6603 (org-end-of-subtree t)))))
6604 (goto-char beg)
6605 (while (re-search-forward org-drawer-regexp end t)
6606 (org-flag-drawer t))))))
6608 (defun org-flag-drawer (flag)
6609 "When FLAG is non-nil, hide the drawer we are within.
6610 Otherwise make it visible."
6611 (save-excursion
6612 (beginning-of-line 1)
6613 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6614 (let ((b (match-end 0)))
6615 (if (re-search-forward
6616 "^[ \t]*:END:"
6617 (save-excursion (outline-next-heading) (point)) t)
6618 (outline-flag-region b (point-at-eol) flag)
6619 (error ":END: line missing at position %s" b))))))
6621 (defun org-subtree-end-visible-p ()
6622 "Is the end of the current subtree visible?"
6623 (pos-visible-in-window-p
6624 (save-excursion (org-end-of-subtree t) (point))))
6626 (defun org-first-headline-recenter (&optional N)
6627 "Move cursor to the first headline and recenter the headline.
6628 Optional argument N means put the headline into the Nth line of the window."
6629 (goto-char (point-min))
6630 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6631 (beginning-of-line)
6632 (recenter (prefix-numeric-value N))))
6634 ;;; Saving and restoring visibility
6636 (defun org-outline-overlay-data (&optional use-markers)
6637 "Return a list of the locations of all outline overlays.
6638 These are overlays with the `invisible' property value `outline'.
6639 The return value is a list of cons cells, with start and stop
6640 positions for each overlay.
6641 If USE-MARKERS is set, return the positions as markers."
6642 (let (beg end)
6643 (save-excursion
6644 (save-restriction
6645 (widen)
6646 (delq nil
6647 (mapcar (lambda (o)
6648 (when (eq (overlay-get o 'invisible) 'outline)
6649 (setq beg (overlay-start o)
6650 end (overlay-end o))
6651 (and beg end (> end beg)
6652 (if use-markers
6653 (cons (move-marker (make-marker) beg)
6654 (move-marker (make-marker) end))
6655 (cons beg end)))))
6656 (overlays-in (point-min) (point-max))))))))
6658 (defun org-set-outline-overlay-data (data)
6659 "Create visibility overlays for all positions in DATA.
6660 DATA should have been made by `org-outline-overlay-data'."
6661 (let (o)
6662 (save-excursion
6663 (save-restriction
6664 (widen)
6665 (show-all)
6666 (mapc (lambda (c)
6667 (outline-flag-region (car c) (cdr c) t))
6668 data)))))
6670 ;;; Folding of blocks
6672 (defvar org-hide-block-overlays nil
6673 "Overlays hiding blocks.")
6674 (make-variable-buffer-local 'org-hide-block-overlays)
6676 (defun org-block-map (function &optional start end)
6677 "Call FUNCTION at the head of all source blocks in the current buffer.
6678 Optional arguments START and END can be used to limit the range."
6679 (let ((start (or start (point-min)))
6680 (end (or end (point-max))))
6681 (save-excursion
6682 (goto-char start)
6683 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6684 (save-excursion
6685 (save-match-data
6686 (goto-char (match-beginning 0))
6687 (funcall function)))))))
6689 (defun org-hide-block-toggle-all ()
6690 "Toggle the visibility of all blocks in the current buffer."
6691 (org-block-map #'org-hide-block-toggle))
6693 (defun org-hide-block-all ()
6694 "Fold all blocks in the current buffer."
6695 (interactive)
6696 (org-show-block-all)
6697 (org-block-map #'org-hide-block-toggle-maybe))
6699 (defun org-show-block-all ()
6700 "Unfold all blocks in the current buffer."
6701 (interactive)
6702 (mapc 'delete-overlay org-hide-block-overlays)
6703 (setq org-hide-block-overlays nil))
6705 (defun org-hide-block-toggle-maybe ()
6706 "Toggle visibility of block at point."
6707 (interactive)
6708 (let ((case-fold-search t))
6709 (if (save-excursion
6710 (beginning-of-line 1)
6711 (looking-at org-block-regexp))
6712 (progn (org-hide-block-toggle)
6713 t) ;; to signal that we took action
6714 nil))) ;; to signal that we did not
6716 (defun org-hide-block-toggle (&optional force)
6717 "Toggle the visibility of the current block."
6718 (interactive)
6719 (save-excursion
6720 (beginning-of-line)
6721 (if (re-search-forward org-block-regexp nil t)
6722 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6723 (end (match-end 0)) ;; end of entire body
6725 (if (memq t (mapcar (lambda (overlay)
6726 (eq (overlay-get overlay 'invisible)
6727 'org-hide-block))
6728 (overlays-at start)))
6729 (if (or (not force) (eq force 'off))
6730 (mapc (lambda (ov)
6731 (when (member ov org-hide-block-overlays)
6732 (setq org-hide-block-overlays
6733 (delq ov org-hide-block-overlays)))
6734 (when (eq (overlay-get ov 'invisible)
6735 'org-hide-block)
6736 (delete-overlay ov)))
6737 (overlays-at start)))
6738 (setq ov (make-overlay start end))
6739 (overlay-put ov 'invisible 'org-hide-block)
6740 ;; make the block accessible to isearch
6741 (overlay-put
6742 ov 'isearch-open-invisible
6743 (lambda (ov)
6744 (when (member ov org-hide-block-overlays)
6745 (setq org-hide-block-overlays
6746 (delq ov org-hide-block-overlays)))
6747 (when (eq (overlay-get ov 'invisible)
6748 'org-hide-block)
6749 (delete-overlay ov))))
6750 (push ov org-hide-block-overlays)))
6751 (error "Not looking at a source block"))))
6753 ;; org-tab-after-check-for-cycling-hook
6754 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6755 ;; Remove overlays when changing major mode
6756 (add-hook 'org-mode-hook
6757 (lambda () (org-add-hook 'change-major-mode-hook
6758 'org-show-block-all 'append 'local)))
6760 ;;; Org-goto
6762 (defvar org-goto-window-configuration nil)
6763 (defvar org-goto-marker nil)
6764 (defvar org-goto-map)
6765 (defun org-goto-map ()
6766 "Set the keymap `org-goto'."
6767 (setq org-goto-map
6768 (let ((map (make-sparse-keymap)))
6769 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6770 mouse-drag-region universal-argument org-occur))
6771 cmd)
6772 (while (setq cmd (pop cmds))
6773 (substitute-key-definition cmd cmd map global-map)))
6774 (suppress-keymap map)
6775 (org-defkey map "\C-m" 'org-goto-ret)
6776 (org-defkey map [(return)] 'org-goto-ret)
6777 (org-defkey map [(left)] 'org-goto-left)
6778 (org-defkey map [(right)] 'org-goto-right)
6779 (org-defkey map [(control ?g)] 'org-goto-quit)
6780 (org-defkey map "\C-i" 'org-cycle)
6781 (org-defkey map [(tab)] 'org-cycle)
6782 (org-defkey map [(down)] 'outline-next-visible-heading)
6783 (org-defkey map [(up)] 'outline-previous-visible-heading)
6784 (if org-goto-auto-isearch
6785 (if (fboundp 'define-key-after)
6786 (define-key-after map [t] 'org-goto-local-auto-isearch)
6787 nil)
6788 (org-defkey map "q" 'org-goto-quit)
6789 (org-defkey map "n" 'outline-next-visible-heading)
6790 (org-defkey map "p" 'outline-previous-visible-heading)
6791 (org-defkey map "f" 'outline-forward-same-level)
6792 (org-defkey map "b" 'outline-backward-same-level)
6793 (org-defkey map "u" 'outline-up-heading))
6794 (org-defkey map "/" 'org-occur)
6795 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6796 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6797 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6798 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6799 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6800 map)))
6802 (defconst org-goto-help
6803 "Browse buffer copy, to find location or copy text.%s
6804 RET=jump to location C-g=quit and return to previous location
6805 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6807 (defvar org-goto-start-pos) ; dynamically scoped parameter
6809 ;; FIXME: Docstring does not mention both interfaces
6810 (defun org-goto (&optional alternative-interface)
6811 "Look up a different location in the current file, keeping current visibility.
6813 When you want look-up or go to a different location in a
6814 document, the fastest way is often to fold the entire buffer and
6815 then dive into the tree. This method has the disadvantage, that
6816 the previous location will be folded, which may not be what you
6817 want.
6819 This command works around this by showing a copy of the current
6820 buffer in an indirect buffer, in overview mode. You can dive
6821 into the tree in that copy, use org-occur and incremental search
6822 to find a location. When pressing RET or `Q', the command
6823 returns to the original buffer in which the visibility is still
6824 unchanged. After RET it will also jump to the location selected
6825 in the indirect buffer and expose the headline hierarchy above.
6827 With a prefix argument, use the alternative interface: e.g. if
6828 `org-goto-interface' is 'outline use 'outline-path-completion."
6829 (interactive "P")
6830 (org-goto-map)
6831 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6832 (org-refile-use-outline-path t)
6833 (org-refile-target-verify-function nil)
6834 (interface
6835 (if (not alternative-interface)
6836 org-goto-interface
6837 (if (eq org-goto-interface 'outline)
6838 'outline-path-completion
6839 'outline)))
6840 (org-goto-start-pos (point))
6841 (selected-point
6842 (if (eq interface 'outline)
6843 (car (org-get-location (current-buffer) org-goto-help))
6844 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6845 (org-refile-check-position pa)
6846 (nth 3 pa)))))
6847 (if selected-point
6848 (progn
6849 (org-mark-ring-push org-goto-start-pos)
6850 (goto-char selected-point)
6851 (if (or (outline-invisible-p) (org-invisible-p2))
6852 (org-show-context 'org-goto)))
6853 (message "Quit"))))
6855 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6856 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6857 (defvar org-goto-local-auto-isearch-map) ; defined below
6859 (defun org-get-location (buf help)
6860 "Let the user select a location in the Org-mode buffer BUF.
6861 This function uses a recursive edit. It returns the selected position
6862 or nil."
6863 (org-no-popups
6864 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6865 (isearch-hide-immediately nil)
6866 (isearch-search-fun-function
6867 (lambda () 'org-goto-local-search-headings))
6868 (org-goto-selected-point org-goto-exit-command))
6869 (save-excursion
6870 (save-window-excursion
6871 (delete-other-windows)
6872 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6873 (org-pop-to-buffer-same-window
6874 (condition-case nil
6875 (make-indirect-buffer (current-buffer) "*org-goto*")
6876 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6877 (with-output-to-temp-buffer "*Org Help*"
6878 (princ (format help (if org-goto-auto-isearch
6879 " Just type for auto-isearch."
6880 " n/p/f/b/u to navigate, q to quit."))))
6881 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6882 (setq buffer-read-only nil)
6883 (let ((org-startup-truncated t)
6884 (org-startup-folded nil)
6885 (org-startup-align-all-tables nil))
6886 (org-mode)
6887 (org-overview))
6888 (setq buffer-read-only t)
6889 (if (and (boundp 'org-goto-start-pos)
6890 (integer-or-marker-p org-goto-start-pos))
6891 (let ((org-show-hierarchy-above t)
6892 (org-show-siblings t)
6893 (org-show-following-heading t))
6894 (goto-char org-goto-start-pos)
6895 (and (outline-invisible-p) (org-show-context)))
6896 (goto-char (point-min)))
6897 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6898 (message "Select location and press RET")
6899 (use-local-map org-goto-map)
6900 (recursive-edit)))
6901 (kill-buffer "*org-goto*")
6902 (cons org-goto-selected-point org-goto-exit-command))))
6904 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6905 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6906 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6907 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6909 (defun org-goto-local-search-headings (string bound noerror)
6910 "Search and make sure that any matches are in headlines."
6911 (catch 'return
6912 (while (if isearch-forward
6913 (search-forward string bound noerror)
6914 (search-backward string bound noerror))
6915 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6916 (and (member :headline context)
6917 (not (member :tags context))))
6918 (throw 'return (point))))))
6920 (defun org-goto-local-auto-isearch ()
6921 "Start isearch."
6922 (interactive)
6923 (goto-char (point-min))
6924 (let ((keys (this-command-keys)))
6925 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6926 (isearch-mode t)
6927 (isearch-process-search-char (string-to-char keys)))))
6929 (defun org-goto-ret (&optional arg)
6930 "Finish `org-goto' by going to the new location."
6931 (interactive "P")
6932 (setq org-goto-selected-point (point)
6933 org-goto-exit-command 'return)
6934 (throw 'exit nil))
6936 (defun org-goto-left ()
6937 "Finish `org-goto' by going to the new location."
6938 (interactive)
6939 (if (org-at-heading-p)
6940 (progn
6941 (beginning-of-line 1)
6942 (setq org-goto-selected-point (point)
6943 org-goto-exit-command 'left)
6944 (throw 'exit nil))
6945 (error "Not on a heading")))
6947 (defun org-goto-right ()
6948 "Finish `org-goto' by going to the new location."
6949 (interactive)
6950 (if (org-at-heading-p)
6951 (progn
6952 (setq org-goto-selected-point (point)
6953 org-goto-exit-command 'right)
6954 (throw 'exit nil))
6955 (error "Not on a heading")))
6957 (defun org-goto-quit ()
6958 "Finish `org-goto' without cursor motion."
6959 (interactive)
6960 (setq org-goto-selected-point nil)
6961 (setq org-goto-exit-command 'quit)
6962 (throw 'exit nil))
6964 ;;; Indirect buffer display of subtrees
6966 (defvar org-indirect-dedicated-frame nil
6967 "This is the frame being used for indirect tree display.")
6968 (defvar org-last-indirect-buffer nil)
6970 (defun org-tree-to-indirect-buffer (&optional arg)
6971 "Create indirect buffer and narrow it to current subtree.
6972 With a numerical prefix ARG, go up to this level and then take that tree.
6973 If ARG is negative, go up that many levels.
6975 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6976 indirect buffer previously made with this command, to avoid proliferation of
6977 indirect buffers. However, when you call the command with a \
6978 \\[universal-argument] prefix, or
6979 when `org-indirect-buffer-display' is `new-frame', the last buffer
6980 is kept so that you can work with several indirect buffers at the same time.
6981 If `org-indirect-buffer-display' is `dedicated-frame', the \
6982 \\[universal-argument] prefix also
6983 requests that a new frame be made for the new buffer, so that the dedicated
6984 frame is not changed."
6985 (interactive "P")
6986 (let ((cbuf (current-buffer))
6987 (cwin (selected-window))
6988 (pos (point))
6989 beg end level heading ibuf)
6990 (save-excursion
6991 (org-back-to-heading t)
6992 (when (numberp arg)
6993 (setq level (org-outline-level))
6994 (if (< arg 0) (setq arg (+ level arg)))
6995 (while (> (setq level (org-outline-level)) arg)
6996 (org-up-heading-safe)))
6997 (setq beg (point)
6998 heading (org-get-heading))
6999 (org-end-of-subtree t t)
7000 (if (org-at-heading-p) (backward-char 1))
7001 (setq end (point)))
7002 (if (and (buffer-live-p org-last-indirect-buffer)
7003 (not (eq org-indirect-buffer-display 'new-frame))
7004 (not arg))
7005 (kill-buffer org-last-indirect-buffer))
7006 (setq ibuf (org-get-indirect-buffer cbuf)
7007 org-last-indirect-buffer ibuf)
7008 (cond
7009 ((or (eq org-indirect-buffer-display 'new-frame)
7010 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7011 (select-frame (make-frame))
7012 (delete-other-windows)
7013 (org-pop-to-buffer-same-window ibuf)
7014 (org-set-frame-title heading))
7015 ((eq org-indirect-buffer-display 'dedicated-frame)
7016 (raise-frame
7017 (select-frame (or (and org-indirect-dedicated-frame
7018 (frame-live-p org-indirect-dedicated-frame)
7019 org-indirect-dedicated-frame)
7020 (setq org-indirect-dedicated-frame (make-frame)))))
7021 (delete-other-windows)
7022 (org-pop-to-buffer-same-window ibuf)
7023 (org-set-frame-title (concat "Indirect: " heading)))
7024 ((eq org-indirect-buffer-display 'current-window)
7025 (org-pop-to-buffer-same-window ibuf))
7026 ((eq org-indirect-buffer-display 'other-window)
7027 (pop-to-buffer ibuf))
7028 (t (error "Invalid value")))
7029 (if (featurep 'xemacs)
7030 (save-excursion (org-mode) (turn-on-font-lock)))
7031 (narrow-to-region beg end)
7032 (show-all)
7033 (goto-char pos)
7034 (run-hook-with-args 'org-cycle-hook 'all)
7035 (and (window-live-p cwin) (select-window cwin))))
7037 (defun org-get-indirect-buffer (&optional buffer)
7038 (setq buffer (or buffer (current-buffer)))
7039 (let ((n 1) (base (buffer-name buffer)) bname)
7040 (while (buffer-live-p
7041 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7042 (setq n (1+ n)))
7043 (condition-case nil
7044 (make-indirect-buffer buffer bname 'clone)
7045 (error (make-indirect-buffer buffer bname)))))
7047 (defun org-set-frame-title (title)
7048 "Set the title of the current frame to the string TITLE."
7049 ;; FIXME: how to name a single frame in XEmacs???
7050 (unless (featurep 'xemacs)
7051 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7053 ;;;; Structure editing
7055 ;;; Inserting headlines
7057 (defun org-previous-line-empty-p ()
7058 (save-excursion
7059 (and (not (bobp))
7060 (or (beginning-of-line 0) t)
7061 (save-match-data
7062 (looking-at "[ \t]*$")))))
7064 (defun org-insert-heading (&optional force-heading invisible-ok)
7065 "Insert a new heading or item with same depth at point.
7066 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7067 If point is at the beginning of a headline, insert a sibling before the
7068 current headline. If point is not at the beginning, split the line,
7069 create the new headline with the text in the current line after point
7070 \(but see also the variable `org-M-RET-may-split-line').
7072 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7073 This is important for non-interactive uses of the command."
7074 (interactive "P")
7075 (if (or (= (buffer-size) 0)
7076 (and (not (save-excursion
7077 (and (ignore-errors (org-back-to-heading invisible-ok))
7078 (org-at-heading-p))))
7079 (or force-heading (not (org-in-item-p)))))
7080 (progn
7081 (insert "\n* ")
7082 (run-hooks 'org-insert-heading-hook))
7083 (when (or force-heading (not (org-insert-item)))
7084 (let* ((empty-line-p nil)
7085 (level nil)
7086 (on-heading (org-at-heading-p))
7087 (head (save-excursion
7088 (condition-case nil
7089 (progn
7090 (org-back-to-heading invisible-ok)
7091 (when (and (not on-heading)
7092 (featurep 'org-inlinetask)
7093 (integerp org-inlinetask-min-level)
7094 (>= (length (match-string 0))
7095 org-inlinetask-min-level))
7096 ;; Find a heading level before the inline task
7097 (while (and (setq level (org-up-heading-safe))
7098 (>= level org-inlinetask-min-level)))
7099 (if (org-at-heading-p)
7100 (org-back-to-heading invisible-ok)
7101 (error "This should not happen")))
7102 (setq empty-line-p (org-previous-line-empty-p))
7103 (match-string 0))
7104 (error "*"))))
7105 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7106 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7107 pos hide-previous previous-pos)
7108 (cond
7109 ((and (org-at-heading-p) (bolp)
7110 (or (bobp)
7111 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7112 ;; insert before the current line
7113 (open-line (if blank 2 1)))
7114 ((and (bolp)
7115 (not org-insert-heading-respect-content)
7116 (or (bobp)
7117 (save-excursion
7118 (backward-char 1) (not (outline-invisible-p)))))
7119 ;; insert right here
7120 nil)
7122 ;; somewhere in the line
7123 (save-excursion
7124 (setq previous-pos (point-at-bol))
7125 (end-of-line)
7126 (setq hide-previous (outline-invisible-p)))
7127 (and org-insert-heading-respect-content (org-show-subtree))
7128 (let ((split
7129 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7130 (save-excursion
7131 (let ((p (point)))
7132 (goto-char (point-at-bol))
7133 (and (looking-at org-complex-heading-regexp)
7134 (match-beginning 4)
7135 (> p (match-beginning 4)))))))
7136 tags pos)
7137 (cond
7138 (org-insert-heading-respect-content
7139 (org-end-of-subtree nil t)
7140 (when (featurep 'org-inlinetask)
7141 (while (and (not (eobp))
7142 (looking-at "\\(\\*+\\)[ \t]+")
7143 (>= (length (match-string 1))
7144 org-inlinetask-min-level))
7145 (org-end-of-subtree nil t)))
7146 (or (bolp) (newline))
7147 (or (org-previous-line-empty-p)
7148 (and blank (newline)))
7149 (open-line 1))
7150 ((org-at-heading-p)
7151 (when hide-previous
7152 (show-children)
7153 (org-show-entry))
7154 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7155 (setq tags (and (match-end 2) (match-string 2)))
7156 (and (match-end 1)
7157 (delete-region (match-beginning 1) (match-end 1)))
7158 (setq pos (point-at-bol))
7159 (or split (end-of-line 1))
7160 (delete-horizontal-space)
7161 (if (string-match "\\`\\*+\\'"
7162 (buffer-substring (point-at-bol) (point)))
7163 (insert " "))
7164 (newline (if blank 2 1))
7165 (when tags
7166 (save-excursion
7167 (goto-char pos)
7168 (end-of-line 1)
7169 (insert " " tags)
7170 (org-set-tags nil 'align))))
7172 (or split (end-of-line 1))
7173 (newline (if blank 2 1)))))))
7174 (insert head) (just-one-space)
7175 (setq pos (point))
7176 (end-of-line 1)
7177 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7178 (when (and org-insert-heading-respect-content hide-previous)
7179 (save-excursion
7180 (goto-char previous-pos)
7181 (hide-subtree)))
7182 (run-hooks 'org-insert-heading-hook)))))
7184 (defun org-get-heading (&optional no-tags no-todo)
7185 "Return the heading of the current entry, without the stars.
7186 When NO-TAGS is non-nil, don't include tags.
7187 When NO-TODO is non-nil, don't include TODO keywords."
7188 (save-excursion
7189 (org-back-to-heading t)
7190 (cond
7191 ((and no-tags no-todo)
7192 (looking-at org-complex-heading-regexp)
7193 (match-string 4))
7194 (no-tags
7195 (looking-at (concat org-outline-regexp
7196 "\\(.*?\\)"
7197 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7198 (match-string 1))
7199 (no-todo
7200 (looking-at org-todo-line-regexp)
7201 (match-string 3))
7202 (t (looking-at org-heading-regexp)
7203 (match-string 2)))))
7205 (defun org-heading-components ()
7206 "Return the components of the current heading.
7207 This is a list with the following elements:
7208 - the level as an integer
7209 - the reduced level, different if `org-odd-levels-only' is set.
7210 - the TODO keyword, or nil
7211 - the priority character, like ?A, or nil if no priority is given
7212 - the headline text itself, or the tags string if no headline text
7213 - the tags string, or nil."
7214 (save-excursion
7215 (org-back-to-heading t)
7216 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7217 (list (length (match-string 1))
7218 (org-reduced-level (length (match-string 1)))
7219 (org-match-string-no-properties 2)
7220 (and (match-end 3) (aref (match-string 3) 2))
7221 (org-match-string-no-properties 4)
7222 (org-match-string-no-properties 5)))))
7224 (defun org-get-entry ()
7225 "Get the entry text, after heading, entire subtree."
7226 (save-excursion
7227 (org-back-to-heading t)
7228 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7230 (defun org-insert-heading-after-current ()
7231 "Insert a new heading with same level as current, after current subtree."
7232 (interactive)
7233 (org-back-to-heading)
7234 (org-insert-heading)
7235 (org-move-subtree-down)
7236 (end-of-line 1))
7238 (defun org-insert-heading-respect-content ()
7239 (interactive)
7240 (let ((org-insert-heading-respect-content t))
7241 (org-insert-heading t)))
7243 (defun org-insert-todo-heading-respect-content (&optional force-state)
7244 (interactive "P")
7245 (let ((org-insert-heading-respect-content t))
7246 (org-insert-todo-heading force-state t)))
7248 (defun org-insert-todo-heading (arg &optional force-heading)
7249 "Insert a new heading with the same level and TODO state as current heading.
7250 If the heading has no TODO state, or if the state is DONE, use the first
7251 state (TODO by default). Also with prefix arg, force first state."
7252 (interactive "P")
7253 (when (or force-heading (not (org-insert-item 'checkbox)))
7254 (org-insert-heading force-heading)
7255 (save-excursion
7256 (org-back-to-heading)
7257 (outline-previous-heading)
7258 (looking-at org-todo-line-regexp))
7259 (let*
7260 ((new-mark-x
7261 (if (or arg
7262 (not (match-beginning 2))
7263 (member (match-string 2) org-done-keywords))
7264 (car org-todo-keywords-1)
7265 (match-string 2)))
7266 (new-mark
7268 (run-hook-with-args-until-success
7269 'org-todo-get-default-hook new-mark-x nil)
7270 new-mark-x)))
7271 (beginning-of-line 1)
7272 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7273 (if org-treat-insert-todo-heading-as-state-change
7274 (org-todo new-mark)
7275 (insert new-mark " "))))
7276 (when org-provide-todo-statistics
7277 (org-update-parent-todo-statistics))))
7279 (defun org-insert-subheading (arg)
7280 "Insert a new subheading and demote it.
7281 Works for outline headings and for plain lists alike."
7282 (interactive "P")
7283 (org-insert-heading arg)
7284 (cond
7285 ((org-at-heading-p) (org-do-demote))
7286 ((org-at-item-p) (org-indent-item))))
7288 (defun org-insert-todo-subheading (arg)
7289 "Insert a new subheading with TODO keyword or checkbox and demote it.
7290 Works for outline headings and for plain lists alike."
7291 (interactive "P")
7292 (org-insert-todo-heading arg)
7293 (cond
7294 ((org-at-heading-p) (org-do-demote))
7295 ((org-at-item-p) (org-indent-item))))
7297 ;;; Promotion and Demotion
7299 (defvar org-after-demote-entry-hook nil
7300 "Hook run after an entry has been demoted.
7301 The cursor will be at the beginning of the entry.
7302 When a subtree is being demoted, the hook will be called for each node.")
7304 (defvar org-after-promote-entry-hook nil
7305 "Hook run after an entry has been promoted.
7306 The cursor will be at the beginning of the entry.
7307 When a subtree is being promoted, the hook will be called for each node.")
7309 (defun org-promote-subtree ()
7310 "Promote the entire subtree.
7311 See also `org-promote'."
7312 (interactive)
7313 (save-excursion
7314 (org-with-limited-levels (org-map-tree 'org-promote)))
7315 (org-fix-position-after-promote))
7317 (defun org-demote-subtree ()
7318 "Demote the entire subtree. See `org-demote'.
7319 See also `org-promote'."
7320 (interactive)
7321 (save-excursion
7322 (org-with-limited-levels (org-map-tree 'org-demote)))
7323 (org-fix-position-after-promote))
7326 (defun org-do-promote ()
7327 "Promote the current heading higher up the tree.
7328 If the region is active in `transient-mark-mode', promote all headings
7329 in the region."
7330 (interactive)
7331 (save-excursion
7332 (if (org-region-active-p)
7333 (org-map-region 'org-promote (region-beginning) (region-end))
7334 (org-promote)))
7335 (org-fix-position-after-promote))
7337 (defun org-do-demote ()
7338 "Demote the current heading lower down the tree.
7339 If the region is active in `transient-mark-mode', demote all headings
7340 in the region."
7341 (interactive)
7342 (save-excursion
7343 (if (org-region-active-p)
7344 (org-map-region 'org-demote (region-beginning) (region-end))
7345 (org-demote)))
7346 (org-fix-position-after-promote))
7348 (defun org-fix-position-after-promote ()
7349 "Make sure that after pro/demotion cursor position is right."
7350 (let ((pos (point)))
7351 (when (save-excursion
7352 (beginning-of-line 1)
7353 (looking-at org-todo-line-regexp)
7354 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7355 (cond ((eobp) (insert " "))
7356 ((eolp) (insert " "))
7357 ((equal (char-after) ?\ ) (forward-char 1))))))
7359 (defun org-current-level ()
7360 "Return the level of the current entry, or nil if before the first headline.
7361 The level is the number of stars at the beginning of the headline."
7362 (save-excursion
7363 (org-with-limited-levels
7364 (if (ignore-errors (org-back-to-heading t))
7365 (funcall outline-level)))))
7367 (defun org-get-previous-line-level ()
7368 "Return the outline depth of the last headline before the current line.
7369 Returns 0 for the first headline in the buffer, and nil if before the
7370 first headline."
7371 (let ((current-level (org-current-level))
7372 (prev-level (when (> (line-number-at-pos) 1)
7373 (save-excursion
7374 (beginning-of-line 0)
7375 (org-current-level)))))
7376 (cond ((null current-level) nil) ; Before first headline
7377 ((null prev-level) 0) ; At first headline
7378 (prev-level))))
7380 (defun org-reduced-level (l)
7381 "Compute the effective level of a heading.
7382 This takes into account the setting of `org-odd-levels-only'."
7383 (cond
7384 ((zerop l) 0)
7385 (org-odd-levels-only (1+ (floor (/ l 2))))
7386 (t l)))
7388 (defun org-level-increment ()
7389 "Return the number of stars that will be added or removed at a
7390 time to headlines when structure editing, based on the value of
7391 `org-odd-levels-only'."
7392 (if org-odd-levels-only 2 1))
7394 (defun org-get-valid-level (level &optional change)
7395 "Rectify a level change under the influence of `org-odd-levels-only'
7396 LEVEL is a current level, CHANGE is by how much the level should be
7397 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7398 even level numbers will become the next higher odd number."
7399 (if org-odd-levels-only
7400 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7401 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7402 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7403 (max 1 (+ level (or change 0)))))
7405 (if (boundp 'define-obsolete-function-alias)
7406 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7407 (define-obsolete-function-alias 'org-get-legal-level
7408 'org-get-valid-level)
7409 (define-obsolete-function-alias 'org-get-legal-level
7410 'org-get-valid-level "23.1")))
7412 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7413 ;; ̀org-with-limited-levels'
7414 (defun org-promote ()
7415 "Promote the current heading higher up the tree.
7416 If the region is active in `transient-mark-mode', promote all headings
7417 in the region."
7418 (org-back-to-heading t)
7419 (let* ((level (save-match-data (funcall outline-level)))
7420 (after-change-functions (remove 'flyspell-after-change-function
7421 after-change-functions))
7422 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7423 (diff (abs (- level (length up-head) -1))))
7424 (cond ((and (= level 1) org-called-with-limited-levels
7425 org-allow-promoting-top-level-subtree)
7426 (replace-match "# " nil t))
7427 ((= level 1)
7428 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7429 (t (replace-match up-head nil t)))
7430 ;; Fixup tag positioning
7431 (unless (= level 1)
7432 (and org-auto-align-tags (org-set-tags nil t))
7433 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7434 (run-hooks 'org-after-promote-entry-hook)))
7436 (defun org-demote ()
7437 "Demote the current heading lower down the tree.
7438 If the region is active in `transient-mark-mode', demote all headings
7439 in the region."
7440 (org-back-to-heading t)
7441 (let* ((level (save-match-data (funcall outline-level)))
7442 (after-change-functions (remove 'flyspell-after-change-function
7443 after-change-functions))
7444 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7445 (diff (abs (- level (length down-head) -1))))
7446 (replace-match down-head nil t)
7447 ;; Fixup tag positioning
7448 (and org-auto-align-tags (org-set-tags nil t))
7449 (if org-adapt-indentation (org-fixup-indentation diff))
7450 (run-hooks 'org-after-demote-entry-hook)))
7452 (defun org-cycle-level ()
7453 "Cycle the level of an empty headline through possible states.
7454 This goes first to child, then to parent, level, then up the hierarchy.
7455 After top level, it switches back to sibling level."
7456 (interactive)
7457 (let ((org-adapt-indentation nil))
7458 (when (org-point-at-end-of-empty-headline)
7459 (setq this-command 'org-cycle-level) ; Only needed for caching
7460 (let ((cur-level (org-current-level))
7461 (prev-level (org-get-previous-line-level)))
7462 (cond
7463 ;; If first headline in file, promote to top-level.
7464 ((= prev-level 0)
7465 (loop repeat (/ (- cur-level 1) (org-level-increment))
7466 do (org-do-promote)))
7467 ;; If same level as prev, demote one.
7468 ((= prev-level cur-level)
7469 (org-do-demote))
7470 ;; If parent is top-level, promote to top level if not already.
7471 ((= prev-level 1)
7472 (loop repeat (/ (- cur-level 1) (org-level-increment))
7473 do (org-do-promote)))
7474 ;; If top-level, return to prev-level.
7475 ((= cur-level 1)
7476 (loop repeat (/ (- prev-level 1) (org-level-increment))
7477 do (org-do-demote)))
7478 ;; If less than prev-level, promote one.
7479 ((< cur-level prev-level)
7480 (org-do-promote))
7481 ;; If deeper than prev-level, promote until higher than
7482 ;; prev-level.
7483 ((> cur-level prev-level)
7484 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7485 do (org-do-promote))))
7486 t))))
7488 (defun org-map-tree (fun)
7489 "Call FUN for every heading underneath the current one."
7490 (org-back-to-heading)
7491 (let ((level (funcall outline-level)))
7492 (save-excursion
7493 (funcall fun)
7494 (while (and (progn
7495 (outline-next-heading)
7496 (> (funcall outline-level) level))
7497 (not (eobp)))
7498 (funcall fun)))))
7500 (defun org-map-region (fun beg end)
7501 "Call FUN for every heading between BEG and END."
7502 (let ((org-ignore-region t))
7503 (save-excursion
7504 (setq end (copy-marker end))
7505 (goto-char beg)
7506 (if (and (re-search-forward org-outline-regexp-bol nil t)
7507 (< (point) end))
7508 (funcall fun))
7509 (while (and (progn
7510 (outline-next-heading)
7511 (< (point) end))
7512 (not (eobp)))
7513 (funcall fun)))))
7515 (defvar org-property-end-re) ; silence byte-compiler
7516 (defun org-fixup-indentation (diff)
7517 "Change the indentation in the current entry by DIFF.
7518 However, if any line in the current entry has no indentation, or if it
7519 would end up with no indentation after the change, nothing at all is done."
7520 (save-excursion
7521 (let ((end (save-excursion (outline-next-heading)
7522 (point-marker)))
7523 (prohibit (if (> diff 0)
7524 "^\\S-"
7525 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7526 col)
7527 (unless (save-excursion (end-of-line 1)
7528 (re-search-forward prohibit end t))
7529 (while (and (< (point) end)
7530 (re-search-forward "^[ \t]+" end t))
7531 (goto-char (match-end 0))
7532 (setq col (current-column))
7533 (if (< diff 0) (replace-match ""))
7534 (org-indent-to-column (+ diff col))))
7535 (move-marker end nil))))
7537 (defun org-convert-to-odd-levels ()
7538 "Convert an org-mode file with all levels allowed to one with odd levels.
7539 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7540 level 5 etc."
7541 (interactive)
7542 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7543 (let ((outline-level 'org-outline-level)
7544 (org-odd-levels-only nil) n)
7545 (save-excursion
7546 (goto-char (point-min))
7547 (while (re-search-forward "^\\*\\*+ " nil t)
7548 (setq n (- (length (match-string 0)) 2))
7549 (while (>= (setq n (1- n)) 0)
7550 (org-demote))
7551 (end-of-line 1))))))
7553 (defun org-convert-to-oddeven-levels ()
7554 "Convert an org-mode file with only odd levels to one with odd/even levels.
7555 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7556 file contains a section with an even level, conversion would
7557 destroy the structure of the file. An error is signaled in this
7558 case."
7559 (interactive)
7560 (goto-char (point-min))
7561 ;; First check if there are no even levels
7562 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7563 (org-show-context t)
7564 (error "Not all levels are odd in this file. Conversion not possible"))
7565 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7566 (let ((outline-regexp org-outline-regexp)
7567 (outline-level 'org-outline-level)
7568 (org-odd-levels-only nil) n)
7569 (save-excursion
7570 (goto-char (point-min))
7571 (while (re-search-forward "^\\*\\*+ " nil t)
7572 (setq n (/ (1- (length (match-string 0))) 2))
7573 (while (>= (setq n (1- n)) 0)
7574 (org-promote))
7575 (end-of-line 1))))))
7577 (defun org-tr-level (n)
7578 "Make N odd if required."
7579 (if org-odd-levels-only (1+ (/ n 2)) n))
7581 ;;; Vertical tree motion, cutting and pasting of subtrees
7583 (defun org-move-subtree-up (&optional arg)
7584 "Move the current subtree up past ARG headlines of the same level."
7585 (interactive "p")
7586 (org-move-subtree-down (- (prefix-numeric-value arg))))
7588 (defun org-move-subtree-down (&optional arg)
7589 "Move the current subtree down past ARG headlines of the same level."
7590 (interactive "p")
7591 (setq arg (prefix-numeric-value arg))
7592 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7593 'org-get-last-sibling))
7594 (ins-point (make-marker))
7595 (cnt (abs arg))
7596 (col (current-column))
7597 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7598 ;; Select the tree
7599 (org-back-to-heading)
7600 (setq beg0 (point))
7601 (save-excursion
7602 (setq ne-beg (org-back-over-empty-lines))
7603 (setq beg (point)))
7604 (save-match-data
7605 (save-excursion (outline-end-of-heading)
7606 (setq folded (outline-invisible-p)))
7607 (outline-end-of-subtree))
7608 (outline-next-heading)
7609 (setq ne-end (org-back-over-empty-lines))
7610 (setq end (point))
7611 (goto-char beg0)
7612 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7613 ;; include less whitespace
7614 (save-excursion
7615 (goto-char beg)
7616 (forward-line (- ne-beg ne-end))
7617 (setq beg (point))))
7618 ;; Find insertion point, with error handling
7619 (while (> cnt 0)
7620 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7621 (progn (goto-char beg0)
7622 (error "Cannot move past superior level or buffer limit")))
7623 (setq cnt (1- cnt)))
7624 (if (> arg 0)
7625 ;; Moving forward - still need to move over subtree
7626 (progn (org-end-of-subtree t t)
7627 (save-excursion
7628 (org-back-over-empty-lines)
7629 (or (bolp) (newline)))))
7630 (setq ne-ins (org-back-over-empty-lines))
7631 (move-marker ins-point (point))
7632 (setq txt (buffer-substring beg end))
7633 (org-save-markers-in-region beg end)
7634 (delete-region beg end)
7635 (org-remove-empty-overlays-at beg)
7636 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7637 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7638 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7639 (let ((bbb (point)))
7640 (insert-before-markers txt)
7641 (org-reinstall-markers-in-region bbb)
7642 (move-marker ins-point bbb))
7643 (or (bolp) (insert "\n"))
7644 (setq ins-end (point))
7645 (goto-char ins-point)
7646 (org-skip-whitespace)
7647 (when (and (< arg 0)
7648 (org-first-sibling-p)
7649 (> ne-ins ne-beg))
7650 ;; Move whitespace back to beginning
7651 (save-excursion
7652 (goto-char ins-end)
7653 (let ((kill-whole-line t))
7654 (kill-line (- ne-ins ne-beg)) (point)))
7655 (insert (make-string (- ne-ins ne-beg) ?\n)))
7656 (move-marker ins-point nil)
7657 (if folded
7658 (hide-subtree)
7659 (org-show-entry)
7660 (show-children)
7661 (org-cycle-hide-drawers 'children))
7662 (org-clean-visibility-after-subtree-move)
7663 ;; move back to the initial column we were at
7664 (move-to-column col)))
7666 (defvar org-subtree-clip ""
7667 "Clipboard for cut and paste of subtrees.
7668 This is actually only a copy of the kill, because we use the normal kill
7669 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7671 (defvar org-subtree-clip-folded nil
7672 "Was the last copied subtree folded?
7673 This is used to fold the tree back after pasting.")
7675 (defun org-cut-subtree (&optional n)
7676 "Cut the current subtree into the clipboard.
7677 With prefix arg N, cut this many sequential subtrees.
7678 This is a short-hand for marking the subtree and then cutting it."
7679 (interactive "p")
7680 (org-copy-subtree n 'cut))
7682 (defun org-copy-subtree (&optional n cut force-store-markers)
7683 "Cut the current subtree into the clipboard.
7684 With prefix arg N, cut this many sequential subtrees.
7685 This is a short-hand for marking the subtree and then copying it.
7686 If CUT is non-nil, actually cut the subtree.
7687 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7688 of some markers in the region, even if CUT is non-nil. This is
7689 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7690 (interactive "p")
7691 (let (beg end folded (beg0 (point)))
7692 (if (org-called-interactively-p 'any)
7693 (org-back-to-heading nil) ; take what looks like a subtree
7694 (org-back-to-heading t)) ; take what is really there
7695 (setq beg (point))
7696 (skip-chars-forward " \t\r\n")
7697 (save-match-data
7698 (save-excursion (outline-end-of-heading)
7699 (setq folded (outline-invisible-p)))
7700 (condition-case nil
7701 (org-forward-heading-same-level (1- n) t)
7702 (error nil))
7703 (org-end-of-subtree t t))
7704 (setq end (point))
7705 (goto-char beg0)
7706 (when (> end beg)
7707 (setq org-subtree-clip-folded folded)
7708 (when (or cut force-store-markers)
7709 (org-save-markers-in-region beg end))
7710 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7711 (setq org-subtree-clip (current-kill 0))
7712 (message "%s: Subtree(s) with %d characters"
7713 (if cut "Cut" "Copied")
7714 (length org-subtree-clip)))))
7716 (defun org-paste-subtree (&optional level tree for-yank)
7717 "Paste the clipboard as a subtree, with modification of headline level.
7718 The entire subtree is promoted or demoted in order to match a new headline
7719 level.
7721 If the cursor is at the beginning of a headline, the same level as
7722 that headline is used to paste the tree
7724 If not, the new level is derived from the *visible* headings
7725 before and after the insertion point, and taken to be the inferior headline
7726 level of the two. So if the previous visible heading is level 3 and the
7727 next is level 4 (or vice versa), level 4 will be used for insertion.
7728 This makes sure that the subtree remains an independent subtree and does
7729 not swallow low level entries.
7731 You can also force a different level, either by using a numeric prefix
7732 argument, or by inserting the heading marker by hand. For example, if the
7733 cursor is after \"*****\", then the tree will be shifted to level 5.
7735 If optional TREE is given, use this text instead of the kill ring.
7737 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7738 move back over whitespace before inserting, and move point to the end of
7739 the inserted text when done."
7740 (interactive "P")
7741 (setq tree (or tree (and kill-ring (current-kill 0))))
7742 (unless (org-kill-is-subtree-p tree)
7743 (error "%s"
7744 (substitute-command-keys
7745 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7746 (org-with-limited-levels
7747 (let* ((visp (not (outline-invisible-p)))
7748 (txt tree)
7749 (^re_ "\\(\\*+\\)[ \t]*")
7750 (old-level (if (string-match org-outline-regexp-bol txt)
7751 (- (match-end 0) (match-beginning 0) 1)
7752 -1))
7753 (force-level (cond (level (prefix-numeric-value level))
7754 ((and (looking-at "[ \t]*$")
7755 (string-match
7756 "^\\*+$" (buffer-substring
7757 (point-at-bol) (point))))
7758 (- (match-end 1) (match-beginning 1)))
7759 ((and (bolp)
7760 (looking-at org-outline-regexp))
7761 (- (match-end 0) (point) 1))))
7762 (previous-level (save-excursion
7763 (condition-case nil
7764 (progn
7765 (outline-previous-visible-heading 1)
7766 (if (looking-at ^re_)
7767 (- (match-end 0) (match-beginning 0) 1)
7769 (error 1))))
7770 (next-level (save-excursion
7771 (condition-case nil
7772 (progn
7773 (or (looking-at org-outline-regexp)
7774 (outline-next-visible-heading 1))
7775 (if (looking-at ^re_)
7776 (- (match-end 0) (match-beginning 0) 1)
7778 (error 1))))
7779 (new-level (or force-level (max previous-level next-level)))
7780 (shift (if (or (= old-level -1)
7781 (= new-level -1)
7782 (= old-level new-level))
7784 (- new-level old-level)))
7785 (delta (if (> shift 0) -1 1))
7786 (func (if (> shift 0) 'org-demote 'org-promote))
7787 (org-odd-levels-only nil)
7788 beg end newend)
7789 ;; Remove the forced level indicator
7790 (if force-level
7791 (delete-region (point-at-bol) (point)))
7792 ;; Paste
7793 (beginning-of-line (if (bolp) 1 2))
7794 (setq beg (point))
7795 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7796 (insert-before-markers txt)
7797 (unless (string-match "\n\\'" txt) (insert "\n"))
7798 (setq newend (point))
7799 (org-reinstall-markers-in-region beg)
7800 (setq end (point))
7801 (goto-char beg)
7802 (skip-chars-forward " \t\n\r")
7803 (setq beg (point))
7804 (if (and (outline-invisible-p) visp)
7805 (save-excursion (outline-show-heading)))
7806 ;; Shift if necessary
7807 (unless (= shift 0)
7808 (save-restriction
7809 (narrow-to-region beg end)
7810 (while (not (= shift 0))
7811 (org-map-region func (point-min) (point-max))
7812 (setq shift (+ delta shift)))
7813 (goto-char (point-min))
7814 (setq newend (point-max))))
7815 (when (or (org-called-interactively-p 'interactive) for-yank)
7816 (message "Clipboard pasted as level %d subtree" new-level))
7817 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7818 kill-ring
7819 (eq org-subtree-clip (current-kill 0))
7820 org-subtree-clip-folded)
7821 ;; The tree was folded before it was killed/copied
7822 (hide-subtree))
7823 (and for-yank (goto-char newend)))))
7825 (defun org-kill-is-subtree-p (&optional txt)
7826 "Check if the current kill is an outline subtree, or a set of trees.
7827 Returns nil if kill does not start with a headline, or if the first
7828 headline level is not the largest headline level in the tree.
7829 So this will actually accept several entries of equal levels as well,
7830 which is OK for `org-paste-subtree'.
7831 If optional TXT is given, check this string instead of the current kill."
7832 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7833 (re (org-get-limited-outline-regexp))
7834 (^re (concat "^" re))
7835 (start-level (and kill
7836 (string-match
7837 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7838 kill)
7839 (- (match-end 2) (match-beginning 2) 1)))
7840 (start (1+ (or (match-beginning 2) -1))))
7841 (if (not start-level)
7842 (progn
7843 nil) ;; does not even start with a heading
7844 (catch 'exit
7845 (while (setq start (string-match ^re kill (1+ start)))
7846 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7847 (throw 'exit nil)))
7848 t))))
7850 (defvar org-markers-to-move nil
7851 "Markers that should be moved with a cut-and-paste operation.
7852 Those markers are stored together with their positions relative to
7853 the start of the region.")
7855 (defun org-save-markers-in-region (beg end)
7856 "Check markers in region.
7857 If these markers are between BEG and END, record their position relative
7858 to BEG, so that after moving the block of text, we can put the markers back
7859 into place.
7860 This function gets called just before an entry or tree gets cut from the
7861 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7862 called immediately, to move the markers with the entries."
7863 (setq org-markers-to-move nil)
7864 (when (featurep 'org-clock)
7865 (org-clock-save-markers-for-cut-and-paste beg end))
7866 (when (featurep 'org-agenda)
7867 (org-agenda-save-markers-for-cut-and-paste beg end)))
7869 (defun org-check-and-save-marker (marker beg end)
7870 "Check if MARKER is between BEG and END.
7871 If yes, remember the marker and the distance to BEG."
7872 (when (and (marker-buffer marker)
7873 (equal (marker-buffer marker) (current-buffer)))
7874 (if (and (>= marker beg) (< marker end))
7875 (push (cons marker (- marker beg)) org-markers-to-move))))
7877 (defun org-reinstall-markers-in-region (beg)
7878 "Move all remembered markers to their position relative to BEG."
7879 (mapc (lambda (x)
7880 (move-marker (car x) (+ beg (cdr x))))
7881 org-markers-to-move)
7882 (setq org-markers-to-move nil))
7884 (defun org-narrow-to-subtree ()
7885 "Narrow buffer to the current subtree."
7886 (interactive)
7887 (save-excursion
7888 (save-match-data
7889 (org-with-limited-levels
7890 (narrow-to-region
7891 (progn (org-back-to-heading t) (point))
7892 (progn (org-end-of-subtree t t)
7893 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7894 (point)))))))
7896 (defun org-narrow-to-block ()
7897 "Narrow buffer to the current block."
7898 (interactive)
7899 (let* ((case-fold-search t)
7900 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7901 "^[ \t]*#\\+end_.*")))
7902 (if blockp
7903 (narrow-to-region (car blockp) (cdr blockp))
7904 (error "Not in a block"))))
7906 (eval-when-compile
7907 (defvar org-property-drawer-re))
7909 (defvar org-property-start-re) ;; defined below
7910 (defun org-clone-subtree-with-time-shift (n &optional shift)
7911 "Clone the task (subtree) at point N times.
7912 The clones will be inserted as siblings.
7914 In interactive use, the user will be prompted for the number of
7915 clones to be produced, and for a time SHIFT, which may be a
7916 repeater as used in time stamps, for example `+3d'.
7918 When a valid repeater is given and the entry contains any time
7919 stamps, the clones will become a sequence in time, with time
7920 stamps in the subtree shifted for each clone produced. If SHIFT
7921 is nil or the empty string, time stamps will be left alone. The
7922 ID property of the original subtree is removed.
7924 If the original subtree did contain time stamps with a repeater,
7925 the following will happen:
7926 - the repeater will be removed in each clone
7927 - an additional clone will be produced, with the current, unshifted
7928 date(s) in the entry.
7929 - the original entry will be placed *after* all the clones, with
7930 repeater intact.
7931 - the start days in the repeater in the original entry will be shifted
7932 to past the last clone.
7933 In this way you can spell out a number of instances of a repeating task,
7934 and still retain the repeater to cover future instances of the task."
7935 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7936 (let (beg end template task idprop
7937 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7938 (drawer-re org-drawer-regexp))
7939 (if (not (and (integerp n) (> n 0)))
7940 (error "Invalid number of replications %s" n))
7941 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7942 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7943 shift)))
7944 (error "Invalid shift specification %s" shift))
7945 (when doshift
7946 (setq shift-n (string-to-number (match-string 1 shift))
7947 shift-what (cdr (assoc (match-string 2 shift)
7948 '(("d" . day) ("w" . week)
7949 ("m" . month) ("y" . year))))))
7950 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7951 (setq nmin 1 nmax n)
7952 (org-back-to-heading t)
7953 (setq beg (point))
7954 (setq idprop (org-entry-get nil "ID"))
7955 (org-end-of-subtree t t)
7956 (or (bolp) (insert "\n"))
7957 (setq end (point))
7958 (setq template (buffer-substring beg end))
7959 (when (and doshift
7960 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7961 (delete-region beg end)
7962 (setq end beg)
7963 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7964 (goto-char end)
7965 (loop for n from nmin to nmax do
7966 ;; prepare clone
7967 (with-temp-buffer
7968 (insert template)
7969 (org-mode)
7970 (goto-char (point-min))
7971 (org-show-subtree)
7972 (and idprop (if org-clone-delete-id
7973 (org-entry-delete nil "ID")
7974 (org-id-get-create t)))
7975 (unless (= n 0)
7976 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7977 (kill-whole-line))
7978 (goto-char (point-min))
7979 (while (re-search-forward drawer-re nil t)
7980 (mapc (lambda (d)
7981 (org-remove-empty-drawer-at d (point))) org-drawers)))
7982 (goto-char (point-min))
7983 (when doshift
7984 (while (re-search-forward org-ts-regexp-both nil t)
7985 (org-timestamp-change (* n shift-n) shift-what))
7986 (unless (= n n-no-remove)
7987 (goto-char (point-min))
7988 (while (re-search-forward org-ts-regexp nil t)
7989 (save-excursion
7990 (goto-char (match-beginning 0))
7991 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7992 (delete-region (match-beginning 1) (match-end 1)))))))
7993 (setq task (buffer-string)))
7994 (insert task))
7995 (goto-char beg)))
7997 ;;; Outline Sorting
7999 (defun org-sort (with-case)
8000 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8001 Optional argument WITH-CASE means sort case-sensitively."
8002 (interactive "P")
8003 (cond
8004 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8005 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8007 (org-call-with-arg 'org-sort-entries with-case))))
8009 (defun org-sort-remove-invisible (s)
8010 (remove-text-properties 0 (length s) org-rm-props s)
8011 (while (string-match org-bracket-link-regexp s)
8012 (setq s (replace-match (if (match-end 2)
8013 (match-string 3 s)
8014 (match-string 1 s)) t t s)))
8017 (defvar org-priority-regexp) ; defined later in the file
8019 (defvar org-after-sorting-entries-or-items-hook nil
8020 "Hook that is run after a bunch of entries or items have been sorted.
8021 When children are sorted, the cursor is in the parent line when this
8022 hook gets called. When a region or a plain list is sorted, the cursor
8023 will be in the first entry of the sorted region/list.")
8025 (defun org-sort-entries
8026 (&optional with-case sorting-type getkey-func compare-func property)
8027 "Sort entries on a certain level of an outline tree.
8028 If there is an active region, the entries in the region are sorted.
8029 Else, if the cursor is before the first entry, sort the top-level items.
8030 Else, the children of the entry at point are sorted.
8032 Sorting can be alphabetically, numerically, by date/time as given by
8033 a time stamp, by a property or by priority.
8035 The command prompts for the sorting type unless it has been given to the
8036 function through the SORTING-TYPE argument, which needs to be a character,
8037 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8038 precise meaning of each character:
8040 n Numerically, by converting the beginning of the entry/item to a number.
8041 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8042 o By order of TODO keywords.
8043 t By date/time, either the first active time stamp in the entry, or, if
8044 none exist, by the first inactive one.
8045 s By the scheduled date/time.
8046 d By deadline date/time.
8047 c By creation time, which is assumed to be the first inactive time stamp
8048 at the beginning of a line.
8049 p By priority according to the cookie.
8050 r By the value of a property.
8052 Capital letters will reverse the sort order.
8054 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8055 called with point at the beginning of the record. It must return either
8056 a string or a number that should serve as the sorting key for that record.
8058 Comparing entries ignores case by default. However, with an optional argument
8059 WITH-CASE, the sorting considers case as well."
8060 (interactive "P")
8061 (let ((case-func (if with-case 'identity 'downcase))
8062 (cmstr
8063 ;; The clock marker is lost when using `sort-subr', let's
8064 ;; store the clocking string.
8065 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8066 (save-excursion
8067 (goto-char org-clock-marker)
8068 (looking-back "^.*") (match-string-no-properties 0))))
8069 start beg end stars re re2
8070 txt what tmp)
8071 ;; Find beginning and end of region to sort
8072 (cond
8073 ((org-region-active-p)
8074 ;; we will sort the region
8075 (setq end (region-end)
8076 what "region")
8077 (goto-char (region-beginning))
8078 (if (not (org-at-heading-p)) (outline-next-heading))
8079 (setq start (point)))
8080 ((or (org-at-heading-p)
8081 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8082 ;; we will sort the children of the current headline
8083 (org-back-to-heading)
8084 (setq start (point)
8085 end (progn (org-end-of-subtree t t)
8086 (or (bolp) (insert "\n"))
8087 (org-back-over-empty-lines)
8088 (point))
8089 what "children")
8090 (goto-char start)
8091 (show-subtree)
8092 (outline-next-heading))
8094 ;; we will sort the top-level entries in this file
8095 (goto-char (point-min))
8096 (or (org-at-heading-p) (outline-next-heading))
8097 (setq start (point))
8098 (goto-char (point-max))
8099 (beginning-of-line 1)
8100 (when (looking-at ".*?\\S-")
8101 ;; File ends in a non-white line
8102 (end-of-line 1)
8103 (insert "\n"))
8104 (setq end (point-max))
8105 (setq what "top-level")
8106 (goto-char start)
8107 (show-all)))
8109 (setq beg (point))
8110 (if (>= beg end) (error "Nothing to sort"))
8112 (looking-at "\\(\\*+\\)")
8113 (setq stars (match-string 1)
8114 re (concat "^" (regexp-quote stars) " +")
8115 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8116 txt (buffer-substring beg end))
8117 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8118 (if (and (not (equal stars "*")) (string-match re2 txt))
8119 (error "Region to sort contains a level above the first entry"))
8121 (unless sorting-type
8122 (message
8123 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8124 [t]ime [s]cheduled [d]eadline [c]reated
8125 A/N/P/R/O/F/T/S/D/C means reversed:"
8126 what)
8127 (setq sorting-type (read-char-exclusive))
8129 (and (= (downcase sorting-type) ?f)
8130 (setq getkey-func
8131 (org-icompleting-read "Sort using function: "
8132 obarray 'fboundp t nil nil))
8133 (setq getkey-func (intern getkey-func)))
8135 (and (= (downcase sorting-type) ?r)
8136 (setq property
8137 (org-icompleting-read "Property: "
8138 (mapcar 'list (org-buffer-property-keys t))
8139 nil t))))
8141 (message "Sorting entries...")
8143 (save-restriction
8144 (narrow-to-region start end)
8145 (let ((dcst (downcase sorting-type))
8146 (case-fold-search nil)
8147 (now (current-time)))
8148 (sort-subr
8149 (/= dcst sorting-type)
8150 ;; This function moves to the beginning character of the "record" to
8151 ;; be sorted.
8152 (lambda nil
8153 (if (re-search-forward re nil t)
8154 (goto-char (match-beginning 0))
8155 (goto-char (point-max))))
8156 ;; This function moves to the last character of the "record" being
8157 ;; sorted.
8158 (lambda nil
8159 (save-match-data
8160 (condition-case nil
8161 (outline-forward-same-level 1)
8162 (error
8163 (goto-char (point-max))))))
8164 ;; This function returns the value that gets sorted against.
8165 (lambda nil
8166 (cond
8167 ((= dcst ?n)
8168 (if (looking-at org-complex-heading-regexp)
8169 (string-to-number (match-string 4))
8170 nil))
8171 ((= dcst ?a)
8172 (if (looking-at org-complex-heading-regexp)
8173 (funcall case-func (match-string 4))
8174 nil))
8175 ((= dcst ?t)
8176 (let ((end (save-excursion (outline-next-heading) (point))))
8177 (if (or (re-search-forward org-ts-regexp end t)
8178 (re-search-forward org-ts-regexp-both end t))
8179 (org-time-string-to-seconds (match-string 0))
8180 (org-float-time now))))
8181 ((= dcst ?c)
8182 (let ((end (save-excursion (outline-next-heading) (point))))
8183 (if (re-search-forward
8184 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8185 end t)
8186 (org-time-string-to-seconds (match-string 0))
8187 (org-float-time now))))
8188 ((= dcst ?s)
8189 (let ((end (save-excursion (outline-next-heading) (point))))
8190 (if (re-search-forward org-scheduled-time-regexp end t)
8191 (org-time-string-to-seconds (match-string 1))
8192 (org-float-time now))))
8193 ((= dcst ?d)
8194 (let ((end (save-excursion (outline-next-heading) (point))))
8195 (if (re-search-forward org-deadline-time-regexp end t)
8196 (org-time-string-to-seconds (match-string 1))
8197 (org-float-time now))))
8198 ((= dcst ?p)
8199 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8200 (string-to-char (match-string 2))
8201 org-default-priority))
8202 ((= dcst ?r)
8203 (or (org-entry-get nil property) ""))
8204 ((= dcst ?o)
8205 (if (looking-at org-complex-heading-regexp)
8206 (- 9999 (length (member (match-string 2)
8207 org-todo-keywords-1)))))
8208 ((= dcst ?f)
8209 (if getkey-func
8210 (progn
8211 (setq tmp (funcall getkey-func))
8212 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8213 tmp)
8214 (error "Invalid key function `%s'" getkey-func)))
8215 (t (error "Invalid sorting type `%c'" sorting-type))))
8217 (cond
8218 ((= dcst ?a) 'string<)
8219 ((= dcst ?f) compare-func)
8220 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8221 (run-hooks 'org-after-sorting-entries-or-items-hook)
8222 ;; Reset the clock marker if needed
8223 (when cmstr
8224 (save-excursion
8225 (goto-char start)
8226 (search-forward cmstr nil t)
8227 (move-marker org-clock-marker (point))))
8228 (message "Sorting entries...done")))
8230 (defun org-do-sort (table what &optional with-case sorting-type)
8231 "Sort TABLE of WHAT according to SORTING-TYPE.
8232 The user will be prompted for the SORTING-TYPE if the call to this
8233 function does not specify it. WHAT is only for the prompt, to indicate
8234 what is being sorted. The sorting key will be extracted from
8235 the car of the elements of the table.
8236 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8237 (unless sorting-type
8238 (message
8239 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8240 what)
8241 (setq sorting-type (read-char-exclusive)))
8242 (let ((dcst (downcase sorting-type))
8243 extractfun comparefun)
8244 ;; Define the appropriate functions
8245 (cond
8246 ((= dcst ?n)
8247 (setq extractfun 'string-to-number
8248 comparefun (if (= dcst sorting-type) '< '>)))
8249 ((= dcst ?a)
8250 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8251 (lambda(x) (downcase (org-sort-remove-invisible x))))
8252 comparefun (if (= dcst sorting-type)
8253 'string<
8254 (lambda (a b) (and (not (string< a b))
8255 (not (string= a b)))))))
8256 ((= dcst ?t)
8257 (setq extractfun
8258 (lambda (x)
8259 (if (or (string-match org-ts-regexp x)
8260 (string-match org-ts-regexp-both x))
8261 (org-float-time
8262 (org-time-string-to-time (match-string 0 x)))
8264 comparefun (if (= dcst sorting-type) '< '>)))
8265 (t (error "Invalid sorting type `%c'" sorting-type)))
8267 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8268 table)
8269 (lambda (a b) (funcall comparefun (car a) (car b))))))
8272 ;;; The orgstruct minor mode
8274 ;; Define a minor mode which can be used in other modes in order to
8275 ;; integrate the org-mode structure editing commands.
8277 ;; This is really a hack, because the org-mode structure commands use
8278 ;; keys which normally belong to the major mode. Here is how it
8279 ;; works: The minor mode defines all the keys necessary to operate the
8280 ;; structure commands, but wraps the commands into a function which
8281 ;; tests if the cursor is currently at a headline or a plain list
8282 ;; item. If that is the case, the structure command is used,
8283 ;; temporarily setting many Org-mode variables like regular
8284 ;; expressions for filling etc. However, when any of those keys is
8285 ;; used at a different location, function uses `key-binding' to look
8286 ;; up if the key has an associated command in another currently active
8287 ;; keymap (minor modes, major mode, global), and executes that
8288 ;; command. There might be problems if any of the keys is otherwise
8289 ;; used as a prefix key.
8291 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8292 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8293 ;; addresses this by checking explicitly for both bindings.
8295 (defvar orgstruct-mode-map (make-sparse-keymap)
8296 "Keymap for the minor `orgstruct-mode'.")
8298 (defvar org-local-vars nil
8299 "List of local variables, for use by `orgstruct-mode'.")
8301 ;;;###autoload
8302 (define-minor-mode orgstruct-mode
8303 "Toggle the minor mode `orgstruct-mode'.
8304 This mode is for using Org-mode structure commands in other
8305 modes. The following keys behave as if Org-mode were active, if
8306 the cursor is on a headline, or on a plain list item (both as
8307 defined by Org-mode).
8309 M-up Move entry/item up
8310 M-down Move entry/item down
8311 M-left Promote
8312 M-right Demote
8313 M-S-up Move entry/item up
8314 M-S-down Move entry/item down
8315 M-S-left Promote subtree
8316 M-S-right Demote subtree
8317 M-q Fill paragraph and items like in Org-mode
8318 C-c ^ Sort entries
8319 C-c - Cycle list bullet
8320 TAB Cycle item visibility
8321 M-RET Insert new heading/item
8322 S-M-RET Insert new TODO heading / Checkbox item
8323 C-c C-c Set tags / toggle checkbox"
8324 nil " OrgStruct" nil
8325 (org-load-modules-maybe)
8326 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8328 ;;;###autoload
8329 (defun turn-on-orgstruct ()
8330 "Unconditionally turn on `orgstruct-mode'."
8331 (orgstruct-mode 1))
8333 (defvar org-fb-vars nil)
8334 (make-variable-buffer-local 'org-fb-vars)
8335 (defun orgstruct++-mode (&optional arg)
8336 "Toggle `orgstruct-mode', the enhanced version of it.
8337 In addition to setting orgstruct-mode, this also exports all
8338 indentation and autofilling variables from org-mode into the
8339 buffer. It will also recognize item context in multiline items."
8340 (interactive "P")
8341 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8342 (if (< arg 1)
8343 (progn (orgstruct-mode -1)
8344 (mapc (lambda(v)
8345 (org-set-local (car v)
8346 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8347 org-fb-vars))
8348 (orgstruct-mode 1)
8349 (setq org-fb-vars nil)
8350 (let (var val)
8351 (mapc
8352 (lambda (x)
8353 (when (string-match
8354 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8355 (symbol-name (car x)))
8356 (setq var (car x) val (nth 1 x))
8357 (push (list var `(quote ,(eval var))) org-fb-vars)
8358 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8359 org-local-vars)
8360 (org-set-local 'orgstruct-is-++ t))))
8362 (defvar orgstruct-is-++ nil
8363 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8364 (make-variable-buffer-local 'orgstruct-is-++)
8366 ;;;###autoload
8367 (defun turn-on-orgstruct++ ()
8368 "Unconditionally turn on `orgstruct++-mode'."
8369 (orgstruct++-mode 1))
8371 (defun orgstruct-error ()
8372 "Error when there is no default binding for a structure key."
8373 (interactive)
8374 (error "This key has no function outside structure elements"))
8376 (defun orgstruct-setup ()
8377 "Setup orgstruct keymaps."
8378 (let ((nfunc 0)
8379 (bindings
8380 (list
8381 '([(meta up)] org-metaup)
8382 '([(meta down)] org-metadown)
8383 '([(meta left)] org-metaleft)
8384 '([(meta right)] org-metaright)
8385 '([(meta shift up)] org-shiftmetaup)
8386 '([(meta shift down)] org-shiftmetadown)
8387 '([(meta shift left)] org-shiftmetaleft)
8388 '([(meta shift right)] org-shiftmetaright)
8389 '([?\e (up)] org-metaup)
8390 '([?\e (down)] org-metadown)
8391 '([?\e (left)] org-metaleft)
8392 '([?\e (right)] org-metaright)
8393 '([?\e (shift up)] org-shiftmetaup)
8394 '([?\e (shift down)] org-shiftmetadown)
8395 '([?\e (shift left)] org-shiftmetaleft)
8396 '([?\e (shift right)] org-shiftmetaright)
8397 '([(shift up)] org-shiftup)
8398 '([(shift down)] org-shiftdown)
8399 '([(shift left)] org-shiftleft)
8400 '([(shift right)] org-shiftright)
8401 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8402 '("\M-q" fill-paragraph)
8403 '("\C-c^" org-sort)
8404 '("\C-c-" org-cycle-list-bullet)))
8405 elt key fun cmd)
8406 (while (setq elt (pop bindings))
8407 (setq nfunc (1+ nfunc))
8408 (setq key (org-key (car elt))
8409 fun (nth 1 elt)
8410 cmd (orgstruct-make-binding fun nfunc key))
8411 (org-defkey orgstruct-mode-map key cmd))
8413 ;; Prevent an error for users who forgot to make autoloads
8414 (require 'org-element)
8416 ;; Special treatment needed for TAB and RET
8417 (org-defkey orgstruct-mode-map [(tab)]
8418 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8419 (org-defkey orgstruct-mode-map "\C-i"
8420 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8422 (org-defkey orgstruct-mode-map "\M-\C-m"
8423 (orgstruct-make-binding 'org-insert-heading 105
8424 "\M-\C-m" [(meta return)]))
8425 (org-defkey orgstruct-mode-map [(meta return)]
8426 (orgstruct-make-binding 'org-insert-heading 106
8427 [(meta return)] "\M-\C-m"))
8429 (org-defkey orgstruct-mode-map [(shift meta return)]
8430 (orgstruct-make-binding 'org-insert-todo-heading 107
8431 [(meta return)] "\M-\C-m"))
8433 (org-defkey orgstruct-mode-map "\e\C-m"
8434 (orgstruct-make-binding 'org-insert-heading 108
8435 "\e\C-m" [?\e (return)]))
8436 (org-defkey orgstruct-mode-map [?\e (return)]
8437 (orgstruct-make-binding 'org-insert-heading 109
8438 [?\e (return)] "\e\C-m"))
8439 (org-defkey orgstruct-mode-map [?\e (shift return)]
8440 (orgstruct-make-binding 'org-insert-todo-heading 110
8441 [?\e (return)] "\e\C-m"))
8443 (unless org-local-vars
8444 (setq org-local-vars (org-get-local-variables)))
8448 (defun orgstruct-make-binding (fun n &rest keys)
8449 "Create a function for binding in the structure minor mode.
8450 FUN is the command to call inside a table. N is used to create a unique
8451 command name. KEYS are keys that should be checked in for a command
8452 to execute outside of tables."
8453 (eval
8454 (list 'defun
8455 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8456 '(arg)
8457 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8458 "Outside of structure, run the binding of `"
8459 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8460 "'.")
8461 '(interactive "p")
8462 (list 'if
8463 `(org-context-p 'headline 'item
8464 (and orgstruct-is-++
8465 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8466 'item-body))
8467 (list 'org-run-like-in-org-mode (list 'quote fun))
8468 (list 'let '(orgstruct-mode)
8469 (list 'call-interactively
8470 (append '(or)
8471 (mapcar (lambda (k)
8472 (list 'key-binding k))
8473 keys)
8474 '('orgstruct-error))))))))
8476 (defun org-contextualize-keys (alist contexts)
8477 "Return valid elements in ALIST depending on CONTEXTS.
8479 `org-agenda-custom-commands' or `org-capture-templates' are the
8480 values used for ALIST, and `org-agenda-custom-commands-contexts'
8481 or `org-capture-templates-contexts' are the associated contexts
8482 definitions."
8483 (let ((contexts
8484 ;; normalize contexts
8485 (mapcar
8486 (lambda(c) (cond ((listp (cadr c))
8487 (list (car c) (car c) (cadr c)))
8488 ((string= "" (cadr c))
8489 (list (car c) (car c) (caddr c)))
8490 (t c))) contexts))
8491 (a alist) c r s)
8492 ;; loop over all commands or templates
8493 (while (setq c (pop a))
8494 (let (vrules repl)
8495 (cond
8496 ((not (assoc (car c) contexts))
8497 (push c r))
8498 ((and (assoc (car c) contexts)
8499 (setq vrules (org-contextualize-validate-key
8500 (car c) contexts)))
8501 (mapc (lambda (vr)
8502 (when (not (equal (car vr) (cadr vr)))
8503 (setq repl vr))) vrules)
8504 (if (not repl) (push c r)
8505 (push (cadr repl) s)
8506 (push
8507 (cons (car c)
8508 (cdr (or (assoc (cadr repl) alist)
8509 (error "Undefined key `%s' as contextual replacement for `%s'"
8510 (cadr repl) (car c)))))
8511 r))))))
8512 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8513 (delq
8515 (delete-dups
8516 (mapcar (lambda (x)
8517 (let ((tpl (car x)))
8518 (when (not (delq
8520 (mapcar (lambda(y)
8521 (equal y tpl)) s))) x)))
8522 (reverse r))))))
8524 (defun org-contextualize-validate-key (key contexts)
8525 "Check CONTEXTS for agenda or capture KEY."
8526 (let (r rr res)
8527 (while (setq r (pop contexts))
8528 (mapc
8529 (lambda (rr)
8530 (when
8531 (and (equal key (car r))
8532 (if (functionp rr) (funcall rr)
8533 (or (and (eq (car rr) 'in-file)
8534 (buffer-file-name)
8535 (string-match (cdr rr) (buffer-file-name)))
8536 (and (eq (car rr) 'in-mode)
8537 (string-match (cdr rr) (symbol-name major-mode)))
8538 (when (and (eq (car rr) 'not-in-file)
8539 (buffer-file-name))
8540 (not (string-match (cdr rr) (buffer-file-name))))
8541 (when (eq (car rr) 'not-in-mode)
8542 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8543 (push r res)))
8544 (car (last r))))
8545 (delete-dups (delq nil res))))
8547 (defun org-context-p (&rest contexts)
8548 "Check if local context is any of CONTEXTS.
8549 Possible values in the list of contexts are `table', `headline', and `item'."
8550 (let ((pos (point)))
8551 (goto-char (point-at-bol))
8552 (prog1 (or (and (memq 'table contexts)
8553 (looking-at "[ \t]*|"))
8554 (and (memq 'headline contexts)
8555 (looking-at org-outline-regexp))
8556 (and (memq 'item contexts)
8557 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8558 (and (memq 'item-body contexts)
8559 (org-in-item-p)))
8560 (goto-char pos))))
8562 (defun org-get-local-variables ()
8563 "Return a list of all local variables in an Org mode buffer."
8564 (let (varlist)
8565 (with-current-buffer (get-buffer-create "*Org tmp*")
8566 (erase-buffer)
8567 (org-mode)
8568 (setq varlist (buffer-local-variables)))
8569 (kill-buffer "*Org tmp*")
8570 (delq nil
8571 (mapcar
8572 (lambda (x)
8573 (setq x
8574 (if (symbolp x)
8575 (list x)
8576 (list (car x) (list 'quote (cdr x)))))
8577 (if (string-match
8578 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8579 (symbol-name (car x)))
8580 x nil))
8581 varlist))))
8583 (defun org-clone-local-variables (from-buffer &optional regexp)
8584 "Clone local variables from FROM-BUFFER.
8585 Optional argument REGEXP selects variables to clone."
8586 (mapc
8587 (lambda (pair)
8588 (and (symbolp (car pair))
8589 (or (null regexp)
8590 (string-match regexp (symbol-name (car pair))))
8591 (set (make-local-variable (car pair))
8592 (cdr pair))))
8593 (buffer-local-variables from-buffer)))
8595 ;;;###autoload
8596 (defun org-run-like-in-org-mode (cmd)
8597 "Run a command, pretending that the current buffer is in Org-mode.
8598 This will temporarily bind local variables that are typically bound in
8599 Org-mode to the values they have in Org-mode, and then interactively
8600 call CMD."
8601 (org-load-modules-maybe)
8602 (unless org-local-vars
8603 (setq org-local-vars (org-get-local-variables)))
8604 (eval (list 'let org-local-vars
8605 (list 'call-interactively (list 'quote cmd)))))
8607 ;;;; Archiving
8609 (defun org-get-category (&optional pos force-refresh)
8610 "Get the category applying to position POS."
8611 (save-match-data
8612 (if force-refresh (org-refresh-category-properties))
8613 (let ((pos (or pos (point))))
8614 (or (get-text-property pos 'org-category)
8615 (progn (org-refresh-category-properties)
8616 (get-text-property pos 'org-category))))))
8618 (defun org-refresh-category-properties ()
8619 "Refresh category text properties in the buffer."
8620 (let ((case-fold-search t)
8621 (inhibit-read-only t)
8622 (def-cat (cond
8623 ((null org-category)
8624 (if buffer-file-name
8625 (file-name-sans-extension
8626 (file-name-nondirectory buffer-file-name))
8627 "???"))
8628 ((symbolp org-category) (symbol-name org-category))
8629 (t org-category)))
8630 beg end cat pos optionp)
8631 (org-unmodified
8632 (save-excursion
8633 (save-restriction
8634 (widen)
8635 (goto-char (point-min))
8636 (put-text-property (point) (point-max) 'org-category def-cat)
8637 (while (re-search-forward
8638 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8639 (setq pos (match-end 0)
8640 optionp (equal (char-after (match-beginning 0)) ?#)
8641 cat (org-trim (match-string 2)))
8642 (if optionp
8643 (setq beg (point-at-bol) end (point-max))
8644 (org-back-to-heading t)
8645 (setq beg (point) end (org-end-of-subtree t t)))
8646 (put-text-property beg end 'org-category cat)
8647 (put-text-property beg end 'org-category-position beg)
8648 (goto-char pos)))))))
8650 (defun org-refresh-properties (dprop tprop)
8651 "Refresh buffer text properties.
8652 DPROP is the drawer property and TPROP is the corresponding text
8653 property to set."
8654 (let ((case-fold-search t)
8655 (inhibit-read-only t) p)
8656 (org-unmodified
8657 (save-excursion
8658 (save-restriction
8659 (widen)
8660 (goto-char (point-min))
8661 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8662 (setq p (org-match-string-no-properties 1))
8663 (save-excursion
8664 (org-back-to-heading t)
8665 (put-text-property
8666 (point-at-bol) (point-at-eol) tprop p))))))))
8669 ;;;; Link Stuff
8671 ;;; Link abbreviations
8673 (defun org-link-expand-abbrev (link)
8674 "Apply replacements as defined in `org-link-abbrev-alist'."
8675 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8676 (let* ((key (match-string 1 link))
8677 (as (or (assoc key org-link-abbrev-alist-local)
8678 (assoc key org-link-abbrev-alist)))
8679 (tag (and (match-end 2) (match-string 3 link)))
8680 rpl)
8681 (if (not as)
8682 link
8683 (setq rpl (cdr as))
8684 (cond
8685 ((symbolp rpl) (funcall rpl tag))
8686 ((string-match "%(\\([^)]+\\))" rpl)
8687 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8688 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8689 ((string-match "%h" rpl)
8690 (replace-match (url-hexify-string (or tag "")) t t rpl))
8691 (t (concat rpl tag)))))
8692 link))
8694 ;;; Storing and inserting links
8696 (defvar org-insert-link-history nil
8697 "Minibuffer history for links inserted with `org-insert-link'.")
8699 (defvar org-stored-links nil
8700 "Contains the links stored with `org-store-link'.")
8702 (defvar org-store-link-plist nil
8703 "Plist with info about the most recently link created with `org-store-link'.")
8705 (defvar org-link-protocols nil
8706 "Link protocols added to Org-mode using `org-add-link-type'.")
8708 (defvar org-store-link-functions nil
8709 "List of functions that are called to create and store a link.
8710 Each function will be called in turn until one returns a non-nil
8711 value. Each function should check if it is responsible for creating
8712 this link (for example by looking at the major mode).
8713 If not, it must exit and return nil.
8714 If yes, it should return a non-nil value after a calling
8715 `org-store-link-props' with a list of properties and values.
8716 Special properties are:
8718 :type The link prefix, like \"http\". This must be given.
8719 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8720 This is obligatory as well.
8721 :description Optional default description for the second pair
8722 of brackets in an Org-mode link. The user can still change
8723 this when inserting this link into an Org-mode buffer.
8725 In addition to these, any additional properties can be specified
8726 and then used in capture templates.")
8728 (defun org-add-link-type (type &optional follow export)
8729 "Add TYPE to the list of `org-link-types'.
8730 Re-compute all regular expressions depending on `org-link-types'
8732 FOLLOW and EXPORT are two functions.
8734 FOLLOW should take the link path as the single argument and do whatever
8735 is necessary to follow the link, for example find a file or display
8736 a mail message.
8738 EXPORT should format the link path for export to one of the export formats.
8739 It should be a function accepting three arguments:
8741 path the path of the link, the text after the prefix (like \"http:\")
8742 desc the description of the link, if any, or a description added by
8743 org-export-normalize-links if there is none
8744 format the export format, a symbol like `html' or `latex' or `ascii'..
8746 The function may use the FORMAT information to return different values
8747 depending on the format. The return value will be put literally into
8748 the exported file. If the return value is nil, this means Org should
8749 do what it normally does with links which do not have EXPORT defined.
8751 Org-mode has a built-in default for exporting links. If you are happy with
8752 this default, there is no need to define an export function for the link
8753 type. For a simple example of an export function, see `org-bbdb.el'."
8754 (add-to-list 'org-link-types type t)
8755 (org-make-link-regexps)
8756 (if (assoc type org-link-protocols)
8757 (setcdr (assoc type org-link-protocols) (list follow export))
8758 (push (list type follow export) org-link-protocols)))
8760 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8761 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8763 ;;;###autoload
8764 (defun org-store-link (arg)
8765 "\\<org-mode-map>Store an org-link to the current location.
8766 This link is added to `org-stored-links' and can later be inserted
8767 into an org-buffer with \\[org-insert-link].
8769 For some link types, a prefix arg is interpreted:
8770 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8771 For file links, arg negates `org-context-in-file-links'."
8772 (interactive "P")
8773 (org-load-modules-maybe)
8774 (setq org-store-link-plist nil) ; reset
8775 (org-with-limited-levels
8776 (let (link cpltxt desc description search txt custom-id agenda-link)
8777 (cond
8779 ((run-hook-with-args-until-success 'org-store-link-functions)
8780 (setq link (plist-get org-store-link-plist :link)
8781 desc (or (plist-get org-store-link-plist :description) link)))
8783 ((org-src-edit-buffer-p)
8784 (let (label gc)
8785 (while (or (not label)
8786 (save-excursion
8787 (save-restriction
8788 (widen)
8789 (goto-char (point-min))
8790 (re-search-forward
8791 (regexp-quote (format org-coderef-label-format label))
8792 nil t))))
8793 (when label (message "Label exists already") (sit-for 2))
8794 (setq label (read-string "Code line label: " label)))
8795 (end-of-line 1)
8796 (setq link (format org-coderef-label-format label))
8797 (setq gc (- 79 (length link)))
8798 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8799 (insert link)
8800 (setq link (concat "(" label ")") desc nil)))
8802 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8803 ;; We are in the agenda, link to referenced location
8804 (let ((m (or (get-text-property (point) 'org-hd-marker)
8805 (get-text-property (point) 'org-marker))))
8806 (when m
8807 (org-with-point-at m
8808 (setq agenda-link
8809 (if (org-called-interactively-p 'any)
8810 (call-interactively 'org-store-link)
8811 (org-store-link nil)))))))
8813 ((eq major-mode 'calendar-mode)
8814 (let ((cd (calendar-cursor-to-date)))
8815 (setq link
8816 (format-time-string
8817 (car org-time-stamp-formats)
8818 (apply 'encode-time
8819 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8820 nil nil nil))))
8821 (org-store-link-props :type "calendar" :date cd)))
8823 ((eq major-mode 'help-mode)
8824 (setq link (concat "help:" (save-excursion
8825 (goto-char (point-min))
8826 (looking-at "^[^ ]+")
8827 (match-string 0))))
8828 (org-store-link-props :type "help"))
8830 ((eq major-mode 'w3-mode)
8831 (setq cpltxt (if (and (buffer-name)
8832 (not (string-match "Untitled" (buffer-name))))
8833 (buffer-name)
8834 (url-view-url t))
8835 link (url-view-url t))
8836 (org-store-link-props :type "w3" :url (url-view-url t)))
8838 ((eq major-mode 'w3m-mode)
8839 (setq cpltxt (or w3m-current-title w3m-current-url)
8840 link w3m-current-url)
8841 (org-store-link-props :type "w3m" :url (url-view-url t)))
8843 ((setq search (run-hook-with-args-until-success
8844 'org-create-file-search-functions))
8845 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8846 "::" search))
8847 (setq cpltxt (or description link)))
8849 ((eq major-mode 'image-mode)
8850 (setq cpltxt (concat "file:"
8851 (abbreviate-file-name buffer-file-name))
8852 link cpltxt)
8853 (org-store-link-props :type "image" :file buffer-file-name))
8855 ((eq major-mode 'dired-mode)
8856 ;; link to the file in the current line
8857 (let ((file (dired-get-filename nil t)))
8858 (setq file (if file
8859 (abbreviate-file-name
8860 (expand-file-name (dired-get-filename nil t)))
8861 ;; otherwise, no file so use current directory.
8862 default-directory))
8863 (setq cpltxt (concat "file:" file)
8864 link cpltxt)))
8866 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8867 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8868 (cond
8869 ((org-in-regexp "<<\\(.*?\\)>>")
8870 (setq cpltxt
8871 (concat "file:"
8872 (abbreviate-file-name
8873 (buffer-file-name (buffer-base-buffer)))
8874 "::" (match-string 1))
8875 link cpltxt))
8876 ((and (featurep 'org-id)
8877 (or (eq org-id-link-to-org-use-id t)
8878 (and (org-called-interactively-p 'any)
8879 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8880 (and (eq org-id-link-to-org-use-id
8881 'create-if-interactive-and-no-custom-id)
8882 (not custom-id))))
8883 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8884 ;; We can make a link using the ID.
8885 (setq link (condition-case nil
8886 (prog1 (org-id-store-link)
8887 (setq desc (plist-get org-store-link-plist :description)))
8888 (error
8889 ;; probably before first headline, link to file only
8890 (concat "file:"
8891 (abbreviate-file-name
8892 (buffer-file-name (buffer-base-buffer))))))))
8894 ;; Just link to current headline
8895 (setq cpltxt (concat "file:"
8896 (abbreviate-file-name
8897 (buffer-file-name (buffer-base-buffer)))))
8898 ;; Add a context search string
8899 (when (org-xor org-context-in-file-links arg)
8900 (setq txt (cond
8901 ((org-at-heading-p) nil)
8902 ((org-region-active-p)
8903 (buffer-substring (region-beginning) (region-end)))))
8904 (when (or (null txt) (string-match "\\S-" txt))
8905 (setq cpltxt
8906 (concat cpltxt "::"
8907 (condition-case nil
8908 (org-make-org-heading-search-string txt)
8909 (error "")))
8910 desc (or (nth 4 (ignore-errors
8911 (org-heading-components))) "NONE"))))
8912 (if (string-match "::\\'" cpltxt)
8913 (setq cpltxt (substring cpltxt 0 -2)))
8914 (setq link cpltxt))))
8916 ((buffer-file-name (buffer-base-buffer))
8917 ;; Just link to this file here.
8918 (setq cpltxt (concat "file:"
8919 (abbreviate-file-name
8920 (buffer-file-name (buffer-base-buffer)))))
8921 ;; Add a context string
8922 (when (org-xor org-context-in-file-links arg)
8923 (setq txt (if (org-region-active-p)
8924 (buffer-substring (region-beginning) (region-end))
8925 (buffer-substring (point-at-bol) (point-at-eol))))
8926 ;; Only use search option if there is some text.
8927 (when (string-match "\\S-" txt)
8928 (setq cpltxt
8929 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8930 desc "NONE")))
8931 (setq link cpltxt))
8933 ((org-called-interactively-p 'interactive)
8934 (error "Cannot link to a buffer which is not visiting a file"))
8936 (t (setq link nil)))
8938 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8939 (setq link (or link cpltxt)
8940 desc (or desc cpltxt))
8941 (if (equal desc "NONE") (setq desc nil))
8943 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8944 (progn
8945 (setq org-stored-links
8946 (cons (list link desc) org-stored-links))
8947 (message "Stored: %s" (or desc link))
8948 (when custom-id
8949 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8950 "::#" custom-id))
8951 (setq org-stored-links
8952 (cons (list link desc) org-stored-links))))
8953 (or agenda-link (and link (org-make-link-string link desc)))))))
8955 (defun org-store-link-props (&rest plist)
8956 "Store link properties, extract names and addresses."
8957 (let (x adr)
8958 (when (setq x (plist-get plist :from))
8959 (setq adr (mail-extract-address-components x))
8960 (setq plist (plist-put plist :fromname (car adr)))
8961 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8962 (when (setq x (plist-get plist :to))
8963 (setq adr (mail-extract-address-components x))
8964 (setq plist (plist-put plist :toname (car adr)))
8965 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8966 (let ((from (plist-get plist :from))
8967 (to (plist-get plist :to)))
8968 (when (and from to org-from-is-user-regexp)
8969 (setq plist
8970 (plist-put plist :fromto
8971 (if (string-match org-from-is-user-regexp from)
8972 (concat "to %t")
8973 (concat "from %f"))))))
8974 (setq org-store-link-plist plist))
8976 (defun org-add-link-props (&rest plist)
8977 "Add these properties to the link property list."
8978 (let (key value)
8979 (while plist
8980 (setq key (pop plist) value (pop plist))
8981 (setq org-store-link-plist
8982 (plist-put org-store-link-plist key value)))))
8984 (defun org-email-link-description (&optional fmt)
8985 "Return the description part of an email link.
8986 This takes information from `org-store-link-plist' and formats it
8987 according to FMT (default from `org-email-link-description-format')."
8988 (setq fmt (or fmt org-email-link-description-format))
8989 (let* ((p org-store-link-plist)
8990 (to (plist-get p :toaddress))
8991 (from (plist-get p :fromaddress))
8992 (table
8993 (list
8994 (cons "%c" (plist-get p :fromto))
8995 (cons "%F" (plist-get p :from))
8996 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8997 (cons "%T" (plist-get p :to))
8998 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8999 (cons "%s" (plist-get p :subject))
9000 (cons "%d" (plist-get p :date))
9001 (cons "%m" (plist-get p :message-id)))))
9002 (when (string-match "%c" fmt)
9003 ;; Check if the user wrote this message
9004 (if (and org-from-is-user-regexp from to
9005 (save-match-data (string-match org-from-is-user-regexp from)))
9006 (setq fmt (replace-match "to %t" t t fmt))
9007 (setq fmt (replace-match "from %f" t t fmt))))
9008 (org-replace-escapes fmt table)))
9010 (defun org-make-org-heading-search-string (&optional string heading)
9011 "Make search string for STRING or current headline."
9012 (interactive)
9013 (let ((s (or string (org-get-heading)))
9014 (lines org-context-in-file-links))
9015 (unless (and string (not heading))
9016 ;; We are using a headline, clean up garbage in there.
9017 (if (string-match org-todo-regexp s)
9018 (setq s (replace-match "" t t s)))
9019 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9020 (setq s (replace-match "" t t s)))
9021 (setq s (org-trim s))
9022 (if (string-match (concat "^\\(" org-quote-string "\\|"
9023 org-comment-string "\\)") s)
9024 (setq s (replace-match "" t t s)))
9025 (while (string-match org-ts-regexp s)
9026 (setq s (replace-match "" t t s))))
9027 (or string (setq s (concat "*" s))) ; Add * for headlines
9028 (when (and string (integerp lines) (> lines 0))
9029 (let ((slines (org-split-string s "\n")))
9030 (when (< lines (length slines))
9031 (setq s (mapconcat
9032 'identity
9033 (reverse (nthcdr (- (length slines) lines)
9034 (reverse slines))) "\n")))))
9035 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9037 (defun org-make-link-string (link &optional description)
9038 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9039 (unless (string-match "\\S-" link)
9040 (error "Empty link"))
9041 (when (and description
9042 (stringp description)
9043 (not (string-match "\\S-" description)))
9044 (setq description nil))
9045 (when (stringp description)
9046 ;; Remove brackets from the description, they are fatal.
9047 (while (string-match "\\[" description)
9048 (setq description (replace-match "{" t t description)))
9049 (while (string-match "\\]" description)
9050 (setq description (replace-match "}" t t description))))
9051 (when (equal link description)
9052 ;; No description needed, it is identical
9053 (setq description nil))
9054 (when (and (not description)
9055 (not (string-match (org-image-file-name-regexp) link))
9056 (not (equal link (org-link-escape link))))
9057 (setq description (org-extract-attributes link)))
9058 (setq link
9059 (cond ((string-match (org-image-file-name-regexp) link) link)
9060 ((string-match org-link-types-re link)
9061 (concat (match-string 1 link)
9062 (org-link-escape (substring link (match-end 1)))))
9063 (t (org-link-escape link))))
9064 (concat "[[" link "]"
9065 (if description (concat "[" description "]") "")
9066 "]"))
9068 (defconst org-link-escape-chars
9069 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9070 "List of characters that should be escaped in link.
9071 This is the list that is used for internal purposes.")
9073 (defconst org-link-escape-chars-browser
9074 '(?\ )
9075 "List of escapes for characters that are problematic in links.
9076 This is the list that is used before handing over to the browser.")
9078 (defun org-link-escape (text &optional table merge)
9079 "Return percent escaped representation of TEXT.
9080 TEXT is a string with the text to escape.
9081 Optional argument TABLE is a list with characters that should be
9082 escaped. When nil, `org-link-escape-chars' is used.
9083 If optional argument MERGE is set, merge TABLE into
9084 `org-link-escape-chars'."
9085 (cond
9086 ((and table merge)
9087 (mapc (lambda (defchr)
9088 (unless (member defchr table)
9089 (setq table (cons defchr table)))) org-link-escape-chars))
9090 ((null table)
9091 (setq table org-link-escape-chars)))
9092 (mapconcat
9093 (lambda (char)
9094 (if (or (member char table)
9095 (and (or (< char 32) (= char 37) (> char 126))
9096 org-url-hexify-p))
9097 (mapconcat (lambda (sequence-element)
9098 (format "%%%.2X" sequence-element))
9099 (or (encode-coding-char char 'utf-8)
9100 (error "Unable to percent escape character: %s"
9101 (char-to-string char))) "")
9102 (char-to-string char))) text ""))
9104 (defun org-link-unescape (str)
9105 "Unhex hexified Unicode strings as returned from the JavaScript function
9106 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9107 (unless (and (null str) (string= "" str))
9108 (let ((pos 0) (case-fold-search t) unhexed)
9109 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9110 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9111 (setq str (replace-match unhexed t t str))
9112 (setq pos (+ pos (length unhexed))))))
9113 str)
9115 (defun org-link-unescape-compound (hex)
9116 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9117 Note: this function also decodes single byte encodings like
9118 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9119 (save-match-data
9120 (let* ((bytes (cdr (split-string hex "%")))
9121 (ret "")
9122 (eat 0)
9123 (sum 0))
9124 (while bytes
9125 (let* ((val (string-to-number (pop bytes) 16))
9126 (shift-xor
9127 (if (= 0 eat)
9128 (cond
9129 ((>= val 252) (cons 6 252))
9130 ((>= val 248) (cons 5 248))
9131 ((>= val 240) (cons 4 240))
9132 ((>= val 224) (cons 3 224))
9133 ((>= val 192) (cons 2 192))
9134 (t (cons 0 0)))
9135 (cons 6 128))))
9136 (if (>= val 192) (setq eat (car shift-xor)))
9137 (setq val (logxor val (cdr shift-xor)))
9138 (setq sum (+ (lsh sum (car shift-xor)) val))
9139 (if (> eat 0) (setq eat (- eat 1)))
9140 (cond
9141 ((= 0 eat) ;multi byte
9142 (setq ret (concat ret (org-char-to-string sum)))
9143 (setq sum 0))
9144 ((not bytes) ; single byte(s)
9145 (setq ret (org-link-unescape-single-byte-sequence hex))))
9146 )) ;; end (while bytes
9147 ret )))
9149 (defun org-link-unescape-single-byte-sequence (hex)
9150 "Unhexify hex-encoded single byte character sequences."
9151 (mapconcat (lambda (byte)
9152 (char-to-string (string-to-number byte 16)))
9153 (cdr (split-string hex "%")) ""))
9155 (defun org-xor (a b)
9156 "Exclusive or."
9157 (if a (not b) b))
9159 (defun org-fixup-message-id-for-http (s)
9160 "Replace special characters in a message id, so it can be used in an http query."
9161 (when (string-match "%" s)
9162 (setq s (mapconcat (lambda (c)
9163 (if (eq c ?%)
9164 "%25"
9165 (char-to-string c)))
9166 s "")))
9167 (while (string-match "<" s)
9168 (setq s (replace-match "%3C" t t s)))
9169 (while (string-match ">" s)
9170 (setq s (replace-match "%3E" t t s)))
9171 (while (string-match "@" s)
9172 (setq s (replace-match "%40" t t s)))
9175 (defun org-link-prettify (link)
9176 "Return a human-readable representation of LINK.
9177 The car of LINK must be a raw link the cdr of LINK must be either
9178 a link description or nil."
9179 (let ((desc (or (cadr link) "<no description>")))
9180 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9181 "<" (car link) ">")))
9183 ;;;###autoload
9184 (defun org-insert-link-global ()
9185 "Insert a link like Org-mode does.
9186 This command can be called in any mode to insert a link in Org-mode syntax."
9187 (interactive)
9188 (org-load-modules-maybe)
9189 (org-run-like-in-org-mode 'org-insert-link))
9191 (defun org-insert-all-links (&optional keep)
9192 "Insert all links in `org-stored-links'."
9193 (interactive "P")
9194 (let ((links (copy-sequence org-stored-links)) l)
9195 (while (setq l (if keep (pop links) (pop org-stored-links)))
9196 (insert "- ")
9197 (org-insert-link nil (car l) (cadr l))
9198 (insert "\n"))))
9200 (defun org-link-fontify-links-to-this-file ()
9201 "Fontify links to the current file in `org-stored-links'."
9202 (let ((f (buffer-file-name)) a b)
9203 (setq a (mapcar (lambda(l)
9204 (let ((ll (car l)))
9205 (when (and (string-match "^file:\\(.+\\)::" ll)
9206 (equal f (expand-file-name (match-string 1 ll))))
9207 ll)))
9208 org-stored-links))
9209 (when (featurep 'org-id)
9210 (setq b (mapcar (lambda(l)
9211 (let ((ll (car l)))
9212 (when (and (string-match "^id:\\(.+\\)$" ll)
9213 (equal f (expand-file-name
9214 (or (org-id-find-id-file
9215 (match-string 1 ll)) ""))))
9216 ll)))
9217 org-stored-links)))
9218 (mapcar (lambda(l)
9219 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9220 (delq nil (append a b)))))
9222 (defvar org-link-links-in-this-file nil)
9223 (defun org-insert-link (&optional complete-file link-location default-description)
9224 "Insert a link. At the prompt, enter the link.
9226 Completion can be used to insert any of the link protocol prefixes like
9227 http or ftp in use.
9229 The history can be used to select a link previously stored with
9230 `org-store-link'. When the empty string is entered (i.e. if you just
9231 press RET at the prompt), the link defaults to the most recently
9232 stored link. As SPC triggers completion in the minibuffer, you need to
9233 use M-SPC or C-q SPC to force the insertion of a space character.
9235 You will also be prompted for a description, and if one is given, it will
9236 be displayed in the buffer instead of the link.
9238 If there is already a link at point, this command will allow you to edit link
9239 and description parts.
9241 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9242 be selected using completion. The path to the file will be relative to the
9243 current directory if the file is in the current directory or a subdirectory.
9244 Otherwise, the link will be the absolute path as completed in the minibuffer
9245 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9246 option `org-link-file-path-type'.
9248 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9249 the current directory or below.
9251 With three \\[universal-argument] prefixes, negate the meaning of
9252 `org-keep-stored-link-after-insertion'.
9254 If `org-make-link-description-function' is non-nil, this function will be
9255 called with the link target, and the result will be the default
9256 link description.
9258 If the LINK-LOCATION parameter is non-nil, this value will be
9259 used as the link location instead of reading one interactively.
9261 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9262 be used as the default description."
9263 (interactive "P")
9264 (let* ((wcf (current-window-configuration))
9265 (region (if (org-region-active-p)
9266 (buffer-substring (region-beginning) (region-end))))
9267 (remove (and region (list (region-beginning) (region-end))))
9268 (desc region)
9269 tmphist ; byte-compile incorrectly complains about this
9270 (link link-location)
9271 (abbrevs org-link-abbrev-alist-local)
9272 entry file all-prefixes auto-desc)
9273 (cond
9274 (link-location) ; specified by arg, just use it.
9275 ((org-in-regexp org-bracket-link-regexp 1)
9276 ;; We do have a link at point, and we are going to edit it.
9277 (setq remove (list (match-beginning 0) (match-end 0)))
9278 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9279 (setq link (read-string "Link: "
9280 (org-link-unescape
9281 (org-match-string-no-properties 1)))))
9282 ((or (org-in-regexp org-angle-link-re)
9283 (org-in-regexp org-plain-link-re))
9284 ;; Convert to bracket link
9285 (setq remove (list (match-beginning 0) (match-end 0))
9286 link (read-string "Link: "
9287 (org-remove-angle-brackets (match-string 0)))))
9288 ((member complete-file '((4) (16)))
9289 ;; Completing read for file names.
9290 (setq link (org-file-complete-link complete-file)))
9292 ;; Read link, with completion for stored links.
9293 (org-link-fontify-links-to-this-file)
9294 (org-switch-to-buffer-other-window "*Org Links*")
9295 (with-current-buffer "*Org Links*"
9296 (erase-buffer)
9297 (insert "Insert a link.
9298 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9299 (when org-stored-links
9300 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9301 (insert (mapconcat 'org-link-prettify
9302 (reverse org-stored-links) "\n")))
9303 (goto-char (point-min)))
9304 (let ((cw (selected-window)))
9305 (select-window (get-buffer-window "*Org Links*" 'visible))
9306 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9307 (unless (pos-visible-in-window-p (point-max))
9308 (org-fit-window-to-buffer))
9309 (and (window-live-p cw) (select-window cw)))
9310 ;; Fake a link history, containing the stored links.
9311 (setq tmphist (append (mapcar 'car org-stored-links)
9312 org-insert-link-history))
9313 (setq all-prefixes (append (mapcar 'car abbrevs)
9314 (mapcar 'car org-link-abbrev-alist)
9315 org-link-types))
9316 (unwind-protect
9317 (progn
9318 (setq link
9319 (let ((org-completion-use-ido nil)
9320 (org-completion-use-iswitchb nil))
9321 (org-completing-read
9322 "Link: "
9323 (append
9324 (mapcar (lambda (x) (list (concat x ":")))
9325 all-prefixes)
9326 (mapcar 'car org-stored-links)
9327 (mapcar 'cadr org-stored-links))
9328 nil nil nil
9329 'tmphist
9330 (caar org-stored-links))))
9331 (if (not (string-match "\\S-" link))
9332 (error "No link selected"))
9333 (mapc (lambda(l)
9334 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9335 org-stored-links)
9336 (if (or (member link all-prefixes)
9337 (and (equal ":" (substring link -1))
9338 (member (substring link 0 -1) all-prefixes)
9339 (setq link (substring link 0 -1))))
9340 (setq link (org-link-try-special-completion link))))
9341 (set-window-configuration wcf)
9342 (kill-buffer "*Org Links*"))
9343 (setq entry (assoc link org-stored-links))
9344 (or entry (push link org-insert-link-history))
9345 (setq desc (or desc (nth 1 entry)))))
9347 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9348 (not org-keep-stored-link-after-insertion))
9349 (setq org-stored-links (delq (assoc link org-stored-links)
9350 org-stored-links)))
9352 (if (string-match org-plain-link-re link)
9353 ;; URL-like link, normalize the use of angular brackets.
9354 (setq link (org-remove-angle-brackets link)))
9356 ;; Check if we are linking to the current file with a search
9357 ;; option If yes, simplify the link by using only the search
9358 ;; option.
9359 (when (and buffer-file-name
9360 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9361 (let* ((path (match-string 1 link))
9362 (case-fold-search nil)
9363 (search (match-string 2 link)))
9364 (save-match-data
9365 (if (equal (file-truename buffer-file-name) (file-truename path))
9366 ;; We are linking to this same file, with a search option
9367 (setq link search)))))
9369 ;; Check if we can/should use a relative path. If yes, simplify the link
9370 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9371 (let* ((type (match-string 1 link))
9372 (path (match-string 2 link))
9373 (origpath path)
9374 (case-fold-search nil))
9375 (cond
9376 ((or (eq org-link-file-path-type 'absolute)
9377 (equal complete-file '(16)))
9378 (setq path (abbreviate-file-name (expand-file-name path))))
9379 ((eq org-link-file-path-type 'noabbrev)
9380 (setq path (expand-file-name path)))
9381 ((eq org-link-file-path-type 'relative)
9382 (setq path (file-relative-name path)))
9384 (save-match-data
9385 (if (string-match (concat "^" (regexp-quote
9386 (expand-file-name
9387 (file-name-as-directory
9388 default-directory))))
9389 (expand-file-name path))
9390 ;; We are linking a file with relative path name.
9391 (setq path (substring (expand-file-name path)
9392 (match-end 0)))
9393 (setq path (abbreviate-file-name (expand-file-name path)))))))
9394 (setq link (concat type path))
9395 (if (equal desc origpath)
9396 (setq desc path))))
9398 (if org-make-link-description-function
9399 (setq desc
9400 (or (condition-case nil
9401 (funcall org-make-link-description-function link desc)
9402 (error (progn (message "Can't get link description from `%s'"
9403 (symbol-name org-make-link-description-function))
9404 (sit-for 2) nil)))
9405 (read-string "Description: " default-description)))
9406 (if default-description (setq desc default-description)
9407 (setq desc (or (and auto-desc desc)
9408 (read-string "Description: " desc)))))
9410 (unless (string-match "\\S-" desc) (setq desc nil))
9411 (if remove (apply 'delete-region remove))
9412 (insert (org-make-link-string link desc))))
9414 (defun org-link-try-special-completion (type)
9415 "If there is completion support for link type TYPE, offer it."
9416 (let ((fun (intern (concat "org-" type "-complete-link"))))
9417 (if (functionp fun)
9418 (funcall fun)
9419 (read-string "Link (no completion support): " (concat type ":")))))
9421 (defun org-file-complete-link (&optional arg)
9422 "Create a file link using completion."
9423 (let (file link)
9424 (setq file (read-file-name "File: "))
9425 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9426 (pwd1 (file-name-as-directory (abbreviate-file-name
9427 (expand-file-name ".")))))
9428 (cond
9429 ((equal arg '(16))
9430 (setq link (concat
9431 "file:"
9432 (abbreviate-file-name (expand-file-name file)))))
9433 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9434 (setq link (concat "file:" (match-string 1 file))))
9435 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9436 (expand-file-name file))
9437 (setq link (concat
9438 "file:" (match-string 1 (expand-file-name file)))))
9439 (t (setq link (concat "file:" file)))))
9440 link))
9442 (defun org-completing-read (&rest args)
9443 "Completing-read with SPACE being a normal character."
9444 (let ((enable-recursive-minibuffers t)
9445 (minibuffer-local-completion-map
9446 (copy-keymap minibuffer-local-completion-map)))
9447 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9448 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9449 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9450 (apply 'org-icompleting-read args)))
9452 (defun org-completing-read-no-i (&rest args)
9453 (let (org-completion-use-ido org-completion-use-iswitchb)
9454 (apply 'org-completing-read args)))
9456 (defun org-iswitchb-completing-read (prompt choices &rest args)
9457 "Use iswitch as a completing-read replacement to choose from choices.
9458 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9459 from."
9460 (let* ((iswitchb-use-virtual-buffers nil)
9461 (iswitchb-make-buflist-hook
9462 (lambda ()
9463 (setq iswitchb-temp-buflist choices))))
9464 (iswitchb-read-buffer prompt)))
9466 (defun org-icompleting-read (&rest args)
9467 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9468 (org-without-partial-completion
9469 (if (and org-completion-use-ido
9470 (fboundp 'ido-completing-read)
9471 (boundp 'ido-mode) ido-mode
9472 (listp (second args)))
9473 (let ((ido-enter-matching-directory nil))
9474 (apply 'ido-completing-read (concat (car args))
9475 (if (consp (car (nth 1 args)))
9476 (mapcar 'car (nth 1 args))
9477 (nth 1 args))
9478 (cddr args)))
9479 (if (and org-completion-use-iswitchb
9480 (boundp 'iswitchb-mode) iswitchb-mode
9481 (listp (second args)))
9482 (apply 'org-iswitchb-completing-read (concat (car args))
9483 (if (consp (car (nth 1 args)))
9484 (mapcar 'car (nth 1 args))
9485 (nth 1 args))
9486 (cddr args))
9487 (apply 'completing-read args)))))
9489 (defun org-extract-attributes (s)
9490 "Extract the attributes cookie from a string and set as text property."
9491 (let (a attr (start 0) key value)
9492 (save-match-data
9493 (when (string-match "{{\\([^}]+\\)}}$" s)
9494 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9495 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9496 (setq key (match-string 1 a) value (match-string 2 a)
9497 start (match-end 0)
9498 attr (plist-put attr (intern key) value))))
9499 (org-add-props s nil 'org-attr attr))
9502 (defun org-extract-attributes-from-string (tag)
9503 (let (key value attr)
9504 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9505 (setq key (match-string 1 tag) value (match-string 2 tag)
9506 tag (replace-match "" t t tag)
9507 attr (plist-put attr (intern key) value)))
9508 (cons tag attr)))
9510 (defun org-attributes-to-string (plist)
9511 "Format a property list into an HTML attribute list."
9512 (let ((s "") key value)
9513 (while plist
9514 (setq key (pop plist) value (pop plist))
9515 (and value
9516 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9519 ;;; Opening/following a link
9521 (defvar org-link-search-failed nil)
9523 (defvar org-open-link-functions nil
9524 "Hook for functions finding a plain text link.
9525 These functions must take a single argument, the link content.
9526 They will be called for links that look like [[link text][description]]
9527 when LINK TEXT does not have a protocol like \"http:\" and does not look
9528 like a filename (e.g. \"./blue.png\").
9530 These functions will be called *before* Org attempts to resolve the
9531 link by doing text searches in the current buffer - so if you want a
9532 link \"[[target]]\" to still find \"<<target>>\", your function should
9533 handle this as a special case.
9535 When the function does handle the link, it must return a non-nil value.
9536 If it decides that it is not responsible for this link, it must return
9537 nil to indicate that that Org-mode can continue with other options
9538 like exact and fuzzy text search.")
9540 (defun org-next-link ()
9541 "Move forward to the next link.
9542 If the link is in hidden text, expose it."
9543 (interactive)
9544 (when (and org-link-search-failed (eq this-command last-command))
9545 (goto-char (point-min))
9546 (message "Link search wrapped back to beginning of buffer"))
9547 (setq org-link-search-failed nil)
9548 (let* ((pos (point))
9549 (ct (org-context))
9550 (a (assoc :link ct)))
9551 (if a (goto-char (nth 2 a)))
9552 (if (re-search-forward org-any-link-re nil t)
9553 (progn
9554 (goto-char (match-beginning 0))
9555 (if (outline-invisible-p) (org-show-context)))
9556 (goto-char pos)
9557 (setq org-link-search-failed t)
9558 (error "No further link found"))))
9560 (defun org-previous-link ()
9561 "Move backward to the previous link.
9562 If the link is in hidden text, expose it."
9563 (interactive)
9564 (when (and org-link-search-failed (eq this-command last-command))
9565 (goto-char (point-max))
9566 (message "Link search wrapped back to end of buffer"))
9567 (setq org-link-search-failed nil)
9568 (let* ((pos (point))
9569 (ct (org-context))
9570 (a (assoc :link ct)))
9571 (if a (goto-char (nth 1 a)))
9572 (if (re-search-backward org-any-link-re nil t)
9573 (progn
9574 (goto-char (match-beginning 0))
9575 (if (outline-invisible-p) (org-show-context)))
9576 (goto-char pos)
9577 (setq org-link-search-failed t)
9578 (error "No further link found"))))
9580 (defun org-translate-link (s)
9581 "Translate a link string if a translation function has been defined."
9582 (if (and org-link-translation-function
9583 (fboundp org-link-translation-function)
9584 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9585 (progn
9586 (setq s (funcall org-link-translation-function
9587 (match-string 1 s) (match-string 2 s)))
9588 (concat (car s) ":" (cdr s)))
9591 (defun org-translate-link-from-planner (type path)
9592 "Translate a link from Emacs Planner syntax so that Org can follow it.
9593 This is still an experimental function, your mileage may vary."
9594 (cond
9595 ((member type '("http" "https" "news" "ftp"))
9596 ;; standard Internet links are the same.
9597 nil)
9598 ((and (equal type "irc") (string-match "^//" path))
9599 ;; Planner has two / at the beginning of an irc link, we have 1.
9600 ;; We should have zero, actually....
9601 (setq path (substring path 1)))
9602 ((and (equal type "lisp") (string-match "^/" path))
9603 ;; Planner has a slash, we do not.
9604 (setq type "elisp" path (substring path 1)))
9605 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9606 ;; A typical message link. Planner has the id after the final slash,
9607 ;; we separate it with a hash mark
9608 (setq path (concat (match-string 1 path) "#"
9609 (org-remove-angle-brackets (match-string 2 path)))))
9611 (cons type path))
9613 (defun org-find-file-at-mouse (ev)
9614 "Open file link or URL at mouse."
9615 (interactive "e")
9616 (mouse-set-point ev)
9617 (org-open-at-point 'in-emacs))
9619 (defun org-open-at-mouse (ev)
9620 "Open file link or URL at mouse.
9621 See the docstring of `org-open-file' for details."
9622 (interactive "e")
9623 (mouse-set-point ev)
9624 (if (eq major-mode 'org-agenda-mode)
9625 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9626 (org-open-at-point))
9628 (defvar org-window-config-before-follow-link nil
9629 "The window configuration before following a link.
9630 This is saved in case the need arises to restore it.")
9632 (defvar org-open-link-marker (make-marker)
9633 "Marker pointing to the location where `org-open-at-point; was called.")
9635 ;;;###autoload
9636 (defun org-open-at-point-global ()
9637 "Follow a link like Org-mode does.
9638 This command can be called in any mode to follow a link that has
9639 Org-mode syntax."
9640 (interactive)
9641 (org-run-like-in-org-mode 'org-open-at-point))
9643 ;;;###autoload
9644 (defun org-open-link-from-string (s &optional arg reference-buffer)
9645 "Open a link in the string S, as if it was in Org-mode."
9646 (interactive "sLink: \nP")
9647 (let ((reference-buffer (or reference-buffer (current-buffer))))
9648 (with-temp-buffer
9649 (let ((org-inhibit-startup (not reference-buffer)))
9650 (org-mode)
9651 (insert s)
9652 (goto-char (point-min))
9653 (when reference-buffer
9654 (setq org-link-abbrev-alist-local
9655 (with-current-buffer reference-buffer
9656 org-link-abbrev-alist-local)))
9657 (org-open-at-point arg reference-buffer)))))
9659 (defvar org-open-at-point-functions nil
9660 "Hook that is run when following a link at point.
9662 Functions in this hook must return t if they identify and follow
9663 a link at point. If they don't find anything interesting at point,
9664 they must return nil.")
9666 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9667 (defun org-open-at-point (&optional arg reference-buffer)
9668 "Open link at or after point.
9669 If there is no link at point, this function will search forward up to
9670 the end of the current line.
9671 Normally, files will be opened by an appropriate application. If the
9672 optional prefix argument ARG is non-nil, Emacs will visit the file.
9673 With a double prefix argument, try to open outside of Emacs, in the
9674 application the system uses for this file type."
9675 (interactive "P")
9676 ;; if in a code block, then open the block's results
9677 (unless (call-interactively #'org-babel-open-src-block-result)
9678 (org-load-modules-maybe)
9679 (move-marker org-open-link-marker (point))
9680 (setq org-window-config-before-follow-link (current-window-configuration))
9681 (org-remove-occur-highlights nil nil t)
9682 (cond
9683 ((and (org-at-heading-p)
9684 (not (org-at-timestamp-p t))
9685 (not (org-in-regexp
9686 (concat org-plain-link-re "\\|"
9687 org-bracket-link-regexp "\\|"
9688 org-angle-link-re "\\|"
9689 "[ \t]:[^ \t\n]+:[ \t]*$")))
9690 (not (get-text-property (point) 'org-linked-text)))
9691 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9692 (lk0 (car lkall))
9693 (lk (if (stringp lk0) (list lk0) lk0))
9694 (lkend (cdr lkall)))
9695 (mapcar (lambda(l)
9696 (search-forward l nil lkend)
9697 (goto-char (match-beginning 0))
9698 (org-open-at-point))
9699 lk))
9700 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9701 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9702 ((and (org-at-timestamp-p t)
9703 (not (org-in-regexp org-bracket-link-regexp)))
9704 (org-follow-timestamp-link))
9705 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9706 (not (org-in-regexp org-any-link-re)))
9707 (org-footnote-action))
9709 (let (type path link line search (pos (point)))
9710 (catch 'match
9711 (save-excursion
9712 (skip-chars-forward "^]\n\r")
9713 (when (org-in-regexp org-bracket-link-regexp 1)
9714 (setq link (org-extract-attributes
9715 (org-link-unescape (org-match-string-no-properties 1))))
9716 (while (string-match " *\n *" link)
9717 (setq link (replace-match " " t t link)))
9718 (setq link (org-link-expand-abbrev link))
9719 (cond
9720 ((or (file-name-absolute-p link)
9721 (string-match "^\\.\\.?/" link))
9722 (setq type "file" path link))
9723 ((string-match org-link-re-with-space3 link)
9724 (setq type (match-string 1 link) path (match-string 2 link)))
9725 ((string-match "^help:+\\(.+\\)" link)
9726 (setq type "help" path (match-string 1 link)))
9727 (t (setq type "thisfile" path link)))
9728 (throw 'match t)))
9730 (when (get-text-property (point) 'org-linked-text)
9731 (setq type "thisfile"
9732 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9733 (1+ (point)) (point))
9734 path (buffer-substring
9735 (or (previous-single-property-change pos 'org-linked-text)
9736 (point-min))
9737 (or (next-single-property-change pos 'org-linked-text)
9738 (point-max))))
9739 (throw 'match t))
9741 (save-excursion
9742 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9743 (when (or (org-in-regexp org-angle-link-re)
9744 (and plinkpos (goto-char (car plinkpos))
9745 (save-match-data (not (looking-back "\\[\\[")))))
9746 (setq type (match-string 1)
9747 path (org-link-unescape (match-string 2)))
9748 (throw 'match t))))
9749 (save-excursion
9750 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9751 (setq type "tags"
9752 path (match-string 1))
9753 (while (string-match ":" path)
9754 (setq path (replace-match "+" t t path)))
9755 (throw 'match t)))
9756 (when (org-in-regexp "<\\([^><\n]+\\)>")
9757 (setq type "tree-match"
9758 path (match-string 1))
9759 (throw 'match t)))
9760 (unless path
9761 (user-error "No link found"))
9763 ;; switch back to reference buffer
9764 ;; needed when if called in a temporary buffer through
9765 ;; org-open-link-from-string
9766 (with-current-buffer (or reference-buffer (current-buffer))
9768 ;; Remove any trailing spaces in path
9769 (if (string-match " +\\'" path)
9770 (setq path (replace-match "" t t path)))
9771 (if (and org-link-translation-function
9772 (fboundp org-link-translation-function))
9773 ;; Check if we need to translate the link
9774 (let ((tmp (funcall org-link-translation-function type path)))
9775 (setq type (car tmp) path (cdr tmp))))
9777 (cond
9779 ((assoc type org-link-protocols)
9780 (funcall (nth 1 (assoc type org-link-protocols)) path))
9782 ((equal type "help")
9783 (let ((f-or-v (intern path)))
9784 (cond ((fboundp f-or-v)
9785 (describe-function f-or-v))
9786 ((boundp f-or-v)
9787 (describe-variable f-or-v))
9788 (t (error "Not a known function or variable")))))
9790 ((equal type "mailto")
9791 (let ((cmd (car org-link-mailto-program))
9792 (args (cdr org-link-mailto-program)) args1
9793 (address path) (subject "") a)
9794 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9795 (setq address (match-string 1 path)
9796 subject (org-link-escape (match-string 2 path))))
9797 (while args
9798 (cond
9799 ((not (stringp (car args))) (push (pop args) args1))
9800 (t (setq a (pop args))
9801 (if (string-match "%a" a)
9802 (setq a (replace-match address t t a)))
9803 (if (string-match "%s" a)
9804 (setq a (replace-match subject t t a)))
9805 (push a args1))))
9806 (apply cmd (nreverse args1))))
9808 ((member type '("http" "https" "ftp" "news"))
9809 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9810 (org-link-escape
9811 path org-link-escape-chars-browser)
9812 path))))
9814 ((string= type "doi")
9815 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9816 (org-link-escape
9817 path org-link-escape-chars-browser)
9818 path))))
9820 ((member type '("message"))
9821 (browse-url (concat type ":" path)))
9823 ((string= type "tags")
9824 (org-tags-view arg path))
9826 ((string= type "tree-match")
9827 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9829 ((string= type "file")
9830 (if (string-match "::\\([0-9]+\\)\\'" path)
9831 (setq line (string-to-number (match-string 1 path))
9832 path (substring path 0 (match-beginning 0)))
9833 (if (string-match "::\\(.+\\)\\'" path)
9834 (setq search (match-string 1 path)
9835 path (substring path 0 (match-beginning 0)))))
9836 (if (string-match "[*?{]" (file-name-nondirectory path))
9837 (dired path)
9838 (org-open-file path arg line search)))
9840 ((string= type "shell")
9841 (let ((buf (generate-new-buffer "*Org Shell Output"))
9842 (cmd path))
9843 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9844 (string-match org-confirm-shell-link-not-regexp cmd))
9845 (not org-confirm-shell-link-function)
9846 (funcall org-confirm-shell-link-function
9847 (format "Execute \"%s\" in shell? "
9848 (org-add-props cmd nil
9849 'face 'org-warning))))
9850 (progn
9851 (message "Executing %s" cmd)
9852 (shell-command cmd buf)
9853 (if (featurep 'midnight)
9854 (setq clean-buffer-list-kill-buffer-names
9855 (cons buf clean-buffer-list-kill-buffer-names))))
9856 (error "Abort"))))
9858 ((string= type "elisp")
9859 (let ((cmd path))
9860 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9861 (string-match org-confirm-elisp-link-not-regexp cmd))
9862 (not org-confirm-elisp-link-function)
9863 (funcall org-confirm-elisp-link-function
9864 (format "Execute \"%s\" as elisp? "
9865 (org-add-props cmd nil
9866 'face 'org-warning))))
9867 (message "%s => %s" cmd
9868 (if (equal (string-to-char cmd) ?\()
9869 (eval (read cmd))
9870 (call-interactively (read cmd))))
9871 (error "Abort"))))
9873 ((and (string= type "thisfile")
9874 (run-hook-with-args-until-success
9875 'org-open-link-functions path)))
9877 ((string= type "thisfile")
9878 (if arg
9879 (switch-to-buffer-other-window
9880 (org-get-buffer-for-internal-link (current-buffer)))
9881 (org-mark-ring-push))
9882 (let ((cmd `(org-link-search
9883 ,path
9884 ,(cond ((equal arg '(4)) ''occur)
9885 ((equal arg '(16)) ''org-occur))
9886 ,pos)))
9887 (condition-case nil (let ((org-link-search-inhibit-query t))
9888 (eval cmd))
9889 (error (progn (widen) (eval cmd))))))
9891 (t (browse-url-at-point)))))))
9892 (move-marker org-open-link-marker nil)
9893 (run-hook-with-args 'org-follow-link-hook)))
9895 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9896 "Offer links in the current entry and return the selected link.
9897 If there is only one link, return it.
9898 If NTH is an integer, return the NTH link found.
9899 If ZERO is a string, check also this string for a link, and if
9900 there is one, return it."
9901 (with-current-buffer buffer
9902 (save-excursion
9903 (save-restriction
9904 (widen)
9905 (goto-char marker)
9906 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9907 "\\(" org-angle-link-re "\\)\\|"
9908 "\\(" org-plain-link-re "\\)"))
9909 (cnt ?0)
9910 (in-emacs (if (integerp nth) nil nth))
9911 have-zero end links link c)
9912 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9913 (push (match-string 0 zero) links)
9914 (setq cnt (1- cnt) have-zero t))
9915 (save-excursion
9916 (org-back-to-heading t)
9917 (setq end (save-excursion (outline-next-heading) (point)))
9918 (while (re-search-forward re end t)
9919 (push (match-string 0) links))
9920 (setq links (org-uniquify (reverse links))))
9921 (cond
9922 ((null links)
9923 (message "No links"))
9924 ((equal (length links) 1)
9925 (setq link (car links)))
9926 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9927 (setq link (nth (if have-zero nth (1- nth)) links)))
9928 (t ; we have to select a link
9929 (save-excursion
9930 (save-window-excursion
9931 (delete-other-windows)
9932 (with-output-to-temp-buffer "*Select Link*"
9933 (mapc (lambda (l)
9934 (if (not (string-match org-bracket-link-regexp l))
9935 (princ (format "[%c] %s\n" (incf cnt)
9936 (org-remove-angle-brackets l)))
9937 (if (match-end 3)
9938 (princ (format "[%c] %s (%s)\n" (incf cnt)
9939 (match-string 3 l) (match-string 1 l)))
9940 (princ (format "[%c] %s\n" (incf cnt)
9941 (match-string 1 l))))))
9942 links))
9943 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9944 (message "Select link to open, RET to open all:")
9945 (setq c (read-char-exclusive))
9946 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9947 (when (equal c ?q) (error "Abort"))
9948 (if (equal c ?\C-m)
9949 (setq link links)
9950 (setq nth (- c ?0))
9951 (if have-zero (setq nth (1+ nth)))
9952 (unless (and (integerp nth) (>= (length links) nth))
9953 (error "Invalid link selection"))
9954 (setq link (nth (1- nth) links)))))
9955 (cons link end))))))
9957 ;; Add special file links that specify the way of opening
9959 (org-add-link-type "file+sys" 'org-open-file-with-system)
9960 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9961 (defun org-open-file-with-system (path)
9962 "Open file at PATH using the system way of opening it."
9963 (org-open-file path 'system))
9964 (defun org-open-file-with-emacs (path)
9965 "Open file at PATH in Emacs."
9966 (org-open-file path 'emacs))
9967 (defun org-remove-file-link-modifiers ()
9968 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9969 (goto-char (point-min))
9970 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9971 (org-if-unprotected
9972 (replace-match "file:" t t))))
9973 (eval-after-load "org-exp"
9974 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9975 'org-remove-file-link-modifiers))
9977 ;;; File search
9979 (defvar org-create-file-search-functions nil
9980 "List of functions to construct the right search string for a file link.
9981 These functions are called in turn with point at the location to
9982 which the link should point.
9984 A function in the hook should first test if it would like to
9985 handle this file type, for example by checking the `major-mode'
9986 or the file extension. If it decides not to handle this file, it
9987 should just return nil to give other functions a chance. If it
9988 does handle the file, it must return the search string to be used
9989 when following the link. The search string will be part of the
9990 file link, given after a double colon, and `org-open-at-point'
9991 will automatically search for it. If special measures must be
9992 taken to make the search successful, another function should be
9993 added to the companion hook `org-execute-file-search-functions',
9994 which see.
9996 A function in this hook may also use `setq' to set the variable
9997 `description' to provide a suggestion for the descriptive text to
9998 be used for this link when it gets inserted into an Org-mode
9999 buffer with \\[org-insert-link].")
10001 (defvar org-execute-file-search-functions nil
10002 "List of functions to execute a file search triggered by a link.
10004 Functions added to this hook must accept a single argument, the
10005 search string that was part of the file link, the part after the
10006 double colon. The function must first check if it would like to
10007 handle this search, for example by checking the `major-mode' or
10008 the file extension. If it decides not to handle this search, it
10009 should just return nil to give other functions a chance. If it
10010 does handle the search, it must return a non-nil value to keep
10011 other functions from trying.
10013 Each function can access the current prefix argument through the
10014 variable `current-prefix-argument'. Note that a single prefix is
10015 used to force opening a link in Emacs, so it may be good to only
10016 use a numeric or double prefix to guide the search function.
10018 In case this is needed, a function in this hook can also restore
10019 the window configuration before `org-open-at-point' was called using:
10021 (set-window-configuration org-window-config-before-follow-link)")
10023 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10024 (defun org-link-search (s &optional type avoid-pos stealth)
10025 "Search for a link search option.
10026 If S is surrounded by forward slashes, it is interpreted as a
10027 regular expression. In org-mode files, this will create an `org-occur'
10028 sparse tree. In ordinary files, `occur' will be used to list matches.
10029 If the current buffer is in `dired-mode', grep will be used to search
10030 in all files. If AVOID-POS is given, ignore matches near that position.
10032 When optional argument STEALTH is non-nil, do not modify
10033 visibility around point, thus ignoring
10034 `org-show-hierarchy-above', `org-show-following-heading' and
10035 `org-show-siblings' variables."
10036 (let ((case-fold-search t)
10037 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10038 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10039 (append '(("") (" ") ("\t") ("\n"))
10040 org-emphasis-alist)
10041 "\\|") "\\)"))
10042 (pos (point))
10043 (pre nil) (post nil)
10044 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10045 (cond
10046 ;; First check if there are any special search functions
10047 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10048 ;; Now try the builtin stuff
10049 ((and (equal (string-to-char s0) ?#)
10050 (> (length s0) 1)
10051 (save-excursion
10052 (goto-char (point-min))
10053 (and
10054 (re-search-forward
10055 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10056 (setq type 'dedicated
10057 pos (match-beginning 0))))
10058 ;; There is an exact target for this
10059 (goto-char pos)
10060 (org-back-to-heading t)))
10061 ((save-excursion
10062 (goto-char (point-min))
10063 (and
10064 (re-search-forward
10065 (concat "<<" (regexp-quote s0) ">>") nil t)
10066 (setq type 'dedicated
10067 pos (match-beginning 0))))
10068 ;; There is an exact target for this
10069 (goto-char pos))
10070 ((save-excursion
10071 (goto-char (point-min))
10072 (and
10073 (re-search-forward
10074 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10075 (setq type 'dedicated pos (match-beginning 0))))
10076 ;; Found an invisible target.
10077 (goto-char pos))
10078 ((save-excursion
10079 (goto-char (point-min))
10080 (and
10081 (re-search-forward
10082 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10083 (setq type 'dedicated pos (match-beginning 0))))
10084 ;; Found an element with a matching #+name affiliated keyword.
10085 (goto-char pos))
10086 ((and (string-match "^(\\(.*\\))$" s0)
10087 (save-excursion
10088 (goto-char (point-min))
10089 (and
10090 (re-search-forward
10091 (concat "[^[]" (regexp-quote
10092 (format org-coderef-label-format
10093 (match-string 1 s0))))
10094 nil t)
10095 (setq type 'dedicated
10096 pos (1+ (match-beginning 0))))))
10097 ;; There is a coderef target for this
10098 (goto-char pos))
10099 ((string-match "^/\\(.*\\)/$" s)
10100 ;; A regular expression
10101 (cond
10102 ((derived-mode-p 'org-mode)
10103 (org-occur (match-string 1 s)))
10104 ;;((eq major-mode 'dired-mode)
10105 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10106 (t (org-do-occur (match-string 1 s)))))
10107 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10108 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10109 (goto-char (point-min))
10110 (cond
10111 ((let (case-fold-search)
10112 (re-search-forward (format org-complex-heading-regexp-format
10113 (regexp-quote s))
10114 nil t))
10115 ;; OK, found a match
10116 (setq type 'dedicated)
10117 (goto-char (match-beginning 0)))
10118 ((and (not org-link-search-inhibit-query)
10119 (eq org-link-search-must-match-exact-headline 'query-to-create)
10120 (y-or-n-p "No match - create this as a new heading? "))
10121 (goto-char (point-max))
10122 (or (bolp) (newline))
10123 (insert "* " s "\n")
10124 (beginning-of-line 0))
10126 (goto-char pos)
10127 (error "No match"))))
10129 ;; A normal search string
10130 (when (equal (string-to-char s) ?*)
10131 ;; Anchor on headlines, post may include tags.
10132 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10133 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10134 s (substring s 1)))
10135 (remove-text-properties
10136 0 (length s)
10137 '(face nil mouse-face nil keymap nil fontified nil) s)
10138 ;; Make a series of regular expressions to find a match
10139 (setq words (org-split-string s "[ \n\r\t]+")
10141 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10142 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10143 "\\)" markers)
10144 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10145 re2a (concat "[ \t\r\n]" re2a_)
10146 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10147 re4 (concat "[^a-zA-Z_]" re4_)
10149 re1 (concat pre re2 post)
10150 re3 (concat pre (if pre re4_ re4) post)
10151 re5 (concat pre ".*" re4)
10152 re2 (concat pre re2)
10153 re2a (concat pre (if pre re2a_ re2a))
10154 re4 (concat pre (if pre re4_ re4))
10155 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10156 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10157 re5 "\\)"
10159 (cond
10160 ((eq type 'org-occur) (org-occur reall))
10161 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10162 (t (goto-char (point-min))
10163 (setq type 'fuzzy)
10164 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10165 (org-search-not-self 1 re1 nil t)
10166 (org-search-not-self 1 re2 nil t)
10167 (org-search-not-self 1 re2a nil t)
10168 (org-search-not-self 1 re3 nil t)
10169 (org-search-not-self 1 re4 nil t)
10170 (org-search-not-self 1 re5 nil t)
10172 (goto-char (match-beginning 1))
10173 (goto-char pos)
10174 (error "No match"))))))
10175 (and (derived-mode-p 'org-mode)
10176 (not stealth)
10177 (org-show-context 'link-search))
10178 type))
10180 (defun org-search-not-self (group &rest args)
10181 "Execute `re-search-forward', but only accept matches that do not
10182 enclose the position of `org-open-link-marker'."
10183 (let ((m org-open-link-marker))
10184 (catch 'exit
10185 (while (apply 're-search-forward args)
10186 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10187 (goto-char (match-end group))
10188 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10189 (> (match-beginning 0) (marker-position m))
10190 (< (match-end 0) (marker-position m)))
10191 (save-match-data
10192 (or (not (org-in-regexp
10193 org-bracket-link-analytic-regexp 1))
10194 (not (match-end 4)) ; no description
10195 (and (<= (match-beginning 4) (point))
10196 (>= (match-end 4) (point))))))
10197 (throw 'exit (point))))))))
10199 (defun org-get-buffer-for-internal-link (buffer)
10200 "Return a buffer to be used for displaying the link target of internal links."
10201 (cond
10202 ((not org-display-internal-link-with-indirect-buffer)
10203 buffer)
10204 ((string-match "(Clone)$" (buffer-name buffer))
10205 (message "Buffer is already a clone, not making another one")
10206 ;; we also do not modify visibility in this case
10207 buffer)
10208 (t ; make a new indirect buffer for displaying the link
10209 (let* ((bn (buffer-name buffer))
10210 (ibn (concat bn "(Clone)"))
10211 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10212 (with-current-buffer ib (org-overview))
10213 ib))))
10215 (defun org-do-occur (regexp &optional cleanup)
10216 "Call the Emacs command `occur'.
10217 If CLEANUP is non-nil, remove the printout of the regular expression
10218 in the *Occur* buffer. This is useful if the regex is long and not useful
10219 to read."
10220 (occur regexp)
10221 (when cleanup
10222 (let ((cwin (selected-window)) win beg end)
10223 (when (setq win (get-buffer-window "*Occur*"))
10224 (select-window win))
10225 (goto-char (point-min))
10226 (when (re-search-forward "match[a-z]+" nil t)
10227 (setq beg (match-end 0))
10228 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10229 (setq end (1- (match-beginning 0)))))
10230 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10231 (goto-char (point-min))
10232 (select-window cwin))))
10234 ;;; The mark ring for links jumps
10236 (defvar org-mark-ring nil
10237 "Mark ring for positions before jumps in Org-mode.")
10238 (defvar org-mark-ring-last-goto nil
10239 "Last position in the mark ring used to go back.")
10240 ;; Fill and close the ring
10241 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10242 (loop for i from 1 to org-mark-ring-length do
10243 (push (make-marker) org-mark-ring))
10244 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10245 org-mark-ring)
10247 (defun org-mark-ring-push (&optional pos buffer)
10248 "Put the current position or POS into the mark ring and rotate it."
10249 (interactive)
10250 (setq pos (or pos (point)))
10251 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10252 (move-marker (car org-mark-ring)
10253 (or pos (point))
10254 (or buffer (current-buffer)))
10255 (message "%s"
10256 (substitute-command-keys
10257 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10259 (defun org-mark-ring-goto (&optional n)
10260 "Jump to the previous position in the mark ring.
10261 With prefix arg N, jump back that many stored positions. When
10262 called several times in succession, walk through the entire ring.
10263 Org-mode commands jumping to a different position in the current file,
10264 or to another Org-mode file, automatically push the old position
10265 onto the ring."
10266 (interactive "p")
10267 (let (p m)
10268 (if (eq last-command this-command)
10269 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10270 (setq p org-mark-ring))
10271 (setq org-mark-ring-last-goto p)
10272 (setq m (car p))
10273 (org-pop-to-buffer-same-window (marker-buffer m))
10274 (goto-char m)
10275 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10277 (defun org-remove-angle-brackets (s)
10278 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10279 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10281 (defun org-add-angle-brackets (s)
10282 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10283 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10285 (defun org-remove-double-quotes (s)
10286 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10287 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10290 ;;; Following specific links
10292 (defun org-follow-timestamp-link ()
10293 "Open an agenda view for the time-stamp date/range at point."
10294 (cond
10295 ((org-at-date-range-p t)
10296 (let ((org-agenda-start-on-weekday)
10297 (t1 (match-string 1))
10298 (t2 (match-string 2)) tt1 tt2)
10299 (setq tt1 (time-to-days (org-time-string-to-time t1))
10300 tt2 (time-to-days (org-time-string-to-time t2)))
10301 (let ((org-agenda-buffer-tmp-name
10302 (format "*Org Agenda(a:%s)"
10303 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10304 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10305 ((org-at-timestamp-p t)
10306 (let ((org-agenda-buffer-tmp-name
10307 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10308 (org-agenda-list nil (time-to-days (org-time-string-to-time
10309 (substring (match-string 1) 0 10)))
10310 1)))
10311 (t (error "This should not happen"))))
10314 ;;; Following file links
10315 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10316 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10317 (declare-function mailcap-mime-info
10318 "mailcap" (string &optional request no-decode))
10319 (defvar org-wait nil)
10320 (defun org-open-file (path &optional in-emacs line search)
10321 "Open the file at PATH.
10322 First, this expands any special file name abbreviations. Then the
10323 configuration variable `org-file-apps' is checked if it contains an
10324 entry for this file type, and if yes, the corresponding command is launched.
10326 If no application is found, Emacs simply visits the file.
10328 With optional prefix argument IN-EMACS, Emacs will visit the file.
10329 With a double \\[universal-argument] \\[universal-argument] \
10330 prefix arg, Org tries to avoid opening in Emacs
10331 and to use an external application to visit the file.
10333 Optional LINE specifies a line to go to, optional SEARCH a string
10334 to search for. If LINE or SEARCH is given, the file will be
10335 opened in Emacs, unless an entry from org-file-apps that makes
10336 use of groups in a regexp matches.
10338 If you want to change the way frames are used when following a
10339 link, please customize `org-link-frame-setup'.
10341 If the file does not exist, an error is thrown."
10342 (let* ((file (if (equal path "")
10343 buffer-file-name
10344 (substitute-in-file-name (expand-file-name path))))
10345 (file-apps (append org-file-apps (org-default-apps)))
10346 (apps (org-remove-if
10347 'org-file-apps-entry-match-against-dlink-p file-apps))
10348 (apps-dlink (org-remove-if-not
10349 'org-file-apps-entry-match-against-dlink-p file-apps))
10350 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10351 (dirp (if remp nil (file-directory-p file)))
10352 (file (if (and dirp org-open-directory-means-index-dot-org)
10353 (concat (file-name-as-directory file) "index.org")
10354 file))
10355 (a-m-a-p (assq 'auto-mode apps))
10356 (dfile (downcase file))
10357 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10358 (link (cond ((and (eq line nil)
10359 (eq search nil))
10360 file)
10361 (line
10362 (concat file "::" (number-to-string line)))
10363 (search
10364 (concat file "::" search))))
10365 (dlink (downcase link))
10366 (old-buffer (current-buffer))
10367 (old-pos (point))
10368 (old-mode major-mode)
10369 ext cmd link-match-data)
10370 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10371 (setq ext (match-string 1 dfile))
10372 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10373 (setq ext (match-string 1 dfile))))
10374 (cond
10375 ((member in-emacs '((16) system))
10376 (setq cmd (cdr (assoc 'system apps))))
10377 (in-emacs (setq cmd 'emacs))
10379 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10380 (and dirp (cdr (assoc 'directory apps)))
10381 ; first, try matching against apps-dlink
10382 ; if we get a match here, store the match data for later
10383 (let ((match (assoc-default dlink apps-dlink
10384 'string-match)))
10385 (if match
10386 (progn (setq link-match-data (match-data))
10387 match)
10388 (progn (setq in-emacs (or in-emacs line search))
10389 nil))) ; if we have no match in apps-dlink,
10390 ; always open the file in emacs if line or search
10391 ; is given (for backwards compatibility)
10392 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10393 'string-match)
10394 (cdr (assoc ext apps))
10395 (cdr (assoc t apps))))))
10396 (when (eq cmd 'system)
10397 (setq cmd (cdr (assoc 'system apps))))
10398 (when (eq cmd 'default)
10399 (setq cmd (cdr (assoc t apps))))
10400 (when (eq cmd 'mailcap)
10401 (require 'mailcap)
10402 (mailcap-parse-mailcaps)
10403 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10404 (command (mailcap-mime-info mime-type)))
10405 (if (stringp command)
10406 (setq cmd command)
10407 (setq cmd 'emacs))))
10408 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10409 (not (file-exists-p file))
10410 (not org-open-non-existing-files))
10411 (error "No such file: %s" file))
10412 (cond
10413 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10414 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10415 (while (string-match "['\"]%s['\"]" cmd)
10416 (setq cmd (replace-match "%s" t t cmd)))
10417 (while (string-match "%s" cmd)
10418 (setq cmd (replace-match
10419 (save-match-data
10420 (shell-quote-argument
10421 (convert-standard-filename file)))
10422 t t cmd)))
10424 ;; Replace "%1", "%2" etc. in command with group matches from regex
10425 (save-match-data
10426 (let ((match-index 1)
10427 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10428 (set-match-data link-match-data)
10429 (while (<= match-index number-of-groups)
10430 (let ((regex (concat "%" (number-to-string match-index)))
10431 (replace-with (match-string match-index dlink)))
10432 (while (string-match regex cmd)
10433 (setq cmd (replace-match replace-with t t cmd))))
10434 (setq match-index (+ match-index 1)))))
10436 (save-window-excursion
10437 (start-process-shell-command cmd nil cmd)
10438 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10440 ((or (stringp cmd)
10441 (eq cmd 'emacs))
10442 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10443 (widen)
10444 (if line (org-goto-line line)
10445 (if search (org-link-search search))))
10446 ((consp cmd)
10447 (let ((file (convert-standard-filename file)))
10448 (save-match-data
10449 (set-match-data link-match-data)
10450 (eval cmd))))
10451 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10452 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10453 (or (not (equal old-buffer (current-buffer)))
10454 (not (equal old-pos (point))))
10455 (org-mark-ring-push old-pos old-buffer))))
10457 (defun org-file-apps-entry-match-against-dlink-p (entry)
10458 "This function returns non-nil if `entry' uses a regular
10459 expression which should be matched against the whole link by
10460 org-open-file.
10462 It assumes that is the case when the entry uses a regular
10463 expression which has at least one grouping construct and the
10464 action is either a lisp form or a command string containing
10465 '%1', i.e. using at least one subexpression match as a
10466 parameter."
10467 (let ((selector (car entry))
10468 (action (cdr entry)))
10469 (if (stringp selector)
10470 (and (> (regexp-opt-depth selector) 0)
10471 (or (and (stringp action)
10472 (string-match "%[0-9]" action))
10473 (consp action)))
10474 nil)))
10476 (defun org-default-apps ()
10477 "Return the default applications for this operating system."
10478 (cond
10479 ((eq system-type 'darwin)
10480 org-file-apps-defaults-macosx)
10481 ((eq system-type 'windows-nt)
10482 org-file-apps-defaults-windowsnt)
10483 (t org-file-apps-defaults-gnu)))
10485 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10486 "Convert extensions to regular expressions in the cars of LIST.
10487 Also, weed out any non-string entries, because the return value is used
10488 only for regexp matching.
10489 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10490 point to the symbol `emacs', indicating that the file should
10491 be opened in Emacs."
10492 (append
10493 (delq nil
10494 (mapcar (lambda (x)
10495 (if (not (stringp (car x)))
10497 (if (string-match "\\W" (car x))
10499 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10500 list))
10501 (if add-auto-mode
10502 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10504 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10505 (defun org-file-remote-p (file)
10506 "Test whether FILE specifies a location on a remote system.
10507 Return non-nil if the location is indeed remote.
10509 For example, the filename \"/user@host:/foo\" specifies a location
10510 on the system \"/user@host:\"."
10511 (cond ((fboundp 'file-remote-p)
10512 (file-remote-p file))
10513 ((fboundp 'tramp-handle-file-remote-p)
10514 (tramp-handle-file-remote-p file))
10515 ((and (boundp 'ange-ftp-name-format)
10516 (string-match (car ange-ftp-name-format) file))
10517 t)))
10520 ;;;; Refiling
10522 (defun org-get-org-file ()
10523 "Read a filename, with default directory `org-directory'."
10524 (let ((default (or org-default-notes-file remember-data-file)))
10525 (read-file-name (format "File name [%s]: " default)
10526 (file-name-as-directory org-directory)
10527 default)))
10529 (defun org-notes-order-reversed-p ()
10530 "Check if the current file should receive notes in reversed order."
10531 (cond
10532 ((not org-reverse-note-order) nil)
10533 ((eq t org-reverse-note-order) t)
10534 ((not (listp org-reverse-note-order)) nil)
10535 (t (catch 'exit
10536 (let ((all org-reverse-note-order)
10537 entry)
10538 (while (setq entry (pop all))
10539 (if (string-match (car entry) buffer-file-name)
10540 (throw 'exit (cdr entry))))
10541 nil)))))
10543 (defvar org-refile-target-table nil
10544 "The list of refile targets, created by `org-refile'.")
10546 (defvar org-agenda-new-buffers nil
10547 "Buffers created to visit agenda files.")
10549 (defvar org-refile-cache nil
10550 "Cache for refile targets.")
10552 (defvar org-refile-markers nil
10553 "All the markers used for caching refile locations.")
10555 (defun org-refile-marker (pos)
10556 "Get a new refile marker, but only if caching is in use."
10557 (if (not org-refile-use-cache)
10559 (let ((m (make-marker)))
10560 (move-marker m pos)
10561 (push m org-refile-markers)
10562 m)))
10564 (defun org-refile-cache-clear ()
10565 "Clear the refile cache and disable all the markers."
10566 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10567 (setq org-refile-markers nil)
10568 (setq org-refile-cache nil)
10569 (message "Refile cache has been cleared"))
10571 (defun org-refile-cache-check-set (set)
10572 "Check if all the markers in the cache still have live buffers."
10573 (let (marker)
10574 (catch 'exit
10575 (while (and set (setq marker (nth 3 (pop set))))
10576 ;; if org-refile-use-outline-path is 'file, marker may be nil
10577 (when (and marker (null (marker-buffer marker)))
10578 (message "not found") (sit-for 3)
10579 (throw 'exit nil)))
10580 t)))
10582 (defun org-refile-cache-put (set &rest identifiers)
10583 "Push the refile targets SET into the cache, under IDENTIFIERS."
10584 (let* ((key (sha1 (prin1-to-string identifiers)))
10585 (entry (assoc key org-refile-cache)))
10586 (if entry
10587 (setcdr entry set)
10588 (push (cons key set) org-refile-cache))))
10590 (defun org-refile-cache-get (&rest identifiers)
10591 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10592 (cond
10593 ((not org-refile-cache) nil)
10594 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10596 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10597 org-refile-cache))))
10598 (and set (org-refile-cache-check-set set) set)))))
10600 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10601 "Produce a table with refile targets."
10602 (let ((case-fold-search nil)
10603 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10604 (entries (or org-refile-targets '((nil . (:level . 1)))))
10605 targets tgs txt re files f desc descre fast-path-p level pos0)
10606 (message "Getting targets...")
10607 (with-current-buffer (or default-buffer (current-buffer))
10608 (while (setq entry (pop entries))
10609 (setq files (car entry) desc (cdr entry))
10610 (setq fast-path-p nil)
10611 (cond
10612 ((null files) (setq files (list (current-buffer))))
10613 ((eq files 'org-agenda-files)
10614 (setq files (org-agenda-files 'unrestricted)))
10615 ((and (symbolp files) (fboundp files))
10616 (setq files (funcall files)))
10617 ((and (symbolp files) (boundp files))
10618 (setq files (symbol-value files))))
10619 (if (stringp files) (setq files (list files)))
10620 (cond
10621 ((eq (car desc) :tag)
10622 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10623 ((eq (car desc) :todo)
10624 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10625 ((eq (car desc) :regexp)
10626 (setq descre (cdr desc)))
10627 ((eq (car desc) :level)
10628 (setq descre (concat "^\\*\\{" (number-to-string
10629 (if org-odd-levels-only
10630 (1- (* 2 (cdr desc)))
10631 (cdr desc)))
10632 "\\}[ \t]")))
10633 ((eq (car desc) :maxlevel)
10634 (setq fast-path-p t)
10635 (setq descre (concat "^\\*\\{1," (number-to-string
10636 (if org-odd-levels-only
10637 (1- (* 2 (cdr desc)))
10638 (cdr desc)))
10639 "\\}[ \t]")))
10640 (t (error "Bad refiling target description %s" desc)))
10641 (while (setq f (pop files))
10642 (with-current-buffer
10643 (if (bufferp f) f (org-get-agenda-file-buffer f))
10645 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10646 (progn
10647 (if (bufferp f) (setq f (buffer-file-name
10648 (buffer-base-buffer f))))
10649 (setq f (and f (expand-file-name f)))
10650 (if (eq org-refile-use-outline-path 'file)
10651 (push (list (file-name-nondirectory f) f nil nil) tgs))
10652 (save-excursion
10653 (save-restriction
10654 (widen)
10655 (goto-char (point-min))
10656 (while (re-search-forward descre nil t)
10657 (goto-char (setq pos0 (point-at-bol)))
10658 (catch 'next
10659 (when org-refile-target-verify-function
10660 (save-match-data
10661 (or (funcall org-refile-target-verify-function)
10662 (throw 'next t))))
10663 (when (and (looking-at org-complex-heading-regexp)
10664 (not (member (match-string 4) excluded-entries))
10665 (match-string 4))
10666 (setq level (org-reduced-level
10667 (- (match-end 1) (match-beginning 1)))
10668 txt (org-link-display-format (match-string 4))
10669 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10670 re (format org-complex-heading-regexp-format
10671 (regexp-quote (match-string 4))))
10672 (when org-refile-use-outline-path
10673 (setq txt (mapconcat
10674 'org-protect-slash
10675 (append
10676 (if (eq org-refile-use-outline-path
10677 'file)
10678 (list (file-name-nondirectory
10679 (buffer-file-name
10680 (buffer-base-buffer))))
10681 (if (eq org-refile-use-outline-path
10682 'full-file-path)
10683 (list (buffer-file-name
10684 (buffer-base-buffer)))))
10685 (org-get-outline-path fast-path-p
10686 level txt)
10687 (list txt))
10688 "/")))
10689 (push (list txt f re (org-refile-marker (point)))
10690 tgs)))
10691 (when (= (point) pos0)
10692 ;; verification function has not moved point
10693 (goto-char (point-at-eol))))))))
10694 (when org-refile-use-cache
10695 (org-refile-cache-put tgs (buffer-file-name) descre))
10696 (setq targets (append tgs targets))
10697 ))))
10698 (message "Getting targets...done")
10699 (nreverse targets)))
10701 (defun org-protect-slash (s)
10702 (while (string-match "/" s)
10703 (setq s (replace-match "\\" t t s)))
10706 (defvar org-olpa (make-vector 20 nil))
10708 (defun org-get-outline-path (&optional fastp level heading)
10709 "Return the outline path to the current entry, as a list.
10711 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10712 routine which makes outline path derivations for an entire file,
10713 avoiding backtracing. Refile target collection makes use of that."
10714 (if fastp
10715 (progn
10716 (if (> level 19)
10717 (error "Outline path failure, more than 19 levels"))
10718 (loop for i from level upto 19 do
10719 (aset org-olpa i nil))
10720 (prog1
10721 (delq nil (append org-olpa nil))
10722 (aset org-olpa level heading)))
10723 (let (rtn case-fold-search)
10724 (save-excursion
10725 (save-restriction
10726 (widen)
10727 (while (org-up-heading-safe)
10728 (when (looking-at org-complex-heading-regexp)
10729 (push (org-match-string-no-properties 4) rtn)))
10730 rtn)))))
10732 (defun org-format-outline-path (path &optional width prefix)
10733 "Format the outline path PATH for display.
10734 Width is the maximum number of characters that is available.
10735 Prefix is a prefix to be included in the returned string,
10736 such as the file name."
10737 (setq width (or width 79))
10738 (if prefix (setq width (- width (length prefix))))
10739 (if (not path)
10740 (or prefix "")
10741 (let* ((nsteps (length path))
10742 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10743 (maxwidth (if (<= total-width width)
10744 10000 ;; everything fits
10745 ;; we need to shorten the level headings
10746 (/ (- width nsteps) nsteps)))
10747 (org-odd-levels-only nil)
10748 (n 0)
10749 (total (1+ (length prefix))))
10750 (setq maxwidth (max maxwidth 10))
10751 (concat prefix
10752 (mapconcat
10753 (lambda (h)
10754 (setq n (1+ n))
10755 (if (and (= n nsteps) (< maxwidth 10000))
10756 (setq maxwidth (- total-width total)))
10757 (if (< (length h) maxwidth)
10758 (progn (setq total (+ total (length h) 1)) h)
10759 (setq h (substring h 0 (- maxwidth 2))
10760 total (+ total maxwidth 1))
10761 (if (string-match "[ \t]+\\'" h)
10762 (setq h (substring h 0 (match-beginning 0))))
10763 (setq h (concat h "..")))
10764 (org-add-props h nil 'face
10765 (nth (% (1- n) org-n-level-faces)
10766 org-level-faces))
10768 path "/")))))
10770 (defun org-display-outline-path (&optional file current)
10771 "Display the current outline path in the echo area."
10772 (interactive "P")
10773 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10774 (case-fold-search nil)
10775 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10776 (if current (setq path (append path
10777 (save-excursion
10778 (org-back-to-heading t)
10779 (if (looking-at org-complex-heading-regexp)
10780 (list (match-string 4)))))))
10781 (message "%s"
10782 (org-format-outline-path
10783 path
10784 (1- (frame-width))
10785 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10787 (defvar org-refile-history nil
10788 "History for refiling operations.")
10790 (defvar org-after-refile-insert-hook nil
10791 "Hook run after `org-refile' has inserted its stuff at the new location.
10792 Note that this is still *before* the stuff will be removed from
10793 the *old* location.")
10795 (defvar org-capture-last-stored-marker)
10796 (defun org-refile (&optional goto default-buffer rfloc)
10797 "Move the entry or entries at point to another heading.
10798 The list of target headings is compiled using the information in
10799 `org-refile-targets', which see.
10801 At the target location, the entry is filed as a subitem of the target
10802 heading. Depending on `org-reverse-note-order', the new subitem will
10803 either be the first or the last subitem.
10805 If there is an active region, all entries in that region will be moved.
10806 However, the region must fulfill the requirement that the first heading
10807 is the first one sets the top-level of the moved text - at most siblings
10808 below it are allowed.
10810 With prefix arg GOTO, the command will only visit the target location
10811 and not actually move anything.
10813 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10814 go to the location where the last refiling operation has put the subtree.
10815 With a prefix argument of `2', refile to the running clock.
10817 RFLOC can be a refile location obtained in a different way.
10819 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10821 If you are using target caching (see `org-refile-use-cache'),
10822 you have to clear the target cache in order to find new targets.
10823 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10824 prefix argument (`C-u C-u C-u C-c C-w')."
10826 (interactive "P")
10827 (if (member goto '(0 (64)))
10828 (org-refile-cache-clear)
10829 (let* ((cbuf (current-buffer))
10830 (regionp (org-region-active-p))
10831 (region-start (and regionp (region-beginning)))
10832 (region-end (and regionp (region-end)))
10833 (region-length (and regionp (- region-end region-start)))
10834 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10835 pos it nbuf file re level reversed)
10836 (setq last-command nil)
10837 (when regionp
10838 (goto-char region-start)
10839 (or (bolp) (goto-char (point-at-bol)))
10840 (setq region-start (point))
10841 (unless (or (org-kill-is-subtree-p
10842 (buffer-substring region-start region-end))
10843 (prog1 org-refile-active-region-within-subtree
10844 (org-toggle-heading)))
10845 (error "The region is not a (sequence of) subtree(s)")))
10846 (if (equal goto '(16))
10847 (org-refile-goto-last-stored)
10848 (when (or
10849 (and (equal goto 2)
10850 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10851 (prog1
10852 (setq it (list (or org-clock-heading "running clock")
10853 (buffer-file-name
10854 (marker-buffer org-clock-hd-marker))
10856 (marker-position org-clock-hd-marker)))
10857 (setq goto nil)))
10858 (setq it (or rfloc
10859 (let (heading-text)
10860 (save-excursion
10861 (unless goto
10862 (org-back-to-heading t)
10863 (setq heading-text
10864 (nth 4 (org-heading-components))))
10865 (org-refile-get-location
10866 (cond (goto "Goto")
10867 (regionp "Refile region to")
10868 (t (concat "Refile subtree \""
10869 heading-text "\" to")))
10870 default-buffer
10871 (and (not (equal '(4) goto))
10872 org-refile-allow-creating-parent-nodes)
10873 goto))))))
10874 (setq file (nth 1 it)
10875 re (nth 2 it)
10876 pos (nth 3 it))
10877 (if (and (not goto)
10879 (equal (buffer-file-name) file)
10880 (if regionp
10881 (and (>= pos region-start)
10882 (<= pos region-end))
10883 (and (>= pos (point))
10884 (< pos (save-excursion
10885 (org-end-of-subtree t t))))))
10886 (error "Cannot refile to position inside the tree or region"))
10888 (setq nbuf (or (find-buffer-visiting file)
10889 (find-file-noselect file)))
10890 (if goto
10891 (progn
10892 (org-pop-to-buffer-same-window nbuf)
10893 (goto-char pos)
10894 (org-show-context 'org-goto))
10895 (if regionp
10896 (progn
10897 (org-kill-new (buffer-substring region-start region-end))
10898 (org-save-markers-in-region region-start region-end))
10899 (org-copy-subtree 1 nil t))
10900 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10901 (find-file-noselect file)))
10902 (setq reversed (org-notes-order-reversed-p))
10903 (save-excursion
10904 (save-restriction
10905 (widen)
10906 (if pos
10907 (progn
10908 (goto-char pos)
10909 (looking-at org-outline-regexp)
10910 (setq level (org-get-valid-level (funcall outline-level) 1))
10911 (goto-char
10912 (if reversed
10913 (or (outline-next-heading) (point-max))
10914 (or (save-excursion (org-get-next-sibling))
10915 (org-end-of-subtree t t)
10916 (point-max)))))
10917 (setq level 1)
10918 (if (not reversed)
10919 (goto-char (point-max))
10920 (goto-char (point-min))
10921 (or (outline-next-heading) (goto-char (point-max)))))
10922 (if (not (bolp)) (newline))
10923 (org-paste-subtree level)
10924 (when org-log-refile
10925 (org-add-log-setup 'refile nil nil 'findpos
10926 org-log-refile)
10927 (unless (eq org-log-refile 'note)
10928 (save-excursion (org-add-log-note))))
10929 (and org-auto-align-tags
10930 (let ((org-loop-over-headlines-in-active-region nil))
10931 (org-set-tags nil t)))
10932 (with-demoted-errors
10933 (bookmark-set "org-refile-last-stored"))
10934 ;; If we are refiling for capture, make sure that the
10935 ;; last-capture pointers point here
10936 (when (org-bound-and-true-p org-refile-for-capture)
10937 (with-demoted-errors
10938 (bookmark-set "org-capture-last-stored-marker"))
10939 (move-marker org-capture-last-stored-marker (point)))
10940 (if (fboundp 'deactivate-mark) (deactivate-mark))
10941 (run-hooks 'org-after-refile-insert-hook))))
10942 (if regionp
10943 (delete-region (point) (+ (point) region-length))
10944 (org-cut-subtree))
10945 (when (featurep 'org-inlinetask)
10946 (org-inlinetask-remove-END-maybe))
10947 (setq org-markers-to-move nil)
10948 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10950 (defun org-refile-goto-last-stored ()
10951 "Go to the location where the last refile was stored."
10952 (interactive)
10953 (bookmark-jump "org-refile-last-stored")
10954 (message "This is the location of the last refile"))
10956 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10957 no-exclude)
10958 "Prompt the user for a refile location, using PROMPT.
10959 PROMPT should not be suffixed with a colon and a space, because
10960 this function appends the default value from
10961 `org-refile-history' automatically, if that is not empty.
10962 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10963 this is used for the GOTO interface."
10964 (let ((org-refile-targets org-refile-targets)
10965 (org-refile-use-outline-path org-refile-use-outline-path)
10966 excluded-entries)
10967 (when (and (derived-mode-p 'org-mode)
10968 (not org-refile-use-cache)
10969 (not no-exclude))
10970 (org-map-tree
10971 (lambda()
10972 (setq excluded-entries
10973 (append excluded-entries (list (org-get-heading t t)))))))
10974 (setq org-refile-target-table
10975 (org-refile-get-targets default-buffer excluded-entries)))
10976 (unless org-refile-target-table
10977 (error "No refile targets"))
10978 (let* ((prompt (concat prompt
10979 (and (car org-refile-history)
10980 (concat " (default " (car org-refile-history) ")"))
10981 ": "))
10982 (cbuf (current-buffer))
10983 (partial-completion-mode nil)
10984 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10985 (cfunc (if (and org-refile-use-outline-path
10986 org-outline-path-complete-in-steps)
10987 'org-olpath-completing-read
10988 'org-icompleting-read))
10989 (extra (if org-refile-use-outline-path "/" ""))
10990 (filename (and cfn (expand-file-name cfn)))
10991 (tbl (mapcar
10992 (lambda (x)
10993 (if (and (not (member org-refile-use-outline-path
10994 '(file full-file-path)))
10995 (not (equal filename (nth 1 x))))
10996 (cons (concat (car x) extra " ("
10997 (file-name-nondirectory (nth 1 x)) ")")
10998 (cdr x))
10999 (cons (concat (car x) extra) (cdr x))))
11000 org-refile-target-table))
11001 (completion-ignore-case t)
11002 pa answ parent-target child parent old-hist)
11003 (setq old-hist org-refile-history)
11004 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11005 nil 'org-refile-history (car org-refile-history)))
11006 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11007 (org-refile-check-position pa)
11008 (if pa
11009 (progn
11010 (when (or (not org-refile-history)
11011 (not (eq old-hist org-refile-history))
11012 (not (equal (car pa) (car org-refile-history))))
11013 (setq org-refile-history
11014 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11015 org-refile-history
11016 (cdr org-refile-history))))
11017 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11018 (pop org-refile-history)))
11020 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11021 (progn
11022 (setq parent (match-string 1 answ)
11023 child (match-string 2 answ))
11024 (setq parent-target (or (assoc parent tbl)
11025 (assoc (concat parent "/") tbl)))
11026 (when (and parent-target
11027 (or (eq new-nodes t)
11028 (and (eq new-nodes 'confirm)
11029 (y-or-n-p (format "Create new node \"%s\"? "
11030 child)))))
11031 (org-refile-new-child parent-target child)))
11032 (error "Invalid target location")))))
11034 (declare-function org-string-nw-p "org-macs" (s))
11035 (defun org-refile-check-position (refile-pointer)
11036 "Check if the refile pointer matches the headline to which it points."
11037 (let* ((file (nth 1 refile-pointer))
11038 (re (nth 2 refile-pointer))
11039 (pos (nth 3 refile-pointer))
11040 buffer)
11041 (if (and (not (markerp pos)) (not file))
11042 (error "Please save the buffer to a file before refiling")
11043 (when (org-string-nw-p re)
11044 (setq buffer (if (markerp pos)
11045 (marker-buffer pos)
11046 (or (find-buffer-visiting file)
11047 (find-file-noselect file))))
11048 (with-current-buffer buffer
11049 (save-excursion
11050 (save-restriction
11051 (widen)
11052 (goto-char pos)
11053 (beginning-of-line 1)
11054 (unless (org-looking-at-p re)
11055 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11057 (defun org-refile-new-child (parent-target child)
11058 "Use refile target PARENT-TARGET to add new CHILD below it."
11059 (unless parent-target
11060 (error "Cannot find parent for new node"))
11061 (let ((file (nth 1 parent-target))
11062 (pos (nth 3 parent-target))
11063 level)
11064 (with-current-buffer (or (find-buffer-visiting file)
11065 (find-file-noselect file))
11066 (save-excursion
11067 (save-restriction
11068 (widen)
11069 (if pos
11070 (goto-char pos)
11071 (goto-char (point-max))
11072 (if (not (bolp)) (newline)))
11073 (when (looking-at org-outline-regexp)
11074 (setq level (funcall outline-level))
11075 (org-end-of-subtree t t))
11076 (org-back-over-empty-lines)
11077 (insert "\n" (make-string
11078 (if pos (org-get-valid-level level 1) 1) ?*)
11079 " " child "\n")
11080 (beginning-of-line 0)
11081 (list (concat (car parent-target) "/" child) file "" (point)))))))
11083 (defun org-olpath-completing-read (prompt collection &rest args)
11084 "Read an outline path like a file name."
11085 (let ((thetable collection)
11086 (org-completion-use-ido nil) ; does not work with ido.
11087 (org-completion-use-iswitchb nil)) ; or iswitchb
11088 (apply
11089 'org-icompleting-read prompt
11090 (lambda (string predicate &optional flag)
11091 (let (rtn r f (l (length string)))
11092 (cond
11093 ((eq flag nil)
11094 ;; try completion
11095 (try-completion string thetable))
11096 ((eq flag t)
11097 ;; all-completions
11098 (setq rtn (all-completions string thetable predicate))
11099 (mapcar
11100 (lambda (x)
11101 (setq r (substring x l))
11102 (if (string-match " ([^)]*)$" x)
11103 (setq f (match-string 0 x))
11104 (setq f ""))
11105 (if (string-match "/" r)
11106 (concat string (substring r 0 (match-end 0)) f)
11108 rtn))
11109 ((eq flag 'lambda)
11110 ;; exact match?
11111 (assoc string thetable)))))
11112 args)))
11114 ;;;; Dynamic blocks
11116 (defun org-find-dblock (name)
11117 "Find the first dynamic block with name NAME in the buffer.
11118 If not found, stay at current position and return nil."
11119 (let ((case-fold-search t) pos)
11120 (save-excursion
11121 (goto-char (point-min))
11122 (setq pos (and (re-search-forward
11123 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11124 (match-beginning 0))))
11125 (if pos (goto-char pos))
11126 pos))
11128 (defconst org-dblock-start-re
11129 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11130 "Matches the start line of a dynamic block, with parameters.")
11132 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11133 "Matches the end of a dynamic block.")
11135 (defun org-create-dblock (plist)
11136 "Create a dynamic block section, with parameters taken from PLIST.
11137 PLIST must contain a :name entry which is used as name of the block."
11138 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11139 (end-of-line 1)
11140 (newline))
11141 (let ((col (current-column))
11142 (name (plist-get plist :name)))
11143 (insert "#+BEGIN: " name)
11144 (while plist
11145 (if (eq (car plist) :name)
11146 (setq plist (cddr plist))
11147 (insert " " (prin1-to-string (pop plist)))))
11148 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11149 (beginning-of-line -2)))
11151 (defun org-prepare-dblock ()
11152 "Prepare dynamic block for refresh.
11153 This empties the block, puts the cursor at the insert position and returns
11154 the property list including an extra property :name with the block name."
11155 (unless (looking-at org-dblock-start-re)
11156 (error "Not at a dynamic block"))
11157 (let* ((begdel (1+ (match-end 0)))
11158 (name (org-no-properties (match-string 1)))
11159 (params (append (list :name name)
11160 (read (concat "(" (match-string 3) ")")))))
11161 (save-excursion
11162 (beginning-of-line 1)
11163 (skip-chars-forward " \t")
11164 (setq params (plist-put params :indentation-column (current-column))))
11165 (unless (re-search-forward org-dblock-end-re nil t)
11166 (error "Dynamic block not terminated"))
11167 (setq params
11168 (append params
11169 (list :content (buffer-substring
11170 begdel (match-beginning 0)))))
11171 (delete-region begdel (match-beginning 0))
11172 (goto-char begdel)
11173 (open-line 1)
11174 params))
11176 (defun org-map-dblocks (&optional command)
11177 "Apply COMMAND to all dynamic blocks in the current buffer.
11178 If COMMAND is not given, use `org-update-dblock'."
11179 (let ((cmd (or command 'org-update-dblock)))
11180 (save-excursion
11181 (goto-char (point-min))
11182 (while (re-search-forward org-dblock-start-re nil t)
11183 (goto-char (match-beginning 0))
11184 (save-excursion
11185 (condition-case nil
11186 (funcall cmd)
11187 (error (message "Error during update of dynamic block"))))
11188 (unless (re-search-forward org-dblock-end-re nil t)
11189 (error "Dynamic block not terminated"))))))
11191 (defun org-dblock-update (&optional arg)
11192 "User command for updating dynamic blocks.
11193 Update the dynamic block at point. With prefix ARG, update all dynamic
11194 blocks in the buffer."
11195 (interactive "P")
11196 (if arg
11197 (org-update-all-dblocks)
11198 (or (looking-at org-dblock-start-re)
11199 (org-beginning-of-dblock))
11200 (org-update-dblock)))
11202 (defun org-update-dblock ()
11203 "Update the dynamic block at point.
11204 This means to empty the block, parse for parameters and then call
11205 the correct writing function."
11206 (interactive)
11207 (save-window-excursion
11208 (let* ((pos (point))
11209 (line (org-current-line))
11210 (params (org-prepare-dblock))
11211 (name (plist-get params :name))
11212 (indent (plist-get params :indentation-column))
11213 (cmd (intern (concat "org-dblock-write:" name))))
11214 (message "Updating dynamic block `%s' at line %d..." name line)
11215 (funcall cmd params)
11216 (message "Updating dynamic block `%s' at line %d...done" name line)
11217 (goto-char pos)
11218 (when (and indent (> indent 0))
11219 (setq indent (make-string indent ?\ ))
11220 (save-excursion
11221 (org-beginning-of-dblock)
11222 (forward-line 1)
11223 (while (not (looking-at org-dblock-end-re))
11224 (insert indent)
11225 (beginning-of-line 2))
11226 (when (looking-at org-dblock-end-re)
11227 (and (looking-at "[ \t]+")
11228 (replace-match ""))
11229 (insert indent)))))))
11231 (defun org-beginning-of-dblock ()
11232 "Find the beginning of the dynamic block at point.
11233 Error if there is no such block at point."
11234 (let ((pos (point))
11235 beg)
11236 (end-of-line 1)
11237 (if (and (re-search-backward org-dblock-start-re nil t)
11238 (setq beg (match-beginning 0))
11239 (re-search-forward org-dblock-end-re nil t)
11240 (> (match-end 0) pos))
11241 (goto-char beg)
11242 (goto-char pos)
11243 (error "Not in a dynamic block"))))
11245 (defun org-update-all-dblocks ()
11246 "Update all dynamic blocks in the buffer.
11247 This function can be used in a hook."
11248 (interactive)
11249 (when (derived-mode-p 'org-mode)
11250 (org-map-dblocks 'org-update-dblock)))
11253 ;;;; Completion
11255 (defconst org-additional-option-like-keywords
11256 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11257 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11258 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11259 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11260 "BEGIN:" "END:"
11261 "ORGTBL" "TBLFM:" "TBLNAME:"
11262 "BEGIN_EXAMPLE" "END_EXAMPLE"
11263 "BEGIN_VERBATIM" "END_VERBATIM"
11264 "BEGIN_QUOTE" "END_QUOTE"
11265 "BEGIN_VERSE" "END_VERSE"
11266 "BEGIN_CENTER" "END_CENTER"
11267 "BEGIN_SRC" "END_SRC"
11268 "BEGIN_RESULT" "END_RESULT"
11269 "BEGIN_lstlisting" "END_lstlisting"
11270 "NAME:" "RESULTS:"
11271 "HEADER:" "HEADERS:"
11272 "COLUMNS:" "PROPERTY:"
11273 "CAPTION:" "LABEL:"
11274 "SETUPFILE:"
11275 "INCLUDE:" "INDEX:"
11276 "BIND:"
11277 "MACRO:"))
11279 (defconst org-options-keywords
11280 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11281 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11282 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11283 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11284 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11285 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11286 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11288 (defconst org-additional-option-like-keywords-for-flyspell
11289 (delete-dups
11290 (split-string
11291 (mapconcat (lambda(k)
11292 (replace-regexp-in-string
11293 "_\\|:" " "
11294 (concat k " " (downcase k) " " (upcase k))))
11295 (append org-options-keywords org-additional-option-like-keywords)
11296 " ")
11297 " +" t)))
11299 (defcustom org-structure-template-alist
11300 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11301 "<src lang=\"?\">\n\n</src>")
11302 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11303 "<example>\n?\n</example>")
11304 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11305 "<quote>\n?\n</quote>")
11306 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11307 "<verse>\n?\n</verse>")
11308 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11309 "<verbatim>\n?\n</verbatim>")
11310 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11311 "<center>\n?\n</center>")
11312 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11313 "<literal style=\"latex\">\n?\n</literal>")
11314 ("L" "#+LaTeX: "
11315 "<literal style=\"latex\">?</literal>")
11316 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11317 "<literal style=\"html\">\n?\n</literal>")
11318 ("H" "#+HTML: "
11319 "<literal style=\"html\">?</literal>")
11320 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11321 ("A" "#+ASCII: ")
11322 ("i" "#+INDEX: ?"
11323 "#+INDEX: ?")
11324 ("I" "#+INCLUDE: %file ?"
11325 "<include file=%file markup=\"?\">"))
11326 "Structure completion elements.
11327 This is a list of abbreviation keys and values. The value gets inserted
11328 if you type `<' followed by the key and then press the completion key,
11329 usually `M-TAB'. %file will be replaced by a file name after prompting
11330 for the file using completion. The cursor will be placed at the position
11331 of the `?` in the template.
11332 There are two templates for each key, the first uses the original Org syntax,
11333 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11334 the default when the /org-mtags.el/ module has been loaded. See also the
11335 variable `org-mtags-prefer-muse-templates'."
11336 :group 'org-completion
11337 :type '(repeat
11338 (string :tag "Key")
11339 (string :tag "Template")
11340 (string :tag "Muse Template")))
11342 (defun org-try-structure-completion ()
11343 "Try to complete a structure template before point.
11344 This looks for strings like \"<e\" on an otherwise empty line and
11345 expands them."
11346 (let ((l (buffer-substring (point-at-bol) (point)))
11348 (when (and (looking-at "[ \t]*$")
11349 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11350 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11351 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11352 (match-beginning 1)) a)
11353 t)))
11355 (defun org-complete-expand-structure-template (start cell)
11356 "Expand a structure template."
11357 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11358 (rpl (nth (if musep 2 1) cell))
11359 (ind ""))
11360 (delete-region start (point))
11361 (when (string-match "\\`#\\+" rpl)
11362 (cond
11363 ((bolp))
11364 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11365 (setq ind (buffer-substring (point-at-bol) (point))))
11366 (t (newline))))
11367 (setq start (point))
11368 (if (string-match "%file" rpl)
11369 (setq rpl (replace-match
11370 (concat
11371 "\""
11372 (save-match-data
11373 (abbreviate-file-name (read-file-name "Include file: ")))
11374 "\"")
11375 t t rpl)))
11376 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11377 (concat "\n" ind)))
11378 (insert rpl)
11379 (if (re-search-backward "\\?" start t) (delete-char 1))))
11381 ;;;; TODO, DEADLINE, Comments
11383 (defun org-toggle-comment ()
11384 "Change the COMMENT state of an entry."
11385 (interactive)
11386 (save-excursion
11387 (org-back-to-heading)
11388 (let (case-fold-search)
11389 (cond
11390 ((looking-at (format org-heading-keyword-regexp-format
11391 org-comment-string))
11392 (goto-char (match-end 1))
11393 (looking-at (concat " +" org-comment-string))
11394 (replace-match "" t t)
11395 (when (eolp) (insert " ")))
11396 ((looking-at org-outline-regexp)
11397 (goto-char (match-end 0))
11398 (insert org-comment-string " "))))))
11400 (defvar org-last-todo-state-is-todo nil
11401 "This is non-nil when the last TODO state change led to a TODO state.
11402 If the last change removed the TODO tag or switched to DONE, then
11403 this is nil.")
11405 (defvar org-setting-tags nil) ; dynamically skipped
11407 (defvar org-todo-setup-filter-hook nil
11408 "Hook for functions that pre-filter todo specs.
11409 Each function takes a todo spec and returns either nil or the spec
11410 transformed into canonical form." )
11412 (defvar org-todo-get-default-hook nil
11413 "Hook for functions that get a default item for todo.
11414 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11415 nil or a string to be used for the todo mark." )
11417 (defvar org-agenda-headline-snapshot-before-repeat)
11419 (defun org-current-effective-time ()
11420 "Return current time adjusted for `org-extend-today-until' variable."
11421 (let* ((ct (org-current-time))
11422 (dct (decode-time ct))
11423 (ct1
11424 (if (and org-use-effective-time
11425 (< (nth 2 dct) org-extend-today-until))
11426 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11427 ct)))
11428 ct1))
11430 (defun org-todo-yesterday (&optional arg)
11431 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11432 (interactive "P")
11433 (if (eq major-mode 'org-agenda-mode)
11434 (apply 'org-agenda-todo-yesterday arg)
11435 (let* ((hour (third (decode-time
11436 (org-current-time))))
11437 (org-extend-today-until (1+ hour)))
11438 (org-todo arg))))
11440 (defun org-todo (&optional arg)
11441 "Change the TODO state of an item.
11442 The state of an item is given by a keyword at the start of the heading,
11443 like
11444 *** TODO Write paper
11445 *** DONE Call mom
11447 The different keywords are specified in the variable `org-todo-keywords'.
11448 By default the available states are \"TODO\" and \"DONE\".
11449 So for this example: when the item starts with TODO, it is changed to DONE.
11450 When it starts with DONE, the DONE is removed. And when neither TODO nor
11451 DONE are present, add TODO at the beginning of the heading.
11453 With \\[universal-argument] prefix arg, use completion to determine the new \
11454 state.
11455 With numeric prefix arg, switch to that state.
11456 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11457 keywords (nextset).
11458 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11459 With a numeric prefix arg of 0, inhibit note taking for the change.
11461 For calling through lisp, arg is also interpreted in the following way:
11462 'none -> empty state
11463 \"\"(empty string) -> switch to empty state
11464 'done -> switch to DONE
11465 'nextset -> switch to the next set of keywords
11466 'previousset -> switch to the previous set of keywords
11467 \"WAITING\" -> switch to the specified keyword, but only if it
11468 really is a member of `org-todo-keywords'."
11469 (interactive "P")
11470 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11471 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11472 'region-start-level 'region))
11473 org-loop-over-headlines-in-active-region)
11474 (org-map-entries
11475 `(org-todo ,arg)
11476 org-loop-over-headlines-in-active-region
11477 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11478 (if (equal arg '(16)) (setq arg 'nextset))
11479 (let ((org-blocker-hook org-blocker-hook)
11480 commentp
11481 case-fold-search)
11482 (when (equal arg '(64))
11483 (setq arg nil org-blocker-hook nil))
11484 (when (and org-blocker-hook
11485 (or org-inhibit-blocking
11486 (org-entry-get nil "NOBLOCKING")))
11487 (setq org-blocker-hook nil))
11488 (save-excursion
11489 (catch 'exit
11490 (org-back-to-heading t)
11491 (when (looking-at (concat "^\\*+ " org-comment-string))
11492 (org-toggle-comment)
11493 (setq commentp t))
11494 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11495 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11496 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11497 (let* ((match-data (match-data))
11498 (startpos (point-at-bol))
11499 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11500 (org-log-done org-log-done)
11501 (org-log-repeat org-log-repeat)
11502 (org-todo-log-states org-todo-log-states)
11503 (org-inhibit-logging
11504 (if (equal arg 0)
11505 (progn (setq arg nil) 'note) org-inhibit-logging))
11506 (this (match-string 1))
11507 (hl-pos (match-beginning 0))
11508 (head (org-get-todo-sequence-head this))
11509 (ass (assoc head org-todo-kwd-alist))
11510 (interpret (nth 1 ass))
11511 (done-word (nth 3 ass))
11512 (final-done-word (nth 4 ass))
11513 (org-last-state (or this ""))
11514 (completion-ignore-case t)
11515 (member (member this org-todo-keywords-1))
11516 (tail (cdr member))
11517 (org-state (cond
11518 ((and org-todo-key-trigger
11519 (or (and (equal arg '(4))
11520 (eq org-use-fast-todo-selection 'prefix))
11521 (and (not arg) org-use-fast-todo-selection
11522 (not (eq org-use-fast-todo-selection
11523 'prefix)))))
11524 ;; Use fast selection
11525 (org-fast-todo-selection))
11526 ((and (equal arg '(4))
11527 (or (not org-use-fast-todo-selection)
11528 (not org-todo-key-trigger)))
11529 ;; Read a state with completion
11530 (org-icompleting-read
11531 "State: " (mapcar (lambda(x) (list x))
11532 org-todo-keywords-1)
11533 nil t))
11534 ((eq arg 'right)
11535 (if this
11536 (if tail (car tail) nil)
11537 (car org-todo-keywords-1)))
11538 ((eq arg 'left)
11539 (if (equal member org-todo-keywords-1)
11541 (if this
11542 (nth (- (length org-todo-keywords-1)
11543 (length tail) 2)
11544 org-todo-keywords-1)
11545 (org-last org-todo-keywords-1))))
11546 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11547 (setq arg nil))) ; hack to fall back to cycling
11548 (arg
11549 ;; user or caller requests a specific state
11550 (cond
11551 ((equal arg "") nil)
11552 ((eq arg 'none) nil)
11553 ((eq arg 'done) (or done-word (car org-done-keywords)))
11554 ((eq arg 'nextset)
11555 (or (car (cdr (member head org-todo-heads)))
11556 (car org-todo-heads)))
11557 ((eq arg 'previousset)
11558 (let ((org-todo-heads (reverse org-todo-heads)))
11559 (or (car (cdr (member head org-todo-heads)))
11560 (car org-todo-heads))))
11561 ((car (member arg org-todo-keywords-1)))
11562 ((stringp arg)
11563 (error "State `%s' not valid in this file" arg))
11564 ((nth (1- (prefix-numeric-value arg))
11565 org-todo-keywords-1))))
11566 ((null member) (or head (car org-todo-keywords-1)))
11567 ((equal this final-done-word) nil) ;; -> make empty
11568 ((null tail) nil) ;; -> first entry
11569 ((memq interpret '(type priority))
11570 (if (eq this-command last-command)
11571 (car tail)
11572 (if (> (length tail) 0)
11573 (or done-word (car org-done-keywords))
11574 nil)))
11576 (car tail))))
11577 (org-state (or
11578 (run-hook-with-args-until-success
11579 'org-todo-get-default-hook org-state org-last-state)
11580 org-state))
11581 (next (if org-state (concat " " org-state " ") " "))
11582 (change-plist (list :type 'todo-state-change :from this :to org-state
11583 :position startpos))
11584 dolog now-done-p)
11585 (when org-blocker-hook
11586 (setq org-last-todo-state-is-todo
11587 (not (member this org-done-keywords)))
11588 (unless (save-excursion
11589 (save-match-data
11590 (org-with-wide-buffer
11591 (run-hook-with-args-until-failure
11592 'org-blocker-hook change-plist))))
11593 (if (org-called-interactively-p 'interactive)
11594 (error "TODO state change from %s to %s blocked" this org-state)
11595 ;; fail silently
11596 (message "TODO state change from %s to %s blocked" this org-state)
11597 (throw 'exit nil))))
11598 (store-match-data match-data)
11599 (replace-match next t t)
11600 (unless (pos-visible-in-window-p hl-pos)
11601 (message "TODO state changed to %s" (org-trim next)))
11602 (unless head
11603 (setq head (org-get-todo-sequence-head org-state)
11604 ass (assoc head org-todo-kwd-alist)
11605 interpret (nth 1 ass)
11606 done-word (nth 3 ass)
11607 final-done-word (nth 4 ass)))
11608 (when (memq arg '(nextset previousset))
11609 (message "Keyword-Set %d/%d: %s"
11610 (- (length org-todo-sets) -1
11611 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11612 (length org-todo-sets)
11613 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11614 (setq org-last-todo-state-is-todo
11615 (not (member org-state org-done-keywords)))
11616 (setq now-done-p (and (member org-state org-done-keywords)
11617 (not (member this org-done-keywords))))
11618 (and logging (org-local-logging logging))
11619 (when (and (or org-todo-log-states org-log-done)
11620 (not (eq org-inhibit-logging t))
11621 (not (memq arg '(nextset previousset))))
11622 ;; we need to look at recording a time and note
11623 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11624 (nth 2 (assoc this org-todo-log-states))))
11625 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11626 (setq dolog 'time))
11627 (when (and org-state
11628 (member org-state org-not-done-keywords)
11629 (not (member this org-not-done-keywords)))
11630 ;; This is now a todo state and was not one before
11631 ;; If there was a CLOSED time stamp, get rid of it.
11632 (org-add-planning-info nil nil 'closed))
11633 (when (and now-done-p org-log-done)
11634 ;; It is now done, and it was not done before
11635 (org-add-planning-info 'closed (org-current-effective-time))
11636 (if (and (not dolog) (eq 'note org-log-done))
11637 (org-add-log-setup 'done org-state this 'findpos 'note)))
11638 (when (and org-state dolog)
11639 ;; This is a non-nil state, and we need to log it
11640 (org-add-log-setup 'state org-state this 'findpos dolog)))
11641 ;; Fixup tag positioning
11642 (org-todo-trigger-tag-changes org-state)
11643 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11644 (when org-provide-todo-statistics
11645 (org-update-parent-todo-statistics))
11646 (run-hooks 'org-after-todo-state-change-hook)
11647 (if (and arg (not (member org-state org-done-keywords)))
11648 (setq head (org-get-todo-sequence-head org-state)))
11649 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11650 ;; Do we need to trigger a repeat?
11651 (when now-done-p
11652 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11653 ;; This is for the agenda, take a snapshot of the headline.
11654 (save-match-data
11655 (setq org-agenda-headline-snapshot-before-repeat
11656 (org-get-heading))))
11657 (org-auto-repeat-maybe org-state))
11658 ;; Fixup cursor location if close to the keyword
11659 (if (and (outline-on-heading-p)
11660 (not (bolp))
11661 (save-excursion (beginning-of-line 1)
11662 (looking-at org-todo-line-regexp))
11663 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11664 (progn
11665 (goto-char (or (match-end 2) (match-end 1)))
11666 (and (looking-at " ") (just-one-space))))
11667 (when org-trigger-hook
11668 (save-excursion
11669 (run-hook-with-args 'org-trigger-hook change-plist)))
11670 (when commentp (org-toggle-comment))))))))
11672 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11673 "Block turning an entry into a TODO, using the hierarchy.
11674 This checks whether the current task should be blocked from state
11675 changes. Such blocking occurs when:
11677 1. The task has children which are not all in a completed state.
11679 2. A task has a parent with the property :ORDERED:, and there
11680 are siblings prior to the current task with incomplete
11681 status.
11683 3. The parent of the task is blocked because it has siblings that should
11684 be done first, or is child of a block grandparent TODO entry."
11686 (if (not org-enforce-todo-dependencies)
11687 t ; if locally turned off don't block
11688 (catch 'dont-block
11689 ;; If this is not a todo state change, or if this entry is already DONE,
11690 ;; do not block
11691 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11692 (member (plist-get change-plist :from)
11693 (cons 'done org-done-keywords))
11694 (member (plist-get change-plist :to)
11695 (cons 'todo org-not-done-keywords))
11696 (not (plist-get change-plist :to)))
11697 (throw 'dont-block t))
11698 ;; If this task has children, and any are undone, it's blocked
11699 (save-excursion
11700 (org-back-to-heading t)
11701 (let ((this-level (funcall outline-level)))
11702 (outline-next-heading)
11703 (let ((child-level (funcall outline-level)))
11704 (while (and (not (eobp))
11705 (> child-level this-level))
11706 ;; this todo has children, check whether they are all
11707 ;; completed
11708 (if (and (not (org-entry-is-done-p))
11709 (org-entry-is-todo-p))
11710 (throw 'dont-block nil))
11711 (outline-next-heading)
11712 (setq child-level (funcall outline-level))))))
11713 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11714 ;; any previous siblings are undone, it's blocked
11715 (save-excursion
11716 (org-back-to-heading t)
11717 (let* ((pos (point))
11718 (parent-pos (and (org-up-heading-safe) (point))))
11719 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11720 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11721 (forward-line 1)
11722 (re-search-forward org-not-done-heading-regexp pos t))
11723 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11724 ;; Search further up the hierarchy, to see if an ancestor is blocked
11725 (while t
11726 (goto-char parent-pos)
11727 (if (not (looking-at org-not-done-heading-regexp))
11728 (throw 'dont-block t)) ; do not block, parent is not a TODO
11729 (setq pos (point))
11730 (setq parent-pos (and (org-up-heading-safe) (point)))
11731 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11732 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11733 (forward-line 1)
11734 (re-search-forward org-not-done-heading-regexp pos t))
11735 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11737 (defcustom org-track-ordered-property-with-tag nil
11738 "Should the ORDERED property also be shown as a tag?
11739 The ORDERED property decides if an entry should require subtasks to be
11740 completed in sequence. Since a property is not very visible, setting
11741 this option means that toggling the ORDERED property with the command
11742 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11743 not relevant for the behavior, but it makes things more visible.
11745 Note that toggling the tag with tags commands will not change the property
11746 and therefore not influence behavior!
11748 This can be t, meaning the tag ORDERED should be used, It can also be a
11749 string to select a different tag for this task."
11750 :group 'org-todo
11751 :type '(choice
11752 (const :tag "No tracking" nil)
11753 (const :tag "Track with ORDERED tag" t)
11754 (string :tag "Use other tag")))
11756 (defun org-toggle-ordered-property ()
11757 "Toggle the ORDERED property of the current entry.
11758 For better visibility, you can track the value of this property with a tag.
11759 See variable `org-track-ordered-property-with-tag'."
11760 (interactive)
11761 (let* ((t1 org-track-ordered-property-with-tag)
11762 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11763 (save-excursion
11764 (org-back-to-heading)
11765 (if (org-entry-get nil "ORDERED")
11766 (progn
11767 (org-delete-property "ORDERED")
11768 (and tag (org-toggle-tag tag 'off))
11769 (message "Subtasks can be completed in arbitrary order"))
11770 (org-entry-put nil "ORDERED" "t")
11771 (and tag (org-toggle-tag tag 'on))
11772 (message "Subtasks must be completed in sequence")))))
11774 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11775 (defun org-block-todo-from-checkboxes (change-plist)
11776 "Block turning an entry into a TODO, using checkboxes.
11777 This checks whether the current task should be blocked from state
11778 changes because there are unchecked boxes in this entry."
11779 (if (not org-enforce-todo-checkbox-dependencies)
11780 t ; if locally turned off don't block
11781 (catch 'dont-block
11782 ;; If this is not a todo state change, or if this entry is already DONE,
11783 ;; do not block
11784 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11785 (member (plist-get change-plist :from)
11786 (cons 'done org-done-keywords))
11787 (member (plist-get change-plist :to)
11788 (cons 'todo org-not-done-keywords))
11789 (not (plist-get change-plist :to)))
11790 (throw 'dont-block t))
11791 ;; If this task has checkboxes that are not checked, it's blocked
11792 (save-excursion
11793 (org-back-to-heading t)
11794 (let ((beg (point)) end)
11795 (outline-next-heading)
11796 (setq end (point))
11797 (goto-char beg)
11798 (if (org-list-search-forward
11799 (concat (org-item-beginning-re)
11800 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11801 "\\[[- ]\\]")
11802 end t)
11803 (progn
11804 (if (boundp 'org-blocked-by-checkboxes)
11805 (setq org-blocked-by-checkboxes t))
11806 (throw 'dont-block nil)))))
11807 t))) ; do not block
11809 (defun org-entry-blocked-p ()
11810 "Is the current entry blocked?"
11811 (org-with-buffer-modified-unmodified
11812 (if (org-entry-get nil "NOBLOCKING")
11813 nil ;; Never block this entry
11814 (not
11815 (run-hook-with-args-until-failure
11816 'org-blocker-hook
11817 (list :type 'todo-state-change
11818 :position (point)
11819 :from 'todo
11820 :to 'done))))))
11822 (defun org-update-statistics-cookies (all)
11823 "Update the statistics cookie, either from TODO or from checkboxes.
11824 This should be called with the cursor in a line with a statistics cookie."
11825 (interactive "P")
11826 (if all
11827 (progn
11828 (org-update-checkbox-count 'all)
11829 (org-map-entries 'org-update-parent-todo-statistics))
11830 (if (not (org-at-heading-p))
11831 (org-update-checkbox-count)
11832 (let ((pos (point-marker))
11833 end l1 l2)
11834 (ignore-errors (org-back-to-heading t))
11835 (if (not (org-at-heading-p))
11836 (org-update-checkbox-count)
11837 (setq l1 (org-outline-level))
11838 (setq end (save-excursion
11839 (outline-next-heading)
11840 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11841 (point)))
11842 (if (and (save-excursion
11843 (re-search-forward
11844 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11845 (not (save-excursion (re-search-forward
11846 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11847 (org-update-checkbox-count)
11848 (if (and l2 (> l2 l1))
11849 (progn
11850 (goto-char end)
11851 (org-update-parent-todo-statistics))
11852 (goto-char pos)
11853 (beginning-of-line 1)
11854 (while (re-search-forward
11855 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11856 (point-at-eol) t)
11857 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11858 (goto-char pos)
11859 (move-marker pos nil)))))
11861 (defvar org-entry-property-inherited-from) ;; defined below
11862 (defun org-update-parent-todo-statistics ()
11863 "Update any statistics cookie in the parent of the current headline.
11864 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11865 the entire subtree and this will travel up the hierarchy and update
11866 statistics everywhere."
11867 (let* ((prop (save-excursion (org-up-heading-safe)
11868 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11869 (recursive (or (not org-hierarchical-todo-statistics)
11870 (and prop (string-match "\\<recursive\\>" prop))))
11871 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11873 (first t)
11874 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11875 level ltoggle l1 new ndel
11876 (cnt-all 0) (cnt-done 0) is-percent kwd
11877 checkbox-beg ov ovs ove cookie-present)
11878 (catch 'exit
11879 (save-excursion
11880 (beginning-of-line 1)
11881 (setq ltoggle (funcall outline-level))
11882 ;; Three situations are to consider:
11884 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11885 ;; to the top-level ancestor on the headline;
11887 ;; 2. If parent has "recursive" property, repeat up to the
11888 ;; headline setting that property, taking inheritance into
11889 ;; account;
11891 ;; 3. Else, move up to direct parent and proceed only once.
11892 (while (and (setq level (org-up-heading-safe))
11893 (or recursive first)
11894 (>= (point) lim))
11895 (setq first nil cookie-present nil)
11896 (unless (and level
11897 (not (string-match
11898 "\\<checkbox\\>"
11899 (downcase (or (org-entry-get nil "COOKIE_DATA")
11900 "")))))
11901 (throw 'exit nil))
11902 (while (re-search-forward box-re (point-at-eol) t)
11903 (setq cnt-all 0 cnt-done 0 cookie-present t)
11904 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11905 (save-match-data
11906 (unless (outline-next-heading) (throw 'exit nil))
11907 (while (and (looking-at org-complex-heading-regexp)
11908 (> (setq l1 (length (match-string 1))) level))
11909 (setq kwd (and (or recursive (= l1 ltoggle))
11910 (match-string 2)))
11911 (if (or (eq org-provide-todo-statistics 'all-headlines)
11912 (and (listp org-provide-todo-statistics)
11913 (or (member kwd org-provide-todo-statistics)
11914 (member kwd org-done-keywords))))
11915 (setq cnt-all (1+ cnt-all))
11916 (if (eq org-provide-todo-statistics t)
11917 (and kwd (setq cnt-all (1+ cnt-all)))))
11918 (and (member kwd org-done-keywords)
11919 (setq cnt-done (1+ cnt-done)))
11920 (outline-next-heading)))
11921 (setq new
11922 (if is-percent
11923 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11924 (format "[%d/%d]" cnt-done cnt-all))
11925 ndel (- (match-end 0) checkbox-beg))
11926 ;; handle overlays when updating cookie from column view
11927 (when (setq ov (car (overlays-at checkbox-beg)))
11928 (setq ovs (overlay-start ov) ove (overlay-end ov))
11929 (delete-overlay ov))
11930 (goto-char checkbox-beg)
11931 (insert new)
11932 (delete-region (point) (+ (point) ndel))
11933 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11934 (when ov (move-overlay ov ovs ove)))
11935 (when cookie-present
11936 (run-hook-with-args 'org-after-todo-statistics-hook
11937 cnt-done (- cnt-all cnt-done))))))
11938 (run-hooks 'org-todo-statistics-hook)))
11940 (defvar org-after-todo-statistics-hook nil
11941 "Hook that is called after a TODO statistics cookie has been updated.
11942 Each function is called with two arguments: the number of not-done entries
11943 and the number of done entries.
11945 For example, the following function, when added to this hook, will switch
11946 an entry to DONE when all children are done, and back to TODO when new
11947 entries are set to a TODO status. Note that this hook is only called
11948 when there is a statistics cookie in the headline!
11950 (defun org-summary-todo (n-done n-not-done)
11951 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11952 (let (org-log-done org-log-states) ; turn off logging
11953 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11956 (defvar org-todo-statistics-hook nil
11957 "Hook that is run whenever Org thinks TODO statistics should be updated.
11958 This hook runs even if there is no statistics cookie present, in which case
11959 `org-after-todo-statistics-hook' would not run.")
11961 (defun org-todo-trigger-tag-changes (state)
11962 "Apply the changes defined in `org-todo-state-tags-triggers'."
11963 (let ((l org-todo-state-tags-triggers)
11964 changes)
11965 (when (or (not state) (equal state ""))
11966 (setq changes (append changes (cdr (assoc "" l)))))
11967 (when (and (stringp state) (> (length state) 0))
11968 (setq changes (append changes (cdr (assoc state l)))))
11969 (when (member state org-not-done-keywords)
11970 (setq changes (append changes (cdr (assoc 'todo l)))))
11971 (when (member state org-done-keywords)
11972 (setq changes (append changes (cdr (assoc 'done l)))))
11973 (dolist (c changes)
11974 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11976 (defun org-local-logging (value)
11977 "Get logging settings from a property VALUE."
11978 (let* (words w a)
11979 ;; directly set the variables, they are already local.
11980 (setq org-log-done nil
11981 org-log-repeat nil
11982 org-todo-log-states nil)
11983 (setq words (org-split-string value))
11984 (while (setq w (pop words))
11985 (cond
11986 ((setq a (assoc w org-startup-options))
11987 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11988 (set (nth 1 a) (nth 2 a))))
11989 ((setq a (org-extract-log-state-settings w))
11990 (and (member (car a) org-todo-keywords-1)
11991 (push a org-todo-log-states)))))))
11993 (defun org-get-todo-sequence-head (kwd)
11994 "Return the head of the TODO sequence to which KWD belongs.
11995 If KWD is not set, check if there is a text property remembering the
11996 right sequence."
11997 (let (p)
11998 (cond
11999 ((not kwd)
12000 (or (get-text-property (point-at-bol) 'org-todo-head)
12001 (progn
12002 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12003 nil (point-at-eol)))
12004 (get-text-property p 'org-todo-head))))
12005 ((not (member kwd org-todo-keywords-1))
12006 (car org-todo-keywords-1))
12007 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12009 (defun org-fast-todo-selection ()
12010 "Fast TODO keyword selection with single keys.
12011 Returns the new TODO keyword, or nil if no state change should occur."
12012 (let* ((fulltable org-todo-key-alist)
12013 (done-keywords org-done-keywords) ;; needed for the faces.
12014 (maxlen (apply 'max (mapcar
12015 (lambda (x)
12016 (if (stringp (car x)) (string-width (car x)) 0))
12017 fulltable)))
12018 (expert nil)
12019 (fwidth (+ maxlen 3 1 3))
12020 (ncol (/ (- (window-width) 4) fwidth))
12021 tg cnt e c tbl
12022 groups ingroup)
12023 (save-excursion
12024 (save-window-excursion
12025 (if expert
12026 (set-buffer (get-buffer-create " *Org todo*"))
12027 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12028 (erase-buffer)
12029 (org-set-local 'org-done-keywords done-keywords)
12030 (setq tbl fulltable cnt 0)
12031 (while (setq e (pop tbl))
12032 (cond
12033 ((equal e '(:startgroup))
12034 (push '() groups) (setq ingroup t)
12035 (when (not (= cnt 0))
12036 (setq cnt 0)
12037 (insert "\n"))
12038 (insert "{ "))
12039 ((equal e '(:endgroup))
12040 (setq ingroup nil cnt 0)
12041 (insert "}\n"))
12042 ((equal e '(:newline))
12043 (when (not (= cnt 0))
12044 (setq cnt 0)
12045 (insert "\n")
12046 (setq e (car tbl))
12047 (while (equal (car tbl) '(:newline))
12048 (insert "\n")
12049 (setq tbl (cdr tbl)))))
12051 (setq tg (car e) c (cdr e))
12052 (if ingroup (push tg (car groups)))
12053 (setq tg (org-add-props tg nil 'face
12054 (org-get-todo-face tg)))
12055 (if (and (= cnt 0) (not ingroup)) (insert " "))
12056 (insert "[" c "] " tg (make-string
12057 (- fwidth 4 (length tg)) ?\ ))
12058 (when (= (setq cnt (1+ cnt)) ncol)
12059 (insert "\n")
12060 (if ingroup (insert " "))
12061 (setq cnt 0)))))
12062 (insert "\n")
12063 (goto-char (point-min))
12064 (if (not expert) (org-fit-window-to-buffer))
12065 (message "[a-z..]:Set [SPC]:clear")
12066 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12067 (cond
12068 ((or (= c ?\C-g)
12069 (and (= c ?q) (not (rassoc c fulltable))))
12070 (setq quit-flag t))
12071 ((= c ?\ ) nil)
12072 ((setq e (rassoc c fulltable) tg (car e))
12074 (t (setq quit-flag t)))))))
12076 (defun org-entry-is-todo-p ()
12077 (member (org-get-todo-state) org-not-done-keywords))
12079 (defun org-entry-is-done-p ()
12080 (member (org-get-todo-state) org-done-keywords))
12082 (defun org-get-todo-state ()
12083 (save-excursion
12084 (org-back-to-heading t)
12085 (and (looking-at org-todo-line-regexp)
12086 (match-end 2)
12087 (match-string 2))))
12089 (defun org-at-date-range-p (&optional inactive-ok)
12090 "Is the cursor inside a date range?"
12091 (interactive)
12092 (save-excursion
12093 (catch 'exit
12094 (let ((pos (point)))
12095 (skip-chars-backward "^[<\r\n")
12096 (skip-chars-backward "<[")
12097 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12098 (>= (match-end 0) pos)
12099 (throw 'exit t))
12100 (skip-chars-backward "^<[\r\n")
12101 (skip-chars-backward "<[")
12102 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12103 (>= (match-end 0) pos)
12104 (throw 'exit t)))
12105 nil)))
12107 (defun org-get-repeat (&optional tagline)
12108 "Check if there is a deadline/schedule with repeater in this entry."
12109 (save-match-data
12110 (save-excursion
12111 (org-back-to-heading t)
12112 (and (re-search-forward (if tagline
12113 (concat tagline "\\s-*" org-repeat-re)
12114 org-repeat-re)
12115 (org-entry-end-position) t)
12116 (match-string-no-properties 1)))))
12118 (defvar org-last-changed-timestamp)
12119 (defvar org-last-inserted-timestamp)
12120 (defvar org-log-post-message)
12121 (defvar org-log-note-purpose)
12122 (defvar org-log-note-how)
12123 (defvar org-log-note-extra)
12124 (defun org-auto-repeat-maybe (done-word)
12125 "Check if the current headline contains a repeated deadline/schedule.
12126 If yes, set TODO state back to what it was and change the base date
12127 of repeating deadline/scheduled time stamps to new date.
12128 This function is run automatically after each state change to a DONE state."
12129 ;; last-state is dynamically scoped into this function
12130 (let* ((repeat (org-get-repeat))
12131 (aa (assoc org-last-state org-todo-kwd-alist))
12132 (interpret (nth 1 aa))
12133 (head (nth 2 aa))
12134 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12135 (msg "Entry repeats: ")
12136 (org-log-done nil)
12137 (org-todo-log-states nil)
12138 re type n what ts time to-state)
12139 (when repeat
12140 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12141 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12142 org-todo-repeat-to-state))
12143 (unless (and to-state (member to-state org-todo-keywords-1))
12144 (setq to-state (if (eq interpret 'type) org-last-state head)))
12145 (org-todo to-state)
12146 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12147 (org-entry-put nil "LAST_REPEAT" (format-time-string
12148 (org-time-stamp-format t t))))
12149 (when org-log-repeat
12150 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12151 (memq 'org-add-log-note post-command-hook))
12152 ;; OK, we are already setup for some record
12153 (if (eq org-log-repeat 'note)
12154 ;; make sure we take a note, not only a time stamp
12155 (setq org-log-note-how 'note))
12156 ;; Set up for taking a record
12157 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12158 org-last-state
12159 'findpos org-log-repeat)))
12160 (org-back-to-heading t)
12161 (org-add-planning-info nil nil 'closed)
12162 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12163 org-deadline-time-regexp "\\)\\|\\("
12164 org-ts-regexp "\\)"))
12165 (while (re-search-forward
12166 re (save-excursion (outline-next-heading) (point)) t)
12167 (setq type (if (match-end 1) org-scheduled-string
12168 (if (match-end 3) org-deadline-string "Plain:"))
12169 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12170 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12171 (setq n (string-to-number (match-string 2 ts))
12172 what (match-string 3 ts))
12173 (if (equal what "w") (setq n (* n 7) what "d"))
12174 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12175 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12176 ;; Preparation, see if we need to modify the start date for the change
12177 (when (match-end 1)
12178 (setq time (save-match-data (org-time-string-to-time ts)))
12179 (cond
12180 ((equal (match-string 1 ts) ".")
12181 ;; Shift starting date to today
12182 (org-timestamp-change
12183 (- (org-today) (time-to-days time))
12184 'day))
12185 ((equal (match-string 1 ts) "+")
12186 (let ((nshiftmax 10) (nshift 0))
12187 (while (or (= nshift 0)
12188 (<= (time-to-days time)
12189 (time-to-days (current-time))))
12190 (when (= (incf nshift) nshiftmax)
12191 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12192 (error "Abort")))
12193 (org-timestamp-change n (cdr (assoc what whata)))
12194 (org-at-timestamp-p t)
12195 (setq ts (match-string 1))
12196 (setq time (save-match-data (org-time-string-to-time ts)))))
12197 (org-timestamp-change (- n) (cdr (assoc what whata)))
12198 ;; rematch, so that we have everything in place for the real shift
12199 (org-at-timestamp-p t)
12200 (setq ts (match-string 1))
12201 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12202 (org-timestamp-change n (cdr (assoc what whata)))
12203 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12204 (setq org-log-post-message msg)
12205 (message "%s" msg))))
12207 (defun org-show-todo-tree (arg)
12208 "Make a compact tree which shows all headlines marked with TODO.
12209 The tree will show the lines where the regexp matches, and all higher
12210 headlines above the match.
12211 With a \\[universal-argument] prefix, prompt for a regexp to match.
12212 With a numeric prefix N, construct a sparse tree for the Nth element
12213 of `org-todo-keywords-1'."
12214 (interactive "P")
12215 (let ((case-fold-search nil)
12216 (kwd-re
12217 (cond ((null arg) org-not-done-regexp)
12218 ((equal arg '(4))
12219 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12220 (mapcar 'list org-todo-keywords-1))))
12221 (concat "\\("
12222 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12223 "\\)\\>")))
12224 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12225 (regexp-quote (nth (1- (prefix-numeric-value arg))
12226 org-todo-keywords-1)))
12227 (t (error "Invalid prefix argument: %s" arg)))))
12228 (message "%d TODO entries found"
12229 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12231 (defun org-deadline (&optional remove time)
12232 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12233 With argument REMOVE, remove any deadline from the item.
12234 With argument TIME, set the deadline at the corresponding date. TIME
12235 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12236 (interactive "P")
12237 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12238 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12239 'region-start-level 'region))
12240 org-loop-over-headlines-in-active-region)
12241 (org-map-entries
12242 `(org-deadline ',remove ,time)
12243 org-loop-over-headlines-in-active-region
12244 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12245 (let* ((old-date (org-entry-get nil "DEADLINE"))
12246 (repeater (and old-date
12247 (string-match
12248 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12249 old-date)
12250 (match-string 1 old-date))))
12251 (if remove
12252 (progn
12253 (when (and old-date org-log-redeadline)
12254 (org-add-log-setup 'deldeadline nil old-date 'findpos
12255 org-log-redeadline))
12256 (org-remove-timestamp-with-keyword org-deadline-string)
12257 (message "Item no longer has a deadline."))
12258 (org-add-planning-info 'deadline time 'closed)
12259 (when (and old-date org-log-redeadline
12260 (not (equal old-date
12261 (substring org-last-inserted-timestamp 1 -1))))
12262 (org-add-log-setup 'redeadline nil old-date 'findpos
12263 org-log-redeadline))
12264 (when repeater
12265 (save-excursion
12266 (org-back-to-heading t)
12267 (when (re-search-forward (concat org-deadline-string " "
12268 org-last-inserted-timestamp)
12269 (save-excursion
12270 (outline-next-heading) (point)) t)
12271 (goto-char (1- (match-end 0)))
12272 (insert " " repeater)
12273 (setq org-last-inserted-timestamp
12274 (concat (substring org-last-inserted-timestamp 0 -1)
12275 " " repeater
12276 (substring org-last-inserted-timestamp -1))))))
12277 (message "Deadline on %s" org-last-inserted-timestamp)))))
12279 (defun org-schedule (&optional remove time)
12280 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12281 With argument REMOVE, remove any scheduling date from the item.
12282 With argument TIME, scheduled at the corresponding date. TIME can
12283 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12284 (interactive "P")
12285 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12286 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12287 'region-start-level 'region))
12288 org-loop-over-headlines-in-active-region)
12289 (org-map-entries
12290 `(org-schedule ',remove ,time)
12291 org-loop-over-headlines-in-active-region
12292 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12293 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12294 (repeater (and old-date
12295 (string-match
12296 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12297 old-date)
12298 (match-string 1 old-date))))
12299 (if remove
12300 (progn
12301 (when (and old-date org-log-reschedule)
12302 (org-add-log-setup 'delschedule nil old-date 'findpos
12303 org-log-reschedule))
12304 (org-remove-timestamp-with-keyword org-scheduled-string)
12305 (message "Item is no longer scheduled."))
12306 (org-add-planning-info 'scheduled time 'closed)
12307 (when (and old-date org-log-reschedule
12308 (not (equal old-date
12309 (substring org-last-inserted-timestamp 1 -1))))
12310 (org-add-log-setup 'reschedule nil old-date 'findpos
12311 org-log-reschedule))
12312 (when repeater
12313 (save-excursion
12314 (org-back-to-heading t)
12315 (when (re-search-forward (concat org-scheduled-string " "
12316 org-last-inserted-timestamp)
12317 (save-excursion
12318 (outline-next-heading) (point)) t)
12319 (goto-char (1- (match-end 0)))
12320 (insert " " repeater)
12321 (setq org-last-inserted-timestamp
12322 (concat (substring org-last-inserted-timestamp 0 -1)
12323 " " repeater
12324 (substring org-last-inserted-timestamp -1))))))
12325 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12327 (defun org-get-scheduled-time (pom &optional inherit)
12328 "Get the scheduled time as a time tuple, of a format suitable
12329 for calling org-schedule with, or if there is no scheduling,
12330 returns nil."
12331 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12332 (when time
12333 (apply 'encode-time (org-parse-time-string time)))))
12335 (defun org-get-deadline-time (pom &optional inherit)
12336 "Get the deadline as a time tuple, of a format suitable for
12337 calling org-deadline with, or if there is no scheduling, returns
12338 nil."
12339 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12340 (when time
12341 (apply 'encode-time (org-parse-time-string time)))))
12343 (defun org-remove-timestamp-with-keyword (keyword)
12344 "Remove all time stamps with KEYWORD in the current entry."
12345 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12346 beg)
12347 (save-excursion
12348 (org-back-to-heading t)
12349 (setq beg (point))
12350 (outline-next-heading)
12351 (while (re-search-backward re beg t)
12352 (replace-match "")
12353 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12354 (equal (char-before) ?\ ))
12355 (backward-delete-char 1)
12356 (if (string-match "^[ \t]*$" (buffer-substring
12357 (point-at-bol) (point-at-eol)))
12358 (delete-region (point-at-bol)
12359 (min (point-max) (1+ (point-at-eol))))))))))
12361 (defun org-add-planning-info (what &optional time &rest remove)
12362 "Insert new timestamp with keyword in the line directly after the headline.
12363 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12364 If non is given, the user is prompted for a date.
12365 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12366 be removed."
12367 (interactive)
12368 (let (org-time-was-given org-end-time-was-given ts
12369 end default-time default-input)
12371 (catch 'exit
12372 (when (and (memq what '(scheduled deadline))
12373 (or (not time)
12374 (and (stringp time)
12375 (string-match "^[-+]+[0-9]" time))))
12376 ;; Try to get a default date/time from existing timestamp
12377 (save-excursion
12378 (org-back-to-heading t)
12379 (setq end (save-excursion (outline-next-heading) (point)))
12380 (when (re-search-forward (if (eq what 'scheduled)
12381 org-scheduled-time-regexp
12382 org-deadline-time-regexp)
12383 end t)
12384 (setq ts (match-string 1)
12385 default-time
12386 (apply 'encode-time (org-parse-time-string ts))
12387 default-input (and ts (org-get-compact-tod ts))))))
12388 (when what
12389 (setq time
12390 (if (stringp time)
12391 ;; This is a string (relative or absolute), set proper date
12392 (apply 'encode-time
12393 (org-read-date-analyze
12394 time default-time (decode-time default-time)))
12395 ;; If necessary, get the time from the user
12396 (or time (org-read-date nil 'to-time nil nil
12397 default-time default-input)))))
12399 (when (and org-insert-labeled-timestamps-at-point
12400 (member what '(scheduled deadline)))
12401 (insert
12402 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12403 (org-insert-time-stamp time org-time-was-given
12404 nil nil nil (list org-end-time-was-given))
12405 (setq what nil))
12406 (save-excursion
12407 (save-restriction
12408 (let (col list elt ts buffer-invisibility-spec)
12409 (org-back-to-heading t)
12410 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12411 (goto-char (match-end 1))
12412 (setq col (current-column))
12413 (goto-char (match-end 0))
12414 (if (eobp) (insert "\n") (forward-char 1))
12415 (when (and (not what)
12416 (not (looking-at
12417 (concat "[ \t]*"
12418 org-keyword-time-not-clock-regexp))))
12419 ;; Nothing to add, nothing to remove...... :-)
12420 (throw 'exit nil))
12421 (if (and (not (looking-at org-outline-regexp))
12422 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12423 "[^\r\n]*"))
12424 (not (equal (match-string 1) org-clock-string)))
12425 (narrow-to-region (match-beginning 0) (match-end 0))
12426 (insert-before-markers "\n")
12427 (backward-char 1)
12428 (narrow-to-region (point) (point))
12429 (and org-adapt-indentation (org-indent-to-column col)))
12430 ;; Check if we have to remove something.
12431 (setq list (cons what remove))
12432 (while list
12433 (setq elt (pop list))
12434 (when (or (and (eq elt 'scheduled)
12435 (re-search-forward org-scheduled-time-regexp nil t))
12436 (and (eq elt 'deadline)
12437 (re-search-forward org-deadline-time-regexp nil t))
12438 (and (eq elt 'closed)
12439 (re-search-forward org-closed-time-regexp nil t)))
12440 (replace-match "")
12441 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12442 (and (looking-at "[ \t]+") (replace-match ""))
12443 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12444 (when what
12445 (insert
12446 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12447 (cond ((eq what 'scheduled) org-scheduled-string)
12448 ((eq what 'deadline) org-deadline-string)
12449 ((eq what 'closed) org-closed-string))
12450 " ")
12451 (setq ts (org-insert-time-stamp
12452 time
12453 (or org-time-was-given
12454 (and (eq what 'closed) org-log-done-with-time))
12455 (eq what 'closed)
12456 nil nil (list org-end-time-was-given)))
12457 (insert
12458 (if (not (or (bolp) (eq (char-before) ?\ )
12459 (memq (char-after) '(32 10))
12460 (eobp))) " " ""))
12461 (end-of-line 1))
12462 (goto-char (point-min))
12463 (widen)
12464 (if (and (looking-at "[ \t]*\n")
12465 (equal (char-before) ?\n))
12466 (delete-region (1- (point)) (point-at-eol)))
12467 ts))))))
12469 (defvar org-log-note-marker (make-marker))
12470 (defvar org-log-note-purpose nil)
12471 (defvar org-log-note-state nil)
12472 (defvar org-log-note-previous-state nil)
12473 (defvar org-log-note-how nil)
12474 (defvar org-log-note-extra nil)
12475 (defvar org-log-note-window-configuration nil)
12476 (defvar org-log-note-return-to (make-marker))
12477 (defvar org-log-note-effective-time nil
12478 "Remembered current time so that dynamically scoped
12479 `org-extend-today-until' affects tha timestamps in state change
12480 log")
12482 (defvar org-log-post-message nil
12483 "Message to be displayed after a log note has been stored.
12484 The auto-repeater uses this.")
12486 (defun org-add-note ()
12487 "Add a note to the current entry.
12488 This is done in the same way as adding a state change note."
12489 (interactive)
12490 (org-add-log-setup 'note nil nil 'findpos nil))
12492 (defvar org-property-end-re)
12493 (defun org-add-log-setup (&optional purpose state prev-state
12494 findpos how extra)
12495 "Set up the post command hook to take a note.
12496 If this is about to TODO state change, the new state is expected in STATE.
12497 When FINDPOS is non-nil, find the correct position for the note in
12498 the current entry. If not, assume that it can be inserted at point.
12499 HOW is an indicator what kind of note should be created.
12500 EXTRA is additional text that will be inserted into the notes buffer."
12501 (let* ((org-log-into-drawer (org-log-into-drawer))
12502 (drawer (cond ((stringp org-log-into-drawer)
12503 org-log-into-drawer)
12504 (org-log-into-drawer "LOGBOOK"))))
12505 (save-restriction
12506 (save-excursion
12507 (when findpos
12508 (org-back-to-heading t)
12509 (narrow-to-region (point) (save-excursion
12510 (outline-next-heading) (point)))
12511 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12512 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12513 "[^\r\n]*\\)?"))
12514 (goto-char (match-end 0))
12515 (cond
12516 (drawer
12517 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12518 nil t)
12519 (progn
12520 (goto-char (match-end 0))
12521 (or org-log-states-order-reversed
12522 (and (re-search-forward org-property-end-re nil t)
12523 (goto-char (1- (match-beginning 0))))))
12524 (insert "\n:" drawer ":\n:END:")
12525 (beginning-of-line 0)
12526 (org-indent-line)
12527 (beginning-of-line 2)
12528 (org-indent-line)
12529 (end-of-line 0)))
12530 ((and org-log-state-notes-insert-after-drawers
12531 (save-excursion
12532 (forward-line) (looking-at org-drawer-regexp)))
12533 (forward-line)
12534 (while (looking-at org-drawer-regexp)
12535 (goto-char (match-end 0))
12536 (re-search-forward org-property-end-re (point-max) t)
12537 (forward-line))
12538 (forward-line -1)))
12539 (unless org-log-states-order-reversed
12540 (and (= (char-after) ?\n) (forward-char 1))
12541 (org-skip-over-state-notes)
12542 (skip-chars-backward " \t\n\r")))
12543 (move-marker org-log-note-marker (point))
12544 (setq org-log-note-purpose purpose
12545 org-log-note-state state
12546 org-log-note-previous-state prev-state
12547 org-log-note-how how
12548 org-log-note-extra extra
12549 org-log-note-effective-time (org-current-effective-time))
12550 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12552 (defun org-skip-over-state-notes ()
12553 "Skip past the list of State notes in an entry."
12554 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12555 (when (ignore-errors (goto-char (org-in-item-p)))
12556 (let* ((struct (org-list-struct))
12557 (prevs (org-list-prevs-alist struct)))
12558 (while (looking-at "[ \t]*- State")
12559 (goto-char (or (org-list-get-next-item (point) struct prevs)
12560 (org-list-get-item-end (point) struct)))))))
12562 (defun org-add-log-note (&optional purpose)
12563 "Pop up a window for taking a note, and add this note later at point."
12564 (remove-hook 'post-command-hook 'org-add-log-note)
12565 (setq org-log-note-window-configuration (current-window-configuration))
12566 (delete-other-windows)
12567 (move-marker org-log-note-return-to (point))
12568 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12569 (goto-char org-log-note-marker)
12570 (org-switch-to-buffer-other-window "*Org Note*")
12571 (erase-buffer)
12572 (if (memq org-log-note-how '(time state))
12573 (let (current-prefix-arg) (org-store-log-note))
12574 (let ((org-inhibit-startup t)) (org-mode))
12575 (insert (format "# Insert note for %s.
12576 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12577 (cond
12578 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12579 ((eq org-log-note-purpose 'done) "closed todo item")
12580 ((eq org-log-note-purpose 'state)
12581 (format "state change from \"%s\" to \"%s\""
12582 (or org-log-note-previous-state "")
12583 (or org-log-note-state "")))
12584 ((eq org-log-note-purpose 'reschedule)
12585 "rescheduling")
12586 ((eq org-log-note-purpose 'delschedule)
12587 "no longer scheduled")
12588 ((eq org-log-note-purpose 'redeadline)
12589 "changing deadline")
12590 ((eq org-log-note-purpose 'deldeadline)
12591 "removing deadline")
12592 ((eq org-log-note-purpose 'refile)
12593 "refiling")
12594 ((eq org-log-note-purpose 'note)
12595 "this entry")
12596 (t (error "This should not happen")))))
12597 (if org-log-note-extra (insert org-log-note-extra))
12598 (org-set-local 'org-finish-function 'org-store-log-note)
12599 (run-hooks 'org-log-buffer-setup-hook)))
12601 (defvar org-note-abort nil) ; dynamically scoped
12602 (defun org-store-log-note ()
12603 "Finish taking a log note, and insert it to where it belongs."
12604 (let ((txt (buffer-string))
12605 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12606 lines ind bul)
12607 (kill-buffer (current-buffer))
12608 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12609 (setq txt (replace-match "" t t txt)))
12610 (if (string-match "\\s-+\\'" txt)
12611 (setq txt (replace-match "" t t txt)))
12612 (setq lines (org-split-string txt "\n"))
12613 (when (and note (string-match "\\S-" note))
12614 (setq note
12615 (org-replace-escapes
12616 note
12617 (list (cons "%u" (user-login-name))
12618 (cons "%U" user-full-name)
12619 (cons "%t" (format-time-string
12620 (org-time-stamp-format 'long 'inactive)
12621 org-log-note-effective-time))
12622 (cons "%T" (format-time-string
12623 (org-time-stamp-format 'long nil)
12624 org-log-note-effective-time))
12625 (cons "%d" (format-time-string
12626 (org-time-stamp-format nil 'inactive)
12627 org-log-note-effective-time))
12628 (cons "%D" (format-time-string
12629 (org-time-stamp-format nil nil)
12630 org-log-note-effective-time))
12631 (cons "%s" (if org-log-note-state
12632 (concat "\"" org-log-note-state "\"")
12633 ""))
12634 (cons "%S" (if org-log-note-previous-state
12635 (concat "\"" org-log-note-previous-state "\"")
12636 "\"\"")))))
12637 (if lines (setq note (concat note " \\\\")))
12638 (push note lines))
12639 (when (or current-prefix-arg org-note-abort)
12640 (when org-log-into-drawer
12641 (org-remove-empty-drawer-at
12642 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12643 org-log-note-marker))
12644 (setq lines nil))
12645 (when lines
12646 (with-current-buffer (marker-buffer org-log-note-marker)
12647 (save-excursion
12648 (goto-char org-log-note-marker)
12649 (move-marker org-log-note-marker nil)
12650 (end-of-line 1)
12651 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12652 (setq ind (save-excursion
12653 (if (ignore-errors (goto-char (org-in-item-p)))
12654 (let ((struct (org-list-struct)))
12655 (org-list-get-ind
12656 (org-list-get-top-point struct) struct))
12657 (skip-chars-backward " \r\t\n")
12658 (cond
12659 ((and (org-at-heading-p)
12660 org-adapt-indentation)
12661 (1+ (org-current-level)))
12662 ((org-at-heading-p) 0)
12663 (t (org-get-indentation))))))
12664 (setq bul (org-list-bullet-string "-"))
12665 (org-indent-line-to ind)
12666 (insert bul (pop lines))
12667 (let ((ind-body (+ (length bul) ind)))
12668 (while lines
12669 (insert "\n")
12670 (org-indent-line-to ind-body)
12671 (insert (pop lines))))
12672 (message "Note stored")
12673 (org-back-to-heading t)
12674 (org-cycle-hide-drawers 'children)))))
12675 (set-window-configuration org-log-note-window-configuration)
12676 (with-current-buffer (marker-buffer org-log-note-return-to)
12677 (goto-char org-log-note-return-to))
12678 (move-marker org-log-note-return-to nil)
12679 (and org-log-post-message (message "%s" org-log-post-message)))
12681 (defun org-remove-empty-drawer-at (drawer pos)
12682 "Remove an empty drawer DRAWER at position POS.
12683 POS may also be a marker."
12684 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12685 (save-excursion
12686 (save-restriction
12687 (widen)
12688 (goto-char pos)
12689 (if (org-in-regexp
12690 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12691 (replace-match ""))))))
12693 (defvar org-ts-type nil)
12694 (defun org-sparse-tree (&optional arg type)
12695 "Create a sparse tree, prompt for the details.
12696 This command can create sparse trees. You first need to select the type
12697 of match used to create the tree:
12699 t Show all TODO entries.
12700 T Show entries with a specific TODO keyword.
12701 m Show entries selected by a tags/property match.
12702 p Enter a property name and its value (both with completion on existing
12703 names/values) and show entries with that property.
12704 r Show entries matching a regular expression (`/' can be used as well).
12705 b Show deadlines and scheduled items before a date.
12706 a Show deadlines and scheduled items after a date.
12707 d Show deadlines due within `org-deadline-warning-days'.
12708 D Show deadlines and scheduled items between a date range."
12709 (interactive "P")
12710 (let (ans kwd value ts-type)
12711 (setq type (or type org-sparse-tree-default-date-type))
12712 (setq org-ts-type type)
12713 (message "Sparse tree: [/]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"
12714 (cond ((eq type 'all) "all timestamps")
12715 ((eq type 'scheduled) "only scheduled")
12716 ((eq type 'deadline) "only deadline")
12717 ((eq type 'active) "only active timestamps")
12718 ((eq type 'inactive) "only inactive timestamps")
12719 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12720 (t "scheduled/deadline")))
12721 (setq ans (read-char-exclusive))
12722 (cond
12723 ((equal ans ?c)
12724 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12725 ((equal ans ?d)
12726 (call-interactively 'org-check-deadlines))
12727 ((equal ans ?b)
12728 (call-interactively 'org-check-before-date))
12729 ((equal ans ?a)
12730 (call-interactively 'org-check-after-date))
12731 ((equal ans ?D)
12732 (call-interactively 'org-check-dates-range))
12733 ((equal ans ?t)
12734 (call-interactively 'org-show-todo-tree))
12735 ((equal ans ?T)
12736 (org-show-todo-tree '(4)))
12737 ((member ans '(?T ?m))
12738 (call-interactively 'org-match-sparse-tree))
12739 ((member ans '(?p ?P))
12740 (setq kwd (org-icompleting-read "Property: "
12741 (mapcar 'list (org-buffer-property-keys))))
12742 (setq value (org-icompleting-read "Value: "
12743 (mapcar 'list (org-property-values kwd))))
12744 (unless (string-match "\\`{.*}\\'" value)
12745 (setq value (concat "\"" value "\"")))
12746 (org-match-sparse-tree arg (concat kwd "=" value)))
12747 ((member ans '(?r ?R ?/))
12748 (call-interactively 'org-occur))
12749 (t (error "No such sparse tree command \"%c\"" ans)))))
12751 (defvar org-occur-highlights nil
12752 "List of overlays used for occur matches.")
12753 (make-variable-buffer-local 'org-occur-highlights)
12754 (defvar org-occur-parameters nil
12755 "Parameters of the active org-occur calls.
12756 This is a list, each call to org-occur pushes as cons cell,
12757 containing the regular expression and the callback, onto the list.
12758 The list can contain several entries if `org-occur' has been called
12759 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12760 will only contain one set of parameters. When the highlights are
12761 removed (for example with `C-c C-c', or with the next edit (depending
12762 on `org-remove-highlights-with-change'), this variable is emptied
12763 as well.")
12764 (make-variable-buffer-local 'org-occur-parameters)
12766 (defun org-occur (regexp &optional keep-previous callback)
12767 "Make a compact tree which shows all matches of REGEXP.
12768 The tree will show the lines where the regexp matches, and all higher
12769 headlines above the match. It will also show the heading after the match,
12770 to make sure editing the matching entry is easy.
12771 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12772 call to `org-occur' will be kept, to allow stacking of calls to this
12773 command.
12774 If CALLBACK is non-nil, it is a function which is called to confirm
12775 that the match should indeed be shown."
12776 (interactive "sRegexp: \nP")
12777 (when (equal regexp "")
12778 (error "Regexp cannot be empty"))
12779 (unless keep-previous
12780 (org-remove-occur-highlights nil nil t))
12781 (push (cons regexp callback) org-occur-parameters)
12782 (let ((cnt 0))
12783 (save-excursion
12784 (goto-char (point-min))
12785 (if (or (not keep-previous) ; do not want to keep
12786 (not org-occur-highlights)) ; no previous matches
12787 ;; hide everything
12788 (org-overview))
12789 (while (re-search-forward regexp nil t)
12790 (when (or (not callback)
12791 (save-match-data (funcall callback)))
12792 (setq cnt (1+ cnt))
12793 (when org-highlight-sparse-tree-matches
12794 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12795 (org-show-context 'occur-tree))))
12796 (when org-remove-highlights-with-change
12797 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12798 nil 'local))
12799 (unless org-sparse-tree-open-archived-trees
12800 (org-hide-archived-subtrees (point-min) (point-max)))
12801 (run-hooks 'org-occur-hook)
12802 (if (org-called-interactively-p 'interactive)
12803 (message "%d match(es) for regexp %s" cnt regexp))
12804 cnt))
12806 (defun org-occur-next-match (&optional n reset)
12807 "Function for `next-error-function' to find sparse tree matches.
12808 N is the number of matches to move, when negative move backwards.
12809 RESET is entirely ignored - this function always goes back to the
12810 starting point when no match is found."
12811 (let* ((limit (if (< n 0) (point-min) (point-max)))
12812 (search-func (if (< n 0)
12813 'previous-single-char-property-change
12814 'next-single-char-property-change))
12815 (n (abs n))
12816 (pos (point))
12818 (catch 'exit
12819 (while (setq p1 (funcall search-func (point) 'org-type))
12820 (when (equal p1 limit)
12821 (goto-char pos)
12822 (error "No more matches"))
12823 (when (equal (get-char-property p1 'org-type) 'org-occur)
12824 (setq n (1- n))
12825 (when (= n 0)
12826 (goto-char p1)
12827 (throw 'exit (point))))
12828 (goto-char p1))
12829 (goto-char p1)
12830 (error "No more matches"))))
12832 (defun org-show-context (&optional key)
12833 "Make sure point and context are visible.
12834 How much context is shown depends upon the variables
12835 `org-show-hierarchy-above', `org-show-following-heading',
12836 `org-show-entry-below' and `org-show-siblings'."
12837 (let ((heading-p (org-at-heading-p t))
12838 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12839 (following-p (org-get-alist-option org-show-following-heading key))
12840 (entry-p (org-get-alist-option org-show-entry-below key))
12841 (siblings-p (org-get-alist-option org-show-siblings key)))
12842 (catch 'exit
12843 ;; Show heading or entry text
12844 (if (and heading-p (not entry-p))
12845 (org-flag-heading nil) ; only show the heading
12846 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12847 (org-show-hidden-entry))) ; show entire entry
12848 (when following-p
12849 ;; Show next sibling, or heading below text
12850 (save-excursion
12851 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12852 (org-flag-heading nil))))
12853 (when siblings-p (org-show-siblings))
12854 (when hierarchy-p
12855 ;; show all higher headings, possibly with siblings
12856 (save-excursion
12857 (while (and (condition-case nil
12858 (progn (org-up-heading-all 1) t)
12859 (error nil))
12860 (not (bobp)))
12861 (org-flag-heading nil)
12862 (when siblings-p (org-show-siblings))))))))
12864 (defvar org-reveal-start-hook nil
12865 "Hook run before revealing a location.")
12867 (defun org-reveal (&optional siblings)
12868 "Show current entry, hierarchy above it, and the following headline.
12869 This can be used to show a consistent set of context around locations
12870 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12871 not t for the search context.
12873 With optional argument SIBLINGS, on each level of the hierarchy all
12874 siblings are shown. This repairs the tree structure to what it would
12875 look like when opened with hierarchical calls to `org-cycle'.
12876 With double optional argument \\[universal-argument] \\[universal-argument], \
12877 go to the parent and show the
12878 entire tree."
12879 (interactive "P")
12880 (run-hooks 'org-reveal-start-hook)
12881 (let ((org-show-hierarchy-above t)
12882 (org-show-following-heading t)
12883 (org-show-siblings (if siblings t org-show-siblings)))
12884 (org-show-context nil))
12885 (when (equal siblings '(16))
12886 (save-excursion
12887 (when (org-up-heading-safe)
12888 (org-show-subtree)
12889 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12891 (defun org-highlight-new-match (beg end)
12892 "Highlight from BEG to END and mark the highlight is an occur headline."
12893 (let ((ov (make-overlay beg end)))
12894 (overlay-put ov 'face 'secondary-selection)
12895 (overlay-put ov 'org-type 'org-occur)
12896 (push ov org-occur-highlights)))
12898 (defun org-remove-occur-highlights (&optional beg end noremove)
12899 "Remove the occur highlights from the buffer.
12900 BEG and END are ignored. If NOREMOVE is nil, remove this function
12901 from the `before-change-functions' in the current buffer."
12902 (interactive)
12903 (unless org-inhibit-highlight-removal
12904 (mapc 'delete-overlay org-occur-highlights)
12905 (setq org-occur-highlights nil)
12906 (setq org-occur-parameters nil)
12907 (unless noremove
12908 (remove-hook 'before-change-functions
12909 'org-remove-occur-highlights 'local))))
12911 ;;;; Priorities
12913 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12914 "Regular expression matching the priority indicator.")
12916 (defvar org-remove-priority-next-time nil)
12918 (defun org-priority-up ()
12919 "Increase the priority of the current item."
12920 (interactive)
12921 (org-priority 'up))
12923 (defun org-priority-down ()
12924 "Decrease the priority of the current item."
12925 (interactive)
12926 (org-priority 'down))
12928 (defun org-priority (&optional action show)
12929 "Change the priority of an item.
12930 ACTION can be `set', `up', `down', or a character."
12931 (interactive "P")
12932 (if (equal action '(4))
12933 (org-show-priority)
12934 (unless org-enable-priority-commands
12935 (error "Priority commands are disabled"))
12936 (setq action (or action 'set))
12937 (let (current new news have remove)
12938 (save-excursion
12939 (org-back-to-heading t)
12940 (if (looking-at org-priority-regexp)
12941 (setq current (string-to-char (match-string 2))
12942 have t))
12943 (cond
12944 ((eq action 'remove)
12945 (setq remove t new ?\ ))
12946 ((or (eq action 'set)
12947 (if (featurep 'xemacs) (characterp action) (integerp action)))
12948 (if (not (eq action 'set))
12949 (setq new action)
12950 (message "Priority %c-%c, SPC to remove: "
12951 org-highest-priority org-lowest-priority)
12952 (save-match-data
12953 (setq new (read-char-exclusive))))
12954 (if (and (= (upcase org-highest-priority) org-highest-priority)
12955 (= (upcase org-lowest-priority) org-lowest-priority))
12956 (setq new (upcase new)))
12957 (cond ((equal new ?\ ) (setq remove t))
12958 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12959 (error "Priority must be between `%c' and `%c'"
12960 org-highest-priority org-lowest-priority))))
12961 ((eq action 'up)
12962 (setq new (if have
12963 (1- current) ; normal cycling
12964 ;; last priority was empty
12965 (if (eq last-command this-command)
12966 org-lowest-priority ; wrap around empty to lowest
12967 ;; default
12968 (if org-priority-start-cycle-with-default
12969 org-default-priority
12970 (1- org-default-priority))))))
12971 ((eq action 'down)
12972 (setq new (if have
12973 (1+ current) ; normal cycling
12974 ;; last priority was empty
12975 (if (eq last-command this-command)
12976 org-highest-priority ; wrap around empty to highest
12977 ;; default
12978 (if org-priority-start-cycle-with-default
12979 org-default-priority
12980 (1+ org-default-priority))))))
12981 (t (error "Invalid action")))
12982 (if (or (< (upcase new) org-highest-priority)
12983 (> (upcase new) org-lowest-priority))
12984 (if (and (memq action '(up down))
12985 (not have) (not (eq last-command this-command)))
12986 ;; `new' is from default priority
12987 (error
12988 "The default can not be set, see `org-default-priority' why")
12989 ;; normal cycling: `new' is beyond highest/lowest priority
12990 ;; and is wrapped around to the empty priority
12991 (setq remove t)))
12992 (setq news (format "%c" new))
12993 (if have
12994 (if remove
12995 (replace-match "" t t nil 1)
12996 (replace-match news t t nil 2))
12997 (if remove
12998 (error "No priority cookie found in line")
12999 (let ((case-fold-search nil))
13000 (looking-at org-todo-line-regexp))
13001 (if (match-end 2)
13002 (progn
13003 (goto-char (match-end 2))
13004 (insert " [#" news "]"))
13005 (goto-char (match-beginning 3))
13006 (insert "[#" news "] "))))
13007 (org-preserve-lc (org-set-tags nil 'align)))
13008 (if remove
13009 (message "Priority removed")
13010 (message "Priority of current item set to %s" news)))))
13012 (defun org-show-priority ()
13013 "Show the priority of the current item.
13014 This priority is composed of the main priority given with the [#A] cookies,
13015 and by additional input from the age of a schedules or deadline entry."
13016 (interactive)
13017 (let ((pri (if (eq major-mode 'org-agenda-mode)
13018 (org-get-at-bol 'priority)
13019 (save-excursion
13020 (save-match-data
13021 (beginning-of-line)
13022 (and (looking-at org-heading-regexp)
13023 (org-get-priority (match-string 0))))))))
13024 (message "Priority is %d" (if pri pri -1000))))
13026 (defun org-get-priority (s)
13027 "Find priority cookie and return priority."
13028 (save-match-data
13029 (if (functionp org-get-priority-function)
13030 (funcall org-get-priority-function)
13031 (if (not (string-match org-priority-regexp s))
13032 (* 1000 (- org-lowest-priority org-default-priority))
13033 (* 1000 (- org-lowest-priority
13034 (string-to-char (match-string 2 s))))))))
13036 ;;;; Tags
13038 (defvar org-agenda-archives-mode)
13039 (defvar org-map-continue-from nil
13040 "Position from where mapping should continue.
13041 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13043 (defvar org-scanner-tags nil
13044 "The current tag list while the tags scanner is running.")
13045 (defvar org-trust-scanner-tags nil
13046 "Should `org-get-tags-at' use the tags for the scanner.
13047 This is for internal dynamical scoping only.
13048 When this is non-nil, the function `org-get-tags-at' will return the value
13049 of `org-scanner-tags' instead of building the list by itself. This
13050 can lead to large speed-ups when the tags scanner is used in a file with
13051 many entries, and when the list of tags is retrieved, for example to
13052 obtain a list of properties. Building the tags list for each entry in such
13053 a file becomes an N^2 operation - but with this variable set, it scales
13054 as N.")
13056 (defun org-scan-tags (action matcher todo-only &optional start-level)
13057 "Scan headline tags with inheritance and produce output ACTION.
13059 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13060 or `agenda' to produce an entry list for an agenda view. It can also be
13061 a Lisp form or a function that should be called at each matched headline, in
13062 this case the return value is a list of all return values from these calls.
13064 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13065 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13066 only lines with a not-done TODO keyword are included in the output.
13067 This should be the same variable that was scoped into
13068 and set by `org-make-tags-matcher' when it constructed MATCHER.
13070 START-LEVEL can be a string with asterisks, reducing the scope to
13071 headlines matching this string."
13072 (require 'org-agenda)
13073 (let* ((re (concat "^"
13074 (if start-level
13075 ;; Get the correct level to match
13076 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13077 org-outline-regexp)
13078 " *\\(\\<\\("
13079 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13080 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13081 (props (list 'face 'default
13082 'done-face 'org-agenda-done
13083 'undone-face 'default
13084 'mouse-face 'highlight
13085 'org-not-done-regexp org-not-done-regexp
13086 'org-todo-regexp org-todo-regexp
13087 'org-complex-heading-regexp org-complex-heading-regexp
13088 'help-echo
13089 (format "mouse-2 or RET jump to org file %s"
13090 (abbreviate-file-name
13091 (or (buffer-file-name (buffer-base-buffer))
13092 (buffer-name (buffer-base-buffer)))))))
13093 (case-fold-search nil)
13094 (org-map-continue-from nil)
13095 lspos tags tags-list
13096 (tags-alist (list (cons 0 org-file-tags)))
13097 (llast 0) rtn rtn1 level category i txt
13098 todo marker entry priority)
13099 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13100 (setq action (list 'lambda nil action)))
13101 (save-excursion
13102 (goto-char (point-min))
13103 (when (eq action 'sparse-tree)
13104 (org-overview)
13105 (org-remove-occur-highlights))
13106 (while (re-search-forward re nil t)
13107 (setq org-map-continue-from nil)
13108 (catch :skip
13109 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13110 tags (if (match-end 4) (org-match-string-no-properties 4)))
13111 (goto-char (setq lspos (match-beginning 0)))
13112 (setq level (org-reduced-level (funcall outline-level))
13113 category (org-get-category))
13114 (setq i llast llast level)
13115 ;; remove tag lists from same and sublevels
13116 (while (>= i level)
13117 (when (setq entry (assoc i tags-alist))
13118 (setq tags-alist (delete entry tags-alist)))
13119 (setq i (1- i)))
13120 ;; add the next tags
13121 (when tags
13122 (setq tags (org-split-string tags ":")
13123 tags-alist
13124 (cons (cons level tags) tags-alist)))
13125 ;; compile tags for current headline
13126 (setq tags-list
13127 (if org-use-tag-inheritance
13128 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13129 tags)
13130 org-scanner-tags tags-list)
13131 (when org-use-tag-inheritance
13132 (setcdr (car tags-alist)
13133 (mapcar (lambda (x)
13134 (setq x (copy-sequence x))
13135 (org-add-prop-inherited x))
13136 (cdar tags-alist))))
13137 (when (and tags org-use-tag-inheritance
13138 (or (not (eq t org-use-tag-inheritance))
13139 org-tags-exclude-from-inheritance))
13140 ;; selective inheritance, remove uninherited ones
13141 (setcdr (car tags-alist)
13142 (org-remove-uninherited-tags (cdar tags-alist))))
13143 (when (and
13145 ;; eval matcher only when the todo condition is OK
13146 (and (or (not todo-only) (member todo org-not-done-keywords))
13147 (let ((case-fold-search t) (org-trust-scanner-tags t))
13148 (eval matcher)))
13150 ;; Call the skipper, but return t if it does not skip,
13151 ;; so that the `and' form continues evaluating
13152 (progn
13153 (unless (eq action 'sparse-tree) (org-agenda-skip))
13156 ;; Check if timestamps are deselecting this entry
13157 (or (not todo-only)
13158 (and (member todo org-not-done-keywords)
13159 (or (not org-agenda-tags-todo-honor-ignore-options)
13160 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13162 ;; select this headline
13163 (cond
13164 ((eq action 'sparse-tree)
13165 (and org-highlight-sparse-tree-matches
13166 (org-get-heading) (match-end 0)
13167 (org-highlight-new-match
13168 (match-beginning 1) (match-end 1)))
13169 (org-show-context 'tags-tree))
13170 ((eq action 'agenda)
13171 (setq txt (org-agenda-format-item
13173 (concat
13174 (if (eq org-tags-match-list-sublevels 'indented)
13175 (make-string (1- level) ?.) "")
13176 (org-get-heading))
13177 category
13178 tags-list)
13179 priority (org-get-priority txt))
13180 (goto-char lspos)
13181 (setq marker (org-agenda-new-marker))
13182 (org-add-props txt props
13183 'org-marker marker 'org-hd-marker marker 'org-category category
13184 'todo-state todo
13185 'priority priority 'type "tagsmatch")
13186 (push txt rtn))
13187 ((functionp action)
13188 (setq org-map-continue-from nil)
13189 (save-excursion
13190 (setq rtn1 (funcall action))
13191 (push rtn1 rtn)))
13192 (t (error "Invalid action")))
13194 ;; if we are to skip sublevels, jump to end of subtree
13195 (unless org-tags-match-list-sublevels
13196 (org-end-of-subtree t)
13197 (backward-char 1))))
13198 ;; Get the correct position from where to continue
13199 (if org-map-continue-from
13200 (goto-char org-map-continue-from)
13201 (and (= (point) lspos) (end-of-line 1)))))
13202 (when (and (eq action 'sparse-tree)
13203 (not org-sparse-tree-open-archived-trees))
13204 (org-hide-archived-subtrees (point-min) (point-max)))
13205 (nreverse rtn)))
13207 (defun org-remove-uninherited-tags (tags)
13208 "Remove all tags that are not inherited from the list TAGS."
13209 (cond
13210 ((eq org-use-tag-inheritance t)
13211 (if org-tags-exclude-from-inheritance
13212 (org-delete-all org-tags-exclude-from-inheritance tags)
13213 tags))
13214 ((not org-use-tag-inheritance) nil)
13215 ((stringp org-use-tag-inheritance)
13216 (delq nil (mapcar
13217 (lambda (x)
13218 (if (and (string-match org-use-tag-inheritance x)
13219 (not (member x org-tags-exclude-from-inheritance)))
13220 x nil))
13221 tags)))
13222 ((listp org-use-tag-inheritance)
13223 (delq nil (mapcar
13224 (lambda (x)
13225 (if (member x org-use-tag-inheritance) x nil))
13226 tags)))))
13228 (defun org-match-sparse-tree (&optional todo-only match)
13229 "Create a sparse tree according to tags string MATCH.
13230 MATCH can contain positive and negative selection of tags, like
13231 \"+WORK+URGENT-WITHBOSS\".
13232 If optional argument TODO-ONLY is non-nil, only select lines that are
13233 also TODO lines."
13234 (interactive "P")
13235 (org-agenda-prepare-buffers (list (current-buffer)))
13236 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13238 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13240 (defvar org-cached-props nil)
13241 (defun org-cached-entry-get (pom property)
13242 (if (or (eq t org-use-property-inheritance)
13243 (and (stringp org-use-property-inheritance)
13244 (string-match org-use-property-inheritance property))
13245 (and (listp org-use-property-inheritance)
13246 (member property org-use-property-inheritance)))
13247 ;; Caching is not possible, check it directly
13248 (org-entry-get pom property 'inherit)
13249 ;; Get all properties, so that we can do complicated checks easily
13250 (cdr (assoc property (or org-cached-props
13251 (setq org-cached-props
13252 (org-entry-properties pom)))))))
13254 (defun org-global-tags-completion-table (&optional files)
13255 "Return the list of all tags in all agenda buffer/files.
13256 Optional FILES argument is a list of files which can be used
13257 instead of the agenda files."
13258 (save-excursion
13259 (org-uniquify
13260 (delq nil
13261 (apply 'append
13262 (mapcar
13263 (lambda (file)
13264 (set-buffer (find-file-noselect file))
13265 (append (org-get-buffer-tags)
13266 (mapcar (lambda (x) (if (stringp (car-safe x))
13267 (list (car-safe x)) nil))
13268 org-tag-alist)))
13269 (if (and files (car files))
13270 files
13271 (org-agenda-files))))))))
13273 (defun org-make-tags-matcher (match)
13274 "Create the TAGS/TODO matcher form for the selection string MATCH.
13276 The variable `todo-only' is scoped dynamically into this function.
13277 It will be set to t if the matcher restricts matching to TODO entries,
13278 otherwise will not be touched.
13280 Returns a cons of the selection string MATCH and the constructed
13281 lisp form implementing the matcher. The matcher is to be evaluated
13282 at an Org entry, with point on the headline, and returns t if the
13283 entry matches the selection string MATCH. The returned lisp form
13284 references two variables with information about the entry, which
13285 must be bound around the form's evaluation: todo, the TODO keyword
13286 at the entry (or nil of none); and tags-list, the list of all tags
13287 at the entry including inherited ones. Additionally, the category
13288 of the entry (if any) must be specified as the text property
13289 'org-category on the headline.
13291 See also `org-scan-tags'.
13293 (declare (special todo-only))
13294 (unless (boundp 'todo-only)
13295 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13296 (unless match
13297 ;; Get a new match request, with completion
13298 (let ((org-last-tags-completion-table
13299 (org-global-tags-completion-table)))
13300 (setq match (org-completing-read-no-i
13301 "Match: " 'org-tags-completion-function nil nil nil
13302 'org-tags-history))))
13304 ;; Parse the string and create a lisp form
13305 (let ((match0 match)
13306 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13307 minus tag mm
13308 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13309 orterms term orlist re-p str-p level-p level-op time-p
13310 prop-p pn pv po gv rest)
13311 (if (string-match "/+" match)
13312 ;; match contains also a todo-matching request
13313 (progn
13314 (setq tagsmatch (substring match 0 (match-beginning 0))
13315 todomatch (substring match (match-end 0)))
13316 (if (string-match "^!" todomatch)
13317 (setq todo-only t todomatch (substring todomatch 1)))
13318 (if (string-match "^\\s-*$" todomatch)
13319 (setq todomatch nil)))
13320 ;; only matching tags
13321 (setq tagsmatch match todomatch nil))
13323 ;; Make the tags matcher
13324 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13325 (setq tagsmatcher t)
13326 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13327 (while (setq term (pop orterms))
13328 (while (and (equal (substring term -1) "\\") orterms)
13329 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13330 (while (string-match re term)
13331 (setq rest (substring term (match-end 0))
13332 minus (and (match-end 1)
13333 (equal (match-string 1 term) "-"))
13334 tag (save-match-data (replace-regexp-in-string
13335 "\\\\-" "-"
13336 (match-string 2 term)))
13337 re-p (equal (string-to-char tag) ?{)
13338 level-p (match-end 4)
13339 prop-p (match-end 5)
13340 mm (cond
13341 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13342 (level-p
13343 (setq level-op (org-op-to-function (match-string 3 term)))
13344 `(,level-op level ,(string-to-number
13345 (match-string 4 term))))
13346 (prop-p
13347 (setq pn (match-string 5 term)
13348 po (match-string 6 term)
13349 pv (match-string 7 term)
13350 re-p (equal (string-to-char pv) ?{)
13351 str-p (equal (string-to-char pv) ?\")
13352 time-p (save-match-data
13353 (string-match "^\"[[<].*[]>]\"$" pv))
13354 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13355 (if time-p (setq pv (org-matcher-time pv)))
13356 (setq po (org-op-to-function po (if time-p 'time str-p)))
13357 (cond
13358 ((equal pn "CATEGORY")
13359 (setq gv '(get-text-property (point) 'org-category)))
13360 ((equal pn "TODO")
13361 (setq gv 'todo))
13363 (setq gv `(org-cached-entry-get nil ,pn))))
13364 (if re-p
13365 (if (eq po 'org<>)
13366 `(not (string-match ,pv (or ,gv "")))
13367 `(string-match ,pv (or ,gv "")))
13368 (if str-p
13369 `(,po (or ,gv "") ,pv)
13370 `(,po (string-to-number (or ,gv ""))
13371 ,(string-to-number pv) ))))
13372 (t `(member ,tag tags-list)))
13373 mm (if minus (list 'not mm) mm)
13374 term rest)
13375 (push mm tagsmatcher))
13376 (push (if (> (length tagsmatcher) 1)
13377 (cons 'and tagsmatcher)
13378 (car tagsmatcher))
13379 orlist)
13380 (setq tagsmatcher nil))
13381 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13382 (setq tagsmatcher
13383 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13384 ;; Make the todo matcher
13385 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13386 (setq todomatcher t)
13387 (setq orterms (org-split-string todomatch "|") orlist nil)
13388 (while (setq term (pop orterms))
13389 (while (string-match re term)
13390 (setq minus (and (match-end 1)
13391 (equal (match-string 1 term) "-"))
13392 kwd (match-string 2 term)
13393 re-p (equal (string-to-char kwd) ?{)
13394 term (substring term (match-end 0))
13395 mm (if re-p
13396 `(string-match ,(substring kwd 1 -1) todo)
13397 (list 'equal 'todo kwd))
13398 mm (if minus (list 'not mm) mm))
13399 (push mm todomatcher))
13400 (push (if (> (length todomatcher) 1)
13401 (cons 'and todomatcher)
13402 (car todomatcher))
13403 orlist)
13404 (setq todomatcher nil))
13405 (setq todomatcher (if (> (length orlist) 1)
13406 (cons 'or orlist) (car orlist))))
13408 ;; Return the string and lisp forms of the matcher
13409 (setq matcher (if todomatcher
13410 (list 'and tagsmatcher todomatcher)
13411 tagsmatcher))
13412 (when todo-only
13413 (setq matcher (list 'and '(member todo org-not-done-keywords)
13414 matcher)))
13415 (cons match0 matcher)))
13417 (defun org-op-to-function (op &optional stringp)
13418 "Turn an operator into the appropriate function."
13419 (setq op
13420 (cond
13421 ((equal op "<" ) '(< string< org-time<))
13422 ((equal op ">" ) '(> org-string> org-time>))
13423 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13424 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13425 ((member op '("=" "==")) '(= string= org-time=))
13426 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13427 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13429 (defun org<> (a b) (not (= a b)))
13430 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13431 (defun org-string>= (a b) (not (string< a b)))
13432 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13433 (defun org-string<> (a b) (not (string= a b)))
13434 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13435 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13436 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13437 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13438 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13439 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13440 (defun org-2ft (s)
13441 "Convert S to a floating point time.
13442 If S is already a number, just return it. If it is a string, parse
13443 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13444 (cond
13445 ((numberp s) s)
13446 ((stringp s)
13447 (condition-case nil
13448 (float-time (apply 'encode-time (org-parse-time-string s)))
13449 (error 0.)))
13450 (t 0.)))
13452 (defun org-time-today ()
13453 "Time in seconds today at 0:00.
13454 Returns the float number of seconds since the beginning of the
13455 epoch to the beginning of today (00:00)."
13456 (float-time (apply 'encode-time
13457 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13459 (defun org-matcher-time (s)
13460 "Interpret a time comparison value."
13461 (save-match-data
13462 (cond
13463 ((string= s "<now>") (float-time))
13464 ((string= s "<today>") (org-time-today))
13465 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13466 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13467 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13468 (+ (org-time-today)
13469 (* (string-to-number (match-string 1 s))
13470 (cdr (assoc (match-string 2 s)
13471 '(("d" . 86400.0) ("w" . 604800.0)
13472 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13473 (t (org-2ft s)))))
13475 (defun org-match-any-p (re list)
13476 "Does re match any element of list?"
13477 (setq list (mapcar (lambda (x) (string-match re x)) list))
13478 (delq nil list))
13480 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13481 (defvar org-tags-overlay (make-overlay 1 1))
13482 (org-detach-overlay org-tags-overlay)
13484 (defun org-get-local-tags-at (&optional pos)
13485 "Get a list of tags defined in the current headline."
13486 (org-get-tags-at pos 'local))
13488 (defun org-get-local-tags ()
13489 "Get a list of tags defined in the current headline."
13490 (org-get-tags-at nil 'local))
13492 (defun org-get-tags-at (&optional pos local)
13493 "Get a list of all headline tags applicable at POS.
13494 POS defaults to point. If tags are inherited, the list contains
13495 the targets in the same sequence as the headlines appear, i.e.
13496 the tags of the current headline come last.
13497 When LOCAL is non-nil, only return tags from the current headline,
13498 ignore inherited ones."
13499 (interactive)
13500 (if (and org-trust-scanner-tags
13501 (or (not pos) (equal pos (point)))
13502 (not local))
13503 org-scanner-tags
13504 (let (tags ltags lastpos parent)
13505 (save-excursion
13506 (save-restriction
13507 (widen)
13508 (goto-char (or pos (point)))
13509 (save-match-data
13510 (catch 'done
13511 (condition-case nil
13512 (progn
13513 (org-back-to-heading t)
13514 (while (not (equal lastpos (point)))
13515 (setq lastpos (point))
13516 (when (looking-at
13517 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13518 (setq ltags (org-split-string
13519 (org-match-string-no-properties 1) ":"))
13520 (when parent
13521 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13522 (setq tags (append
13523 (if parent
13524 (org-remove-uninherited-tags ltags)
13525 ltags)
13526 tags)))
13527 (or org-use-tag-inheritance (throw 'done t))
13528 (if local (throw 'done t))
13529 (or (org-up-heading-safe) (error nil))
13530 (setq parent t)))
13531 (error nil)))))
13532 (if local
13533 tags
13534 (reverse (delete-dups
13535 (reverse (append
13536 (org-remove-uninherited-tags
13537 org-file-tags) tags)))))))))
13539 (defun org-add-prop-inherited (s)
13540 (add-text-properties 0 (length s) '(inherited t) s)
13543 (defun org-toggle-tag (tag &optional onoff)
13544 "Toggle the tag TAG for the current line.
13545 If ONOFF is `on' or `off', don't toggle but set to this state."
13546 (let (res current)
13547 (save-excursion
13548 (org-back-to-heading t)
13549 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13550 (point-at-eol) t)
13551 (progn
13552 (setq current (match-string 1))
13553 (replace-match ""))
13554 (setq current ""))
13555 (setq current (nreverse (org-split-string current ":")))
13556 (cond
13557 ((eq onoff 'on)
13558 (setq res t)
13559 (or (member tag current) (push tag current)))
13560 ((eq onoff 'off)
13561 (or (not (member tag current)) (setq current (delete tag current))))
13562 (t (if (member tag current)
13563 (setq current (delete tag current))
13564 (setq res t)
13565 (push tag current))))
13566 (end-of-line 1)
13567 (if current
13568 (progn
13569 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13570 (org-set-tags nil t))
13571 (delete-horizontal-space))
13572 (run-hooks 'org-after-tags-change-hook))
13573 res))
13575 (defun org-align-tags-here (to-col)
13576 ;; Assumes that this is a headline
13577 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13578 (beginning-of-line 1)
13579 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13580 (< pos (match-beginning 2)))
13581 (progn
13582 (setq tags-l (- (match-end 2) (match-beginning 2)))
13583 (goto-char (match-beginning 1))
13584 (insert " ")
13585 (delete-region (point) (1+ (match-beginning 2)))
13586 (setq ncol (max (current-column)
13587 (1+ col)
13588 (if (> to-col 0)
13589 to-col
13590 (- (abs to-col) tags-l))))
13591 (setq p (point))
13592 (insert (make-string (- ncol (current-column)) ?\ ))
13593 (setq ncol (current-column))
13594 (when indent-tabs-mode (tabify p (point-at-eol)))
13595 (org-move-to-column (min ncol col) t))
13596 (goto-char pos))))
13598 (defun org-set-tags-command (&optional arg just-align)
13599 "Call the set-tags command for the current entry."
13600 (interactive "P")
13601 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13602 (org-set-tags arg just-align)
13603 (save-excursion
13604 (org-back-to-heading t)
13605 (org-set-tags arg just-align))))
13607 (defun org-set-tags-to (data)
13608 "Set the tags of the current entry to DATA, replacing the current tags.
13609 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13610 If DATA is nil or the empty string, any tags will be removed."
13611 (interactive "sTags: ")
13612 (setq data
13613 (cond
13614 ((eq data nil) "")
13615 ((equal data "") "")
13616 ((stringp data)
13617 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13618 ":"))
13619 ((listp data)
13620 (concat ":" (mapconcat 'identity data ":") ":"))))
13621 (when data
13622 (save-excursion
13623 (org-back-to-heading t)
13624 (when (looking-at org-complex-heading-regexp)
13625 (if (match-end 5)
13626 (progn
13627 (goto-char (match-beginning 5))
13628 (insert data)
13629 (delete-region (point) (point-at-eol))
13630 (org-set-tags nil 'align))
13631 (goto-char (point-at-eol))
13632 (insert " " data)
13633 (org-set-tags nil 'align)))
13634 (beginning-of-line 1)
13635 (if (looking-at ".*?\\([ \t]+\\)$")
13636 (delete-region (match-beginning 1) (match-end 1))))))
13638 (defun org-align-all-tags ()
13639 "Align the tags i all headings."
13640 (interactive)
13641 (save-excursion
13642 (or (ignore-errors (org-back-to-heading t))
13643 (outline-next-heading))
13644 (if (org-at-heading-p)
13645 (org-set-tags t)
13646 (message "No headings"))))
13648 (defvar org-indent-indentation-per-level)
13649 (defun org-set-tags (&optional arg just-align)
13650 "Set the tags for the current headline.
13651 With prefix ARG, realign all tags in headings in the current buffer."
13652 (interactive "P")
13653 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13654 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13655 'region-start-level 'region))
13656 org-loop-over-headlines-in-active-region)
13657 (org-map-entries
13658 ;; We don't use ARG and JUST-ALIGN here these args are not
13659 ;; useful when looping over headlines
13660 `(org-set-tags)
13661 org-loop-over-headlines-in-active-region
13662 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13663 (let* ((re org-outline-regexp-bol)
13664 (current (unless arg (org-get-tags-string)))
13665 (col (current-column))
13666 (org-setting-tags t)
13667 table current-tags inherited-tags ; computed below when needed
13668 tags p0 c0 c1 rpl di tc level)
13669 (if arg
13670 (save-excursion
13671 (goto-char (point-min))
13672 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13673 (while (re-search-forward re nil t)
13674 (org-set-tags nil t)
13675 (end-of-line 1)))
13676 (message "All tags realigned to column %d" org-tags-column))
13677 (if just-align
13678 (setq tags current)
13679 ;; Get a new set of tags from the user
13680 (save-excursion
13681 (setq table (append org-tag-persistent-alist
13682 (or org-tag-alist (org-get-buffer-tags))
13683 (and
13684 org-complete-tags-always-offer-all-agenda-tags
13685 (org-global-tags-completion-table
13686 (org-agenda-files))))
13687 org-last-tags-completion-table table
13688 current-tags (org-split-string current ":")
13689 inherited-tags (nreverse
13690 (nthcdr (length current-tags)
13691 (nreverse (org-get-tags-at))))
13692 tags
13693 (if (or (eq t org-use-fast-tag-selection)
13694 (and org-use-fast-tag-selection
13695 (delq nil (mapcar 'cdr table))))
13696 (org-fast-tag-selection
13697 current-tags inherited-tags table
13698 (if org-fast-tag-selection-include-todo
13699 org-todo-key-alist))
13700 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13701 (org-trim
13702 (org-icompleting-read "Tags: "
13703 'org-tags-completion-function
13704 nil nil current 'org-tags-history))))))
13705 (while (string-match "[-+&]+" tags)
13706 ;; No boolean logic, just a list
13707 (setq tags (replace-match ":" t t tags))))
13709 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13711 (if org-tags-sort-function
13712 (setq tags (mapconcat 'identity
13713 (sort (org-split-string
13714 tags (org-re "[^[:alnum:]_@#%]+"))
13715 org-tags-sort-function) ":")))
13717 (if (string-match "\\`[\t ]*\\'" tags)
13718 (setq tags "")
13719 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13720 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13722 ;; Insert new tags at the correct column
13723 (beginning-of-line 1)
13724 (setq level (or (and (looking-at org-outline-regexp)
13725 (- (match-end 0) (point) 1))
13727 (cond
13728 ((and (equal current "") (equal tags "")))
13729 ((re-search-forward
13730 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13731 (point-at-eol) t)
13732 (if (equal tags "")
13733 (setq rpl "")
13734 (goto-char (match-beginning 0))
13735 (setq c0 (current-column)
13736 ;; compute offset for the case of org-indent-mode active
13737 di (if org-indent-mode
13738 (* (1- org-indent-indentation-per-level) (1- level))
13740 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13741 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13742 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13743 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13744 (replace-match rpl t t)
13745 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13746 tags)
13747 (t (error "Tags alignment failed")))
13748 (org-move-to-column col)
13749 (unless just-align
13750 (run-hooks 'org-after-tags-change-hook))))))
13752 (defun org-change-tag-in-region (beg end tag off)
13753 "Add or remove TAG for each entry in the region.
13754 This works in the agenda, and also in an org-mode buffer."
13755 (interactive
13756 (list (region-beginning) (region-end)
13757 (let ((org-last-tags-completion-table
13758 (if (derived-mode-p 'org-mode)
13759 (org-get-buffer-tags)
13760 (org-global-tags-completion-table))))
13761 (org-icompleting-read
13762 "Tag: " 'org-tags-completion-function nil nil nil
13763 'org-tags-history))
13764 (progn
13765 (message "[s]et or [r]emove? ")
13766 (equal (read-char-exclusive) ?r))))
13767 (if (fboundp 'deactivate-mark) (deactivate-mark))
13768 (let ((agendap (equal major-mode 'org-agenda-mode))
13769 l1 l2 m buf pos newhead (cnt 0))
13770 (goto-char end)
13771 (setq l2 (1- (org-current-line)))
13772 (goto-char beg)
13773 (setq l1 (org-current-line))
13774 (loop for l from l1 to l2 do
13775 (org-goto-line l)
13776 (setq m (get-text-property (point) 'org-hd-marker))
13777 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13778 (and agendap m))
13779 (setq buf (if agendap (marker-buffer m) (current-buffer))
13780 pos (if agendap m (point)))
13781 (with-current-buffer buf
13782 (save-excursion
13783 (save-restriction
13784 (goto-char pos)
13785 (setq cnt (1+ cnt))
13786 (org-toggle-tag tag (if off 'off 'on))
13787 (setq newhead (org-get-heading)))))
13788 (and agendap (org-agenda-change-all-lines newhead m))))
13789 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13791 (defun org-tags-completion-function (string predicate &optional flag)
13792 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13793 (confirm (lambda (x) (stringp (car x)))))
13794 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13795 (setq s1 (match-string 1 string)
13796 s2 (match-string 2 string))
13797 (setq s1 "" s2 string))
13798 (cond
13799 ((eq flag nil)
13800 ;; try completion
13801 (setq rtn (try-completion s2 ctable confirm))
13802 (if (stringp rtn)
13803 (setq rtn
13804 (concat s1 s2 (substring rtn (length s2))
13805 (if (and org-add-colon-after-tag-completion
13806 (assoc rtn ctable))
13807 ":" ""))))
13808 rtn)
13809 ((eq flag t)
13810 ;; all-completions
13811 (all-completions s2 ctable confirm)
13813 ((eq flag 'lambda)
13814 ;; exact match?
13815 (assoc s2 ctable)))
13818 (defun org-fast-tag-insert (kwd tags face &optional end)
13819 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13820 (insert (format "%-12s" (concat kwd ":"))
13821 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13822 (or end "")))
13824 (defun org-fast-tag-show-exit (flag)
13825 (save-excursion
13826 (org-goto-line 3)
13827 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13828 (replace-match ""))
13829 (when flag
13830 (end-of-line 1)
13831 (org-move-to-column (- (window-width) 19) t)
13832 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13834 (defun org-set-current-tags-overlay (current prefix)
13835 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13836 (if (featurep 'xemacs)
13837 (org-overlay-display org-tags-overlay (concat prefix s)
13838 'secondary-selection)
13839 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13840 (org-overlay-display org-tags-overlay (concat prefix s)))))
13842 (defvar org-last-tag-selection-key nil)
13843 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13844 "Fast tag selection with single keys.
13845 CURRENT is the current list of tags in the headline, INHERITED is the
13846 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13847 possibly with grouping information. TODO-TABLE is a similar table with
13848 TODO keywords, should these have keys assigned to them.
13849 If the keys are nil, a-z are automatically assigned.
13850 Returns the new tags string, or nil to not change the current settings."
13851 (let* ((fulltable (append table todo-table))
13852 (maxlen (apply 'max (mapcar
13853 (lambda (x)
13854 (if (stringp (car x)) (string-width (car x)) 0))
13855 fulltable)))
13856 (buf (current-buffer))
13857 (expert (eq org-fast-tag-selection-single-key 'expert))
13858 (buffer-tags nil)
13859 (fwidth (+ maxlen 3 1 3))
13860 (ncol (/ (- (window-width) 4) fwidth))
13861 (i-face 'org-done)
13862 (c-face 'org-todo)
13863 tg cnt e c char c1 c2 ntable tbl rtn
13864 ov-start ov-end ov-prefix
13865 (exit-after-next org-fast-tag-selection-single-key)
13866 (done-keywords org-done-keywords)
13867 groups ingroup)
13868 (save-excursion
13869 (beginning-of-line 1)
13870 (if (looking-at
13871 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13872 (setq ov-start (match-beginning 1)
13873 ov-end (match-end 1)
13874 ov-prefix "")
13875 (setq ov-start (1- (point-at-eol))
13876 ov-end (1+ ov-start))
13877 (skip-chars-forward "^\n\r")
13878 (setq ov-prefix
13879 (concat
13880 (buffer-substring (1- (point)) (point))
13881 (if (> (current-column) org-tags-column)
13883 (make-string (- org-tags-column (current-column)) ?\ ))))))
13884 (move-overlay org-tags-overlay ov-start ov-end)
13885 (save-window-excursion
13886 (if expert
13887 (set-buffer (get-buffer-create " *Org tags*"))
13888 (delete-other-windows)
13889 (split-window-vertically)
13890 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13891 (erase-buffer)
13892 (org-set-local 'org-done-keywords done-keywords)
13893 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13894 (org-fast-tag-insert "Current" current c-face "\n\n")
13895 (org-fast-tag-show-exit exit-after-next)
13896 (org-set-current-tags-overlay current ov-prefix)
13897 (setq tbl fulltable char ?a cnt 0)
13898 (while (setq e (pop tbl))
13899 (cond
13900 ((equal (car e) :startgroup)
13901 (push '() groups) (setq ingroup t)
13902 (when (not (= cnt 0))
13903 (setq cnt 0)
13904 (insert "\n"))
13905 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13906 ((equal (car e) :endgroup)
13907 (setq ingroup nil cnt 0)
13908 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13909 ((equal e '(:newline))
13910 (when (not (= cnt 0))
13911 (setq cnt 0)
13912 (insert "\n")
13913 (setq e (car tbl))
13914 (while (equal (car tbl) '(:newline))
13915 (insert "\n")
13916 (setq tbl (cdr tbl)))))
13918 (setq tg (copy-sequence (car e)) c2 nil)
13919 (if (cdr e)
13920 (setq c (cdr e))
13921 ;; automatically assign a character.
13922 (setq c1 (string-to-char
13923 (downcase (substring
13924 tg (if (= (string-to-char tg) ?@) 1 0)))))
13925 (if (or (rassoc c1 ntable) (rassoc c1 table))
13926 (while (or (rassoc char ntable) (rassoc char table))
13927 (setq char (1+ char)))
13928 (setq c2 c1))
13929 (setq c (or c2 char)))
13930 (if ingroup (push tg (car groups)))
13931 (setq tg (org-add-props tg nil 'face
13932 (cond
13933 ((not (assoc tg table))
13934 (org-get-todo-face tg))
13935 ((member tg current) c-face)
13936 ((member tg inherited) i-face))))
13937 (if (and (= cnt 0) (not ingroup)) (insert " "))
13938 (insert "[" c "] " tg (make-string
13939 (- fwidth 4 (length tg)) ?\ ))
13940 (push (cons tg c) ntable)
13941 (when (= (setq cnt (1+ cnt)) ncol)
13942 (insert "\n")
13943 (if ingroup (insert " "))
13944 (setq cnt 0)))))
13945 (setq ntable (nreverse ntable))
13946 (insert "\n")
13947 (goto-char (point-min))
13948 (if (not expert) (org-fit-window-to-buffer))
13949 (setq rtn
13950 (catch 'exit
13951 (while t
13952 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13953 (if (not groups) "no " "")
13954 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13955 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13956 (setq org-last-tag-selection-key c)
13957 (cond
13958 ((= c ?\r) (throw 'exit t))
13959 ((= c ?!)
13960 (setq groups (not groups))
13961 (goto-char (point-min))
13962 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13963 ((= c ?\C-c)
13964 (if (not expert)
13965 (org-fast-tag-show-exit
13966 (setq exit-after-next (not exit-after-next)))
13967 (setq expert nil)
13968 (delete-other-windows)
13969 (set-window-buffer (split-window-vertically) " *Org tags*")
13970 (org-switch-to-buffer-other-window " *Org tags*")
13971 (org-fit-window-to-buffer)))
13972 ((or (= c ?\C-g)
13973 (and (= c ?q) (not (rassoc c ntable))))
13974 (org-detach-overlay org-tags-overlay)
13975 (setq quit-flag t))
13976 ((= c ?\ )
13977 (setq current nil)
13978 (if exit-after-next (setq exit-after-next 'now)))
13979 ((= c ?\t)
13980 (condition-case nil
13981 (setq tg (org-icompleting-read
13982 "Tag: "
13983 (or buffer-tags
13984 (with-current-buffer buf
13985 (org-get-buffer-tags)))))
13986 (quit (setq tg "")))
13987 (when (string-match "\\S-" tg)
13988 (add-to-list 'buffer-tags (list tg))
13989 (if (member tg current)
13990 (setq current (delete tg current))
13991 (push tg current)))
13992 (if exit-after-next (setq exit-after-next 'now)))
13993 ((setq e (rassoc c todo-table) tg (car e))
13994 (with-current-buffer buf
13995 (save-excursion (org-todo tg)))
13996 (if exit-after-next (setq exit-after-next 'now)))
13997 ((setq e (rassoc c ntable) tg (car e))
13998 (if (member tg current)
13999 (setq current (delete tg current))
14000 (loop for g in groups do
14001 (if (member tg g)
14002 (mapc (lambda (x)
14003 (setq current (delete x current)))
14004 g)))
14005 (push tg current))
14006 (if exit-after-next (setq exit-after-next 'now))))
14008 ;; Create a sorted list
14009 (setq current
14010 (sort current
14011 (lambda (a b)
14012 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14013 (if (eq exit-after-next 'now) (throw 'exit t))
14014 (goto-char (point-min))
14015 (beginning-of-line 2)
14016 (delete-region (point) (point-at-eol))
14017 (org-fast-tag-insert "Current" current c-face)
14018 (org-set-current-tags-overlay current ov-prefix)
14019 (while (re-search-forward
14020 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14021 (setq tg (match-string 1))
14022 (add-text-properties
14023 (match-beginning 1) (match-end 1)
14024 (list 'face
14025 (cond
14026 ((member tg current) c-face)
14027 ((member tg inherited) i-face)
14028 (t (get-text-property (match-beginning 1) 'face))))))
14029 (goto-char (point-min)))))
14030 (org-detach-overlay org-tags-overlay)
14031 (if rtn
14032 (mapconcat 'identity current ":")
14033 nil))))
14035 (defun org-get-tags-string ()
14036 "Get the TAGS string in the current headline."
14037 (unless (org-at-heading-p t)
14038 (error "Not on a heading"))
14039 (save-excursion
14040 (beginning-of-line 1)
14041 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14042 (org-match-string-no-properties 1)
14043 "")))
14045 (defun org-get-tags ()
14046 "Get the list of tags specified in the current headline."
14047 (org-split-string (org-get-tags-string) ":"))
14049 (defun org-get-buffer-tags ()
14050 "Get a table of all tags used in the buffer, for completion."
14051 (let (tags)
14052 (save-excursion
14053 (goto-char (point-min))
14054 (while (re-search-forward
14055 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14056 (when (equal (char-after (point-at-bol 0)) ?*)
14057 (mapc (lambda (x) (add-to-list 'tags x))
14058 (org-split-string (org-match-string-no-properties 1) ":")))))
14059 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14060 (mapcar 'list tags)))
14062 ;;;; The mapping API
14064 (defun org-map-entries (func &optional match scope &rest skip)
14065 "Call FUNC at each headline selected by MATCH in SCOPE.
14067 FUNC is a function or a lisp form. The function will be called without
14068 arguments, with the cursor positioned at the beginning of the headline.
14069 The return values of all calls to the function will be collected and
14070 returned as a list.
14072 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14073 does not need to preserve point. After evaluation, the cursor will be
14074 moved to the end of the line (presumably of the headline of the
14075 processed entry) and search continues from there. Under some
14076 circumstances, this may not produce the wanted results. For example,
14077 if you have removed (e.g. archived) the current (sub)tree it could
14078 mean that the next entry will be skipped entirely. In such cases, you
14079 can specify the position from where search should continue by making
14080 FUNC set the variable `org-map-continue-from' to the desired buffer
14081 position.
14083 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14084 Only headlines that are matched by this query will be considered during
14085 the iteration. When MATCH is nil or t, all headlines will be
14086 visited by the iteration.
14088 SCOPE determines the scope of this command. It can be any of:
14090 nil The current buffer, respecting the restriction if any
14091 tree The subtree started with the entry at point
14092 region The entries within the active region, if any
14093 region-start-level
14094 The entries within the active region, but only those at
14095 the same level than the first one.
14096 file The current buffer, without restriction
14097 file-with-archives
14098 The current buffer, and any archives associated with it
14099 agenda All agenda files
14100 agenda-with-archives
14101 All agenda files with any archive files associated with them
14102 \(file1 file2 ...)
14103 If this is a list, all files in the list will be scanned
14105 The remaining args are treated as settings for the skipping facilities of
14106 the scanner. The following items can be given here:
14108 archive skip trees with the archive tag.
14109 comment skip trees with the COMMENT keyword
14110 function or Emacs Lisp form:
14111 will be used as value for `org-agenda-skip-function', so whenever
14112 the function returns t, FUNC will not be called for that
14113 entry and search will continue from the point where the
14114 function leaves it.
14116 If your function needs to retrieve the tags including inherited tags
14117 at the *current* entry, you can use the value of the variable
14118 `org-scanner-tags' which will be much faster than getting the value
14119 with `org-get-tags-at'. If your function gets properties with
14120 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14121 to t around the call to `org-entry-properties' to get the same speedup.
14122 Note that if your function moves around to retrieve tags and properties at
14123 a *different* entry, you cannot use these techniques."
14124 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14125 (not (org-region-active-p)))
14126 (let* ((org-agenda-archives-mode nil) ; just to make sure
14127 (org-agenda-skip-archived-trees (memq 'archive skip))
14128 (org-agenda-skip-comment-trees (memq 'comment skip))
14129 (org-agenda-skip-function
14130 (car (org-delete-all '(comment archive) skip)))
14131 (org-tags-match-list-sublevels t)
14132 (start-level (eq scope 'region-start-level))
14133 matcher file res
14134 org-todo-keywords-for-agenda
14135 org-done-keywords-for-agenda
14136 org-todo-keyword-alist-for-agenda
14137 org-drawers-for-agenda
14138 org-tag-alist-for-agenda
14139 todo-only)
14141 (cond
14142 ((eq match t) (setq matcher t))
14143 ((eq match nil) (setq matcher t))
14144 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14146 (save-excursion
14147 (save-restriction
14148 (cond ((eq scope 'tree)
14149 (org-back-to-heading t)
14150 (org-narrow-to-subtree)
14151 (setq scope nil))
14152 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14153 (org-region-active-p))
14154 ;; If needed, set start-level to a string like "2"
14155 (when start-level
14156 (save-excursion
14157 (goto-char (region-beginning))
14158 (unless (org-at-heading-p) (outline-next-heading))
14159 (setq start-level (org-current-level))))
14160 (narrow-to-region (region-beginning)
14161 (save-excursion
14162 (goto-char (region-end))
14163 (unless (and (bolp) (org-at-heading-p))
14164 (outline-next-heading))
14165 (point)))
14166 (setq scope nil)))
14168 (if (not scope)
14169 (progn
14170 (org-agenda-prepare-buffers
14171 (list (buffer-file-name (current-buffer))))
14172 (setq res (org-scan-tags func matcher todo-only start-level)))
14173 ;; Get the right scope
14174 (cond
14175 ((and scope (listp scope) (symbolp (car scope)))
14176 (setq scope (eval scope)))
14177 ((eq scope 'agenda)
14178 (setq scope (org-agenda-files t)))
14179 ((eq scope 'agenda-with-archives)
14180 (setq scope (org-agenda-files t))
14181 (setq scope (org-add-archive-files scope)))
14182 ((eq scope 'file)
14183 (setq scope (list (buffer-file-name))))
14184 ((eq scope 'file-with-archives)
14185 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14186 (org-agenda-prepare-buffers scope)
14187 (while (setq file (pop scope))
14188 (with-current-buffer (org-find-base-buffer-visiting file)
14189 (save-excursion
14190 (save-restriction
14191 (widen)
14192 (goto-char (point-min))
14193 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14194 res)))
14196 ;;;; Properties
14198 ;;; Setting and retrieving properties
14200 (defconst org-special-properties
14201 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14202 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14203 "The special properties valid in Org-mode.
14205 These are properties that are not defined in the property drawer,
14206 but in some other way.")
14208 (defconst org-default-properties
14209 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14210 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14211 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14212 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14213 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14214 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14215 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14216 "Some properties that are used by Org-mode for various purposes.
14217 Being in this list makes sure that they are offered for completion.")
14219 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14220 "Regular expression matching the first line of a property drawer.")
14222 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14223 "Regular expression matching the last line of a property drawer.")
14225 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14226 "Regular expression matching the first line of a property drawer.")
14228 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14229 "Regular expression matching the first line of a property drawer.")
14231 (defconst org-property-drawer-re
14232 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14233 org-property-end-re "\\)\n?")
14234 "Matches an entire property drawer.")
14236 (defconst org-clock-drawer-re
14237 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14238 org-property-end-re "\\)\n?")
14239 "Matches an entire clock drawer.")
14241 (defsubst org-re-property (property)
14242 "Return a regexp matching a PROPERTY line.
14243 Match group 1 will be set to the value."
14244 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14246 (defsubst org-re-property-keyword (property)
14247 "Return a regexp matching a PROPERTY line, possibly with no
14248 value for the property."
14249 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14251 (defun org-property-action ()
14252 "Do an action on properties."
14253 (interactive)
14254 (let (c)
14255 (org-at-property-p)
14256 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14257 (setq c (read-char-exclusive))
14258 (cond
14259 ((equal c ?s)
14260 (call-interactively 'org-set-property))
14261 ((equal c ?d)
14262 (call-interactively 'org-delete-property))
14263 ((equal c ?D)
14264 (call-interactively 'org-delete-property-globally))
14265 ((equal c ?c)
14266 (call-interactively 'org-compute-property-at-point))
14267 (t (error "No such property action %c" c)))))
14269 (defun org-inc-effort ()
14270 "Increment the value of the effort property in the current entry."
14271 (interactive)
14272 (org-set-effort nil t))
14274 (defun org-set-effort (&optional value increment)
14275 "Set the effort property of the current entry.
14276 With numerical prefix arg, use the nth allowed value, 0 stands for the
14277 10th allowed value.
14279 When INCREMENT is non-nil, set the property to the next allowed value."
14280 (interactive "P")
14281 (if (equal value 0) (setq value 10))
14282 (let* ((completion-ignore-case t)
14283 (prop org-effort-property)
14284 (cur (org-entry-get nil prop))
14285 (allowed (org-property-get-allowed-values nil prop 'table))
14286 (existing (mapcar 'list (org-property-values prop)))
14288 (val (cond
14289 ((stringp value) value)
14290 ((and allowed (integerp value))
14291 (or (car (nth (1- value) allowed))
14292 (car (org-last allowed))))
14293 ((and allowed increment)
14294 (or (caadr (member (list cur) allowed))
14295 (error "Allowed effort values are not set")))
14296 (allowed
14297 (message "Select 1-9,0, [RET%s]: %s"
14298 (if cur (concat "=" cur) "")
14299 (mapconcat 'car allowed " "))
14300 (setq rpl (read-char-exclusive))
14301 (if (equal rpl ?\r)
14303 (setq rpl (- rpl ?0))
14304 (if (equal rpl 0) (setq rpl 10))
14305 (if (and (> rpl 0) (<= rpl (length allowed)))
14306 (car (nth (1- rpl) allowed))
14307 (org-completing-read "Effort: " allowed nil))))
14309 (let (org-completion-use-ido org-completion-use-iswitchb)
14310 (org-completing-read
14311 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14312 (concat "[" cur "]") "")
14313 ": ")
14314 existing nil nil "" nil cur))))))
14315 (unless (equal (org-entry-get nil prop) val)
14316 (org-entry-put nil prop val))
14317 (save-excursion
14318 (org-back-to-heading t)
14319 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14320 (message "%s is now %s" prop val)))
14322 (defun org-at-property-p ()
14323 "Is cursor inside a property drawer?"
14324 (save-excursion
14325 (beginning-of-line 1)
14326 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14327 (save-match-data ;; Used by calling procedures
14328 (let ((p (point))
14329 (range (unless (org-before-first-heading-p)
14330 (org-get-property-block))))
14331 (and range (<= (car range) p) (< p (cdr range))))))))
14333 (defun org-get-property-block (&optional beg end force)
14334 "Return the (beg . end) range of the body of the property drawer.
14335 BEG and END are the beginning and end of the current subtree, or of
14336 the part before the first headline. If they are not given, they will
14337 be found. If the drawer does not exist and FORCE is non-nil, create
14338 the drawer."
14339 (catch 'exit
14340 (save-excursion
14341 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14342 (progn (org-back-to-heading t) (point))))
14343 (end (or end (and (not (outline-next-heading)) (point-max))
14344 (point))))
14345 (goto-char beg)
14346 (if (re-search-forward org-property-start-re end t)
14347 (setq beg (1+ (match-end 0)))
14348 (if force
14349 (save-excursion
14350 (org-insert-property-drawer)
14351 (setq end (progn (outline-next-heading) (point))))
14352 (throw 'exit nil))
14353 (goto-char beg)
14354 (if (re-search-forward org-property-start-re end t)
14355 (setq beg (1+ (match-end 0)))))
14356 (if (re-search-forward org-property-end-re end t)
14357 (setq end (match-beginning 0))
14358 (or force (throw 'exit nil))
14359 (goto-char beg)
14360 (setq end beg)
14361 (org-indent-line)
14362 (insert ":END:\n"))
14363 (cons beg end)))))
14365 (defun org-entry-properties (&optional pom which specific)
14366 "Get all properties of the entry at point-or-marker POM.
14367 This includes the TODO keyword, the tags, time strings for deadline,
14368 scheduled, and clocking, and any additional properties defined in the
14369 entry. The return value is an alist, keys may occur multiple times
14370 if the property key was used several times.
14371 POM may also be nil, in which case the current entry is used.
14372 If WHICH is nil or `all', get all properties. If WHICH is
14373 `special' or `standard', only get that subclass. If WHICH
14374 is a string only get exactly this property. SPECIFIC can be a string, the
14375 specific property we are interested in. Specifying it can speed
14376 things up because then unnecessary parsing is avoided."
14377 (setq which (or which 'all))
14378 (org-with-point-at pom
14379 (let ((clockstr (substring org-clock-string 0 -1))
14380 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14381 (case-fold-search nil)
14382 beg end range props sum-props key key1 value string clocksum clocksumt)
14383 (save-excursion
14384 (when (condition-case nil
14385 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14386 (error nil))
14387 (setq beg (point))
14388 (setq sum-props (get-text-property (point) 'org-summaries))
14389 (setq clocksum (get-text-property (point) :org-clock-minutes)
14390 clocksumt (get-text-property (point) :org-clock-minutes-today))
14391 (outline-next-heading)
14392 (setq end (point))
14393 (when (memq which '(all special))
14394 ;; Get the special properties, like TODO and tags
14395 (goto-char beg)
14396 (when (and (or (not specific) (string= specific "TODO"))
14397 (looking-at org-todo-line-regexp) (match-end 2))
14398 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14399 (when (and (or (not specific) (string= specific "PRIORITY"))
14400 (looking-at org-priority-regexp))
14401 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14402 (when (or (not specific) (string= specific "FILE"))
14403 (push (cons "FILE" buffer-file-name) props))
14404 (when (and (or (not specific) (string= specific "TAGS"))
14405 (setq value (org-get-tags-string))
14406 (string-match "\\S-" value))
14407 (push (cons "TAGS" value) props))
14408 (when (and (or (not specific) (string= specific "ALLTAGS"))
14409 (setq value (org-get-tags-at)))
14410 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14411 ":"))
14412 props))
14413 (when (or (not specific) (string= specific "BLOCKED"))
14414 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14415 (when (or (not specific)
14416 (member specific
14417 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14418 "TIMESTAMP" "TIMESTAMP_IA")))
14419 (catch 'match
14420 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14421 (setq key (if (match-end 1)
14422 (substring (org-match-string-no-properties 1)
14423 0 -1))
14424 string (if (equal key clockstr)
14425 (org-trim
14426 (buffer-substring-no-properties
14427 (match-beginning 3) (goto-char
14428 (point-at-eol))))
14429 (substring (org-match-string-no-properties 3)
14430 1 -1)))
14431 ;; Get the correct property name from the key. This is
14432 ;; necessary if the user has configured time keywords.
14433 (setq key1 (concat key ":"))
14434 (cond
14435 ((not key)
14436 (setq key
14437 (if (= (char-after (match-beginning 3)) ?\[)
14438 "TIMESTAMP_IA" "TIMESTAMP")))
14439 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14440 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14441 ((equal key1 org-closed-string) (setq key "CLOSED"))
14442 ((equal key1 org-clock-string) (setq key "CLOCK")))
14443 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14444 (progn
14445 (push (cons key string) props)
14446 ;; no need to search further if match is found
14447 (throw 'match t))
14448 (when (or (equal key "CLOCK") (not (assoc key props)))
14449 (push (cons key string) props)))))))
14451 (when (memq which '(all standard))
14452 ;; Get the standard properties, like :PROP: ...
14453 (setq range (org-get-property-block beg end))
14454 (when range
14455 (goto-char (car range))
14456 (while (re-search-forward
14457 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14458 (cdr range) t)
14459 (setq key (org-match-string-no-properties 1)
14460 value (org-trim (or (org-match-string-no-properties 2) "")))
14461 (unless (member key excluded)
14462 (push (cons key (or value "")) props)))))
14463 (if clocksum
14464 (push (cons "CLOCKSUM"
14465 (org-columns-number-to-string (/ (float clocksum) 60.)
14466 'add_times))
14467 props))
14468 (if clocksumt
14469 (push (cons "CLOCKSUM_T"
14470 (org-columns-number-to-string (/ (float clocksumt) 60.)
14471 'add_times))
14472 props))
14473 (unless (assoc "CATEGORY" props)
14474 (push (cons "CATEGORY" (org-get-category)) props))
14475 (append sum-props (nreverse props)))))))
14477 (defun org-entry-get (pom property &optional inherit literal-nil)
14478 "Get value of PROPERTY for entry or content at point-or-marker POM.
14479 If INHERIT is non-nil and the entry does not have the property,
14480 then also check higher levels of the hierarchy.
14481 If INHERIT is the symbol `selective', use inheritance only if the setting
14482 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14483 If the property is present but empty, the return value is the empty string.
14484 If the property is not present at all, nil is returned.
14486 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14487 do not interpret it as the list atom nil. This is used for inheritance
14488 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14489 (org-with-point-at pom
14490 (if (and inherit (if (eq inherit 'selective)
14491 (org-property-inherit-p property)
14493 (org-entry-get-with-inheritance property literal-nil)
14494 (if (member property org-special-properties)
14495 ;; We need a special property. Use `org-entry-properties' to
14496 ;; retrieve it, but specify the wanted property
14497 (cdr (assoc property (org-entry-properties nil 'special property)))
14498 (let ((range (org-get-property-block)))
14499 (when (and range (not (eq (car range) (cdr range))))
14500 (let* ((props (list (or (assoc property org-file-properties)
14501 (assoc property org-global-properties)
14502 (assoc property org-global-properties-fixed))))
14503 (ap (lambda (key)
14504 (when (re-search-forward
14505 (org-re-property key) (cdr range) t)
14506 (setq props
14507 (org-update-property-plist
14509 (if (match-end 1)
14510 (org-match-string-no-properties 1) "")
14511 props)))))
14512 val)
14513 (goto-char (car range))
14514 (funcall ap property)
14515 (goto-char (car range))
14516 (while (funcall ap (concat property "+")))
14517 (setq val (cdr (assoc property props)))
14518 (when val (if literal-nil val (org-not-nil val))))))))))
14520 (defun org-property-or-variable-value (var &optional inherit)
14521 "Check if there is a property fixing the value of VAR.
14522 If yes, return this value. If not, return the current value of the variable."
14523 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14524 (if (and prop (stringp prop) (string-match "\\S-" prop))
14525 (read prop)
14526 (symbol-value var))))
14528 (defun org-entry-delete (pom property)
14529 "Delete the property PROPERTY from entry at point-or-marker POM."
14530 (org-with-point-at pom
14531 (if (member property org-special-properties)
14532 nil ; cannot delete these properties.
14533 (let ((range (org-get-property-block)))
14534 (if (and range
14535 (goto-char (car range))
14536 (re-search-forward
14537 (org-re-property property)
14538 (cdr range) t))
14539 (progn
14540 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14542 nil)))))
14544 ;; Multi-values properties are properties that contain multiple values
14545 ;; These values are assumed to be single words, separated by whitespace.
14546 (defun org-entry-add-to-multivalued-property (pom property value)
14547 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14548 (let* ((old (org-entry-get pom property))
14549 (values (and old (org-split-string old "[ \t]"))))
14550 (setq value (org-entry-protect-space value))
14551 (unless (member value values)
14552 (setq values (cons value values))
14553 (org-entry-put pom property
14554 (mapconcat 'identity values " ")))))
14556 (defun org-entry-remove-from-multivalued-property (pom property value)
14557 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14558 (let* ((old (org-entry-get pom property))
14559 (values (and old (org-split-string old "[ \t]"))))
14560 (setq value (org-entry-protect-space value))
14561 (when (member value values)
14562 (setq values (delete value values))
14563 (org-entry-put pom property
14564 (mapconcat 'identity values " ")))))
14566 (defun org-entry-member-in-multivalued-property (pom property value)
14567 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14568 (let* ((old (org-entry-get pom property))
14569 (values (and old (org-split-string old "[ \t]"))))
14570 (setq value (org-entry-protect-space value))
14571 (member value values)))
14573 (defun org-entry-get-multivalued-property (pom property)
14574 "Return a list of values in a multivalued property."
14575 (let* ((value (org-entry-get pom property))
14576 (values (and value (org-split-string value "[ \t]"))))
14577 (mapcar 'org-entry-restore-space values)))
14579 (defun org-entry-put-multivalued-property (pom property &rest values)
14580 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14581 VALUES should be a list of strings. Spaces will be protected."
14582 (org-entry-put pom property
14583 (mapconcat 'org-entry-protect-space values " "))
14584 (let* ((value (org-entry-get pom property))
14585 (values (and value (org-split-string value "[ \t]"))))
14586 (mapcar 'org-entry-restore-space values)))
14588 (defun org-entry-protect-space (s)
14589 "Protect spaces and newline in string S."
14590 (while (string-match " " s)
14591 (setq s (replace-match "%20" t t s)))
14592 (while (string-match "\n" s)
14593 (setq s (replace-match "%0A" t t s)))
14596 (defun org-entry-restore-space (s)
14597 "Restore spaces and newline in string S."
14598 (while (string-match "%20" s)
14599 (setq s (replace-match " " t t s)))
14600 (while (string-match "%0A" s)
14601 (setq s (replace-match "\n" t t s)))
14604 (defvar org-entry-property-inherited-from (make-marker)
14605 "Marker pointing to the entry from where a property was inherited.
14606 Each call to `org-entry-get-with-inheritance' will set this marker to the
14607 location of the entry where the inheritance search matched. If there was
14608 no match, the marker will point nowhere.
14609 Note that also `org-entry-get' calls this function, if the INHERIT flag
14610 is set.")
14612 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14613 "Get PROPERTY of entry or content at point, search higher levels if needed.
14614 The search will stop at the first ancestor which has the property defined.
14615 If the value found is \"nil\", return nil to show that the property
14616 should be considered as undefined (this is the meaning of nil here).
14617 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14618 (move-marker org-entry-property-inherited-from nil)
14619 (let (tmp)
14620 (save-excursion
14621 (save-restriction
14622 (widen)
14623 (catch 'ex
14624 (while t
14625 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14626 (or (ignore-errors (org-back-to-heading t))
14627 (goto-char (point-min)))
14628 (move-marker org-entry-property-inherited-from (point))
14629 (throw 'ex tmp))
14630 (or (ignore-errors (org-up-heading-safe))
14631 (throw 'ex nil))))))
14632 (setq tmp (or tmp
14633 (cdr (assoc property org-file-properties))
14634 (cdr (assoc property org-global-properties))
14635 (cdr (assoc property org-global-properties-fixed))))
14636 (if literal-nil tmp (org-not-nil tmp))))
14638 (defvar org-property-changed-functions nil
14639 "Hook called when the value of a property has changed.
14640 Each hook function should accept two arguments, the name of the property
14641 and the new value.")
14643 (defun org-entry-put (pom property value)
14644 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14645 (org-with-point-at pom
14646 (org-back-to-heading t)
14647 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14648 range)
14649 (cond
14650 ((equal property "TODO")
14651 (when (and (stringp value) (string-match "\\S-" value)
14652 (not (member value org-todo-keywords-1)))
14653 (error "\"%s\" is not a valid TODO state" value))
14654 (if (or (not value)
14655 (not (string-match "\\S-" value)))
14656 (setq value 'none))
14657 (org-todo value)
14658 (org-set-tags nil 'align))
14659 ((equal property "PRIORITY")
14660 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14661 (string-to-char value) ?\ ))
14662 (org-set-tags nil 'align))
14663 ((equal property "SCHEDULED")
14664 (if (re-search-forward org-scheduled-time-regexp end t)
14665 (cond
14666 ((eq value 'earlier) (org-timestamp-change -1 'day))
14667 ((eq value 'later) (org-timestamp-change 1 'day))
14668 (t (call-interactively 'org-schedule)))
14669 (call-interactively 'org-schedule)))
14670 ((equal property "DEADLINE")
14671 (if (re-search-forward org-deadline-time-regexp end t)
14672 (cond
14673 ((eq value 'earlier) (org-timestamp-change -1 'day))
14674 ((eq value 'later) (org-timestamp-change 1 'day))
14675 (t (call-interactively 'org-deadline)))
14676 (call-interactively 'org-deadline)))
14677 ((member property org-special-properties)
14678 (error "The %s property can not yet be set with `org-entry-put'"
14679 property))
14680 (t ; a non-special property
14681 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14682 (setq range (org-get-property-block beg end 'force))
14683 (goto-char (car range))
14684 (if (re-search-forward
14685 (org-re-property-keyword property) (cdr range) t)
14686 (progn
14687 (delete-region (match-beginning 0) (match-end 0))
14688 (goto-char (match-beginning 0)))
14689 (goto-char (cdr range))
14690 (insert "\n")
14691 (backward-char 1)
14692 (org-indent-line))
14693 (insert ":" property ":")
14694 (and value (insert " " value))
14695 (org-indent-line)))))
14696 (run-hook-with-args 'org-property-changed-functions property value)))
14698 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14699 "Get all property keys in the current buffer.
14700 With INCLUDE-SPECIALS, also list the special properties that reflect things
14701 like tags and TODO state.
14702 With INCLUDE-DEFAULTS, also include properties that has special meaning
14703 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14704 and others.
14705 With INCLUDE-COLUMNS, also include property names given in COLUMN
14706 formats in the current buffer."
14707 (let (rtn range cfmt s p)
14708 (save-excursion
14709 (save-restriction
14710 (widen)
14711 (goto-char (point-min))
14712 (while (re-search-forward org-property-start-re nil t)
14713 (setq range (org-get-property-block))
14714 (goto-char (car range))
14715 (while (re-search-forward
14716 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14717 (cdr range) t)
14718 (add-to-list 'rtn (org-match-string-no-properties 1)))
14719 (outline-next-heading))))
14721 (when include-specials
14722 (setq rtn (append org-special-properties rtn)))
14724 (when include-defaults
14725 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14726 (add-to-list 'rtn org-effort-property))
14728 (when include-columns
14729 (save-excursion
14730 (save-restriction
14731 (widen)
14732 (goto-char (point-min))
14733 (while (re-search-forward
14734 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14735 nil t)
14736 (setq cfmt (match-string 2) s 0)
14737 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14738 cfmt s)
14739 (setq s (match-end 0)
14740 p (match-string 1 cfmt))
14741 (unless (or (equal p "ITEM")
14742 (member p org-special-properties))
14743 (add-to-list 'rtn (match-string 1 cfmt))))))))
14745 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14747 (defun org-property-values (key)
14748 "Return a list of all values of property KEY in the current buffer."
14749 (save-excursion
14750 (save-restriction
14751 (widen)
14752 (goto-char (point-min))
14753 (let ((re (org-re-property key))
14754 values)
14755 (while (re-search-forward re nil t)
14756 (add-to-list 'values (org-trim (match-string 1))))
14757 (delete "" values)))))
14759 (defun org-insert-property-drawer ()
14760 "Insert a property drawer into the current entry."
14761 (org-back-to-heading t)
14762 (looking-at org-outline-regexp)
14763 (let ((indent (if org-adapt-indentation
14764 (- (match-end 0) (match-beginning 0))
14766 (beg (point))
14767 (re (concat "^[ \t]*" org-keyword-time-regexp))
14768 end hiddenp)
14769 (outline-next-heading)
14770 (setq end (point))
14771 (goto-char beg)
14772 (while (re-search-forward re end t))
14773 (setq hiddenp (outline-invisible-p))
14774 (end-of-line 1)
14775 (and (equal (char-after) ?\n) (forward-char 1))
14776 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14777 (if (member (match-string 1) '("CLOCK:" ":END:"))
14778 ;; just skip this line
14779 (beginning-of-line 2)
14780 ;; Drawer start, find the end
14781 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14782 (beginning-of-line 1)))
14783 (org-skip-over-state-notes)
14784 (skip-chars-backward " \t\n\r")
14785 (if (eq (char-before) ?*) (forward-char 1))
14786 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14787 (beginning-of-line 0)
14788 (org-indent-to-column indent)
14789 (beginning-of-line 2)
14790 (org-indent-to-column indent)
14791 (beginning-of-line 0)
14792 (if hiddenp
14793 (save-excursion
14794 (org-back-to-heading t)
14795 (hide-entry))
14796 (org-flag-drawer t))))
14798 (defun org-insert-drawer (&optional arg drawer)
14799 "Insert a drawer at point.
14801 Optional argument DRAWER, when non-nil, is a string representing
14802 drawer's name. Otherwise, the user is prompted for a name.
14804 If a region is active, insert the drawer around that region
14805 instead.
14807 Point is left between drawer's boundaries."
14808 (interactive "P")
14809 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14810 "LOGBOOK"))
14811 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14812 ;; internally by Org. They are meant to be inserted
14813 ;; automatically.
14814 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14815 ;; Remove system drawers from list. Note: For some reason,
14816 ;; `org-completing-read' ignores the predicate while
14817 ;; `completing-read' handles it fine.
14818 (drawer (if arg "PROPERTIES"
14819 (or drawer
14820 (completing-read
14821 "Drawer: " org-drawers
14822 (lambda (d) (not (member d system-drawers))))))))
14823 (cond
14824 ;; With C-u, fall back on `org-insert-property-drawer'
14825 (arg (org-insert-property-drawer))
14826 ;; With an active region, insert a drawer at point.
14827 ((not (org-region-active-p))
14828 (progn
14829 (unless (bolp) (insert "\n"))
14830 (insert (format ":%s:\n\n:END:\n" drawer))
14831 (forward-line -2)))
14832 ;; Otherwise, insert the drawer at point
14834 (let ((rbeg (region-beginning))
14835 (rend (copy-marker (region-end))))
14836 (unwind-protect
14837 (progn
14838 (goto-char rbeg)
14839 (beginning-of-line)
14840 (when (save-excursion
14841 (re-search-forward org-outline-regexp-bol rend t))
14842 (error "Drawers cannot contain headlines"))
14843 ;; Position point at the beginning of the first
14844 ;; non-blank line in region. Insert drawer's opening
14845 ;; there, then indent it.
14846 (org-skip-whitespace)
14847 (beginning-of-line)
14848 (insert ":" drawer ":\n")
14849 (forward-line -1)
14850 (indent-for-tab-command)
14851 ;; Move point to the beginning of the first blank line
14852 ;; after the last non-blank line in region. Insert
14853 ;; drawer's closing, then indent it.
14854 (goto-char rend)
14855 (skip-chars-backward " \r\t\n")
14856 (insert "\n:END:")
14857 (deactivate-mark t)
14858 (indent-for-tab-command)
14859 (unless (eolp) (insert "\n")))
14860 ;; Clear marker, whatever the outcome of insertion is.
14861 (set-marker rend nil)))))))
14863 (defvar org-property-set-functions-alist nil
14864 "Property set function alist.
14865 Each entry should have the following format:
14867 (PROPERTY . READ-FUNCTION)
14869 The read function will be called with the same argument as
14870 `org-completing-read'.")
14872 (defun org-set-property-function (property)
14873 "Get the function that should be used to set PROPERTY.
14874 This is computed according to `org-property-set-functions-alist'."
14875 (or (cdr (assoc property org-property-set-functions-alist))
14876 'org-completing-read))
14878 (defun org-read-property-value (property)
14879 "Read PROPERTY value from user."
14880 (let* ((completion-ignore-case t)
14881 (allowed (org-property-get-allowed-values nil property 'table))
14882 (cur (org-entry-get nil property))
14883 (prompt (concat property " value"
14884 (if (and cur (string-match "\\S-" cur))
14885 (concat " [" cur "]") "") ": "))
14886 (set-function (org-set-property-function property))
14887 (val (if allowed
14888 (funcall set-function prompt allowed nil
14889 (not (get-text-property 0 'org-unrestricted
14890 (caar allowed))))
14891 (let (org-completion-use-ido org-completion-use-iswitchb)
14892 (funcall set-function prompt
14893 (mapcar 'list (org-property-values property))
14894 nil nil "" nil cur)))))
14895 (if (equal val "")
14897 val)))
14899 (defvar org-last-set-property nil)
14900 (defun org-read-property-name ()
14901 "Read a property name."
14902 (let* ((completion-ignore-case t)
14903 (keys (org-buffer-property-keys nil t t))
14904 (default-prop (or (save-excursion
14905 (save-match-data
14906 (beginning-of-line)
14907 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14908 (null (string= (match-string 1) "END"))
14909 (match-string 1))))
14910 org-last-set-property))
14911 (property (org-icompleting-read
14912 (concat "Property"
14913 (if default-prop (concat " [" default-prop "]") "")
14914 ": ")
14915 (mapcar 'list keys)
14916 nil nil nil nil
14917 default-prop
14919 (if (member property keys)
14920 property
14921 (or (cdr (assoc (downcase property)
14922 (mapcar (lambda (x) (cons (downcase x) x))
14923 keys)))
14924 property))))
14926 (defun org-set-property (property value)
14927 "In the current entry, set PROPERTY to VALUE.
14928 When called interactively, this will prompt for a property name, offering
14929 completion on existing and default properties. And then it will prompt
14930 for a value, offering completion either on allowed values (via an inherited
14931 xxx_ALL property) or on existing values in other instances of this property
14932 in the current file."
14933 (interactive (list nil nil))
14934 (let* ((property (or property (org-read-property-name)))
14935 (value (or value (org-read-property-value property)))
14936 (fn (cdr (assoc property org-properties-postprocess-alist))))
14937 (setq org-last-set-property property)
14938 ;; Possibly postprocess the inserted value:
14939 (when fn (setq value (funcall fn value)))
14940 (unless (equal (org-entry-get nil property) value)
14941 (org-entry-put nil property value))))
14943 (defun org-delete-property (property)
14944 "In the current entry, delete PROPERTY."
14945 (interactive
14946 (let* ((completion-ignore-case t)
14947 (prop (org-icompleting-read "Property: "
14948 (org-entry-properties nil 'standard))))
14949 (list prop)))
14950 (message "Property %s %s" property
14951 (if (org-entry-delete nil property)
14952 "deleted"
14953 "was not present in the entry")))
14955 (defun org-delete-property-globally (property)
14956 "Remove PROPERTY globally, from all entries."
14957 (interactive
14958 (let* ((completion-ignore-case t)
14959 (prop (org-icompleting-read
14960 "Globally remove property: "
14961 (mapcar 'list (org-buffer-property-keys)))))
14962 (list prop)))
14963 (save-excursion
14964 (save-restriction
14965 (widen)
14966 (goto-char (point-min))
14967 (let ((cnt 0))
14968 (while (re-search-forward
14969 (org-re-property property)
14970 nil t)
14971 (setq cnt (1+ cnt))
14972 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14973 (message "Property \"%s\" removed from %d entries" property cnt)))))
14975 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14977 (defun org-compute-property-at-point ()
14978 "Compute the property at point.
14979 This looks for an enclosing column format, extracts the operator and
14980 then applies it to the property in the column format's scope."
14981 (interactive)
14982 (unless (org-at-property-p)
14983 (error "Not at a property"))
14984 (let ((prop (org-match-string-no-properties 2)))
14985 (org-columns-get-format-and-top-level)
14986 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14987 (error "No operator defined for property %s" prop))
14988 (org-columns-compute prop)))
14990 (defvar org-property-allowed-value-functions nil
14991 "Hook for functions supplying allowed values for a specific property.
14992 The functions must take a single argument, the name of the property, and
14993 return a flat list of allowed values. If \":ETC\" is one of
14994 the values, this means that these values are intended as defaults for
14995 completion, but that other values should be allowed too.
14996 The functions must return nil if they are not responsible for this
14997 property.")
14999 (defun org-property-get-allowed-values (pom property &optional table)
15000 "Get allowed values for the property PROPERTY.
15001 When TABLE is non-nil, return an alist that can directly be used for
15002 completion."
15003 (let (vals)
15004 (cond
15005 ((equal property "TODO")
15006 (setq vals (org-with-point-at pom
15007 (append org-todo-keywords-1 '("")))))
15008 ((equal property "PRIORITY")
15009 (let ((n org-lowest-priority))
15010 (while (>= n org-highest-priority)
15011 (push (char-to-string n) vals)
15012 (setq n (1- n)))))
15013 ((member property org-special-properties))
15014 ((setq vals (run-hook-with-args-until-success
15015 'org-property-allowed-value-functions property)))
15017 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15018 (when (and vals (string-match "\\S-" vals))
15019 (setq vals (car (read-from-string (concat "(" vals ")"))))
15020 (setq vals (mapcar (lambda (x)
15021 (cond ((stringp x) x)
15022 ((numberp x) (number-to-string x))
15023 ((symbolp x) (symbol-name x))
15024 (t "???")))
15025 vals)))))
15026 (when (member ":ETC" vals)
15027 (setq vals (remove ":ETC" vals))
15028 (org-add-props (car vals) '(org-unrestricted t)))
15029 (if table (mapcar 'list vals) vals)))
15031 (defun org-property-previous-allowed-value (&optional previous)
15032 "Switch to the next allowed value for this property."
15033 (interactive)
15034 (org-property-next-allowed-value t))
15036 (defun org-property-next-allowed-value (&optional previous)
15037 "Switch to the next allowed value for this property."
15038 (interactive)
15039 (unless (org-at-property-p)
15040 (error "Not at a property"))
15041 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15042 (key (match-string 2))
15043 (value (match-string 3))
15044 (allowed (or (org-property-get-allowed-values (point) key)
15045 (and (member value '("[ ]" "[-]" "[X]"))
15046 '("[ ]" "[X]"))))
15047 nval)
15048 (unless allowed
15049 (error "Allowed values for this property have not been defined"))
15050 (if previous (setq allowed (reverse allowed)))
15051 (if (member value allowed)
15052 (setq nval (car (cdr (member value allowed)))))
15053 (setq nval (or nval (car allowed)))
15054 (if (equal nval value)
15055 (error "Only one allowed value for this property"))
15056 (org-at-property-p)
15057 (replace-match (concat " :" key ": " nval) t t)
15058 (org-indent-line)
15059 (beginning-of-line 1)
15060 (skip-chars-forward " \t")
15061 (when (equal prop org-effort-property)
15062 (save-excursion
15063 (org-back-to-heading t)
15064 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15065 (run-hook-with-args 'org-property-changed-functions key nval)))
15067 (defun org-find-olp (path &optional this-buffer)
15068 "Return a marker pointing to the entry at outline path OLP.
15069 If anything goes wrong, throw an error.
15070 You can wrap this call to catch the error like this:
15072 (condition-case msg
15073 (org-mobile-locate-entry (match-string 4))
15074 (error (nth 1 msg)))
15076 The return value will then be either a string with the error message,
15077 or a marker if everything is OK.
15079 If THIS-BUFFER is set, the outline path does not contain a file,
15080 only headings."
15081 (let* ((file (if this-buffer buffer-file-name (pop path)))
15082 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15083 (level 1)
15084 (lmin 1)
15085 (lmax 1)
15086 limit re end found pos heading cnt flevel)
15087 (unless buffer (error "File not found :%s" file))
15088 (with-current-buffer buffer
15089 (save-excursion
15090 (save-restriction
15091 (widen)
15092 (setq limit (point-max))
15093 (goto-char (point-min))
15094 (while (setq heading (pop path))
15095 (setq re (format org-complex-heading-regexp-format
15096 (regexp-quote heading)))
15097 (setq cnt 0 pos (point))
15098 (while (re-search-forward re end t)
15099 (setq level (- (match-end 1) (match-beginning 1)))
15100 (if (and (>= level lmin) (<= level lmax))
15101 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15102 (when (= cnt 0) (error "Heading not found on level %d: %s"
15103 lmax heading))
15104 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15105 lmax heading))
15106 (goto-char found)
15107 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15108 (setq end (save-excursion (org-end-of-subtree t t))))
15109 (when (org-at-heading-p)
15110 (point-marker)))))))
15112 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15113 "Find node HEADING in BUFFER.
15114 Return a marker to the heading if it was found, or nil if not.
15115 If POS-ONLY is set, return just the position instead of a marker.
15117 The heading text must match exact, but it may have a TODO keyword,
15118 a priority cookie and tags in the standard locations."
15119 (with-current-buffer (or buffer (current-buffer))
15120 (save-excursion
15121 (save-restriction
15122 (widen)
15123 (goto-char (point-min))
15124 (let (case-fold-search)
15125 (if (re-search-forward
15126 (format org-complex-heading-regexp-format
15127 (regexp-quote heading)) nil t)
15128 (if pos-only
15129 (match-beginning 0)
15130 (move-marker (make-marker) (match-beginning 0)))))))))
15132 (defun org-find-exact-heading-in-directory (heading &optional dir)
15133 "Find Org node headline HEADING in all .org files in directory DIR.
15134 When the target headline is found, return a marker to this location."
15135 (let ((files (directory-files (or dir default-directory)
15136 nil "\\`[^.#].*\\.org\\'"))
15137 file visiting m buffer)
15138 (catch 'found
15139 (while (setq file (pop files))
15140 (message "trying %s" file)
15141 (setq visiting (org-find-base-buffer-visiting file))
15142 (setq buffer (or visiting (find-file-noselect file)))
15143 (setq m (org-find-exact-headline-in-buffer
15144 heading buffer))
15145 (when (and (not m) (not visiting)) (kill-buffer buffer))
15146 (and m (throw 'found m))))))
15148 (defun org-find-entry-with-id (ident)
15149 "Locate the entry that contains the ID property with exact value IDENT.
15150 IDENT can be a string, a symbol or a number, this function will search for
15151 the string representation of it.
15152 Return the position where this entry starts, or nil if there is no such entry."
15153 (interactive "sID: ")
15154 (let ((id (cond
15155 ((stringp ident) ident)
15156 ((symbol-name ident) (symbol-name ident))
15157 ((numberp ident) (number-to-string ident))
15158 (t (error "IDENT %s must be a string, symbol or number" ident))))
15159 (case-fold-search nil))
15160 (save-excursion
15161 (save-restriction
15162 (widen)
15163 (goto-char (point-min))
15164 (when (re-search-forward
15165 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15166 nil t)
15167 (org-back-to-heading t)
15168 (point))))))
15170 ;;;; Timestamps
15172 (defvar org-last-changed-timestamp nil)
15173 (defvar org-last-inserted-timestamp nil
15174 "The last time stamp inserted with `org-insert-time-stamp'.")
15175 (defvar org-time-was-given) ; dynamically scoped parameter
15176 (defvar org-end-time-was-given) ; dynamically scoped parameter
15177 (defvar org-ts-what) ; dynamically scoped parameter
15179 (defun org-time-stamp (arg &optional inactive)
15180 "Prompt for a date/time and insert a time stamp.
15181 If the user specifies a time like HH:MM or if this command is
15182 called with at least one prefix argument, the time stamp contains
15183 the date and the time. Otherwise, only the date is be included.
15185 All parts of a date not specified by the user is filled in from
15186 the current date/time. So if you just press return without
15187 typing anything, the time stamp will represent the current
15188 date/time.
15190 If there is already a timestamp at the cursor, it will be
15191 modified.
15193 With two universal prefix arguments, insert an active timestamp
15194 with the current time without prompting the user."
15195 (interactive "P")
15196 (let* ((ts nil)
15197 (default-time
15198 ;; Default time is either today, or, when entering a range,
15199 ;; the range start.
15200 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15201 (save-excursion
15202 (re-search-backward
15203 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15204 (- (point) 20) t)))
15205 (apply 'encode-time (org-parse-time-string (match-string 1)))
15206 (current-time)))
15207 (default-input (and ts (org-get-compact-tod ts)))
15208 (repeater (save-excursion
15209 (save-match-data
15210 (beginning-of-line)
15211 (when (re-search-forward
15212 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15213 (save-excursion (progn (end-of-line) (point))) t)
15214 (match-string 0)))))
15215 org-time-was-given org-end-time-was-given time)
15216 (cond
15217 ((and (org-at-timestamp-p t)
15218 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15219 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15220 (insert "--")
15221 (setq time (let ((this-command this-command))
15222 (org-read-date arg 'totime nil nil
15223 default-time default-input inactive)))
15224 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15225 ((org-at-timestamp-p t)
15226 (setq time (let ((this-command this-command))
15227 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15228 (when (org-at-timestamp-p t) ; just to get the match data
15229 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15230 (replace-match "")
15231 (setq org-last-changed-timestamp
15232 (org-insert-time-stamp
15233 time (or org-time-was-given arg)
15234 inactive nil nil (list org-end-time-was-given)))
15235 (when repeater (goto-char (1- (point))) (insert " " repeater)
15236 (setq org-last-changed-timestamp
15237 (concat (substring org-last-inserted-timestamp 0 -1)
15238 " " repeater ">"))))
15239 (message "Timestamp updated"))
15240 ((equal arg '(16))
15241 (org-insert-time-stamp (current-time) t))
15243 (setq time (let ((this-command this-command))
15244 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15245 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15246 nil nil (list org-end-time-was-given))))))
15248 ;; FIXME: can we use this for something else, like computing time differences?
15249 (defun org-get-compact-tod (s)
15250 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15251 (let* ((t1 (match-string 1 s))
15252 (h1 (string-to-number (match-string 2 s)))
15253 (m1 (string-to-number (match-string 3 s)))
15254 (t2 (and (match-end 4) (match-string 5 s)))
15255 (h2 (and t2 (string-to-number (match-string 6 s))))
15256 (m2 (and t2 (string-to-number (match-string 7 s))))
15257 dh dm)
15258 (if (not t2)
15260 (setq dh (- h2 h1) dm (- m2 m1))
15261 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15262 (concat t1 "+" (number-to-string dh)
15263 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15265 (defun org-time-stamp-inactive (&optional arg)
15266 "Insert an inactive time stamp.
15267 An inactive time stamp is enclosed in square brackets instead of angle
15268 brackets. It is inactive in the sense that it does not trigger agenda entries,
15269 does not link to the calendar and cannot be changed with the S-cursor keys.
15270 So these are more for recording a certain time/date."
15271 (interactive "P")
15272 (org-time-stamp arg 'inactive))
15274 (defvar org-date-ovl (make-overlay 1 1))
15275 (overlay-put org-date-ovl 'face 'org-date-selected)
15276 (org-detach-overlay org-date-ovl)
15278 (defvar org-ans1) ; dynamically scoped parameter
15279 (defvar org-ans2) ; dynamically scoped parameter
15281 (defvar org-plain-time-of-day-regexp) ; defined below
15283 (defvar org-overriding-default-time nil) ; dynamically scoped
15284 (defvar org-read-date-overlay nil)
15285 (defvar org-dcst nil) ; dynamically scoped
15286 (defvar org-read-date-history nil)
15287 (defvar org-read-date-final-answer nil)
15288 (defvar org-read-date-analyze-futurep nil)
15289 (defvar org-read-date-analyze-forced-year nil)
15290 (defvar org-read-date-inactive)
15292 (defun org-read-date (&optional org-with-time to-time from-string prompt
15293 default-time default-input inactive)
15294 "Read a date, possibly a time, and make things smooth for the user.
15295 The prompt will suggest to enter an ISO date, but you can also enter anything
15296 which will at least partially be understood by `parse-time-string'.
15297 Unrecognized parts of the date will default to the current day, month, year,
15298 hour and minute. If this command is called to replace a timestamp at point,
15299 or to enter the second timestamp of a range, the default time is taken
15300 from the existing stamp. Furthermore, the command prefers the future,
15301 so if you are giving a date where the year is not given, and the day-month
15302 combination is already past in the current year, it will assume you
15303 mean next year. For details, see the manual. A few examples:
15305 3-2-5 --> 2003-02-05
15306 feb 15 --> currentyear-02-15
15307 2/15 --> currentyear-02-15
15308 sep 12 9 --> 2009-09-12
15309 12:45 --> today 12:45
15310 22 sept 0:34 --> currentyear-09-22 0:34
15311 12 --> currentyear-currentmonth-12
15312 Fri --> nearest Friday (today or later)
15313 etc.
15315 Furthermore you can specify a relative date by giving, as the *first* thing
15316 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15317 change in days weeks, months, years.
15318 With a single plus or minus, the date is relative to today. With a double
15319 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15320 +4d --> four days from today
15321 +4 --> same as above
15322 +2w --> two weeks from today
15323 ++5 --> five days from default date
15325 The function understands only English month and weekday abbreviations.
15327 While prompting, a calendar is popped up - you can also select the
15328 date with the mouse (button 1). The calendar shows a period of three
15329 months. To scroll it to other months, use the keys `>' and `<'.
15330 If you don't like the calendar, turn it off with
15331 \(setq org-read-date-popup-calendar nil)
15333 With optional argument TO-TIME, the date will immediately be converted
15334 to an internal time.
15335 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15336 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15337 still enter a time, and this function will inform the calling routine
15338 about this change. The calling routine may then choose to change the
15339 format used to insert the time stamp into the buffer to include the time.
15340 With optional argument FROM-STRING, read from this string instead from
15341 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15342 the time/date that is used for everything that is not specified by the
15343 user."
15344 (require 'parse-time)
15345 (let* ((org-time-stamp-rounding-minutes
15346 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15347 (org-dcst org-display-custom-times)
15348 (ct (org-current-time))
15349 (org-def (or org-overriding-default-time default-time ct))
15350 (org-defdecode (decode-time org-def))
15351 (dummy (progn
15352 (when (< (nth 2 org-defdecode) org-extend-today-until)
15353 (setcar (nthcdr 2 org-defdecode) -1)
15354 (setcar (nthcdr 1 org-defdecode) 59)
15355 (setq org-def (apply 'encode-time org-defdecode)
15356 org-defdecode (decode-time org-def)))))
15357 (mouse-autoselect-window nil) ; Don't let the mouse jump
15358 (calendar-frame-setup nil)
15359 (calendar-setup nil)
15360 (calendar-move-hook nil)
15361 (calendar-view-diary-initially-flag nil)
15362 (calendar-view-holidays-initially-flag nil)
15363 (timestr (format-time-string
15364 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15365 (prompt (concat (if prompt (concat prompt " ") "")
15366 (format "Date+time [%s]: " timestr)))
15367 ans (org-ans0 "") org-ans1 org-ans2 final)
15369 (cond
15370 (from-string (setq ans from-string))
15371 (org-read-date-popup-calendar
15372 (save-excursion
15373 (save-window-excursion
15374 (calendar)
15375 (org-eval-in-calendar '(setq cursor-type nil) t)
15376 (unwind-protect
15377 (progn
15378 (calendar-forward-day (- (time-to-days org-def)
15379 (calendar-absolute-from-gregorian
15380 (calendar-current-date))))
15381 (org-eval-in-calendar nil t)
15382 (let* ((old-map (current-local-map))
15383 (map (copy-keymap calendar-mode-map))
15384 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15385 (org-defkey map (kbd "RET") 'org-calendar-select)
15386 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15387 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15388 (org-defkey minibuffer-local-map [(meta shift left)]
15389 (lambda () (interactive)
15390 (org-eval-in-calendar '(calendar-backward-month 1))))
15391 (org-defkey minibuffer-local-map [(meta shift right)]
15392 (lambda () (interactive)
15393 (org-eval-in-calendar '(calendar-forward-month 1))))
15394 (org-defkey minibuffer-local-map [(meta shift up)]
15395 (lambda () (interactive)
15396 (org-eval-in-calendar '(calendar-backward-year 1))))
15397 (org-defkey minibuffer-local-map [(meta shift down)]
15398 (lambda () (interactive)
15399 (org-eval-in-calendar '(calendar-forward-year 1))))
15400 (org-defkey minibuffer-local-map [?\e (shift left)]
15401 (lambda () (interactive)
15402 (org-eval-in-calendar '(calendar-backward-month 1))))
15403 (org-defkey minibuffer-local-map [?\e (shift right)]
15404 (lambda () (interactive)
15405 (org-eval-in-calendar '(calendar-forward-month 1))))
15406 (org-defkey minibuffer-local-map [?\e (shift up)]
15407 (lambda () (interactive)
15408 (org-eval-in-calendar '(calendar-backward-year 1))))
15409 (org-defkey minibuffer-local-map [?\e (shift down)]
15410 (lambda () (interactive)
15411 (org-eval-in-calendar '(calendar-forward-year 1))))
15412 (org-defkey minibuffer-local-map [(shift up)]
15413 (lambda () (interactive)
15414 (org-eval-in-calendar '(calendar-backward-week 1))))
15415 (org-defkey minibuffer-local-map [(shift down)]
15416 (lambda () (interactive)
15417 (org-eval-in-calendar '(calendar-forward-week 1))))
15418 (org-defkey minibuffer-local-map [(shift left)]
15419 (lambda () (interactive)
15420 (org-eval-in-calendar '(calendar-backward-day 1))))
15421 (org-defkey minibuffer-local-map [(shift right)]
15422 (lambda () (interactive)
15423 (org-eval-in-calendar '(calendar-forward-day 1))))
15424 (org-defkey minibuffer-local-map ">"
15425 (lambda () (interactive)
15426 (org-eval-in-calendar '(scroll-calendar-left 1))))
15427 (org-defkey minibuffer-local-map "<"
15428 (lambda () (interactive)
15429 (org-eval-in-calendar '(scroll-calendar-right 1))))
15430 (org-defkey minibuffer-local-map "\C-v"
15431 (lambda () (interactive)
15432 (org-eval-in-calendar
15433 '(calendar-scroll-left-three-months 1))))
15434 (org-defkey minibuffer-local-map "\M-v"
15435 (lambda () (interactive)
15436 (org-eval-in-calendar
15437 '(calendar-scroll-right-three-months 1))))
15438 (run-hooks 'org-read-date-minibuffer-setup-hook)
15439 (unwind-protect
15440 (progn
15441 (use-local-map map)
15442 (setq org-read-date-inactive inactive)
15443 (add-hook 'post-command-hook 'org-read-date-display)
15444 (setq org-ans0 (read-string prompt default-input
15445 'org-read-date-history nil))
15446 ;; org-ans0: from prompt
15447 ;; org-ans1: from mouse click
15448 ;; org-ans2: from calendar motion
15449 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15450 (remove-hook 'post-command-hook 'org-read-date-display)
15451 (use-local-map old-map)
15452 (when org-read-date-overlay
15453 (delete-overlay org-read-date-overlay)
15454 (setq org-read-date-overlay nil)))))
15455 (bury-buffer "*Calendar*")))))
15457 (t ; Naked prompt only
15458 (unwind-protect
15459 (setq ans (read-string prompt default-input
15460 'org-read-date-history timestr))
15461 (when org-read-date-overlay
15462 (delete-overlay org-read-date-overlay)
15463 (setq org-read-date-overlay nil)))))
15465 (setq final (org-read-date-analyze ans org-def org-defdecode))
15467 (when org-read-date-analyze-forced-year
15468 (message "Year was forced into %s"
15469 (if org-read-date-force-compatible-dates
15470 "compatible range (1970-2037)"
15471 "range representable on this machine"))
15472 (ding))
15474 ;; One round trip to get rid of 34th of August and stuff like that....
15475 (setq final (decode-time (apply 'encode-time final)))
15477 (setq org-read-date-final-answer ans)
15479 (if to-time
15480 (apply 'encode-time final)
15481 (if (and (boundp 'org-time-was-given) org-time-was-given)
15482 (format "%04d-%02d-%02d %02d:%02d"
15483 (nth 5 final) (nth 4 final) (nth 3 final)
15484 (nth 2 final) (nth 1 final))
15485 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15487 (defvar org-def)
15488 (defvar org-defdecode)
15489 (defvar org-with-time)
15490 (defun org-read-date-display ()
15491 "Display the current date prompt interpretation in the minibuffer."
15492 (when org-read-date-display-live
15493 (when org-read-date-overlay
15494 (delete-overlay org-read-date-overlay))
15495 (when (minibufferp (current-buffer))
15496 (save-excursion
15497 (end-of-line 1)
15498 (while (not (equal (buffer-substring
15499 (max (point-min) (- (point) 4)) (point))
15500 " "))
15501 (insert " ")))
15502 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15503 " " (or org-ans1 org-ans2)))
15504 (org-end-time-was-given nil)
15505 (f (org-read-date-analyze ans org-def org-defdecode))
15506 (fmts (if org-dcst
15507 org-time-stamp-custom-formats
15508 org-time-stamp-formats))
15509 (fmt (if (or org-with-time
15510 (and (boundp 'org-time-was-given) org-time-was-given))
15511 (cdr fmts)
15512 (car fmts)))
15513 (txt (format-time-string fmt (apply 'encode-time f)))
15514 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15515 (txt (concat "=> " txt)))
15516 (when (and org-end-time-was-given
15517 (string-match org-plain-time-of-day-regexp txt))
15518 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15519 org-end-time-was-given
15520 (substring txt (match-end 0)))))
15521 (when org-read-date-analyze-futurep
15522 (setq txt (concat txt " (=>F)")))
15523 (setq org-read-date-overlay
15524 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15525 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15527 (defun org-read-date-analyze (ans org-def org-defdecode)
15528 "Analyze the combined answer of the date prompt."
15529 ;; FIXME: cleanup and comment
15530 (let ((nowdecode (decode-time (current-time)))
15531 delta deltan deltaw deltadef year month day
15532 hour minute second wday pm h2 m2 tl wday1
15533 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15534 (setq org-read-date-analyze-futurep nil
15535 org-read-date-analyze-forced-year nil)
15536 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15537 (setq ans "+0"))
15539 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15540 (setq ans (replace-match "" t t ans)
15541 deltan (car delta)
15542 deltaw (nth 1 delta)
15543 deltadef (nth 2 delta)))
15545 ;; Check if there is an iso week date in there. If yes, store the
15546 ;; info and postpone interpreting it until the rest of the parsing
15547 ;; is done.
15548 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15549 (setq iso-year (if (match-end 1)
15550 (org-small-year-to-year
15551 (string-to-number (match-string 1 ans))))
15552 iso-weekday (if (match-end 3)
15553 (string-to-number (match-string 3 ans)))
15554 iso-week (string-to-number (match-string 2 ans)))
15555 (setq ans (replace-match "" t t ans)))
15557 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15558 (when (string-match
15559 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15560 (setq year (if (match-end 2)
15561 (string-to-number (match-string 2 ans))
15562 (progn (setq kill-year t)
15563 (string-to-number (format-time-string "%Y"))))
15564 month (string-to-number (match-string 3 ans))
15565 day (string-to-number (match-string 4 ans)))
15566 (if (< year 100) (setq year (+ 2000 year)))
15567 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15568 t nil ans)))
15570 ;; Help matching dotted european dates
15571 (when (string-match
15572 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15573 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15574 (setq kill-year t)
15575 (string-to-number (format-time-string "%Y")))
15576 day (string-to-number (match-string 1 ans))
15577 month (string-to-number (match-string 2 ans))
15578 ans (replace-match (format "%04d-%02d-%02d" year month day)
15579 t nil ans)))
15581 ;; Help matching american dates, like 5/30 or 5/30/7
15582 (when (string-match
15583 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15584 (setq year (if (match-end 4)
15585 (string-to-number (match-string 4 ans))
15586 (progn (setq kill-year t)
15587 (string-to-number (format-time-string "%Y"))))
15588 month (string-to-number (match-string 1 ans))
15589 day (string-to-number (match-string 2 ans)))
15590 (if (< year 100) (setq year (+ 2000 year)))
15591 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15592 t nil ans)))
15593 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15594 ;; If there is a time with am/pm, and *no* time without it, we convert
15595 ;; so that matching will be successful.
15596 (loop for i from 1 to 2 do ; twice, for end time as well
15597 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15598 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15599 (setq hour (string-to-number (match-string 1 ans))
15600 minute (if (match-end 3)
15601 (string-to-number (match-string 3 ans))
15603 pm (equal ?p
15604 (string-to-char (downcase (match-string 4 ans)))))
15605 (if (and (= hour 12) (not pm))
15606 (setq hour 0)
15607 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15608 (setq ans (replace-match (format "%02d:%02d" hour minute)
15609 t t ans))))
15611 ;; Check if a time range is given as a duration
15612 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15613 (setq hour (string-to-number (match-string 1 ans))
15614 h2 (+ hour (string-to-number (match-string 3 ans)))
15615 minute (string-to-number (match-string 2 ans))
15616 m2 (+ minute (if (match-end 5) (string-to-number
15617 (match-string 5 ans))0)))
15618 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15619 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15620 t t ans)))
15622 ;; Check if there is a time range
15623 (when (boundp 'org-end-time-was-given)
15624 (setq org-time-was-given nil)
15625 (when (and (string-match org-plain-time-of-day-regexp ans)
15626 (match-end 8))
15627 (setq org-end-time-was-given (match-string 8 ans))
15628 (setq ans (concat (substring ans 0 (match-beginning 7))
15629 (substring ans (match-end 7))))))
15631 (setq tl (parse-time-string ans)
15632 day (or (nth 3 tl) (nth 3 org-defdecode))
15633 month (or (nth 4 tl)
15634 (if (and org-read-date-prefer-future
15635 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15636 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15637 (nth 4 org-defdecode)))
15638 year (or (and (not kill-year) (nth 5 tl))
15639 (if (and org-read-date-prefer-future
15640 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15641 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15642 (nth 5 org-defdecode)))
15643 hour (or (nth 2 tl) (nth 2 org-defdecode))
15644 minute (or (nth 1 tl) (nth 1 org-defdecode))
15645 second (or (nth 0 tl) 0)
15646 wday (nth 6 tl))
15648 (when (and (eq org-read-date-prefer-future 'time)
15649 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15650 (equal day (nth 3 nowdecode))
15651 (equal month (nth 4 nowdecode))
15652 (equal year (nth 5 nowdecode))
15653 (nth 2 tl)
15654 (or (< (nth 2 tl) (nth 2 nowdecode))
15655 (and (= (nth 2 tl) (nth 2 nowdecode))
15656 (nth 1 tl)
15657 (< (nth 1 tl) (nth 1 nowdecode)))))
15658 (setq day (1+ day)
15659 futurep t))
15661 ;; Special date definitions below
15662 (cond
15663 (iso-week
15664 ;; There was an iso week
15665 (require 'cal-iso)
15666 (setq futurep nil)
15667 (setq year (or iso-year year)
15668 day (or iso-weekday wday 1)
15669 wday nil ; to make sure that the trigger below does not match
15670 iso-date (calendar-gregorian-from-absolute
15671 (calendar-absolute-from-iso
15672 (list iso-week day year))))
15673 ; FIXME: Should we also push ISO weeks into the future?
15674 ; (when (and org-read-date-prefer-future
15675 ; (not iso-year)
15676 ; (< (calendar-absolute-from-gregorian iso-date)
15677 ; (time-to-days (current-time))))
15678 ; (setq year (1+ year)
15679 ; iso-date (calendar-gregorian-from-absolute
15680 ; (calendar-absolute-from-iso
15681 ; (list iso-week day year)))))
15682 (setq month (car iso-date)
15683 year (nth 2 iso-date)
15684 day (nth 1 iso-date)))
15685 (deltan
15686 (setq futurep nil)
15687 (unless deltadef
15688 (let ((now (decode-time (current-time))))
15689 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15690 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15691 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15692 ((equal deltaw "m") (setq month (+ month deltan)))
15693 ((equal deltaw "y") (setq year (+ year deltan)))))
15694 ((and wday (not (nth 3 tl)))
15695 ;; Weekday was given, but no day, so pick that day in the week
15696 ;; on or after the derived date.
15697 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15698 (unless (equal wday wday1)
15699 (setq day (+ day (% (- wday wday1 -7) 7))))))
15700 (if (and (boundp 'org-time-was-given)
15701 (nth 2 tl))
15702 (setq org-time-was-given t))
15703 (if (< year 100) (setq year (+ 2000 year)))
15704 ;; Check of the date is representable
15705 (if org-read-date-force-compatible-dates
15706 (progn
15707 (if (< year 1970)
15708 (setq year 1970 org-read-date-analyze-forced-year t))
15709 (if (> year 2037)
15710 (setq year 2037 org-read-date-analyze-forced-year t)))
15711 (condition-case nil
15712 (ignore (encode-time second minute hour day month year))
15713 (error
15714 (setq year (nth 5 org-defdecode))
15715 (setq org-read-date-analyze-forced-year t))))
15716 (setq org-read-date-analyze-futurep futurep)
15717 (list second minute hour day month year)))
15719 (defvar parse-time-weekdays)
15720 (defun org-read-date-get-relative (s today default)
15721 "Check string S for special relative date string.
15722 TODAY and DEFAULT are internal times, for today and for a default.
15723 Return shift list (N what def-flag)
15724 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15725 N is the number of WHATs to shift.
15726 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15727 the DEFAULT date rather than TODAY."
15728 (require 'parse-time)
15729 (when (and
15730 (string-match
15731 (concat
15732 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15733 "\\([0-9]+\\)?"
15734 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15735 "\\([ \t]\\|$\\)") s)
15736 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15737 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15738 (string-to-char (substring (match-string 1 s) -1))
15739 ?+))
15740 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15741 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15742 (what (if (match-end 3) (match-string 3 s) "d"))
15743 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15744 (date (if rel default today))
15745 (wday (nth 6 (decode-time date)))
15746 delta)
15747 (if wday1
15748 (progn
15749 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15750 (if (= dir ?-) (setq delta (- delta 7)))
15751 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15752 (list delta "d" rel))
15753 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15755 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15756 "Turn a user-specified date into the internal representation.
15757 The internal representation needed by the calendar is (month day year).
15758 This is a wrapper to handle the brain-dead convention in calendar that
15759 user function argument order change dependent on argument order."
15760 (if (boundp 'calendar-date-style)
15761 (cond
15762 ((eq calendar-date-style 'american)
15763 (list arg1 arg2 arg3))
15764 ((eq calendar-date-style 'european)
15765 (list arg2 arg1 arg3))
15766 ((eq calendar-date-style 'iso)
15767 (list arg2 arg3 arg1)))
15768 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15769 (if (org-bound-and-true-p european-calendar-style)
15770 (list arg2 arg1 arg3)
15771 (list arg1 arg2 arg3)))))
15773 (defun org-eval-in-calendar (form &optional keepdate)
15774 "Eval FORM in the calendar window and return to current window.
15775 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15776 otherwise stick to the current value of `org-ans2'."
15777 (let ((sf (selected-frame))
15778 (sw (selected-window)))
15779 (select-window (get-buffer-window "*Calendar*" t))
15780 (eval form)
15781 (when (and (not keepdate) (calendar-cursor-to-date))
15782 (let* ((date (calendar-cursor-to-date))
15783 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15784 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15785 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15786 (select-window sw)
15787 (org-select-frame-set-input-focus sf)))
15789 (defun org-calendar-select ()
15790 "Return to `org-read-date' with the date currently selected.
15791 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15792 (interactive)
15793 (when (calendar-cursor-to-date)
15794 (let* ((date (calendar-cursor-to-date))
15795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15796 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15797 (if (active-minibuffer-window) (exit-minibuffer))))
15799 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15800 "Insert a date stamp for the date given by the internal TIME.
15801 WITH-HM means use the stamp format that includes the time of the day.
15802 INACTIVE means use square brackets instead of angular ones, so that the
15803 stamp will not contribute to the agenda.
15804 PRE and POST are optional strings to be inserted before and after the
15805 stamp.
15806 The command returns the inserted time stamp."
15807 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15808 stamp)
15809 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15810 (insert-before-markers (or pre ""))
15811 (when (listp extra)
15812 (setq extra (car extra))
15813 (if (and (stringp extra)
15814 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15815 (setq extra (format "-%02d:%02d"
15816 (string-to-number (match-string 1 extra))
15817 (string-to-number (match-string 2 extra))))
15818 (setq extra nil)))
15819 (when extra
15820 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15821 (insert-before-markers (setq stamp (format-time-string fmt time)))
15822 (insert-before-markers (or post ""))
15823 (setq org-last-inserted-timestamp stamp)))
15825 (defun org-toggle-time-stamp-overlays ()
15826 "Toggle the use of custom time stamp formats."
15827 (interactive)
15828 (setq org-display-custom-times (not org-display-custom-times))
15829 (unless org-display-custom-times
15830 (let ((p (point-min)) (bmp (buffer-modified-p)))
15831 (while (setq p (next-single-property-change p 'display))
15832 (if (and (get-text-property p 'display)
15833 (eq (get-text-property p 'face) 'org-date))
15834 (remove-text-properties
15835 p (setq p (next-single-property-change p 'display))
15836 '(display t))))
15837 (set-buffer-modified-p bmp)))
15838 (if (featurep 'xemacs)
15839 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15840 (org-restart-font-lock)
15841 (setq org-table-may-need-update t)
15842 (if org-display-custom-times
15843 (message "Time stamps are overlaid with custom format")
15844 (message "Time stamp overlays removed")))
15846 (defun org-display-custom-time (beg end)
15847 "Overlay modified time stamp format over timestamp between BEG and END."
15848 (let* ((ts (buffer-substring beg end))
15849 t1 w1 with-hm tf time str w2 (off 0))
15850 (save-match-data
15851 (setq t1 (org-parse-time-string ts t))
15852 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15853 (setq off (- (match-end 0) (match-beginning 0)))))
15854 (setq end (- end off))
15855 (setq w1 (- end beg)
15856 with-hm (and (nth 1 t1) (nth 2 t1))
15857 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15858 time (org-fix-decoded-time t1)
15859 str (org-add-props
15860 (format-time-string
15861 (substring tf 1 -1) (apply 'encode-time time))
15862 nil 'mouse-face 'highlight)
15863 w2 (length str))
15864 (if (not (= w2 w1))
15865 (add-text-properties (1+ beg) (+ 2 beg)
15866 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15867 (if (featurep 'xemacs)
15868 (progn
15869 (put-text-property beg end 'invisible t)
15870 (put-text-property beg end 'end-glyph (make-glyph str)))
15871 (put-text-property beg end 'display str))))
15873 (defun org-translate-time (string)
15874 "Translate all timestamps in STRING to custom format.
15875 But do this only if the variable `org-display-custom-times' is set."
15876 (when org-display-custom-times
15877 (save-match-data
15878 (let* ((start 0)
15879 (re org-ts-regexp-both)
15880 t1 with-hm inactive tf time str beg end)
15881 (while (setq start (string-match re string start))
15882 (setq beg (match-beginning 0)
15883 end (match-end 0)
15884 t1 (save-match-data
15885 (org-parse-time-string (substring string beg end) t))
15886 with-hm (and (nth 1 t1) (nth 2 t1))
15887 inactive (equal (substring string beg (1+ beg)) "[")
15888 tf (funcall (if with-hm 'cdr 'car)
15889 org-time-stamp-custom-formats)
15890 time (org-fix-decoded-time t1)
15891 str (format-time-string
15892 (concat
15893 (if inactive "[" "<") (substring tf 1 -1)
15894 (if inactive "]" ">"))
15895 (apply 'encode-time time))
15896 string (replace-match str t t string)
15897 start (+ start (length str)))))))
15898 string)
15900 (defun org-fix-decoded-time (time)
15901 "Set 0 instead of nil for the first 6 elements of time.
15902 Don't touch the rest."
15903 (let ((n 0))
15904 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15906 (defun org-days-to-time (timestamp-string)
15907 "Difference between TIMESTAMP-STRING and now in days."
15908 (- (time-to-days (org-time-string-to-time timestamp-string))
15909 (time-to-days (current-time))))
15911 (defun org-deadline-close (timestamp-string &optional ndays)
15912 "Is the time in TIMESTAMP-STRING close to the current date?"
15913 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15914 (and (< (org-days-to-time timestamp-string) ndays)
15915 (not (org-entry-is-done-p))))
15917 (defun org-get-wdays (ts)
15918 "Get the deadline lead time appropriate for timestring TS."
15919 (cond
15920 ((<= org-deadline-warning-days 0)
15921 ;; 0 or negative, enforce this value no matter what
15922 (- org-deadline-warning-days))
15923 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15924 ;; lead time is specified.
15925 (floor (* (string-to-number (match-string 1 ts))
15926 (cdr (assoc (match-string 2 ts)
15927 '(("d" . 1) ("w" . 7)
15928 ("m" . 30.4) ("y" . 365.25)))))))
15929 ;; go for the default.
15930 (t org-deadline-warning-days)))
15932 (defun org-calendar-select-mouse (ev)
15933 "Return to `org-read-date' with the date currently selected.
15934 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15935 (interactive "e")
15936 (mouse-set-point ev)
15937 (when (calendar-cursor-to-date)
15938 (let* ((date (calendar-cursor-to-date))
15939 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15940 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15941 (if (active-minibuffer-window) (exit-minibuffer))))
15943 (defun org-check-deadlines (ndays)
15944 "Check if there are any deadlines due or past due.
15945 A deadline is considered due if it happens within `org-deadline-warning-days'
15946 days from today's date. If the deadline appears in an entry marked DONE,
15947 it is not shown. The prefix arg NDAYS can be used to test that many
15948 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15949 (interactive "P")
15950 (let* ((org-warn-days
15951 (cond
15952 ((equal ndays '(4)) 100000)
15953 (ndays (prefix-numeric-value ndays))
15954 (t (abs org-deadline-warning-days))))
15955 (case-fold-search nil)
15956 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15957 (callback
15958 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15960 (message "%d deadlines past-due or due within %d days"
15961 (org-occur regexp nil callback)
15962 org-warn-days)))
15964 (defsubst org-re-timestamp (type)
15965 "Return a regexp for timestamp TYPE.
15966 Allowed values for TYPE are:
15968 all: all timestamps
15969 active: only active timestamps (<...>)
15970 inactive: only inactive timestamps ([...])
15971 scheduled: only scheduled timestamps
15972 deadline: only deadline timestamps
15974 When TYPE is nil, fall back on returning a regexp that matches
15975 both scheduled and deadline timestamps."
15976 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15977 ((eq type 'active) org-ts-regexp)
15978 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15979 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15980 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15981 ((eq type 'scheduled-or-deadline)
15982 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15984 (defun org-check-before-date (date)
15985 "Check if there are deadlines or scheduled entries before DATE."
15986 (interactive (list (org-read-date)))
15987 (let ((case-fold-search nil)
15988 (regexp (org-re-timestamp org-ts-type))
15989 (callback
15990 (lambda () (time-less-p
15991 (org-time-string-to-time (match-string 1))
15992 (org-time-string-to-time date)))))
15993 (message "%d entries before %s"
15994 (org-occur regexp nil callback) date)))
15996 (defun org-check-after-date (date)
15997 "Check if there are deadlines or scheduled entries after DATE."
15998 (interactive (list (org-read-date)))
15999 (let ((case-fold-search nil)
16000 (regexp (org-re-timestamp org-ts-type))
16001 (callback
16002 (lambda () (not
16003 (time-less-p
16004 (org-time-string-to-time (match-string 1))
16005 (org-time-string-to-time date))))))
16006 (message "%d entries after %s"
16007 (org-occur regexp nil callback) date)))
16009 (defun org-check-dates-range (start-date end-date)
16010 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16011 (interactive (list (org-read-date nil nil nil "Range starts")
16012 (org-read-date nil nil nil "Range end")))
16013 (let ((case-fold-search nil)
16014 (regexp (org-re-timestamp org-ts-type))
16015 (callback
16016 (lambda ()
16017 (let ((match (match-string 1)))
16018 (and
16019 (not (time-less-p
16020 (org-time-string-to-time match)
16021 (org-time-string-to-time start-date)))
16022 (time-less-p
16023 (org-time-string-to-time match)
16024 (org-time-string-to-time end-date)))))))
16025 (message "%d entries between %s and %s"
16026 (org-occur regexp nil callback) start-date end-date)))
16028 (defun org-evaluate-time-range (&optional to-buffer)
16029 "Evaluate a time range by computing the difference between start and end.
16030 Normally the result is just printed in the echo area, but with prefix arg
16031 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16032 If the time range is actually in a table, the result is inserted into the
16033 next column.
16034 For time difference computation, a year is assumed to be exactly 365
16035 days in order to avoid rounding problems."
16036 (interactive "P")
16038 (org-clock-update-time-maybe)
16039 (save-excursion
16040 (unless (org-at-date-range-p t)
16041 (goto-char (point-at-bol))
16042 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16043 (if (not (org-at-date-range-p t))
16044 (error "Not at a time-stamp range, and none found in current line")))
16045 (let* ((ts1 (match-string 1))
16046 (ts2 (match-string 2))
16047 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16048 (match-end (match-end 0))
16049 (time1 (org-time-string-to-time ts1))
16050 (time2 (org-time-string-to-time ts2))
16051 (t1 (org-float-time time1))
16052 (t2 (org-float-time time2))
16053 (diff (abs (- t2 t1)))
16054 (negative (< (- t2 t1) 0))
16055 ;; (ys (floor (* 365 24 60 60)))
16056 (ds (* 24 60 60))
16057 (hs (* 60 60))
16058 (fy "%dy %dd %02d:%02d")
16059 (fy1 "%dy %dd")
16060 (fd "%dd %02d:%02d")
16061 (fd1 "%dd")
16062 (fh "%02d:%02d")
16063 y d h m align)
16064 (if havetime
16065 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16067 d (floor (/ diff ds)) diff (mod diff ds)
16068 h (floor (/ diff hs)) diff (mod diff hs)
16069 m (floor (/ diff 60)))
16070 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16072 d (floor (+ (/ diff ds) 0.5))
16073 h 0 m 0))
16074 (if (not to-buffer)
16075 (message "%s" (org-make-tdiff-string y d h m))
16076 (if (org-at-table-p)
16077 (progn
16078 (goto-char match-end)
16079 (setq align t)
16080 (and (looking-at " *|") (goto-char (match-end 0))))
16081 (goto-char match-end))
16082 (if (looking-at
16083 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16084 (replace-match ""))
16085 (if negative (insert " -"))
16086 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16087 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16088 (insert " " (format fh h m))))
16089 (if align (org-table-align))
16090 (message "Time difference inserted")))))
16092 (defun org-make-tdiff-string (y d h m)
16093 (let ((fmt "")
16094 (l nil))
16095 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16096 l (push y l)))
16097 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16098 l (push d l)))
16099 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16100 l (push h l)))
16101 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16102 l (push m l)))
16103 (apply 'format fmt (nreverse l))))
16105 (defun org-time-string-to-time (s &optional buffer pos)
16106 "Convert a timestamp string into internal time."
16107 (condition-case errdata
16108 (apply 'encode-time (org-parse-time-string s))
16109 (error (error "Bad timestamp `%s'%s\nError was: %s"
16110 s (if (not (and buffer pos))
16112 (format " at %d in buffer `%s'" pos buffer))
16113 (cdr errdata)))))
16115 (defun org-time-string-to-seconds (s)
16116 "Convert a timestamp string to a number of seconds."
16117 (org-float-time (org-time-string-to-time s)))
16119 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16120 "Convert a time stamp to an absolute day number.
16121 If there is a specifier for a cyclic time stamp, get the closest date to
16122 DAYNR.
16123 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16124 The variable date is bound by the calendar when this is called."
16125 (cond
16126 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16127 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16128 daynr
16129 (+ daynr 1000)))
16130 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16131 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16132 (time-to-days (current-time))) (match-string 0 s)
16133 prefer show-all))
16134 (t (time-to-days
16135 (condition-case errdata
16136 (apply 'encode-time (org-parse-time-string s))
16137 (error (error "Bad timestamp `%s'%s\nError was: %s"
16138 s (if (not (and buffer pos))
16140 (format " at %d in buffer `%s'" pos buffer))
16141 (cdr errdata))))))))
16143 (defun org-days-to-iso-week (days)
16144 "Return the iso week number."
16145 (require 'cal-iso)
16146 (car (calendar-iso-from-absolute days)))
16148 (defun org-small-year-to-year (year)
16149 "Convert 2-digit years into 4-digit years.
16150 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16151 The year 2000 cannot be abbreviated. Any year larger than 99
16152 is returned unchanged."
16153 (if (< year 38)
16154 (setq year (+ 2000 year))
16155 (if (< year 100)
16156 (setq year (+ 1900 year))))
16157 year)
16159 (defun org-time-from-absolute (d)
16160 "Return the time corresponding to date D.
16161 D may be an absolute day number, or a calendar-type list (month day year)."
16162 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16163 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16165 (defun org-calendar-holiday ()
16166 "List of holidays, for Diary display in Org-mode."
16167 (require 'holidays)
16168 (let ((hl (funcall
16169 (if (fboundp 'calendar-check-holidays)
16170 'calendar-check-holidays 'check-calendar-holidays) date)))
16171 (if hl (mapconcat 'identity hl "; "))))
16173 (defun org-diary-sexp-entry (sexp entry date)
16174 "Process a SEXP diary ENTRY for DATE."
16175 (require 'diary-lib)
16176 (let ((result (if calendar-debug-sexp
16177 (let ((stack-trace-on-error t))
16178 (eval (car (read-from-string sexp))))
16179 (condition-case nil
16180 (eval (car (read-from-string sexp)))
16181 (error
16182 (beep)
16183 (message "Bad sexp at line %d in %s: %s"
16184 (org-current-line)
16185 (buffer-file-name) sexp)
16186 (sleep-for 2))))))
16187 (cond ((stringp result) (split-string result "; "))
16188 ((and (consp result)
16189 (not (consp (cdr result)))
16190 (stringp (cdr result))) (cdr result))
16191 ((and (consp result)
16192 (stringp (car result))) result)
16193 (result entry))))
16195 (defun org-diary-to-ical-string (frombuf)
16196 "Get iCalendar entries from diary entries in buffer FROMBUF.
16197 This uses the icalendar.el library."
16198 (let* ((tmpdir (if (featurep 'xemacs)
16199 (temp-directory)
16200 temporary-file-directory))
16201 (tmpfile (make-temp-name
16202 (expand-file-name "orgics" tmpdir)))
16203 buf rtn b e)
16204 (with-current-buffer frombuf
16205 (icalendar-export-region (point-min) (point-max) tmpfile)
16206 (setq buf (find-buffer-visiting tmpfile))
16207 (set-buffer buf)
16208 (goto-char (point-min))
16209 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16210 (setq b (match-beginning 0)))
16211 (goto-char (point-max))
16212 (if (re-search-backward "^END:VEVENT" nil t)
16213 (setq e (match-end 0)))
16214 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16215 (kill-buffer buf)
16216 (delete-file tmpfile)
16217 rtn))
16219 (defun org-closest-date (start current change prefer show-all)
16220 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16221 When PREFER is `past', return a date that is either CURRENT or past.
16222 When PREFER is `future', return a date that is either CURRENT or future.
16223 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16224 ;; Make the proper lists from the dates
16225 (catch 'exit
16226 (let ((a1 '(("h" . hour)
16227 ("d" . day)
16228 ("w" . week)
16229 ("m" . month)
16230 ("y" . year)))
16231 (shour (nth 2 (org-parse-time-string start)))
16232 dn dw sday cday n1 n2 n0
16233 d m y y1 y2 date1 date2 nmonths nm ny m2)
16235 (setq start (org-date-to-gregorian start)
16236 current (org-date-to-gregorian
16237 (if show-all
16238 current
16239 (time-to-days (current-time))))
16240 sday (calendar-absolute-from-gregorian start)
16241 cday (calendar-absolute-from-gregorian current))
16243 (if (<= cday sday) (throw 'exit sday))
16245 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16246 (setq dn (string-to-number (match-string 1 change))
16247 dw (cdr (assoc (match-string 2 change) a1)))
16248 (error "Invalid change specifier: %s" change))
16249 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16250 (cond
16251 ((eq dw 'hour)
16252 (let ((missing-hours
16253 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16254 dn)))
16255 (setq n1 (if (zerop missing-hours) cday
16256 (- cday (1+ (floor (/ missing-hours 24)))))
16257 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16258 ((eq dw 'day)
16259 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16260 n2 (+ n1 dn)))
16261 ((eq dw 'year)
16262 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16263 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16264 (setq date1 (list m d y1)
16265 n1 (calendar-absolute-from-gregorian date1)
16266 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16267 n2 (calendar-absolute-from-gregorian date2)))
16268 ((eq dw 'month)
16269 ;; approx number of month between the two dates
16270 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16271 ;; How often does dn fit in there?
16272 (setq d (nth 1 start) m (car start) y (nth 2 start)
16273 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16274 m (+ m nm)
16275 ny (floor (/ m 12))
16276 y (+ y ny)
16277 m (- m (* ny 12)))
16278 (while (> m 12) (setq m (- m 12) y (1+ y)))
16279 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16280 (setq m2 (+ m dn) y2 y)
16281 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16282 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16283 (while (<= n2 cday)
16284 (setq n1 n2 m m2 y y2)
16285 (setq m2 (+ m dn) y2 y)
16286 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16287 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16288 ;; Make sure n1 is the earlier date
16289 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16290 (if show-all
16291 (cond
16292 ((eq prefer 'past) (if (= cday n2) n2 n1))
16293 ((eq prefer 'future) (if (= cday n1) n1 n2))
16294 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16295 (cond
16296 ((eq prefer 'past) (if (= cday n2) n2 n1))
16297 ((eq prefer 'future) (if (= cday n1) n1 n2))
16298 (t (if (= cday n1) n1 n2)))))))
16300 (defun org-date-to-gregorian (date)
16301 "Turn any specification of DATE into a Gregorian date for the calendar."
16302 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16303 ((and (listp date) (= (length date) 3)) date)
16304 ((stringp date)
16305 (setq date (org-parse-time-string date))
16306 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16307 ((listp date)
16308 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16310 (defun org-parse-time-string (s &optional nodefault)
16311 "Parse the standard Org-mode time string.
16312 This should be a lot faster than the normal `parse-time-string'.
16313 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16314 hour and minute fields will be nil if not given."
16315 (if (string-match org-ts-regexp0 s)
16316 (list 0
16317 (if (or (match-beginning 8) (not nodefault))
16318 (string-to-number (or (match-string 8 s) "0")))
16319 (if (or (match-beginning 7) (not nodefault))
16320 (string-to-number (or (match-string 7 s) "0")))
16321 (string-to-number (match-string 4 s))
16322 (string-to-number (match-string 3 s))
16323 (string-to-number (match-string 2 s))
16324 nil nil nil)
16325 (error "Not a standard Org-mode time string: %s" s)))
16327 (defun org-timestamp-up (&optional arg)
16328 "Increase the date item at the cursor by one.
16329 If the cursor is on the year, change the year. If it is on the month,
16330 the day or the time, change that.
16331 With prefix ARG, change by that many units."
16332 (interactive "p")
16333 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16335 (defun org-timestamp-down (&optional arg)
16336 "Decrease the date item at the cursor by one.
16337 If the cursor is on the year, change the year. If it is on the month,
16338 the day or the time, change that.
16339 With prefix ARG, change by that many units."
16340 (interactive "p")
16341 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16343 (defun org-timestamp-up-day (&optional arg)
16344 "Increase the date in the time stamp by one day.
16345 With prefix ARG, change that many days."
16346 (interactive "p")
16347 (if (and (not (org-at-timestamp-p t))
16348 (org-at-heading-p))
16349 (org-todo 'up)
16350 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16352 (defun org-timestamp-down-day (&optional arg)
16353 "Decrease the date in the time stamp by one day.
16354 With prefix ARG, change that many days."
16355 (interactive "p")
16356 (if (and (not (org-at-timestamp-p t))
16357 (org-at-heading-p))
16358 (org-todo 'down)
16359 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16361 (defun org-at-timestamp-p (&optional inactive-ok)
16362 "Determine if the cursor is in or at a timestamp."
16363 (interactive)
16364 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16365 (pos (point))
16366 (ans (or (looking-at tsr)
16367 (save-excursion
16368 (skip-chars-backward "^[<\n\r\t")
16369 (if (> (point) (point-min)) (backward-char 1))
16370 (and (looking-at tsr)
16371 (> (- (match-end 0) pos) -1))))))
16372 (and ans
16373 (boundp 'org-ts-what)
16374 (setq org-ts-what
16375 (cond
16376 ((= pos (match-beginning 0)) 'bracket)
16377 ;; Point is considered to be "on the bracket" whether
16378 ;; it's really on it or right after it.
16379 ((= pos (1- (match-end 0))) 'bracket)
16380 ((= pos (match-end 0)) 'after)
16381 ((org-pos-in-match-range pos 2) 'year)
16382 ((org-pos-in-match-range pos 3) 'month)
16383 ((org-pos-in-match-range pos 7) 'hour)
16384 ((org-pos-in-match-range pos 8) 'minute)
16385 ((or (org-pos-in-match-range pos 4)
16386 (org-pos-in-match-range pos 5)) 'day)
16387 ((and (> pos (or (match-end 8) (match-end 5)))
16388 (< pos (match-end 0)))
16389 (- pos (or (match-end 8) (match-end 5))))
16390 (t 'day))))
16391 ans))
16393 (defun org-toggle-timestamp-type ()
16394 "Toggle the type (<active> or [inactive]) of a time stamp."
16395 (interactive)
16396 (when (org-at-timestamp-p t)
16397 (let ((beg (match-beginning 0)) (end (match-end 0))
16398 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16399 (save-excursion
16400 (goto-char beg)
16401 (while (re-search-forward "[][<>]" end t)
16402 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16403 t t)))
16404 (message "Timestamp is now %sactive"
16405 (if (equal (char-after beg) ?<) "" "in")))))
16407 (defvar org-clock-history) ; defined in org-clock.el
16408 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16409 (defun org-timestamp-change (n &optional what updown)
16410 "Change the date in the time stamp at point.
16411 The date will be changed by N times WHAT. WHAT can be `day', `month',
16412 `year', `minute', `second'. If WHAT is not given, the cursor position
16413 in the timestamp determines what will be changed."
16414 (let ((origin (point)) origin-cat
16415 with-hm inactive
16416 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16417 org-ts-what
16418 extra rem
16419 ts time time0 fixnext clrgx)
16420 (if (not (org-at-timestamp-p t))
16421 (error "Not at a timestamp"))
16422 (if (and (not what) (eq org-ts-what 'bracket))
16423 (org-toggle-timestamp-type)
16424 ;; Point isn't on brackets. Remember the part of the time-stamp
16425 ;; the point was in. Indeed, size of time-stamps may change,
16426 ;; but point must be kept in the same category nonetheless.
16427 (setq origin-cat org-ts-what)
16428 (if (and (not what) (not (eq org-ts-what 'day))
16429 org-display-custom-times
16430 (get-text-property (point) 'display)
16431 (not (get-text-property (1- (point)) 'display)))
16432 (setq org-ts-what 'day))
16433 (setq org-ts-what (or what org-ts-what)
16434 inactive (= (char-after (match-beginning 0)) ?\[)
16435 ts (match-string 0))
16436 (replace-match "")
16437 (if (string-match
16438 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16440 (setq extra (match-string 1 ts)))
16441 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16442 (setq with-hm t))
16443 (setq time0 (org-parse-time-string ts))
16444 (when (and updown
16445 (eq org-ts-what 'minute)
16446 (not current-prefix-arg))
16447 ;; This looks like s-up and s-down. Change by one rounding step.
16448 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16449 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16450 (setcar (cdr time0) (+ (nth 1 time0)
16451 (if (> n 0) (- rem) (- dm rem))))))
16452 (setq time
16453 (encode-time (or (car time0) 0)
16454 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16455 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16456 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16457 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16458 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16459 (nthcdr 6 time0)))
16460 (when (and (member org-ts-what '(hour minute))
16461 extra
16462 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16463 (setq extra (org-modify-ts-extra
16464 extra
16465 (if (eq org-ts-what 'hour) 2 5)
16466 n dm)))
16467 (when (integerp org-ts-what)
16468 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16469 (if (eq what 'calendar)
16470 (let ((cal-date (org-get-date-from-calendar)))
16471 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16472 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16473 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16474 (setcar time0 (or (car time0) 0))
16475 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16476 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16477 (setq time (apply 'encode-time time0))))
16478 ;; Insert the new time-stamp, and ensure point stays in the same
16479 ;; category as before (i.e. not after the last position in that
16480 ;; category).
16481 (let ((pos (point)))
16482 ;; Stay before inserted string. `save-excursion' is of no use.
16483 (setq org-last-changed-timestamp
16484 (org-insert-time-stamp time with-hm inactive nil nil extra))
16485 (goto-char pos))
16486 (save-match-data
16487 (looking-at org-ts-regexp3)
16488 (goto-char (cond
16489 ;; `day' category ends before `hour' if any, or at
16490 ;; the end of the day name.
16491 ((eq origin-cat 'day)
16492 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16493 ((eq origin-cat 'hour) (min (match-end 7) origin))
16494 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16495 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16496 ;; `year' and `month' have both fixed size: point
16497 ;; couldn't have moved into another part.
16498 (t origin))))
16499 ;; Update clock if on a CLOCK line.
16500 (org-clock-update-time-maybe)
16501 ;; Maybe adjust the closest clock in `org-clock-history'
16502 (when org-clock-adjust-closest
16503 (if (not (and (org-at-clock-log-p)
16504 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16505 org-clock-history))))))
16506 (message "No clock to adjust")
16507 (cond ((save-excursion ; fix previous clock?
16508 (re-search-backward org-ts-regexp0 nil t)
16509 (org-looking-back (concat org-clock-string " \\[")))
16510 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16511 ((save-excursion ; fix next clock?
16512 (re-search-backward org-ts-regexp0 nil t)
16513 (looking-at (concat org-ts-regexp0 "\\] =>")))
16514 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16515 (save-window-excursion
16516 ;; Find closest clock to point, adjust the previous/next one in history
16517 (let* ((p (save-excursion (org-back-to-heading t)))
16518 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16519 (clfixnth
16520 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16521 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16522 (if (not clfixpos)
16523 (message "No clock to adjust")
16524 (save-excursion
16525 (org-goto-marker-or-bmk clfixpos)
16526 (org-show-subtree)
16527 (when (re-search-forward clrgx nil t)
16528 (goto-char (match-beginning 1))
16529 (let (org-clock-adjust-closest)
16530 (org-timestamp-change n org-ts-what updown))
16531 (message "Clock adjusted in %s for heading: %s"
16532 (file-name-nondirectory (buffer-file-name))
16533 (org-get-heading t t)))))))))
16534 ;; Try to recenter the calendar window, if any.
16535 (if (and org-calendar-follow-timestamp-change
16536 (get-buffer-window "*Calendar*" t)
16537 (memq org-ts-what '(day month year)))
16538 (org-recenter-calendar (time-to-days time))))))
16540 (defun org-modify-ts-extra (s pos n dm)
16541 "Change the different parts of the lead-time and repeat fields in timestamp."
16542 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16543 ng h m new rem)
16544 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16545 (cond
16546 ((or (org-pos-in-match-range pos 2)
16547 (org-pos-in-match-range pos 3))
16548 (setq m (string-to-number (match-string 3 s))
16549 h (string-to-number (match-string 2 s)))
16550 (if (org-pos-in-match-range pos 2)
16551 (setq h (+ h n))
16552 (setq n (* dm (org-no-warnings (signum n))))
16553 (when (not (= 0 (setq rem (% m dm))))
16554 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16555 (setq m (+ m n)))
16556 (if (< m 0) (setq m (+ m 60) h (1- h)))
16557 (if (> m 59) (setq m (- m 60) h (1+ h)))
16558 (setq h (min 24 (max 0 h)))
16559 (setq ng 1 new (format "-%02d:%02d" h m)))
16560 ((org-pos-in-match-range pos 6)
16561 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16562 ((org-pos-in-match-range pos 5)
16563 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16565 ((org-pos-in-match-range pos 9)
16566 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16567 ((org-pos-in-match-range pos 8)
16568 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16570 (when ng
16571 (setq s (concat
16572 (substring s 0 (match-beginning ng))
16574 (substring s (match-end ng))))))
16577 (defun org-recenter-calendar (date)
16578 "If the calendar is visible, recenter it to DATE."
16579 (let ((cwin (get-buffer-window "*Calendar*" t)))
16580 (when cwin
16581 (let ((calendar-move-hook nil))
16582 (with-selected-window cwin
16583 (calendar-goto-date (if (listp date) date
16584 (calendar-gregorian-from-absolute date))))))))
16586 (defun org-goto-calendar (&optional arg)
16587 "Go to the Emacs calendar at the current date.
16588 If there is a time stamp in the current line, go to that date.
16589 A prefix ARG can be used to force the current date."
16590 (interactive "P")
16591 (let ((tsr org-ts-regexp) diff
16592 (calendar-move-hook nil)
16593 (calendar-view-holidays-initially-flag nil)
16594 (calendar-view-diary-initially-flag nil))
16595 (if (or (org-at-timestamp-p)
16596 (save-excursion
16597 (beginning-of-line 1)
16598 (looking-at (concat ".*" tsr))))
16599 (let ((d1 (time-to-days (current-time)))
16600 (d2 (time-to-days
16601 (org-time-string-to-time (match-string 1)))))
16602 (setq diff (- d2 d1))))
16603 (calendar)
16604 (calendar-goto-today)
16605 (if (and diff (not arg)) (calendar-forward-day diff))))
16607 (defun org-get-date-from-calendar ()
16608 "Return a list (month day year) of date at point in calendar."
16609 (with-current-buffer "*Calendar*"
16610 (save-match-data
16611 (calendar-cursor-to-date))))
16613 (defun org-date-from-calendar ()
16614 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16615 If there is already a time stamp at the cursor position, update it."
16616 (interactive)
16617 (if (org-at-timestamp-p t)
16618 (org-timestamp-change 0 'calendar)
16619 (let ((cal-date (org-get-date-from-calendar)))
16620 (org-insert-time-stamp
16621 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16623 (defun org-minutes-to-hh:mm-string (m)
16624 "Compute H:MM from a number of minutes."
16625 (let ((h (/ m 60)))
16626 (setq m (- m (* 60 h)))
16627 (format org-time-clocksum-format h m)))
16629 (defun org-hh:mm-string-to-minutes (s)
16630 "Convert a string H:MM to a number of minutes.
16631 If the string is just a number, interpret it as minutes.
16632 In fact, the first hh:mm or number in the string will be taken,
16633 there can be extra stuff in the string.
16634 If no number is found, the return value is 0."
16635 (cond
16636 ((integerp s) s)
16637 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16638 (+ (* (string-to-number (match-string 1 s)) 60)
16639 (string-to-number (match-string 2 s))))
16640 ((string-match "\\([0-9]+\\)" s)
16641 (string-to-number (match-string 1 s)))
16642 (t 0)))
16644 (defcustom org-effort-durations
16645 `(("h" . 60)
16646 ("d" . ,(* 60 8))
16647 ("w" . ,(* 60 8 5))
16648 ("m" . ,(* 60 8 5 4))
16649 ("y" . ,(* 60 8 5 40)))
16650 "Conversion factor to minutes for an effort modifier.
16652 Each entry has the form (MODIFIER . MINUTES).
16654 In an effort string, a number followed by MODIFIER is multiplied
16655 by the specified number of MINUTES to obtain an effort in
16656 minutes.
16658 For example, if the value of this variable is ((\"hours\" . 60)), then an
16659 effort string \"2hours\" is equivalent to 120 minutes."
16660 :group 'org-agenda
16661 :version "24.1"
16662 :type '(alist :key-type (string :tag "Modifier")
16663 :value-type (number :tag "Minutes")))
16665 (defun org-duration-string-to-minutes (s &optional output-to-string)
16666 "Convert a duration string S to minutes.
16668 A bare number is interpreted as minutes, modifiers can be set by
16669 customizing `org-effort-durations' (which see).
16671 Entries containing a colon are interpreted as H:MM by
16672 `org-hh:mm-string-to-minutes'."
16673 (let ((result 0)
16674 (re (concat "\\([0-9.]+\\) *\\("
16675 (regexp-opt (mapcar 'car org-effort-durations))
16676 "\\)")))
16677 (while (string-match re s)
16678 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16679 (string-to-number (match-string 1 s))))
16680 (setq s (replace-match "" nil t s)))
16681 (setq result (floor result))
16682 (incf result (org-hh:mm-string-to-minutes s))
16683 (if output-to-string (number-to-string result) result)))
16685 ;;;; Files
16687 (defun org-save-all-org-buffers ()
16688 "Save all Org-mode buffers without user confirmation."
16689 (interactive)
16690 (message "Saving all Org-mode buffers...")
16691 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16692 (when (featurep 'org-id) (org-id-locations-save))
16693 (message "Saving all Org-mode buffers... done"))
16695 (defun org-revert-all-org-buffers ()
16696 "Revert all Org-mode buffers.
16697 Prompt for confirmation when there are unsaved changes.
16698 Be sure you know what you are doing before letting this function
16699 overwrite your changes.
16701 This function is useful in a setup where one tracks org files
16702 with a version control system, to revert on one machine after pulling
16703 changes from another. I believe the procedure must be like this:
16705 1. M-x org-save-all-org-buffers
16706 2. Pull changes from the other machine, resolve conflicts
16707 3. M-x org-revert-all-org-buffers"
16708 (interactive)
16709 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16710 (error "Abort"))
16711 (save-excursion
16712 (save-window-excursion
16713 (mapc
16714 (lambda (b)
16715 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16716 (with-current-buffer b buffer-file-name))
16717 (org-pop-to-buffer-same-window b)
16718 (revert-buffer t 'no-confirm)))
16719 (buffer-list))
16720 (when (and (featurep 'org-id) org-id-track-globally)
16721 (org-id-locations-load)))))
16723 ;;;; Agenda files
16725 ;;;###autoload
16726 (defun org-switchb (&optional arg)
16727 "Switch between Org buffers.
16728 With one prefix argument, restrict available buffers to files.
16729 With two prefix arguments, restrict available buffers to agenda files.
16731 Defaults to `iswitchb' for buffer name completion.
16732 Set `org-completion-use-ido' to make it use ido instead."
16733 (interactive "P")
16734 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16735 ((equal arg '(16)) (org-buffer-list 'agenda))
16736 (t (org-buffer-list))))
16737 (org-completion-use-iswitchb org-completion-use-iswitchb)
16738 (org-completion-use-ido org-completion-use-ido))
16739 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16740 (setq org-completion-use-iswitchb t))
16741 (org-pop-to-buffer-same-window
16742 (org-icompleting-read "Org buffer: "
16743 (mapcar 'list (mapcar 'buffer-name blist))
16744 nil t))))
16746 ;;; Define some older names previously used for this functionality
16747 ;;;###autoload
16748 (defalias 'org-ido-switchb 'org-switchb)
16749 ;;;###autoload
16750 (defalias 'org-iswitchb 'org-switchb)
16752 (defun org-buffer-list (&optional predicate exclude-tmp)
16753 "Return a list of Org buffers.
16754 PREDICATE can be `export', `files' or `agenda'.
16756 export restrict the list to Export buffers.
16757 files restrict the list to buffers visiting Org files.
16758 agenda restrict the list to buffers visiting agenda files.
16760 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16761 (let* ((bfn nil)
16762 (agenda-files (and (eq predicate 'agenda)
16763 (mapcar 'file-truename (org-agenda-files t))))
16764 (filter
16765 (cond
16766 ((eq predicate 'files)
16767 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16768 ((eq predicate 'export)
16769 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16770 ((eq predicate 'agenda)
16771 (lambda (b)
16772 (with-current-buffer b
16773 (and (derived-mode-p 'org-mode)
16774 (setq bfn (buffer-file-name b))
16775 (member (file-truename bfn) agenda-files)))))
16776 (t (lambda (b) (with-current-buffer b
16777 (or (derived-mode-p 'org-mode)
16778 (string-match "\*Org .*Export"
16779 (buffer-name b)))))))))
16780 (delq nil
16781 (mapcar
16782 (lambda(b)
16783 (if (and (funcall filter b)
16784 (or (not exclude-tmp)
16785 (not (string-match "tmp" (buffer-name b)))))
16787 nil))
16788 (buffer-list)))))
16790 (defun org-agenda-files (&optional unrestricted archives)
16791 "Get the list of agenda files.
16792 Optional UNRESTRICTED means return the full list even if a restriction
16793 is currently in place.
16794 When ARCHIVES is t, include all archive files that are really being
16795 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16796 `org-agenda-archives-mode' is t."
16797 (let ((files
16798 (cond
16799 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16800 ((stringp org-agenda-files) (org-read-agenda-file-list))
16801 ((listp org-agenda-files) org-agenda-files)
16802 (t (error "Invalid value of `org-agenda-files'")))))
16803 (setq files (apply 'append
16804 (mapcar (lambda (f)
16805 (if (file-directory-p f)
16806 (directory-files
16807 f t org-agenda-file-regexp)
16808 (list f)))
16809 files)))
16810 (when org-agenda-skip-unavailable-files
16811 (setq files (delq nil
16812 (mapcar (function
16813 (lambda (file)
16814 (and (file-readable-p file) file)))
16815 files))))
16816 (when (or (eq archives t)
16817 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16818 (setq files (org-add-archive-files files)))
16819 files))
16821 (defun org-agenda-file-p (&optional file)
16822 "Return non-nil, if FILE is an agenda file.
16823 If FILE is omitted, use the file associated with the current
16824 buffer."
16825 (member (or file (buffer-file-name))
16826 (org-agenda-files t)))
16828 (defun org-edit-agenda-file-list ()
16829 "Edit the list of agenda files.
16830 Depending on setup, this either uses customize to edit the variable
16831 `org-agenda-files', or it visits the file that is holding the list. In the
16832 latter case, the buffer is set up in a way that saving it automatically kills
16833 the buffer and restores the previous window configuration."
16834 (interactive)
16835 (if (stringp org-agenda-files)
16836 (let ((cw (current-window-configuration)))
16837 (find-file org-agenda-files)
16838 (org-set-local 'org-window-configuration cw)
16839 (org-add-hook 'after-save-hook
16840 (lambda ()
16841 (set-window-configuration
16842 (prog1 org-window-configuration
16843 (kill-buffer (current-buffer))))
16844 (org-install-agenda-files-menu)
16845 (message "New agenda file list installed"))
16846 nil 'local)
16847 (message "%s" (substitute-command-keys
16848 "Edit list and finish with \\[save-buffer]")))
16849 (customize-variable 'org-agenda-files)))
16851 (defun org-store-new-agenda-file-list (list)
16852 "Set new value for the agenda file list and save it correctly."
16853 (if (stringp org-agenda-files)
16854 (let ((fe (org-read-agenda-file-list t)) b u)
16855 (while (setq b (find-buffer-visiting org-agenda-files))
16856 (kill-buffer b))
16857 (with-temp-file org-agenda-files
16858 (insert
16859 (mapconcat
16860 (lambda (f) ;; Keep un-expanded entries.
16861 (if (setq u (assoc f fe))
16862 (cdr u)
16864 list "\n")
16865 "\n")))
16866 (let ((org-mode-hook nil) (org-inhibit-startup t)
16867 (org-insert-mode-line-in-empty-file nil))
16868 (setq org-agenda-files list)
16869 (customize-save-variable 'org-agenda-files org-agenda-files))))
16871 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16872 "Read the list of agenda files from a file.
16873 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16874 filenames, used by `org-store-new-agenda-file-list' to write back
16875 un-expanded file names."
16876 (when (file-directory-p org-agenda-files)
16877 (error "`org-agenda-files' cannot be a single directory"))
16878 (when (stringp org-agenda-files)
16879 (with-temp-buffer
16880 (insert-file-contents org-agenda-files)
16881 (mapcar
16882 (lambda (f)
16883 (let ((e (expand-file-name (substitute-in-file-name f)
16884 org-directory)))
16885 (if pair-with-expansion
16886 (cons e f)
16887 e)))
16888 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16890 ;;;###autoload
16891 (defun org-cycle-agenda-files ()
16892 "Cycle through the files in `org-agenda-files'.
16893 If the current buffer visits an agenda file, find the next one in the list.
16894 If the current buffer does not, find the first agenda file."
16895 (interactive)
16896 (let* ((fs (org-agenda-files t))
16897 (files (append fs (list (car fs))))
16898 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16899 file)
16900 (unless files (error "No agenda files"))
16901 (catch 'exit
16902 (while (setq file (pop files))
16903 (if (equal (file-truename file) tcf)
16904 (when (car files)
16905 (find-file (car files))
16906 (throw 'exit t))))
16907 (find-file (car fs)))
16908 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16910 (defun org-agenda-file-to-front (&optional to-end)
16911 "Move/add the current file to the top of the agenda file list.
16912 If the file is not present in the list, it is added to the front. If it is
16913 present, it is moved there. With optional argument TO-END, add/move to the
16914 end of the list."
16915 (interactive "P")
16916 (let ((org-agenda-skip-unavailable-files nil)
16917 (file-alist (mapcar (lambda (x)
16918 (cons (file-truename x) x))
16919 (org-agenda-files t)))
16920 (ctf (file-truename
16921 (or buffer-file-name
16922 (error "Please save the current buffer to a file"))))
16923 x had)
16924 (setq x (assoc ctf file-alist) had x)
16926 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16927 (if to-end
16928 (setq file-alist (append (delq x file-alist) (list x)))
16929 (setq file-alist (cons x (delq x file-alist))))
16930 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16931 (org-install-agenda-files-menu)
16932 (message "File %s to %s of agenda file list"
16933 (if had "moved" "added") (if to-end "end" "front"))))
16935 (defun org-remove-file (&optional file)
16936 "Remove current file from the list of files in variable `org-agenda-files'.
16937 These are the files which are being checked for agenda entries.
16938 Optional argument FILE means use this file instead of the current."
16939 (interactive)
16940 (let* ((org-agenda-skip-unavailable-files nil)
16941 (file (or file buffer-file-name
16942 (error "Current buffer does not visit a file")))
16943 (true-file (file-truename file))
16944 (afile (abbreviate-file-name file))
16945 (files (delq nil (mapcar
16946 (lambda (x)
16947 (if (equal true-file
16948 (file-truename x))
16949 nil x))
16950 (org-agenda-files t)))))
16951 (if (not (= (length files) (length (org-agenda-files t))))
16952 (progn
16953 (org-store-new-agenda-file-list files)
16954 (org-install-agenda-files-menu)
16955 (message "Removed file: %s" afile))
16956 (message "File was not in list: %s (not removed)" afile))))
16958 (defun org-file-menu-entry (file)
16959 (vector file (list 'find-file file) t))
16961 (defun org-check-agenda-file (file)
16962 "Make sure FILE exists. If not, ask user what to do."
16963 (when (not (file-exists-p file))
16964 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16965 (abbreviate-file-name file))
16966 (let ((r (downcase (read-char-exclusive))))
16967 (cond
16968 ((equal r ?r)
16969 (org-remove-file file)
16970 (throw 'nextfile t))
16971 (t (error "Abort"))))))
16973 (defun org-get-agenda-file-buffer (file)
16974 "Get a buffer visiting FILE. If the buffer needs to be created, add
16975 it to the list of buffers which might be released later."
16976 (let ((buf (org-find-base-buffer-visiting file)))
16977 (if buf
16978 buf ; just return it
16979 ;; Make a new buffer and remember it
16980 (setq buf (find-file-noselect file))
16981 (if buf (push buf org-agenda-new-buffers))
16982 buf)))
16984 (defun org-release-buffers (blist)
16985 "Release all buffers in list, asking the user for confirmation when needed.
16986 When a buffer is unmodified, it is just killed. When modified, it is saved
16987 \(if the user agrees) and then killed."
16988 (let (buf file)
16989 (while (setq buf (pop blist))
16990 (setq file (buffer-file-name buf))
16991 (when (and (buffer-modified-p buf)
16992 file
16993 (y-or-n-p (format "Save file %s? " file)))
16994 (with-current-buffer buf (save-buffer)))
16995 (kill-buffer buf))))
16997 (defun org-agenda-prepare-buffers (files)
16998 "Create buffers for all agenda files, protect archived trees and comments."
16999 (interactive)
17000 (let ((pa '(:org-archived t))
17001 (pc '(:org-comment t))
17002 (pall '(:org-archived t :org-comment t))
17003 (inhibit-read-only t)
17004 (rea (concat ":" org-archive-tag ":"))
17005 bmp file re)
17006 (save-excursion
17007 (save-restriction
17008 (while (setq file (pop files))
17009 (catch 'nextfile
17010 (if (bufferp file)
17011 (set-buffer file)
17012 (org-check-agenda-file file)
17013 (set-buffer (org-get-agenda-file-buffer file)))
17014 (widen)
17015 (setq bmp (buffer-modified-p))
17016 (org-refresh-category-properties)
17017 (org-refresh-properties org-effort-property 'org-effort)
17018 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17019 (setq org-todo-keywords-for-agenda
17020 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17021 (setq org-done-keywords-for-agenda
17022 (append org-done-keywords-for-agenda org-done-keywords))
17023 (setq org-todo-keyword-alist-for-agenda
17024 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17025 (setq org-drawers-for-agenda
17026 (append org-drawers-for-agenda org-drawers))
17027 (setq org-tag-alist-for-agenda
17028 (append org-tag-alist-for-agenda org-tag-alist))
17030 (save-excursion
17031 (remove-text-properties (point-min) (point-max) pall)
17032 (when org-agenda-skip-archived-trees
17033 (goto-char (point-min))
17034 (while (re-search-forward rea nil t)
17035 (if (org-at-heading-p t)
17036 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17037 (goto-char (point-min))
17038 (setq re (format org-heading-keyword-regexp-format
17039 org-comment-string))
17040 (while (re-search-forward re nil t)
17041 (add-text-properties
17042 (match-beginning 0) (org-end-of-subtree t) pc)))
17043 (set-buffer-modified-p bmp)))))
17044 (setq org-todo-keywords-for-agenda
17045 (org-uniquify org-todo-keywords-for-agenda))
17046 (setq org-todo-keyword-alist-for-agenda
17047 (org-uniquify org-todo-keyword-alist-for-agenda)
17048 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17050 ;;;; Embedded LaTeX
17052 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17053 "Keymap for the minor `org-cdlatex-mode'.")
17055 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17056 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17057 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17058 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17059 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17061 (defvar org-cdlatex-texmathp-advice-is-done nil
17062 "Flag remembering if we have applied the advice to texmathp already.")
17064 (define-minor-mode org-cdlatex-mode
17065 "Toggle the minor `org-cdlatex-mode'.
17066 This mode supports entering LaTeX environment and math in LaTeX fragments
17067 in Org-mode.
17068 \\{org-cdlatex-mode-map}"
17069 nil " OCDL" nil
17070 (when org-cdlatex-mode
17071 (require 'cdlatex)
17072 (run-hooks 'cdlatex-mode-hook)
17073 (cdlatex-compute-tables))
17074 (unless org-cdlatex-texmathp-advice-is-done
17075 (setq org-cdlatex-texmathp-advice-is-done t)
17076 (defadvice texmathp (around org-math-always-on activate)
17077 "Always return t in org-mode buffers.
17078 This is because we want to insert math symbols without dollars even outside
17079 the LaTeX math segments. If Orgmode thinks that point is actually inside
17080 an embedded LaTeX fragment, let texmathp do its job.
17081 \\[org-cdlatex-mode-map]"
17082 (interactive)
17083 (let (p)
17084 (cond
17085 ((not (derived-mode-p 'org-mode)) ad-do-it)
17086 ((eq this-command 'cdlatex-math-symbol)
17087 (setq ad-return-value t
17088 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17090 (let ((p (org-inside-LaTeX-fragment-p)))
17091 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17092 (setq ad-return-value t
17093 texmathp-why '("Org-mode embedded math" . 0))
17094 (if p ad-do-it)))))))))
17096 (defun turn-on-org-cdlatex ()
17097 "Unconditionally turn on `org-cdlatex-mode'."
17098 (org-cdlatex-mode 1))
17100 (defun org-inside-LaTeX-fragment-p ()
17101 "Test if point is inside a LaTeX fragment.
17102 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17103 sequence appearing also before point.
17104 Even though the matchers for math are configurable, this function assumes
17105 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17106 delimiters are skipped when they have been removed by customization.
17107 The return value is nil, or a cons cell with the delimiter and the
17108 position of this delimiter.
17110 This function does a reasonably good job, but can locally be fooled by
17111 for example currency specifications. For example it will assume being in
17112 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17113 fragments that are properly closed, but during editing, we have to live
17114 with the uncertainty caused by missing closing delimiters. This function
17115 looks only before point, not after."
17116 (catch 'exit
17117 (let ((pos (point))
17118 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17119 (lim (progn
17120 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17121 (point)))
17122 dd-on str (start 0) m re)
17123 (goto-char pos)
17124 (when dodollar
17125 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17126 re (nth 1 (assoc "$" org-latex-regexps)))
17127 (while (string-match re str start)
17128 (cond
17129 ((= (match-end 0) (length str))
17130 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17131 ((= (match-end 0) (- (length str) 5))
17132 (throw 'exit nil))
17133 (t (setq start (match-end 0))))))
17134 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17135 (goto-char pos)
17136 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17137 (and (match-beginning 2) (throw 'exit nil))
17138 ;; count $$
17139 (while (re-search-backward "\\$\\$" lim t)
17140 (setq dd-on (not dd-on)))
17141 (goto-char pos)
17142 (if dd-on (cons "$$" m))))))
17144 (defun org-inside-latex-macro-p ()
17145 "Is point inside a LaTeX macro or its arguments?"
17146 (save-match-data
17147 (org-in-regexp
17148 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17150 (defun org-try-cdlatex-tab ()
17151 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17152 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17153 - inside a LaTeX fragment, or
17154 - after the first word in a line, where an abbreviation expansion could
17155 insert a LaTeX environment."
17156 (when org-cdlatex-mode
17157 (cond
17158 ;; Before any word on the line: No expansion possible.
17159 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17160 ;; Just after first word on the line: Expand it. Make sure it
17161 ;; cannot happen on headlines, though.
17162 ((save-excursion
17163 (skip-chars-backward "a-zA-Z0-9*")
17164 (skip-chars-backward " \t")
17165 (and (bolp) (not (org-at-heading-p))))
17166 (cdlatex-tab) t)
17167 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17169 (defun org-cdlatex-underscore-caret (&optional arg)
17170 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17171 Revert to the normal definition outside of these fragments."
17172 (interactive "P")
17173 (if (org-inside-LaTeX-fragment-p)
17174 (call-interactively 'cdlatex-sub-superscript)
17175 (let (org-cdlatex-mode)
17176 (call-interactively (key-binding (vector last-input-event))))))
17178 (defun org-cdlatex-math-modify (&optional arg)
17179 "Execute `cdlatex-math-modify' in LaTeX fragments.
17180 Revert to the normal definition outside of these fragments."
17181 (interactive "P")
17182 (if (org-inside-LaTeX-fragment-p)
17183 (call-interactively 'cdlatex-math-modify)
17184 (let (org-cdlatex-mode)
17185 (call-interactively (key-binding (vector last-input-event))))))
17187 (defvar org-latex-fragment-image-overlays nil
17188 "List of overlays carrying the images of latex fragments.")
17189 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17191 (defun org-remove-latex-fragment-image-overlays ()
17192 "Remove all overlays with LaTeX fragment images in current buffer."
17193 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17194 (setq org-latex-fragment-image-overlays nil))
17196 (defun org-preview-latex-fragment (&optional subtree)
17197 "Preview the LaTeX fragment at point, or all locally or globally.
17198 If the cursor is in a LaTeX fragment, create the image and overlay
17199 it over the source code. If there is no fragment at point, display
17200 all fragments in the current text, from one headline to the next. With
17201 prefix SUBTREE, display all fragments in the current subtree. With a
17202 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17203 the cursor is before the first headline,
17204 display all fragments in the buffer.
17205 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17206 (interactive "P")
17207 (unless buffer-file-name
17208 (error "Can't preview LaTeX fragment in a non-file buffer"))
17209 (org-remove-latex-fragment-image-overlays)
17210 (save-excursion
17211 (save-restriction
17212 (let (beg end at msg)
17213 (cond
17214 ((or (equal subtree '(16))
17215 (not (save-excursion
17216 (re-search-backward org-outline-regexp-bol nil t))))
17217 (setq beg (point-min) end (point-max)
17218 msg "Creating images for buffer...%s"))
17219 ((equal subtree '(4))
17220 (org-back-to-heading)
17221 (setq beg (point) end (org-end-of-subtree t)
17222 msg "Creating images for subtree...%s"))
17224 (if (setq at (org-inside-LaTeX-fragment-p))
17225 (goto-char (max (point-min) (- (cdr at) 2)))
17226 (org-back-to-heading))
17227 (setq beg (point) end (progn (outline-next-heading) (point))
17228 msg (if at "Creating image...%s"
17229 "Creating images for entry...%s"))))
17230 (message msg "")
17231 (narrow-to-region beg end)
17232 (goto-char beg)
17233 (org-format-latex
17234 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17235 (file-name-nondirectory
17236 buffer-file-name)))
17237 default-directory 'overlays msg at 'forbuffer
17238 org-latex-create-formula-image-program)
17239 (message msg "done. Use `C-c C-c' to remove images.")))))
17241 (defvar org-latex-regexps
17242 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17243 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17244 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17245 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17246 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17247 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17248 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17249 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17250 "Regular expressions for matching embedded LaTeX.")
17252 (defvar org-export-have-math nil) ;; dynamic scoping
17253 (defun org-format-latex (prefix &optional dir overlays msg at
17254 forbuffer processing-type)
17255 "Replace LaTeX fragments with links to an image, and produce images.
17256 Some of the options can be changed using the variable
17257 `org-format-latex-options'."
17258 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17259 (let* ((prefixnodir (file-name-nondirectory prefix))
17260 (absprefix (expand-file-name prefix dir))
17261 (todir (file-name-directory absprefix))
17262 (opt org-format-latex-options)
17263 (matchers (plist-get opt :matchers))
17264 (re-list org-latex-regexps)
17265 (org-format-latex-header-extra
17266 (plist-get (org-infile-export-plist) :latex-header-extra))
17267 (cnt 0) txt hash link beg end re e checkdir
17268 executables-checked string
17269 m n block-type block linkfile movefile ov)
17270 ;; Check the different regular expressions
17271 (while (setq e (pop re-list))
17272 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17273 block (if block-type "\n\n" ""))
17274 (when (member m matchers)
17275 (goto-char (point-min))
17276 (while (re-search-forward re nil t)
17277 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17278 (not (get-text-property (match-beginning n)
17279 'org-protected))
17280 (or (not overlays)
17281 (not (eq (get-char-property (match-beginning n)
17282 'org-overlay-type)
17283 'org-latex-overlay))))
17284 (setq org-export-have-math t)
17285 (cond
17286 ((eq processing-type 'verbatim)
17287 ;; Leave the text verbatim, just protect it
17288 (add-text-properties (match-beginning n) (match-end n)
17289 '(org-protected t)))
17290 ((eq processing-type 'mathjax)
17291 ;; Prepare for MathJax processing
17292 (setq string (match-string n))
17293 (if (member m '("$" "$1"))
17294 (save-excursion
17295 (delete-region (match-beginning n) (match-end n))
17296 (goto-char (match-beginning n))
17297 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17298 "\\)")
17299 '(org-protected t))))
17300 (add-text-properties (match-beginning n) (match-end n)
17301 '(org-protected t))))
17302 ((or (eq processing-type 'dvipng)
17303 (eq processing-type 'imagemagick))
17304 ;; Process to an image
17305 (setq txt (match-string n)
17306 beg (match-beginning n) end (match-end n)
17307 cnt (1+ cnt))
17308 (let (print-length print-level) ; make sure full list is printed
17309 (setq hash (sha1 (prin1-to-string
17310 (list org-format-latex-header
17311 org-format-latex-header-extra
17312 org-export-latex-default-packages-alist
17313 org-export-latex-packages-alist
17314 org-format-latex-options
17315 forbuffer txt)))
17316 linkfile (format "%s_%s.png" prefix hash)
17317 movefile (format "%s_%s.png" absprefix hash)))
17318 (setq link (concat block "[[file:" linkfile "]]" block))
17319 (if msg (message msg cnt))
17320 (goto-char beg)
17321 (unless checkdir ; make sure the directory exists
17322 (setq checkdir t)
17323 (or (file-directory-p todir) (make-directory todir t)))
17324 (cond
17325 ((eq processing-type 'dvipng)
17326 (unless executables-checked
17327 (org-check-external-command
17328 "latex" "needed to convert LaTeX fragments to images")
17329 (org-check-external-command
17330 "dvipng" "needed to convert LaTeX fragments to images")
17331 (setq executables-checked t))
17332 (unless (file-exists-p movefile)
17333 (org-create-formula-image-with-dvipng
17334 txt movefile opt forbuffer)))
17335 ((eq processing-type 'imagemagick)
17336 (unless executables-checked
17337 (org-check-external-command
17338 "convert" "you need to install imagemagick")
17339 (setq executables-checked t))
17340 (unless (file-exists-p movefile)
17341 (org-create-formula-image-with-imagemagick
17342 txt movefile opt forbuffer))))
17343 (if overlays
17344 (progn
17345 (mapc (lambda (o)
17346 (if (eq (overlay-get o 'org-overlay-type)
17347 'org-latex-overlay)
17348 (delete-overlay o)))
17349 (overlays-in beg end))
17350 (setq ov (make-overlay beg end))
17351 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17352 (if (featurep 'xemacs)
17353 (progn
17354 (overlay-put ov 'invisible t)
17355 (overlay-put
17356 ov 'end-glyph
17357 (make-glyph (vector 'png :file movefile))))
17358 (overlay-put
17359 ov 'display
17360 (list 'image :type 'png :file movefile :ascent 'center)))
17361 (push ov org-latex-fragment-image-overlays)
17362 (goto-char end))
17363 (delete-region beg end)
17364 (insert (org-add-props link
17365 (list 'org-latex-src
17366 (replace-regexp-in-string
17367 "\"" "" txt)
17368 'org-latex-src-embed-type
17369 (if block-type 'paragraph 'character))))))
17370 ((eq processing-type 'mathml)
17371 ;; Process to MathML
17372 (unless executables-checked
17373 (unless (save-match-data (org-format-latex-mathml-available-p))
17374 (error "LaTeX to MathML converter not configured"))
17375 (setq executables-checked t))
17376 (setq txt (match-string n)
17377 beg (match-beginning n) end (match-end n)
17378 cnt (1+ cnt))
17379 (if msg (message msg cnt))
17380 (goto-char beg)
17381 (delete-region beg end)
17382 (insert (org-format-latex-as-mathml
17383 txt block-type prefix dir)))
17385 (error "Unknown conversion type %s for latex fragments"
17386 processing-type)))))))))
17388 (defun org-create-math-formula (latex-frag &optional mathml-file)
17389 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17390 Use `org-latex-to-mathml-convert-command'. If the conversion is
17391 sucessful, return the portion between \"<math...> </math>\"
17392 elements otherwise return nil. When MATHML-FILE is specified,
17393 write the results in to that file. When invoked as an
17394 interactive command, prompt for LATEX-FRAG, with initial value
17395 set to the current active region and echo the results for user
17396 inspection."
17397 (interactive (list (let ((frag (when (org-region-active-p)
17398 (buffer-substring-no-properties
17399 (region-beginning) (region-end)))))
17400 (read-string "LaTeX Fragment: " frag nil frag))))
17401 (unless latex-frag (error "Invalid latex-frag"))
17402 (let* ((tmp-in-file (file-relative-name
17403 (make-temp-name (expand-file-name "ltxmathml-in"))))
17404 (ignore (write-region latex-frag nil tmp-in-file))
17405 (tmp-out-file (file-relative-name
17406 (make-temp-name (expand-file-name "ltxmathml-out"))))
17407 (cmd (format-spec
17408 org-latex-to-mathml-convert-command
17409 `((?j . ,(shell-quote-argument
17410 (expand-file-name org-latex-to-mathml-jar-file)))
17411 (?I . ,(shell-quote-argument tmp-in-file))
17412 (?o . ,(shell-quote-argument tmp-out-file)))))
17413 mathml shell-command-output)
17414 (when (org-called-interactively-p 'any)
17415 (unless (org-format-latex-mathml-available-p)
17416 (error "LaTeX to MathML converter not configured")))
17417 (message "Running %s" cmd)
17418 (setq shell-command-output (shell-command-to-string cmd))
17419 (setq mathml
17420 (when (file-readable-p tmp-out-file)
17421 (with-current-buffer (find-file-noselect tmp-out-file t)
17422 (goto-char (point-min))
17423 (when (re-search-forward
17424 (concat
17425 (regexp-quote
17426 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17427 "\\(.\\|\n\\)*"
17428 (regexp-quote "</math>")) nil t)
17429 (prog1 (match-string 0) (kill-buffer))))))
17430 (cond
17431 (mathml
17432 (setq mathml
17433 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17434 (when mathml-file
17435 (write-region mathml nil mathml-file))
17436 (when (org-called-interactively-p 'any)
17437 (message mathml)))
17438 ((message "LaTeX to MathML conversion failed")
17439 (message shell-command-output)))
17440 (delete-file tmp-in-file)
17441 (when (file-exists-p tmp-out-file)
17442 (delete-file tmp-out-file))
17443 mathml))
17445 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17446 prefix &optional dir)
17447 "Use `org-create-math-formula' but check local cache first."
17448 (let* ((absprefix (expand-file-name prefix dir))
17449 (print-length nil) (print-level nil)
17450 (formula-id (concat
17451 "formula-"
17452 (sha1
17453 (prin1-to-string
17454 (list latex-frag
17455 org-latex-to-mathml-convert-command)))))
17456 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17457 (formula-cache-dir (file-name-directory formula-cache)))
17459 (unless (file-directory-p formula-cache-dir)
17460 (make-directory formula-cache-dir t))
17462 (unless (file-exists-p formula-cache)
17463 (org-create-math-formula latex-frag formula-cache))
17465 (if (file-exists-p formula-cache)
17466 ;; Successful conversion. Return the link to MathML file.
17467 (org-add-props
17468 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17469 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17470 'org-latex-src-embed-type (if latex-frag-type
17471 'paragraph 'character)))
17472 ;; Failed conversion. Return the LaTeX fragment verbatim
17473 (add-text-properties
17474 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17475 latex-frag)))
17477 ;; This function borrows from Ganesh Swami's latex2png.el
17478 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17479 "This calls dvipng."
17480 (require 'org-latex)
17481 (let* ((tmpdir (if (featurep 'xemacs)
17482 (temp-directory)
17483 temporary-file-directory))
17484 (texfilebase (make-temp-name
17485 (expand-file-name "orgtex" tmpdir)))
17486 (texfile (concat texfilebase ".tex"))
17487 (dvifile (concat texfilebase ".dvi"))
17488 (pngfile (concat texfilebase ".png"))
17489 (fnh (if (featurep 'xemacs)
17490 (font-height (face-font 'default))
17491 (face-attribute 'default :height nil)))
17492 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17493 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17494 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17495 "Black"))
17496 (bg (or (plist-get options (if buffer :background :html-background))
17497 "Transparent")))
17498 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17499 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17500 (with-temp-file texfile
17501 (insert (org-splice-latex-header
17502 org-format-latex-header
17503 org-export-latex-default-packages-alist
17504 org-export-latex-packages-alist t
17505 org-format-latex-header-extra))
17506 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17507 (require 'org-latex)
17508 (org-export-latex-fix-inputenc))
17509 (let ((dir default-directory))
17510 (condition-case nil
17511 (progn
17512 (cd tmpdir)
17513 (call-process "latex" nil nil nil texfile))
17514 (error nil))
17515 (cd dir))
17516 (if (not (file-exists-p dvifile))
17517 (progn (message "Failed to create dvi file from %s" texfile) nil)
17518 (condition-case nil
17519 (if (featurep 'xemacs)
17520 (call-process "dvipng" nil nil nil
17521 "-fg" fg "-bg" bg
17522 "-T" "tight"
17523 "-o" pngfile
17524 dvifile)
17525 (call-process "dvipng" nil nil nil
17526 "-fg" fg "-bg" bg
17527 "-D" dpi
17528 ;;"-x" scale "-y" scale
17529 "-T" "tight"
17530 "-o" pngfile
17531 dvifile))
17532 (error nil))
17533 (if (not (file-exists-p pngfile))
17534 (if org-format-latex-signal-error
17535 (error "Failed to create png file from %s" texfile)
17536 (message "Failed to create png file from %s" texfile)
17537 nil)
17538 ;; Use the requested file name and clean up
17539 (copy-file pngfile tofile 'replace)
17540 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17541 (if (file-exists-p (concat texfilebase e))
17542 (delete-file (concat texfilebase e))))
17543 pngfile))))
17545 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17546 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17547 "This calls convert, which is included into imagemagick."
17548 (require 'org-latex)
17549 (let* ((tmpdir (if (featurep 'xemacs)
17550 (temp-directory)
17551 temporary-file-directory))
17552 (texfilebase (make-temp-name
17553 (expand-file-name "orgtex" tmpdir)))
17554 (texfile (concat texfilebase ".tex"))
17555 (pdffile (concat texfilebase ".pdf"))
17556 (pngfile (concat texfilebase ".png"))
17557 (fnh (if (featurep 'xemacs)
17558 (font-height (face-font 'default))
17559 (face-attribute 'default :height nil)))
17560 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17561 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17562 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17563 "black"))
17564 (bg (or (plist-get options (if buffer :background :html-background))
17565 "white")))
17566 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17567 (setq fg (org-latex-color-format fg)))
17568 (if (eq bg 'default) (setq bg (org-latex-color :background))
17569 (setq bg (org-latex-color-format
17570 (if (string= bg "Transparent")(setq bg "white")))))
17571 (with-temp-file texfile
17572 (insert (org-splice-latex-header
17573 org-format-latex-header
17574 org-export-latex-default-packages-alist
17575 org-export-latex-packages-alist t
17576 org-format-latex-header-extra))
17577 (insert "\n\\begin{document}\n"
17578 "\\definecolor{fg}{rgb}{" fg "}\n"
17579 "\\definecolor{bg}{rgb}{" bg "}\n"
17580 "\n\\pagecolor{bg}\n"
17581 "\n{\\color{fg}\n"
17582 string
17583 "\n}\n"
17584 "\n\\end{document}\n" )
17585 (require 'org-latex)
17586 (org-export-latex-fix-inputenc))
17587 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17588 (condition-case nil
17589 (progn
17590 (cd tmpdir)
17591 (setq cmds org-latex-to-pdf-process)
17592 (while cmds
17593 (setq latex-frags-cmds (pop cmds))
17594 (if (listp latex-frags-cmds)
17595 (setq cmds nil)
17596 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17597 (while latex-frags-cmds
17598 (setq cmd (pop latex-frags-cmds))
17599 (while (string-match "%b" cmd)
17600 (setq cmd (replace-match
17601 (save-match-data
17602 (shell-quote-argument texfile))
17603 t t cmd)))
17604 (while (string-match "%f" cmd)
17605 (setq cmd (replace-match
17606 (save-match-data
17607 (shell-quote-argument (file-name-nondirectory texfile)))
17608 t t cmd)))
17609 (while (string-match "%o" cmd)
17610 (setq cmd (replace-match
17611 (save-match-data
17612 (shell-quote-argument (file-name-directory texfile)))
17613 t t cmd)))
17614 (setq cmd (split-string cmd))
17615 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17616 (error nil))
17617 (cd dir))
17618 (if (not (file-exists-p pdffile))
17619 (progn (message "Failed to create pdf file from %s" texfile) nil)
17620 (condition-case nil
17621 (if (featurep 'xemacs)
17622 (call-process "convert" nil nil nil
17623 "-density" "96"
17624 "-trim"
17625 "-antialias"
17626 pdffile
17627 "-quality" "100"
17628 ;; "-sharpen" "0x1.0"
17629 pngfile)
17630 (call-process "convert" nil nil nil
17631 "-density" dpi
17632 "-trim"
17633 "-antialias"
17634 pdffile
17635 "-quality" "100"
17636 ; "-sharpen" "0x1.0"
17637 pngfile))
17638 (error nil))
17639 (if (not (file-exists-p pngfile))
17640 (if org-format-latex-signal-error
17641 (error "Failed to create png file from %s" texfile)
17642 (message "Failed to create png file from %s" texfile)
17643 nil)
17644 ;; Use the requested file name and clean up
17645 (copy-file pngfile tofile 'replace)
17646 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17647 (if (file-exists-p (concat texfilebase e))
17648 (delete-file (concat texfilebase e))))
17649 pngfile))))
17651 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17652 "Fill a LaTeX header template TPL.
17653 In the template, the following place holders will be recognized:
17655 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17656 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17657 [PACKAGES] \\usepackage statements for PKG
17658 [NO-PACKAGES] do not include PKG
17659 [EXTRA] the string EXTRA
17660 [NO-EXTRA] do not include EXTRA
17662 For backward compatibility, if both the positive and the negative place
17663 holder is missing, the positive one (without the \"NO-\") will be
17664 assumed to be present at the end of the template.
17665 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17666 EXTRA is a string.
17667 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17668 (let (rpl (end ""))
17669 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17670 (setq rpl (if (or (match-end 1) (not def-pkg))
17671 "" (org-latex-packages-to-string def-pkg snippets-p t))
17672 tpl (replace-match rpl t t tpl))
17673 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17675 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17676 (setq rpl (if (or (match-end 1) (not pkg))
17677 "" (org-latex-packages-to-string pkg snippets-p t))
17678 tpl (replace-match rpl t t tpl))
17679 (if pkg (setq end
17680 (concat end "\n"
17681 (org-latex-packages-to-string pkg snippets-p)))))
17683 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17684 (setq rpl (if (or (match-end 1) (not extra))
17685 "" (concat extra "\n"))
17686 tpl (replace-match rpl t t tpl))
17687 (if (and extra (string-match "\\S-" extra))
17688 (setq end (concat end "\n" extra))))
17690 (if (string-match "\\S-" end)
17691 (concat tpl "\n" end)
17692 tpl)))
17694 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17695 "Turn an alist of packages into a string with the \\usepackage macros."
17696 (setq pkg (mapconcat (lambda(p)
17697 (cond
17698 ((stringp p) p)
17699 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17700 (format "%% Package %s omitted" (cadr p)))
17701 ((equal "" (car p))
17702 (format "\\usepackage{%s}" (cadr p)))
17704 (format "\\usepackage[%s]{%s}"
17705 (car p) (cadr p)))))
17707 "\n"))
17708 (if newline (concat pkg "\n") pkg))
17710 (defun org-dvipng-color (attr)
17711 "Return a RGB color specification for dvipng."
17712 (apply 'format "rgb %s %s %s"
17713 (mapcar 'org-normalize-color
17714 (if (featurep 'xemacs)
17715 (color-rgb-components
17716 (face-property 'default
17717 (cond ((eq attr :foreground) 'foreground)
17718 ((eq attr :background) 'background))))
17719 (color-values (face-attribute 'default attr nil))))))
17721 (defun org-latex-color (attr)
17722 "Return a RGB color for the LaTeX color package."
17723 (apply 'format "%s,%s,%s"
17724 (mapcar 'org-normalize-color
17725 (if (featurep 'xemacs)
17726 (color-rgb-components
17727 (face-property 'default
17728 (cond ((eq attr :foreground) 'foreground)
17729 ((eq attr :background) 'background))))
17730 (color-values (face-attribute 'default attr nil))))))
17732 (defun org-latex-color-format (color-name)
17733 "Convert COLOR-NAME to a RGB color value."
17734 (apply 'format "%s,%s,%s"
17735 (mapcar 'org-normalize-color
17736 (color-values color-name))))
17738 (defun org-normalize-color (value)
17739 "Return string to be used as color value for an RGB component."
17740 (format "%g" (/ value 65535.0)))
17742 ;; Image display
17745 (defvar org-inline-image-overlays nil)
17746 (make-variable-buffer-local 'org-inline-image-overlays)
17748 (defun org-toggle-inline-images (&optional include-linked)
17749 "Toggle the display of inline images.
17750 INCLUDE-LINKED is passed to `org-display-inline-images'."
17751 (interactive "P")
17752 (if org-inline-image-overlays
17753 (progn
17754 (org-remove-inline-images)
17755 (message "Inline image display turned off"))
17756 (org-display-inline-images include-linked)
17757 (if org-inline-image-overlays
17758 (message "%d images displayed inline"
17759 (length org-inline-image-overlays))
17760 (message "No images to display inline"))))
17762 (defun org-redisplay-inline-images ()
17763 "Refresh the display of inline images."
17764 (interactive)
17765 (if (not org-inline-image-overlays)
17766 (org-toggle-inline-images)
17767 (org-toggle-inline-images)
17768 (org-toggle-inline-images)))
17770 (defun org-display-inline-images (&optional include-linked refresh beg end)
17771 "Display inline images.
17772 Normally only links without a description part are inlined, because this
17773 is how it will work for export. When INCLUDE-LINKED is set, also links
17774 with a description part will be inlined. This can be nice for a quick
17775 look at those images, but it does not reflect what exported files will look
17776 like.
17777 When REFRESH is set, refresh existing images between BEG and END.
17778 This will create new image displays only if necessary.
17779 BEG and END default to the buffer boundaries."
17780 (interactive "P")
17781 (unless refresh
17782 (org-remove-inline-images)
17783 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17784 (save-excursion
17785 (save-restriction
17786 (widen)
17787 (setq beg (or beg (point-min)) end (or end (point-max)))
17788 (goto-char beg)
17789 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17790 (substring (org-image-file-name-regexp) 0 -2)
17791 "\\)\\]" (if include-linked "" "\\]")))
17792 old file ov img)
17793 (while (re-search-forward re end t)
17794 (setq old (get-char-property-and-overlay (match-beginning 1)
17795 'org-image-overlay))
17796 (setq file (expand-file-name
17797 (concat (or (match-string 3) "") (match-string 4))))
17798 (when (file-exists-p file)
17799 (if (and (car-safe old) refresh)
17800 (image-refresh (overlay-get (cdr old) 'display))
17801 (setq img (save-match-data (create-image file)))
17802 (when img
17803 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17804 (overlay-put ov 'display img)
17805 (overlay-put ov 'face 'default)
17806 (overlay-put ov 'org-image-overlay t)
17807 (overlay-put ov 'modification-hooks
17808 (list 'org-display-inline-remove-overlay))
17809 (push ov org-inline-image-overlays)))))))))
17811 (define-obsolete-function-alias
17812 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17814 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17815 "Remove inline-display overlay if a corresponding region is modified."
17816 (let ((inhibit-modification-hooks t))
17817 (when (and ov after)
17818 (delete ov org-inline-image-overlays)
17819 (delete-overlay ov))))
17821 (defun org-remove-inline-images ()
17822 "Remove inline display of images."
17823 (interactive)
17824 (mapc 'delete-overlay org-inline-image-overlays)
17825 (setq org-inline-image-overlays nil))
17827 ;;;; Key bindings
17829 ;; Outline functions from `outline-mode-prefix-map'
17830 ;; that can be remapped in Org:
17831 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17832 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17833 (define-key org-mode-map [remap outline-forward-same-level]
17834 'org-forward-heading-same-level)
17835 (define-key org-mode-map [remap outline-backward-same-level]
17836 'org-backward-heading-same-level)
17837 (define-key org-mode-map [remap show-branches]
17838 'org-kill-note-or-show-branches)
17839 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17840 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17841 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17843 ;; Outline functions from `outline-mode-prefix-map' that can not
17844 ;; be remapped in Org:
17846 ;; - the column "key binding" shows whether the Outline function is still
17847 ;; available in Org mode on the same key that it has been bound to in
17848 ;; Outline mode:
17849 ;; - "overridden": key used for a different functionality in Org mode
17850 ;; - else: key still bound to the same Outline function in Org mode
17852 ;; | Outline function | key binding | Org replacement |
17853 ;; |------------------------------------+-------------+-----------------------|
17854 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17855 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17856 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17857 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17858 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17859 ;; | `show-entry' | overridden | no replacement |
17860 ;; | `show-children' | `C-c C-i' | visibility cycling |
17861 ;; | `show-branches' | `C-c C-k' | still same function |
17862 ;; | `show-subtree' | overridden | visibility cycling |
17863 ;; | `show-all' | overridden | no replacement |
17864 ;; | `hide-subtree' | overridden | visibility cycling |
17865 ;; | `hide-body' | overridden | no replacement |
17866 ;; | `hide-entry' | overridden | visibility cycling |
17867 ;; | `hide-leaves' | overridden | no replacement |
17868 ;; | `hide-sublevels' | overridden | no replacement |
17869 ;; | `hide-other' | overridden | no replacement |
17871 ;; Make `C-c C-x' a prefix key
17872 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17874 ;; TAB key with modifiers
17875 (org-defkey org-mode-map "\C-i" 'org-cycle)
17876 (org-defkey org-mode-map [(tab)] 'org-cycle)
17877 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17878 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17879 ;; The following line is necessary under Suse GNU/Linux
17880 (unless (featurep 'xemacs)
17881 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17882 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17883 (define-key org-mode-map [backtab] 'org-shifttab)
17885 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17886 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17887 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17889 ;; Cursor keys with modifiers
17890 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17891 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17892 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17893 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17895 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17896 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17897 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17898 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17900 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17901 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17902 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17903 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17905 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17906 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17907 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17908 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17910 ;; Babel keys
17911 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17912 (mapc (lambda (pair)
17913 (define-key org-babel-map (car pair) (cdr pair)))
17914 org-babel-key-bindings)
17916 ;;; Extra keys for tty access.
17917 ;; We only set them when really needed because otherwise the
17918 ;; menus don't show the simple keys
17920 (when (or org-use-extra-keys
17921 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17922 (not window-system))
17923 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17924 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17925 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17926 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17927 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17928 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17929 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17930 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17931 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17932 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17933 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17934 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17935 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17936 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17937 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17938 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17939 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17940 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17941 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17942 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17943 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17944 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17945 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17946 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17947 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17948 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17949 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17950 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17952 ;; All the other keys
17954 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17955 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17956 (if (boundp 'narrow-map)
17957 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17958 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17959 (if (boundp 'narrow-map)
17960 (org-defkey narrow-map "b" 'org-narrow-to-block)
17961 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17962 (if (boundp 'narrow-map)
17963 (org-defkey narrow-map "e" 'org-narrow-to-element)
17964 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17965 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17966 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17967 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17968 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17969 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17970 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17971 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17972 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17973 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17974 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17975 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17976 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17977 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17978 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17979 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17980 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17981 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17982 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17983 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17984 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17985 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17986 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17987 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17988 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17989 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17990 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17991 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17992 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17993 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17994 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17995 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17996 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17997 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17998 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17999 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18000 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18001 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18002 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18003 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18004 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18005 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18006 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18007 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18008 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18009 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18010 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18011 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18012 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18013 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18014 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18015 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18016 (org-defkey org-mode-map "\C-c^" 'org-sort)
18017 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18018 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18019 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18020 (org-defkey org-mode-map "\C-m" 'org-return)
18021 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18022 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18023 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18024 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18025 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18026 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18027 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18028 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18029 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18030 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18031 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18032 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18033 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18034 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18035 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18036 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18037 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18038 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18039 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18040 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18041 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18042 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18043 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18045 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18046 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18047 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18049 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18050 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18051 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18052 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18053 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18054 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18055 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18056 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18057 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18058 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18059 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18060 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18061 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18062 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18063 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18064 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18065 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18066 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18067 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18068 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18069 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18070 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18072 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18073 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18074 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18075 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18076 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18078 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18080 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18082 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18083 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18085 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18088 (when (featurep 'xemacs)
18089 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18092 (defconst org-speed-commands-default
18094 ("Outline Navigation")
18095 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18096 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18097 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18098 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18099 ("u" . (org-speed-move-safe 'outline-up-heading))
18100 ("j" . org-goto)
18101 ("g" . (org-refile t))
18102 ("Outline Visibility")
18103 ("c" . org-cycle)
18104 ("C" . org-shifttab)
18105 (" " . org-display-outline-path)
18106 ("=" . org-columns)
18107 ("Outline Structure Editing")
18108 ("U" . org-shiftmetaup)
18109 ("D" . org-shiftmetadown)
18110 ("r" . org-metaright)
18111 ("l" . org-metaleft)
18112 ("R" . org-shiftmetaright)
18113 ("L" . org-shiftmetaleft)
18114 ("i" . (progn (forward-char 1) (call-interactively
18115 'org-insert-heading-respect-content)))
18116 ("^" . org-sort)
18117 ("w" . org-refile)
18118 ("a" . org-archive-subtree-default-with-confirmation)
18119 ("." . org-mark-subtree)
18120 ("#" . org-toggle-comment)
18121 ("Clock Commands")
18122 ("I" . org-clock-in)
18123 ("O" . org-clock-out)
18124 ("Meta Data Editing")
18125 ("t" . org-todo)
18126 ("," . (org-priority))
18127 ("0" . (org-priority ?\ ))
18128 ("1" . (org-priority ?A))
18129 ("2" . (org-priority ?B))
18130 ("3" . (org-priority ?C))
18131 (":" . org-set-tags-command)
18132 ("e" . org-set-effort)
18133 ("E" . org-inc-effort)
18134 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18135 (org-entry-put (point) "APPT_WARNTIME" m)))
18136 ("Agenda Views etc")
18137 ("v" . org-agenda)
18138 ("/" . org-sparse-tree)
18139 ("Misc")
18140 ("o" . org-open-at-point)
18141 ("?" . org-speed-command-help)
18142 ("<" . (org-agenda-set-restriction-lock 'subtree))
18143 (">" . (org-agenda-remove-restriction-lock))
18145 "The default speed commands.")
18147 (defun org-print-speed-command (e)
18148 (if (> (length (car e)) 1)
18149 (progn
18150 (princ "\n")
18151 (princ (car e))
18152 (princ "\n")
18153 (princ (make-string (length (car e)) ?-))
18154 (princ "\n"))
18155 (princ (car e))
18156 (princ " ")
18157 (if (symbolp (cdr e))
18158 (princ (symbol-name (cdr e)))
18159 (prin1 (cdr e)))
18160 (princ "\n")))
18162 (defun org-speed-command-help ()
18163 "Show the available speed commands."
18164 (interactive)
18165 (if (not org-use-speed-commands)
18166 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18167 (with-output-to-temp-buffer "*Help*"
18168 (princ "User-defined Speed commands\n===========================\n")
18169 (mapc 'org-print-speed-command org-speed-commands-user)
18170 (princ "\n")
18171 (princ "Built-in Speed commands\n=======================\n")
18172 (mapc 'org-print-speed-command org-speed-commands-default))
18173 (with-current-buffer "*Help*"
18174 (setq truncate-lines t))))
18176 (defun org-speed-move-safe (cmd)
18177 "Execute CMD, but make sure that the cursor always ends up in a headline.
18178 If not, return to the original position and throw an error."
18179 (interactive)
18180 (let ((pos (point)))
18181 (call-interactively cmd)
18182 (unless (and (bolp) (org-at-heading-p))
18183 (goto-char pos)
18184 (error "Boundary reached while executing %s" cmd))))
18186 (defvar org-self-insert-command-undo-counter 0)
18188 (defvar org-table-auto-blank-field) ; defined in org-table.el
18189 (defvar org-speed-command nil)
18191 (define-obsolete-function-alias
18192 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18194 (defun org-speed-command-activate (keys)
18195 "Hook for activating single-letter speed commands.
18196 `org-speed-commands-default' specifies a minimal command set.
18197 Use `org-speed-commands-user' for further customization."
18198 (when (or (and (bolp) (looking-at org-outline-regexp))
18199 (and (functionp org-use-speed-commands)
18200 (funcall org-use-speed-commands)))
18201 (cdr (assoc keys (append org-speed-commands-user
18202 org-speed-commands-default)))))
18204 (define-obsolete-function-alias
18205 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18207 (defun org-babel-speed-command-activate (keys)
18208 "Hook for activating single-letter code block commands."
18209 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18210 (cdr (assoc keys org-babel-key-bindings))))
18212 (defcustom org-speed-command-hook
18213 '(org-speed-command-default-hook org-babel-speed-command-hook)
18214 "Hook for activating speed commands at strategic locations.
18215 Hook functions are called in sequence until a valid handler is
18216 found.
18218 Each hook takes a single argument, a user-pressed command key
18219 which is also a `self-insert-command' from the global map.
18221 Within the hook, examine the cursor position and the command key
18222 and return nil or a valid handler as appropriate. Handler could
18223 be one of an interactive command, a function, or a form.
18225 Set `org-use-speed-commands' to non-nil value to enable this
18226 hook. The default setting is `org-speed-command-activate'."
18227 :group 'org-structure
18228 :version "24.1"
18229 :type 'hook)
18231 (defun org-self-insert-command (N)
18232 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18233 If the cursor is in a table looking at whitespace, the whitespace is
18234 overwritten, and the table is not marked as requiring realignment."
18235 (interactive "p")
18236 (org-check-before-invisible-edit 'insert)
18237 (cond
18238 ((and org-use-speed-commands
18239 (setq org-speed-command
18240 (run-hook-with-args-until-success
18241 'org-speed-command-hook (this-command-keys))))
18242 (cond
18243 ((commandp org-speed-command)
18244 (setq this-command org-speed-command)
18245 (call-interactively org-speed-command))
18246 ((functionp org-speed-command)
18247 (funcall org-speed-command))
18248 ((and org-speed-command (listp org-speed-command))
18249 (eval org-speed-command))
18250 (t (let (org-use-speed-commands)
18251 (call-interactively 'org-self-insert-command)))))
18252 ((and
18253 (org-table-p)
18254 (progn
18255 ;; check if we blank the field, and if that triggers align
18256 (and (featurep 'org-table) org-table-auto-blank-field
18257 (member last-command
18258 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18259 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18260 ;; got extra space, this field does not determine column width
18261 (let (org-table-may-need-update) (org-table-blank-field))
18262 ;; no extra space, this field may determine column width
18263 (org-table-blank-field)))
18265 (eq N 1)
18266 (looking-at "[^|\n]* |"))
18267 (let (org-table-may-need-update)
18268 (goto-char (1- (match-end 0)))
18269 (backward-delete-char 1)
18270 (goto-char (match-beginning 0))
18271 (self-insert-command N)))
18273 (setq org-table-may-need-update t)
18274 (self-insert-command N)
18275 (org-fix-tags-on-the-fly)
18276 (if org-self-insert-cluster-for-undo
18277 (if (not (eq last-command 'org-self-insert-command))
18278 (setq org-self-insert-command-undo-counter 1)
18279 (if (>= org-self-insert-command-undo-counter 20)
18280 (setq org-self-insert-command-undo-counter 1)
18281 (and (> org-self-insert-command-undo-counter 0)
18282 buffer-undo-list (listp buffer-undo-list)
18283 (not (cadr buffer-undo-list)) ; remove nil entry
18284 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18285 (setq org-self-insert-command-undo-counter
18286 (1+ org-self-insert-command-undo-counter))))))))
18288 (defun org-check-before-invisible-edit (kind)
18289 "Check is editing if kind KIND would be dangerous with invisible text around.
18290 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18291 ;; First, try to get out of here as quickly as possible, to reduce overhead
18292 (if (and org-catch-invisible-edits
18293 (or (not (boundp 'visible-mode)) (not visible-mode))
18294 (or (get-char-property (point) 'invisible)
18295 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18296 ;; OK, we need to take a closer look
18297 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18298 (invisible-before-point (if (bobp) nil (get-char-property
18299 (1- (point)) 'invisible)))
18300 (border-and-ok-direction
18302 ;; Check if we are acting predictably before invisible text
18303 (and invisible-at-point (not invisible-before-point)
18304 (memq kind '(insert delete-backward)))
18305 ;; Check if we are acting predictably after invisible text
18306 ;; This works not well, and I have turned it off. It seems
18307 ;; better to always show and stop after invisible text.
18308 ;; (and (not invisible-at-point) invisible-before-point
18309 ;; (memq kind '(insert delete)))
18311 (when (or (memq invisible-at-point '(outline org-hide-block t))
18312 (memq invisible-before-point '(outline org-hide-block t)))
18313 (if (eq org-catch-invisible-edits 'error)
18314 (error "Editing in invisible areas is prohibited - make visible first"))
18315 (if (and org-custom-properties-overlays
18316 (y-or-n-p "Display invisible properties in this buffer? "))
18317 (org-toggle-custom-properties-visibility)
18318 ;; Make the area visible
18319 (save-excursion
18320 (if invisible-before-point
18321 (goto-char (previous-single-char-property-change
18322 (point) 'invisible)))
18323 (org-cycle))
18324 (cond
18325 ((eq org-catch-invisible-edits 'show)
18326 ;; That's it, we do the edit after showing
18327 (message
18328 "Unfolding invisible region around point before editing")
18329 (sit-for 1))
18330 ((and (eq org-catch-invisible-edits 'smart)
18331 border-and-ok-direction)
18332 (message "Unfolding invisible region around point before editing"))
18334 ;; Don't do the edit, make the user repeat it in full visibility
18335 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18337 (defun org-fix-tags-on-the-fly ()
18338 (when (and (equal (char-after (point-at-bol)) ?*)
18339 (org-at-heading-p))
18340 (org-align-tags-here org-tags-column)))
18342 (defun org-delete-backward-char (N)
18343 "Like `delete-backward-char', insert whitespace at field end in tables.
18344 When deleting backwards, in tables this function will insert whitespace in
18345 front of the next \"|\" separator, to keep the table aligned. The table will
18346 still be marked for re-alignment if the field did fill the entire column,
18347 because, in this case the deletion might narrow the column."
18348 (interactive "p")
18349 (save-match-data
18350 (org-check-before-invisible-edit 'delete-backward)
18351 (if (and (org-table-p)
18352 (eq N 1)
18353 (string-match "|" (buffer-substring (point-at-bol) (point)))
18354 (looking-at ".*?|"))
18355 (let ((pos (point))
18356 (noalign (looking-at "[^|\n\r]* |"))
18357 (c org-table-may-need-update))
18358 (backward-delete-char N)
18359 (if (not overwrite-mode)
18360 (progn
18361 (skip-chars-forward "^|")
18362 (insert " ")
18363 (goto-char (1- pos))))
18364 ;; noalign: if there were two spaces at the end, this field
18365 ;; does not determine the width of the column.
18366 (if noalign (setq org-table-may-need-update c)))
18367 (backward-delete-char N)
18368 (org-fix-tags-on-the-fly))))
18370 (defun org-delete-char (N)
18371 "Like `delete-char', but insert whitespace at field end in tables.
18372 When deleting characters, in tables this function will insert whitespace in
18373 front of the next \"|\" separator, to keep the table aligned. The table will
18374 still be marked for re-alignment if the field did fill the entire column,
18375 because, in this case the deletion might narrow the column."
18376 (interactive "p")
18377 (save-match-data
18378 (org-check-before-invisible-edit 'delete)
18379 (if (and (org-table-p)
18380 (not (bolp))
18381 (not (= (char-after) ?|))
18382 (eq N 1))
18383 (if (looking-at ".*?|")
18384 (let ((pos (point))
18385 (noalign (looking-at "[^|\n\r]* |"))
18386 (c org-table-may-need-update))
18387 (replace-match (concat
18388 (substring (match-string 0) 1 -1)
18389 " |"))
18390 (goto-char pos)
18391 ;; noalign: if there were two spaces at the end, this field
18392 ;; does not determine the width of the column.
18393 (if noalign (setq org-table-may-need-update c)))
18394 (delete-char N))
18395 (delete-char N)
18396 (org-fix-tags-on-the-fly))))
18398 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18399 (put 'org-self-insert-command 'delete-selection t)
18400 (put 'orgtbl-self-insert-command 'delete-selection t)
18401 (put 'org-delete-char 'delete-selection 'supersede)
18402 (put 'org-delete-backward-char 'delete-selection 'supersede)
18403 (put 'org-yank 'delete-selection 'yank)
18405 ;; Make `flyspell-mode' delay after some commands
18406 (put 'org-self-insert-command 'flyspell-delayed t)
18407 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18408 (put 'org-delete-char 'flyspell-delayed t)
18409 (put 'org-delete-backward-char 'flyspell-delayed t)
18411 ;; Make pabbrev-mode expand after org-mode commands
18412 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18413 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18415 ;; How to do this: Measure non-white length of current string
18416 ;; If equal to column width, we should realign.
18418 (defun org-remap (map &rest commands)
18419 "In MAP, remap the functions given in COMMANDS.
18420 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18421 (let (new old)
18422 (while commands
18423 (setq old (pop commands) new (pop commands))
18424 (if (fboundp 'command-remapping)
18425 (org-defkey map (vector 'remap old) new)
18426 (substitute-key-definition old new map global-map)))))
18428 (when (eq org-enable-table-editor 'optimized)
18429 ;; If the user wants maximum table support, we need to hijack
18430 ;; some standard editing functions
18431 (org-remap org-mode-map
18432 'self-insert-command 'org-self-insert-command
18433 'delete-char 'org-delete-char
18434 'delete-backward-char 'org-delete-backward-char)
18435 (org-defkey org-mode-map "|" 'org-force-self-insert))
18437 (defvar org-ctrl-c-ctrl-c-hook nil
18438 "Hook for functions attaching themselves to `C-c C-c'.
18440 This can be used to add additional functionality to the C-c C-c
18441 key which executes context-dependent commands. This hook is run
18442 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18443 run after the last test.
18445 Each function will be called with no arguments. The function
18446 must check if the context is appropriate for it to act. If yes,
18447 it should do its thing and then return a non-nil value. If the
18448 context is wrong, just do nothing and return nil.")
18450 (defvar org-ctrl-c-ctrl-c-final-hook nil
18451 "Hook for functions attaching themselves to `C-c C-c'.
18453 This can be used to add additional functionality to the C-c C-c
18454 key which executes context-dependent commands. This hook is run
18455 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18456 before the first test.
18458 Each function will be called with no arguments. The function
18459 must check if the context is appropriate for it to act. If yes,
18460 it should do its thing and then return a non-nil value. If the
18461 context is wrong, just do nothing and return nil.")
18463 (defvar org-tab-first-hook nil
18464 "Hook for functions to attach themselves to TAB.
18465 See `org-ctrl-c-ctrl-c-hook' for more information.
18466 This hook runs as the first action when TAB is pressed, even before
18467 `org-cycle' messes around with the `outline-regexp' to cater for
18468 inline tasks and plain list item folding.
18469 If any function in this hook returns t, any other actions that
18470 would have been caused by TAB (such as table field motion or visibility
18471 cycling) will not occur.")
18473 (defvar org-tab-after-check-for-table-hook nil
18474 "Hook for functions to attach themselves to TAB.
18475 See `org-ctrl-c-ctrl-c-hook' for more information.
18476 This hook runs after it has been established that the cursor is not in a
18477 table, but before checking if the cursor is in a headline or if global cycling
18478 should be done.
18479 If any function in this hook returns t, not other actions like visibility
18480 cycling will be done.")
18482 (defvar org-tab-after-check-for-cycling-hook nil
18483 "Hook for functions to attach themselves to TAB.
18484 See `org-ctrl-c-ctrl-c-hook' for more information.
18485 This hook runs after it has been established that not table field motion and
18486 not visibility should be done because of current context. This is probably
18487 the place where a package like yasnippets can hook in.")
18489 (defvar org-tab-before-tab-emulation-hook nil
18490 "Hook for functions to attach themselves to TAB.
18491 See `org-ctrl-c-ctrl-c-hook' for more information.
18492 This hook runs after every other options for TAB have been exhausted, but
18493 before indentation and \t insertion takes place.")
18495 (defvar org-metaleft-hook nil
18496 "Hook for functions attaching themselves to `M-left'.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.")
18498 (defvar org-metaright-hook nil
18499 "Hook for functions attaching themselves to `M-right'.
18500 See `org-ctrl-c-ctrl-c-hook' for more information.")
18501 (defvar org-metaup-hook nil
18502 "Hook for functions attaching themselves to `M-up'.
18503 See `org-ctrl-c-ctrl-c-hook' for more information.")
18504 (defvar org-metadown-hook nil
18505 "Hook for functions attaching themselves to `M-down'.
18506 See `org-ctrl-c-ctrl-c-hook' for more information.")
18507 (defvar org-shiftmetaleft-hook nil
18508 "Hook for functions attaching themselves to `M-S-left'.
18509 See `org-ctrl-c-ctrl-c-hook' for more information.")
18510 (defvar org-shiftmetaright-hook nil
18511 "Hook for functions attaching themselves to `M-S-right'.
18512 See `org-ctrl-c-ctrl-c-hook' for more information.")
18513 (defvar org-shiftmetaup-hook nil
18514 "Hook for functions attaching themselves to `M-S-up'.
18515 See `org-ctrl-c-ctrl-c-hook' for more information.")
18516 (defvar org-shiftmetadown-hook nil
18517 "Hook for functions attaching themselves to `M-S-down'.
18518 See `org-ctrl-c-ctrl-c-hook' for more information.")
18519 (defvar org-metareturn-hook nil
18520 "Hook for functions attaching themselves to `M-RET'.
18521 See `org-ctrl-c-ctrl-c-hook' for more information.")
18522 (defvar org-shiftup-hook nil
18523 "Hook for functions attaching themselves to `S-up'.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-shiftup-final-hook nil
18526 "Hook for functions attaching themselves to `S-up'.
18527 This one runs after all other options except shift-select have been excluded.
18528 See `org-ctrl-c-ctrl-c-hook' for more information.")
18529 (defvar org-shiftdown-hook nil
18530 "Hook for functions attaching themselves to `S-down'.
18531 See `org-ctrl-c-ctrl-c-hook' for more information.")
18532 (defvar org-shiftdown-final-hook nil
18533 "Hook for functions attaching themselves to `S-down'.
18534 This one runs after all other options except shift-select have been excluded.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.")
18536 (defvar org-shiftleft-hook nil
18537 "Hook for functions attaching themselves to `S-left'.
18538 See `org-ctrl-c-ctrl-c-hook' for more information.")
18539 (defvar org-shiftleft-final-hook nil
18540 "Hook for functions attaching themselves to `S-left'.
18541 This one runs after all other options except shift-select have been excluded.
18542 See `org-ctrl-c-ctrl-c-hook' for more information.")
18543 (defvar org-shiftright-hook nil
18544 "Hook for functions attaching themselves to `S-right'.
18545 See `org-ctrl-c-ctrl-c-hook' for more information.")
18546 (defvar org-shiftright-final-hook nil
18547 "Hook for functions attaching themselves to `S-right'.
18548 This one runs after all other options except shift-select have been excluded.
18549 See `org-ctrl-c-ctrl-c-hook' for more information.")
18551 (defun org-modifier-cursor-error ()
18552 "Throw an error, a modified cursor command was applied in wrong context."
18553 (error "This command is active in special context like tables, headlines or items"))
18555 (defun org-shiftselect-error ()
18556 "Throw an error because Shift-Cursor command was applied in wrong context."
18557 (if (and (boundp 'shift-select-mode) shift-select-mode)
18558 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18559 (error "This command works only in special context like headlines or timestamps")))
18561 (defun org-call-for-shift-select (cmd)
18562 (let ((this-command-keys-shift-translated t))
18563 (call-interactively cmd)))
18565 (defun org-shifttab (&optional arg)
18566 "Global visibility cycling or move to previous table field.
18567 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18568 on context.
18569 See the individual commands for more information."
18570 (interactive "P")
18571 (cond
18572 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18573 ((integerp arg)
18574 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18575 (message "Content view to level: %d" arg)
18576 (org-content (prefix-numeric-value arg2))
18577 (setq org-cycle-global-status 'overview)))
18578 (t (call-interactively 'org-global-cycle))))
18580 (defun org-shiftmetaleft ()
18581 "Promote subtree or delete table column.
18582 Calls `org-promote-subtree', `org-outdent-item-tree', or
18583 `org-table-delete-column', depending on context. See the
18584 individual commands for more information."
18585 (interactive)
18586 (cond
18587 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18588 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18589 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18590 ((if (not (org-region-active-p)) (org-at-item-p)
18591 (save-excursion (goto-char (region-beginning))
18592 (org-at-item-p)))
18593 (call-interactively 'org-outdent-item-tree))
18594 (t (org-modifier-cursor-error))))
18596 (defun org-shiftmetaright ()
18597 "Demote subtree or insert table column.
18598 Calls `org-demote-subtree', `org-indent-item-tree', or
18599 `org-table-insert-column', depending on context. See the
18600 individual commands for more information."
18601 (interactive)
18602 (cond
18603 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18604 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18605 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18606 ((if (not (org-region-active-p)) (org-at-item-p)
18607 (save-excursion (goto-char (region-beginning))
18608 (org-at-item-p)))
18609 (call-interactively 'org-indent-item-tree))
18610 (t (org-modifier-cursor-error))))
18612 (defun org-shiftmetaup (&optional arg)
18613 "Move subtree up or kill table row.
18614 Calls `org-move-subtree-up' or `org-table-kill-row' or
18615 `org-move-item-up' or `org-timestamp-up', depending on context.
18616 See the individual commands for more information."
18617 (interactive "P")
18618 (cond
18619 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18620 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18621 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18622 ((org-at-item-p) (call-interactively 'org-move-item-up))
18623 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18624 (call-interactively 'org-timestamp-up)))
18625 (t (org-modifier-cursor-error))))
18627 (defun org-shiftmetadown (&optional arg)
18628 "Move subtree down or insert table row.
18629 Calls `org-move-subtree-down' or `org-table-insert-row' or
18630 `org-move-item-down' or `org-timestamp-up', depending on context.
18631 See the individual commands for more information."
18632 (interactive "P")
18633 (cond
18634 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18635 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18636 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18637 ((org-at-item-p) (call-interactively 'org-move-item-down))
18638 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18639 (call-interactively 'org-timestamp-down)))
18640 (t (org-modifier-cursor-error))))
18642 (defsubst org-hidden-tree-error ()
18643 (error
18644 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18646 (defun org-metaleft (&optional arg)
18647 "Promote heading or move table column to left.
18648 Calls `org-do-promote' or `org-table-move-column', depending on context.
18649 With no specific context, calls the Emacs default `backward-word'.
18650 See the individual commands for more information."
18651 (interactive "P")
18652 (cond
18653 ((run-hook-with-args-until-success 'org-metaleft-hook))
18654 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18655 ((org-with-limited-levels
18656 (or (org-at-heading-p)
18657 (and (org-region-active-p)
18658 (save-excursion
18659 (goto-char (region-beginning))
18660 (org-at-heading-p)))))
18661 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18662 (call-interactively 'org-do-promote))
18663 ;; At an inline task.
18664 ((org-at-heading-p)
18665 (call-interactively 'org-inlinetask-promote))
18666 ((or (org-at-item-p)
18667 (and (org-region-active-p)
18668 (save-excursion
18669 (goto-char (region-beginning))
18670 (org-at-item-p))))
18671 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18672 (call-interactively 'org-outdent-item))
18673 (t (call-interactively 'backward-word))))
18675 (defun org-metaright (&optional arg)
18676 "Demote a subtree, a list item or move table column to right.
18677 In front of a drawer or a block keyword, indent it correctly.
18678 With no specific context, calls the Emacs default `forward-word'.
18679 See the individual commands for more information."
18680 (interactive "P")
18681 (cond
18682 ((run-hook-with-args-until-success 'org-metaright-hook))
18683 ((org-at-table-p) (call-interactively 'org-table-move-column))
18684 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18685 ((org-at-block-p) (call-interactively 'org-indent-block))
18686 ((org-with-limited-levels
18687 (or (org-at-heading-p)
18688 (and (org-region-active-p)
18689 (save-excursion
18690 (goto-char (region-beginning))
18691 (org-at-heading-p)))))
18692 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18693 (call-interactively 'org-do-demote))
18694 ;; At an inline task.
18695 ((org-at-heading-p)
18696 (call-interactively 'org-inlinetask-demote))
18697 ((or (org-at-item-p)
18698 (and (org-region-active-p)
18699 (save-excursion
18700 (goto-char (region-beginning))
18701 (org-at-item-p))))
18702 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18703 (call-interactively 'org-indent-item))
18704 (t (call-interactively 'forward-word))))
18706 (defun org-check-for-hidden (what)
18707 "Check if there are hidden headlines/items in the current visual line.
18708 WHAT can be either `headlines' or `items'. If the current line is
18709 an outline or item heading and it has a folded subtree below it,
18710 this function returns t, nil otherwise."
18711 (let ((re (cond
18712 ((eq what 'headlines) org-outline-regexp-bol)
18713 ((eq what 'items) (org-item-beginning-re))
18714 (t (error "This should not happen"))))
18715 beg end)
18716 (save-excursion
18717 (catch 'exit
18718 (unless (org-region-active-p)
18719 (setq beg (point-at-bol))
18720 (beginning-of-line 2)
18721 (while (and (not (eobp)) ;; this is like `next-line'
18722 (get-char-property (1- (point)) 'invisible))
18723 (beginning-of-line 2))
18724 (setq end (point))
18725 (goto-char beg)
18726 (goto-char (point-at-eol))
18727 (setq end (max end (point)))
18728 (while (re-search-forward re end t)
18729 (if (get-char-property (match-beginning 0) 'invisible)
18730 (throw 'exit t))))
18731 nil))))
18733 (autoload 'org-element-at-point "org-element")
18734 (autoload 'org-element-type "org-element")
18736 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18737 (declare-function org-element-type "org-element" (element))
18738 (declare-function org-element-contents "org-element" (element))
18739 (declare-function org-element-property "org-element" (property element))
18740 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18741 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18742 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18743 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18744 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18746 (defun org-metaup (&optional arg)
18747 "Move subtree up or move table row up.
18748 Calls `org-move-subtree-up' or `org-table-move-row' or
18749 `org-move-item-up', depending on context. See the individual commands
18750 for more information."
18751 (interactive "P")
18752 (cond
18753 ((run-hook-with-args-until-success 'org-metaup-hook))
18754 ((org-region-active-p)
18755 (let* ((a (min (region-beginning) (region-end)))
18756 (b (1- (max (region-beginning) (region-end))))
18757 (c (save-excursion (goto-char a)
18758 (move-beginning-of-line 0)))
18759 (d (save-excursion (goto-char a)
18760 (move-end-of-line 0) (point))))
18761 (transpose-regions a b c d)
18762 (goto-char c)))
18763 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18764 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18765 ((org-at-item-p) (call-interactively 'org-move-item-up))
18766 (t (org-drag-element-backward))))
18768 (defun org-metadown (&optional arg)
18769 "Move subtree down or move table row down.
18770 Calls `org-move-subtree-down' or `org-table-move-row' or
18771 `org-move-item-down', depending on context. See the individual
18772 commands for more information."
18773 (interactive "P")
18774 (cond
18775 ((run-hook-with-args-until-success 'org-metadown-hook))
18776 ((org-region-active-p)
18777 (let* ((a (min (region-beginning) (region-end)))
18778 (b (max (region-beginning) (region-end)))
18779 (c (save-excursion (goto-char b)
18780 (move-beginning-of-line 1)))
18781 (d (save-excursion (goto-char b)
18782 (move-end-of-line 1) (1+ (point)))))
18783 (transpose-regions a b c d)
18784 (goto-char d)))
18785 ((org-at-table-p) (call-interactively 'org-table-move-row))
18786 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18787 ((org-at-item-p) (call-interactively 'org-move-item-down))
18788 (t (org-drag-element-forward))))
18790 (defun org-shiftup (&optional arg)
18791 "Increase item in timestamp or increase priority of current headline.
18792 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18793 depending on context. See the individual commands for more information."
18794 (interactive "P")
18795 (cond
18796 ((run-hook-with-args-until-success 'org-shiftup-hook))
18797 ((and org-support-shift-select (org-region-active-p))
18798 (org-call-for-shift-select 'previous-line))
18799 ((org-at-timestamp-p t)
18800 (call-interactively (if org-edit-timestamp-down-means-later
18801 'org-timestamp-down 'org-timestamp-up)))
18802 ((and (not (eq org-support-shift-select 'always))
18803 org-enable-priority-commands
18804 (org-at-heading-p))
18805 (call-interactively 'org-priority-up))
18806 ((and (not org-support-shift-select) (org-at-item-p))
18807 (call-interactively 'org-previous-item))
18808 ((org-clocktable-try-shift 'up arg))
18809 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18810 (org-support-shift-select
18811 (org-call-for-shift-select 'previous-line))
18812 (t (org-shiftselect-error))))
18814 (defun org-shiftdown (&optional arg)
18815 "Decrease item in timestamp or decrease priority of current headline.
18816 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18817 depending on context. See the individual commands for more information."
18818 (interactive "P")
18819 (cond
18820 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18821 ((and org-support-shift-select (org-region-active-p))
18822 (org-call-for-shift-select 'next-line))
18823 ((org-at-timestamp-p t)
18824 (call-interactively (if org-edit-timestamp-down-means-later
18825 'org-timestamp-up 'org-timestamp-down)))
18826 ((and (not (eq org-support-shift-select 'always))
18827 org-enable-priority-commands
18828 (org-at-heading-p))
18829 (call-interactively 'org-priority-down))
18830 ((and (not org-support-shift-select) (org-at-item-p))
18831 (call-interactively 'org-next-item))
18832 ((org-clocktable-try-shift 'down arg))
18833 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18834 (org-support-shift-select
18835 (org-call-for-shift-select 'next-line))
18836 (t (org-shiftselect-error))))
18838 (defun org-shiftright (&optional arg)
18839 "Cycle the thing at point or in the current line, depending on context.
18840 Depending on context, this does one of the following:
18842 - switch a timestamp at point one day into the future
18843 - on a headline, switch to the next TODO keyword.
18844 - on an item, switch entire list to the next bullet type
18845 - on a property line, switch to the next allowed value
18846 - on a clocktable definition line, move time block into the future"
18847 (interactive "P")
18848 (cond
18849 ((run-hook-with-args-until-success 'org-shiftright-hook))
18850 ((and org-support-shift-select (org-region-active-p))
18851 (org-call-for-shift-select 'forward-char))
18852 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18853 ((and (not (eq org-support-shift-select 'always))
18854 (org-at-heading-p))
18855 (let ((org-inhibit-logging
18856 (not org-treat-S-cursor-todo-selection-as-state-change))
18857 (org-inhibit-blocking
18858 (not org-treat-S-cursor-todo-selection-as-state-change)))
18859 (org-call-with-arg 'org-todo 'right)))
18860 ((or (and org-support-shift-select
18861 (not (eq org-support-shift-select 'always))
18862 (org-at-item-bullet-p))
18863 (and (not org-support-shift-select) (org-at-item-p)))
18864 (org-call-with-arg 'org-cycle-list-bullet nil))
18865 ((and (not (eq org-support-shift-select 'always))
18866 (org-at-property-p))
18867 (call-interactively 'org-property-next-allowed-value))
18868 ((org-clocktable-try-shift 'right arg))
18869 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18870 (org-support-shift-select
18871 (org-call-for-shift-select 'forward-char))
18872 (t (org-shiftselect-error))))
18874 (defun org-shiftleft (&optional arg)
18875 "Cycle the thing at point or in the current line, depending on context.
18876 Depending on context, this does one of the following:
18878 - switch a timestamp at point one day into the past
18879 - on a headline, switch to the previous TODO keyword.
18880 - on an item, switch entire list to the previous bullet type
18881 - on a property line, switch to the previous allowed value
18882 - on a clocktable definition line, move time block into the past"
18883 (interactive "P")
18884 (cond
18885 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18886 ((and org-support-shift-select (org-region-active-p))
18887 (org-call-for-shift-select 'backward-char))
18888 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18889 ((and (not (eq org-support-shift-select 'always))
18890 (org-at-heading-p))
18891 (let ((org-inhibit-logging
18892 (not org-treat-S-cursor-todo-selection-as-state-change))
18893 (org-inhibit-blocking
18894 (not org-treat-S-cursor-todo-selection-as-state-change)))
18895 (org-call-with-arg 'org-todo 'left)))
18896 ((or (and org-support-shift-select
18897 (not (eq org-support-shift-select 'always))
18898 (org-at-item-bullet-p))
18899 (and (not org-support-shift-select) (org-at-item-p)))
18900 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18901 ((and (not (eq org-support-shift-select 'always))
18902 (org-at-property-p))
18903 (call-interactively 'org-property-previous-allowed-value))
18904 ((org-clocktable-try-shift 'left arg))
18905 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18906 (org-support-shift-select
18907 (org-call-for-shift-select 'backward-char))
18908 (t (org-shiftselect-error))))
18910 (defun org-shiftcontrolright ()
18911 "Switch to next TODO set."
18912 (interactive)
18913 (cond
18914 ((and org-support-shift-select (org-region-active-p))
18915 (org-call-for-shift-select 'forward-word))
18916 ((and (not (eq org-support-shift-select 'always))
18917 (org-at-heading-p))
18918 (org-call-with-arg 'org-todo 'nextset))
18919 (org-support-shift-select
18920 (org-call-for-shift-select 'forward-word))
18921 (t (org-shiftselect-error))))
18923 (defun org-shiftcontrolleft ()
18924 "Switch to previous TODO set."
18925 (interactive)
18926 (cond
18927 ((and org-support-shift-select (org-region-active-p))
18928 (org-call-for-shift-select 'backward-word))
18929 ((and (not (eq org-support-shift-select 'always))
18930 (org-at-heading-p))
18931 (org-call-with-arg 'org-todo 'previousset))
18932 (org-support-shift-select
18933 (org-call-for-shift-select 'backward-word))
18934 (t (org-shiftselect-error))))
18936 (defun org-shiftcontrolup ()
18937 "Change timestamps synchronously up in CLOCK log lines."
18938 (interactive)
18939 (cond ((and (not org-support-shift-select)
18940 (org-at-clock-log-p)
18941 (org-at-timestamp-p t))
18942 (org-clock-timestamps-up))
18943 (t (org-shiftselect-error))))
18945 (defun org-shiftcontroldown ()
18946 "Change timestamps synchronously down in CLOCK log lines."
18947 (interactive)
18948 (cond ((and (not org-support-shift-select)
18949 (org-at-clock-log-p)
18950 (org-at-timestamp-p t))
18951 (org-clock-timestamps-down))
18952 (t (org-shiftselect-error))))
18954 (defun org-ctrl-c-ret ()
18955 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18956 (interactive)
18957 (cond
18958 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18959 (t (call-interactively 'org-insert-heading))))
18961 (defun org-find-visible ()
18962 (let ((s (point)))
18963 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18964 (get-char-property s 'invisible)))
18966 (defun org-find-invisible ()
18967 (let ((s (point)))
18968 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18969 (not (get-char-property s 'invisible))))
18972 (defun org-copy-visible (beg end)
18973 "Copy the visible parts of the region."
18974 (interactive "r")
18975 (let (snippets s)
18976 (save-excursion
18977 (save-restriction
18978 (narrow-to-region beg end)
18979 (setq s (goto-char (point-min)))
18980 (while (not (= (point) (point-max)))
18981 (goto-char (org-find-invisible))
18982 (push (buffer-substring s (point)) snippets)
18983 (setq s (goto-char (org-find-visible))))))
18984 (kill-new (apply 'concat (nreverse snippets)))))
18986 (defun org-copy-special ()
18987 "Copy region in table or copy current subtree.
18988 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18989 See the individual commands for more information."
18990 (interactive)
18991 (call-interactively
18992 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18994 (defun org-cut-special ()
18995 "Cut region in table or cut current subtree.
18996 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18997 See the individual commands for more information."
18998 (interactive)
18999 (call-interactively
19000 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19002 (defun org-paste-special (arg)
19003 "Paste rectangular region into table, or past subtree relative to level.
19004 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19005 See the individual commands for more information."
19006 (interactive "P")
19007 (if (org-at-table-p)
19008 (org-table-paste-rectangle)
19009 (org-paste-subtree arg)))
19011 (defsubst org-in-fixed-width-region-p ()
19012 "Is point in a fixed-width region?"
19013 (save-match-data
19014 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19016 (defun org-edit-special (&optional arg)
19017 "Call a special editor for the stuff at point.
19018 When at a table, call the formula editor with `org-table-edit-formulas'.
19019 When in a source code block, call `org-edit-src-code'.
19020 When in a fixed-width region, call `org-edit-fixed-width-region'.
19021 When in an #+include line, visit the included file.
19022 On a link, call `ffap' to visit the link at point.
19023 Otherwise, return a user error."
19024 (interactive)
19025 ;; possibly prep session before editing source
19026 (when (and (org-in-src-block-p) arg)
19027 (let* ((info (org-babel-get-src-block-info))
19028 (lang (nth 0 info))
19029 (params (nth 2 info))
19030 (session (cdr (assoc :session params))))
19031 (when (and info session) ;; we are in a source-code block with a session
19032 (funcall
19033 (intern (concat "org-babel-prep-session:" lang)) session params))))
19034 (cond ;; proceed with `org-edit-special'
19035 ((save-excursion
19036 (beginning-of-line 1)
19037 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19038 (find-file (org-trim (match-string 1))))
19039 ((org-at-table.el-p) (org-edit-src-code))
19040 ((or (org-at-table-p)
19041 (save-excursion
19042 (beginning-of-line 1)
19043 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19044 (call-interactively 'org-table-edit-formulas))
19045 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19046 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19047 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19048 (t (user-error "No special environment to edit here"))))
19050 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19051 (defun org-ctrl-c-ctrl-c (&optional arg)
19052 "Set tags in headline, or update according to changed information at point.
19054 This command does many different things, depending on context:
19056 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19057 this is what we do.
19059 - If the cursor is on a statistics cookie, update it.
19061 - If the cursor is in a headline, prompt for tags and insert them
19062 into the current line, aligned to `org-tags-column'. When called
19063 with prefix arg, realign all tags in the current buffer.
19065 - If the cursor is in one of the special #+KEYWORD lines, this
19066 triggers scanning the buffer for these lines and updating the
19067 information.
19069 - If the cursor is inside a table, realign the table. This command
19070 works even if the automatic table editor has been turned off.
19072 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19073 the entire table.
19075 - If the cursor is at a footnote reference or definition, jump to
19076 the corresponding definition or references, respectively.
19078 - If the cursor is a the beginning of a dynamic block, update it.
19080 - If the current buffer is a capture buffer, close note and file it.
19082 - If the cursor is on a <<<target>>>, update radio targets and
19083 corresponding links in this buffer.
19085 - If the cursor is on a numbered item in a plain list, renumber the
19086 ordered list.
19088 - If the cursor is on a checkbox, toggle it.
19090 - If the cursor is on a code block, evaluate it. The variable
19091 `org-confirm-babel-evaluate' can be used to control prompting
19092 before code block evaluation, by default every code block
19093 evaluation requires confirmation. Code block evaluation can be
19094 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19095 (interactive "P")
19096 (let ((org-enable-table-editor t))
19097 (cond
19098 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19099 org-occur-highlights
19100 org-latex-fragment-image-overlays)
19101 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19102 (org-remove-occur-highlights)
19103 (org-remove-latex-fragment-image-overlays)
19104 (message "Temporary highlights/overlays removed from current buffer"))
19105 ((and (local-variable-p 'org-finish-function (current-buffer))
19106 (fboundp org-finish-function))
19107 (funcall org-finish-function))
19108 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19109 ((org-in-regexp org-ts-regexp-both)
19110 (org-timestamp-change 0 'day))
19111 ((or (looking-at org-property-start-re)
19112 (org-at-property-p))
19113 (call-interactively 'org-property-action))
19114 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19115 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19116 (or (org-at-heading-p) (org-at-item-p)))
19117 (call-interactively 'org-update-statistics-cookies))
19118 ((org-at-heading-p) (call-interactively 'org-set-tags))
19119 ((org-at-table.el-p)
19120 (message "Use C-c ' to edit table.el tables"))
19121 ((org-at-table-p)
19122 (org-table-maybe-eval-formula)
19123 (if arg
19124 (call-interactively 'org-table-recalculate)
19125 (org-table-maybe-recalculate-line))
19126 (call-interactively 'org-table-align)
19127 (orgtbl-send-table 'maybe))
19128 ((or (org-footnote-at-reference-p)
19129 (org-footnote-at-definition-p))
19130 (call-interactively 'org-footnote-action))
19131 ((org-at-item-checkbox-p)
19132 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19133 ;; list only if at top item.
19134 (let* ((cbox (match-string 1))
19135 (struct (org-list-struct))
19136 (old-struct (copy-tree struct))
19137 (parents (org-list-parents-alist struct))
19138 (orderedp (org-entry-get nil "ORDERED"))
19139 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19140 block-item)
19141 ;; Use a light version of `org-toggle-checkbox' to avoid
19142 ;; computing list structure twice.
19143 (let ((new-box (cond
19144 ((equal arg '(16)) "[-]")
19145 ((equal arg '(4)) nil)
19146 ((equal "[X]" cbox) "[ ]")
19147 (t "[X]"))))
19148 (if (and firstp arg)
19149 ;; If at first item of sub-list, remove check-box from
19150 ;; every item at the same level.
19151 (mapc
19152 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19153 (org-list-get-all-items
19154 (point-at-bol) struct (org-list-prevs-alist struct)))
19155 (org-list-set-checkbox (point-at-bol) struct new-box)))
19156 ;; Replicate `org-list-write-struct', while grabbing a return
19157 ;; value from `org-list-struct-fix-box'.
19158 (org-list-struct-fix-ind struct parents 2)
19159 (org-list-struct-fix-item-end struct)
19160 (let ((prevs (org-list-prevs-alist struct)))
19161 (org-list-struct-fix-bul struct prevs)
19162 (org-list-struct-fix-ind struct parents)
19163 (setq block-item
19164 (org-list-struct-fix-box struct parents prevs orderedp)))
19165 (if (equal struct old-struct)
19166 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19167 (org-list-struct-apply-struct struct old-struct)
19168 (org-update-checkbox-count-maybe))
19169 (when block-item
19170 (message
19171 "Checkboxes were removed due to unchecked box at line %d"
19172 (org-current-line block-item)))
19173 (when firstp (org-list-send-list 'maybe))))
19174 ((org-at-item-p)
19175 ;; Cursor at an item: repair list. Do checkbox related actions
19176 ;; only if function was called with an argument. Send list only
19177 ;; if at top item.
19178 (let* ((struct (org-list-struct))
19179 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19180 old-struct)
19181 (when arg
19182 (setq old-struct (copy-tree struct))
19183 (if firstp
19184 ;; If at first item of sub-list, add check-box to every
19185 ;; item at the same level.
19186 (mapc
19187 (lambda (pos)
19188 (unless (org-list-get-checkbox pos struct)
19189 (org-list-set-checkbox pos struct "[ ]")))
19190 (org-list-get-all-items
19191 (point-at-bol) struct (org-list-prevs-alist struct)))
19192 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19193 (org-list-write-struct
19194 struct (org-list-parents-alist struct) old-struct)
19195 (when arg (org-update-checkbox-count-maybe))
19196 (when firstp (org-list-send-list 'maybe))))
19197 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19198 ;; Dynamic block
19199 (beginning-of-line 1)
19200 (save-excursion (org-update-dblock)))
19201 ((save-excursion
19202 (let ((case-fold-search t))
19203 (beginning-of-line 1)
19204 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19205 (cond
19206 ((or (equal (match-string 1) "TBLFM")
19207 (equal (match-string 1) "tblfm"))
19208 ;; Recalculate the table before this line
19209 (save-excursion
19210 (beginning-of-line 1)
19211 (skip-chars-backward " \r\n\t")
19212 (if (org-at-table-p)
19213 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19215 (let ((org-inhibit-startup-visibility-stuff t)
19216 (org-startup-align-all-tables nil))
19217 (when (boundp 'org-table-coordinate-overlays)
19218 (mapc 'delete-overlay org-table-coordinate-overlays)
19219 (setq org-table-coordinate-overlays nil))
19220 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19221 (message "Local setup has been refreshed"))))
19222 ((org-clock-update-time-maybe))
19224 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19225 (error "C-c C-c can do nothing useful at this location"))))))
19227 (defun org-mode-restart ()
19228 "Restart Org-mode, to scan again for special lines.
19229 Also updates the keyword regular expressions."
19230 (interactive)
19231 (org-mode)
19232 (message "Org-mode restarted"))
19234 (defun org-kill-note-or-show-branches ()
19235 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19236 (interactive)
19237 (if (not org-finish-function)
19238 (progn
19239 (hide-subtree)
19240 (call-interactively 'show-branches))
19241 (let ((org-note-abort t))
19242 (funcall org-finish-function))))
19244 (defun org-return (&optional indent)
19245 "Goto next table row or insert a newline.
19246 Calls `org-table-next-row' or `newline', depending on context.
19247 See the individual commands for more information."
19248 (interactive)
19249 (let (org-ts-what)
19250 (cond
19251 ((or (bobp) (org-in-src-block-p))
19252 (if indent (newline-and-indent) (newline)))
19253 ((org-at-table-p)
19254 (org-table-justify-field-maybe)
19255 (call-interactively 'org-table-next-row))
19256 ;; when `newline-and-indent' is called within a list, make sure
19257 ;; text moved stays inside the item.
19258 ((and (org-in-item-p) indent)
19259 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19260 (progn
19261 (save-match-data (newline))
19262 (org-indent-line-to (length (match-string 0))))
19263 (let ((ind (org-get-indentation)))
19264 (newline)
19265 (if (org-looking-back org-list-end-re)
19266 (org-indent-line)
19267 (org-indent-line-to ind)))))
19268 ((and org-return-follows-link
19269 (org-at-timestamp-p t)
19270 (not (eq org-ts-what 'after)))
19271 (org-follow-timestamp-link))
19272 ((and org-return-follows-link
19273 (let ((tprop (get-text-property (point) 'face)))
19274 (or (eq tprop 'org-link)
19275 (and (listp tprop) (memq 'org-link tprop)))))
19276 (call-interactively 'org-open-at-point))
19277 ((and (org-at-heading-p)
19278 (looking-at
19279 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19280 (org-show-entry)
19281 (end-of-line 1)
19282 (newline))
19283 (t (if indent (newline-and-indent) (newline))))))
19285 (defun org-return-indent ()
19286 "Goto next table row or insert a newline and indent.
19287 Calls `org-table-next-row' or `newline-and-indent', depending on
19288 context. See the individual commands for more information."
19289 (interactive)
19290 (org-return t))
19292 (defun org-ctrl-c-star ()
19293 "Compute table, or change heading status of lines.
19294 Calls `org-table-recalculate' or `org-toggle-heading',
19295 depending on context."
19296 (interactive)
19297 (cond
19298 ((org-at-table-p)
19299 (call-interactively 'org-table-recalculate))
19301 ;; Convert all lines in region to list items
19302 (call-interactively 'org-toggle-heading))))
19304 (defun org-ctrl-c-minus ()
19305 "Insert separator line in table or modify bullet status of line.
19306 Also turns a plain line or a region of lines into list items.
19307 Calls `org-table-insert-hline', `org-toggle-item', or
19308 `org-cycle-list-bullet', depending on context."
19309 (interactive)
19310 (cond
19311 ((org-at-table-p)
19312 (call-interactively 'org-table-insert-hline))
19313 ((org-region-active-p)
19314 (call-interactively 'org-toggle-item))
19315 ((org-in-item-p)
19316 (call-interactively 'org-cycle-list-bullet))
19318 (call-interactively 'org-toggle-item))))
19320 (defun org-toggle-item (arg)
19321 "Convert headings or normal lines to items, items to normal lines.
19322 If there is no active region, only the current line is considered.
19324 If the first non blank line in the region is an headline, convert
19325 all headlines to items, shifting text accordingly.
19327 If it is an item, convert all items to normal lines.
19329 If it is normal text, change region into an item. With a prefix
19330 argument ARG, change each line in region into an item."
19331 (interactive "P")
19332 (let ((shift-text
19333 (function
19334 ;; Shift text in current section to IND, from point to END.
19335 ;; The function leaves point to END line.
19336 (lambda (ind end)
19337 (let ((min-i 1000) (end (copy-marker end)))
19338 ;; First determine the minimum indentation (MIN-I) of
19339 ;; the text.
19340 (save-excursion
19341 (catch 'exit
19342 (while (< (point) end)
19343 (let ((i (org-get-indentation)))
19344 (cond
19345 ;; Skip blank lines and inline tasks.
19346 ((looking-at "^[ \t]*$"))
19347 ((looking-at org-outline-regexp-bol))
19348 ;; We can't find less than 0 indentation.
19349 ((zerop i) (throw 'exit (setq min-i 0)))
19350 ((< i min-i) (setq min-i i))))
19351 (forward-line))))
19352 ;; Then indent each line so that a line indented to
19353 ;; MIN-I becomes indented to IND. Ignore blank lines
19354 ;; and inline tasks in the process.
19355 (let ((delta (- ind min-i)))
19356 (while (< (point) end)
19357 (unless (or (looking-at "^[ \t]*$")
19358 (looking-at org-outline-regexp-bol))
19359 (org-indent-line-to (+ (org-get-indentation) delta)))
19360 (forward-line)))))))
19361 (skip-blanks
19362 (function
19363 ;; Return beginning of first non-blank line, starting from
19364 ;; line at POS.
19365 (lambda (pos)
19366 (save-excursion
19367 (goto-char pos)
19368 (skip-chars-forward " \r\t\n")
19369 (point-at-bol)))))
19370 beg end)
19371 ;; Determine boundaries of changes.
19372 (if (org-region-active-p)
19373 (setq beg (funcall skip-blanks (region-beginning))
19374 end (copy-marker (region-end)))
19375 (setq beg (funcall skip-blanks (point-at-bol))
19376 end (copy-marker (point-at-eol))))
19377 ;; Depending on the starting line, choose an action on the text
19378 ;; between BEG and END.
19379 (org-with-limited-levels
19380 (save-excursion
19381 (goto-char beg)
19382 (cond
19383 ;; Case 1. Start at an item: de-itemize. Note that it only
19384 ;; happens when a region is active: `org-ctrl-c-minus'
19385 ;; would call `org-cycle-list-bullet' otherwise.
19386 ((org-at-item-p)
19387 (while (< (point) end)
19388 (when (org-at-item-p)
19389 (skip-chars-forward " \t")
19390 (delete-region (point) (match-end 0)))
19391 (forward-line)))
19392 ;; Case 2. Start at an heading: convert to items.
19393 ((org-at-heading-p)
19394 (let* ((bul (org-list-bullet-string "-"))
19395 (bul-len (length bul))
19396 ;; Indentation of the first heading. It should be
19397 ;; relative to the indentation of its parent, if any.
19398 (start-ind (save-excursion
19399 (cond
19400 ((not org-adapt-indentation) 0)
19401 ((not (outline-previous-heading)) 0)
19402 (t (length (match-string 0))))))
19403 ;; Level of first heading. Further headings will be
19404 ;; compared to it to determine hierarchy in the list.
19405 (ref-level (org-reduced-level (org-outline-level))))
19406 (while (< (point) end)
19407 (let* ((level (org-reduced-level (org-outline-level)))
19408 (delta (max 0 (- level ref-level))))
19409 ;; If current headline is less indented than the first
19410 ;; one, set it as reference, in order to preserve
19411 ;; subtrees.
19412 (when (< level ref-level) (setq ref-level level))
19413 (replace-match bul t t)
19414 (org-indent-line-to (+ start-ind (* delta bul-len)))
19415 ;; Ensure all text down to END (or SECTION-END) belongs
19416 ;; to the newly created item.
19417 (let ((section-end (save-excursion
19418 (or (outline-next-heading) (point)))))
19419 (forward-line)
19420 (funcall shift-text
19421 (+ start-ind (* (1+ delta) bul-len))
19422 (min end section-end)))))))
19423 ;; Case 3. Normal line with ARG: turn each non-item line into
19424 ;; an item.
19425 (arg
19426 (while (< (point) end)
19427 (unless (or (org-at-heading-p) (org-at-item-p))
19428 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19429 (replace-match
19430 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19431 (forward-line)))
19432 ;; Case 4. Normal line without ARG: make the first line of
19433 ;; region an item, and shift indentation of others
19434 ;; lines to set them as item's body.
19435 (t (let* ((bul (org-list-bullet-string "-"))
19436 (bul-len (length bul))
19437 (ref-ind (org-get-indentation)))
19438 (skip-chars-forward " \t")
19439 (insert bul)
19440 (forward-line)
19441 (while (< (point) end)
19442 ;; Ensure that lines less indented than first one
19443 ;; still get included in item body.
19444 (funcall shift-text
19445 (+ ref-ind bul-len)
19446 (min end (save-excursion (or (outline-next-heading)
19447 (point)))))
19448 (forward-line)))))))))
19450 (defun org-toggle-heading (&optional nstars)
19451 "Convert headings to normal text, or items or text to headings.
19452 If there is no active region, only the current line is considered.
19454 With a \\[universal-argument] prefix, convert the whole list at
19455 point into heading.
19457 In a region:
19459 - If the first non blank line is an headline, remove the stars
19460 from all headlines in the region.
19462 - If it is a normal line turn each and every normal line (i.e. not an
19463 heading or an item) in the region into a heading.
19465 - If it is a plain list item, turn all plain list items into headings.
19467 When converting a line into a heading, the number of stars is chosen
19468 such that the lines become children of the current entry. However,
19469 when a prefix argument is given, its value determines the number of
19470 stars to add."
19471 (interactive "P")
19472 (let ((skip-blanks
19473 (function
19474 ;; Return beginning of first non-blank line, starting from
19475 ;; line at POS.
19476 (lambda (pos)
19477 (save-excursion
19478 (goto-char pos)
19479 (while (org-at-comment-p) (forward-line))
19480 (skip-chars-forward " \r\t\n")
19481 (point-at-bol)))))
19482 beg end toggled)
19483 ;; Determine boundaries of changes. If a universal prefix has
19484 ;; been given, put the list in a region. If region ends at a bol,
19485 ;; do not consider the last line to be in the region.
19487 (when (and current-prefix-arg (org-at-item-p))
19488 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19489 (org-mark-element))
19491 (if (org-region-active-p)
19492 (setq beg (funcall skip-blanks (region-beginning))
19493 end (copy-marker (save-excursion
19494 (goto-char (region-end))
19495 (if (bolp) (point) (point-at-eol)))))
19496 (setq beg (funcall skip-blanks (point-at-bol))
19497 end (copy-marker (point-at-eol))))
19498 ;; Ensure inline tasks don't count as headings.
19499 (org-with-limited-levels
19500 (save-excursion
19501 (goto-char beg)
19502 (cond
19503 ;; Case 1. Started at an heading: de-star headings.
19504 ((org-at-heading-p)
19505 (while (< (point) end)
19506 (when (org-at-heading-p t)
19507 (looking-at org-outline-regexp) (replace-match "")
19508 (setq toggled t))
19509 (forward-line)))
19510 ;; Case 2. Started at an item: change items into headlines.
19511 ;; One star will be added by `org-list-to-subtree'.
19512 ((org-at-item-p)
19513 (let* ((stars (make-string
19514 (if nstars
19515 ;; subtract the star that will be added again by
19516 ;; `org-list-to-subtree'
19517 (1- (prefix-numeric-value current-prefix-arg))
19518 (or (org-current-level) 0))
19519 ?*))
19520 (add-stars
19521 (cond (nstars "") ; stars from prefix only
19522 ((equal stars "") "") ; before first heading
19523 (org-odd-levels-only "*") ; inside heading, odd
19524 (t "")))) ; inside heading, oddeven
19525 (while (< (point) end)
19526 (when (org-at-item-p)
19527 ;; Pay attention to cases when region ends before list.
19528 (let* ((struct (org-list-struct))
19529 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19530 (save-restriction
19531 (narrow-to-region (point) list-end)
19532 (insert
19533 (org-list-to-subtree
19534 (org-list-parse-list t)
19535 '(:istart (concat stars add-stars (funcall get-stars depth))
19536 :icount (concat stars add-stars (funcall get-stars depth)))))))
19537 (setq toggled t))
19538 (forward-line))))
19539 ;; Case 3. Started at normal text: make every line an heading,
19540 ;; skipping headlines and items.
19541 (t (let* ((stars (make-string
19542 (if nstars
19543 (prefix-numeric-value current-prefix-arg)
19544 (or (org-current-level) 0))
19545 ?*))
19546 (add-stars
19547 (cond (nstars "") ; stars from prefix only
19548 ((equal stars "") "*") ; before first heading
19549 (org-odd-levels-only "**") ; inside heading, odd
19550 (t "*"))) ; inside heading, oddeven
19551 (rpl (concat stars add-stars " ")))
19552 (while (< (point) end)
19553 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19554 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19555 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19556 (forward-line)))))))
19557 (unless toggled (message "Cannot toggle heading from here"))))
19559 (defun org-meta-return (&optional arg)
19560 "Insert a new heading or wrap a region in a table.
19561 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19562 See the individual commands for more information."
19563 (interactive "P")
19564 (cond
19565 ((run-hook-with-args-until-success 'org-metareturn-hook))
19566 ((or (org-at-drawer-p) (org-at-property-p))
19567 (newline-and-indent))
19568 ((org-at-table-p)
19569 (call-interactively 'org-table-wrap-region))
19570 (t (call-interactively 'org-insert-heading))))
19572 ;;; Menu entries
19574 (defsubst org-in-subtree-not-table-p ()
19575 "Are we in a subtree and not in a table?"
19576 (and (not (org-before-first-heading-p))
19577 (not (org-at-table-p))))
19579 ;; Define the Org-mode menus
19580 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19581 '("Tbl"
19582 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19583 ["Next Field" org-cycle (org-at-table-p)]
19584 ["Previous Field" org-shifttab (org-at-table-p)]
19585 ["Next Row" org-return (org-at-table-p)]
19586 "--"
19587 ["Blank Field" org-table-blank-field (org-at-table-p)]
19588 ["Edit Field" org-table-edit-field (org-at-table-p)]
19589 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19590 "--"
19591 ("Column"
19592 ["Move Column Left" org-metaleft (org-at-table-p)]
19593 ["Move Column Right" org-metaright (org-at-table-p)]
19594 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19595 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19596 ("Row"
19597 ["Move Row Up" org-metaup (org-at-table-p)]
19598 ["Move Row Down" org-metadown (org-at-table-p)]
19599 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19600 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19601 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19602 "--"
19603 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19604 ("Rectangle"
19605 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19606 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19607 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19608 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19609 "--"
19610 ("Calculate"
19611 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19612 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19613 ["Edit Formulas" org-edit-special (org-at-table-p)]
19614 "--"
19615 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19616 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19617 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19618 "--"
19619 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19620 "--"
19621 ["Sum Column/Rectangle" org-table-sum
19622 (or (org-at-table-p) (org-region-active-p))]
19623 ["Which Column?" org-table-current-column (org-at-table-p)])
19624 ["Debug Formulas"
19625 org-table-toggle-formula-debugger
19626 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19627 ["Show Col/Row Numbers"
19628 org-table-toggle-coordinate-overlays
19629 :style toggle
19630 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19631 "--"
19632 ["Create" org-table-create (and (not (org-at-table-p))
19633 org-enable-table-editor)]
19634 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19635 ["Import from File" org-table-import (not (org-at-table-p))]
19636 ["Export to File" org-table-export (org-at-table-p)]
19637 "--"
19638 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19640 (easy-menu-define org-org-menu org-mode-map "Org menu"
19641 '("Org"
19642 ("Show/Hide"
19643 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19644 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19645 ["Sparse Tree..." org-sparse-tree t]
19646 ["Reveal Context" org-reveal t]
19647 ["Show All" show-all t]
19648 "--"
19649 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19650 "--"
19651 ["New Heading" org-insert-heading t]
19652 ("Navigate Headings"
19653 ["Up" outline-up-heading t]
19654 ["Next" outline-next-visible-heading t]
19655 ["Previous" outline-previous-visible-heading t]
19656 ["Next Same Level" outline-forward-same-level t]
19657 ["Previous Same Level" outline-backward-same-level t]
19658 "--"
19659 ["Jump" org-goto t])
19660 ("Edit Structure"
19661 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19662 "--"
19663 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19664 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19665 "--"
19666 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19667 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19668 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19669 "--"
19670 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19671 "--"
19672 ["Copy visible text" org-copy-visible t]
19673 "--"
19674 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19675 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19676 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19677 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19678 "--"
19679 ["Sort Region/Children" org-sort t]
19680 "--"
19681 ["Convert to odd levels" org-convert-to-odd-levels t]
19682 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19683 ("Editing"
19684 ["Emphasis..." org-emphasize t]
19685 ["Edit Source Example" org-edit-special t]
19686 "--"
19687 ["Footnote new/jump" org-footnote-action t]
19688 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19689 ("Archive"
19690 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19691 "--"
19692 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19693 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19694 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19696 "--"
19697 ("Hyperlinks"
19698 ["Store Link (Global)" org-store-link t]
19699 ["Find existing link to here" org-occur-link-in-agenda-files t]
19700 ["Insert Link" org-insert-link t]
19701 ["Follow Link" org-open-at-point t]
19702 "--"
19703 ["Next link" org-next-link t]
19704 ["Previous link" org-previous-link t]
19705 "--"
19706 ["Descriptive Links"
19707 org-toggle-link-display
19708 :style radio
19709 :selected org-descriptive-links
19711 ["Literal Links"
19712 org-toggle-link-display
19713 :style radio
19714 :selected (not org-descriptive-links)])
19715 "--"
19716 ("TODO Lists"
19717 ["TODO/DONE/-" org-todo t]
19718 ("Select keyword"
19719 ["Next keyword" org-shiftright (org-at-heading-p)]
19720 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19721 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19722 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19723 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19724 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19725 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19726 "--"
19727 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19728 :selected org-enforce-todo-dependencies :style toggle :active t]
19729 "Settings for tree at point"
19730 ["Do Children sequentially" org-toggle-ordered-property :style radio
19731 :selected (org-entry-get nil "ORDERED")
19732 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19733 ["Do Children parallel" org-toggle-ordered-property :style radio
19734 :selected (not (org-entry-get nil "ORDERED"))
19735 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19736 "--"
19737 ["Set Priority" org-priority t]
19738 ["Priority Up" org-shiftup t]
19739 ["Priority Down" org-shiftdown t]
19740 "--"
19741 ["Get news from all feeds" org-feed-update-all t]
19742 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19743 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19744 ("TAGS and Properties"
19745 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19746 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19747 "--"
19748 ["Set property" org-set-property (not (org-before-first-heading-p))]
19749 ["Column view of properties" org-columns t]
19750 ["Insert Column View DBlock" org-insert-columns-dblock t])
19751 ("Dates and Scheduling"
19752 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19753 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19754 ("Change Date"
19755 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19756 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19757 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19758 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19759 ["Compute Time Range" org-evaluate-time-range t]
19760 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19761 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19762 "--"
19763 ["Custom time format" org-toggle-time-stamp-overlays
19764 :style radio :selected org-display-custom-times]
19765 "--"
19766 ["Goto Calendar" org-goto-calendar t]
19767 ["Date from Calendar" org-date-from-calendar t]
19768 "--"
19769 ["Start/Restart Timer" org-timer-start t]
19770 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19771 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19772 ["Insert Timer String" org-timer t]
19773 ["Insert Timer Item" org-timer-item t])
19774 ("Logging work"
19775 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19776 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19777 ["Clock out" org-clock-out t]
19778 ["Clock cancel" org-clock-cancel t]
19779 "--"
19780 ["Mark as default task" org-clock-mark-default-task t]
19781 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19782 ["Goto running clock" org-clock-goto t]
19783 "--"
19784 ["Display times" org-clock-display t]
19785 ["Create clock table" org-clock-report t]
19786 "--"
19787 ["Record DONE time"
19788 (progn (setq org-log-done (not org-log-done))
19789 (message "Switching to %s will %s record a timestamp"
19790 (car org-done-keywords)
19791 (if org-log-done "automatically" "not")))
19792 :style toggle :selected org-log-done])
19793 "--"
19794 ["Agenda Command..." org-agenda t]
19795 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19796 ("File List for Agenda")
19797 ("Special views current file"
19798 ["TODO Tree" org-show-todo-tree t]
19799 ["Check Deadlines" org-check-deadlines t]
19800 ["Timeline" org-timeline t]
19801 ["Tags/Property tree" org-match-sparse-tree t])
19802 "--"
19803 ["Export/Publish..." org-export t]
19804 ("LaTeX"
19805 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19806 :selected org-cdlatex-mode]
19807 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19808 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19809 ["Modify math symbol" org-cdlatex-math-modify
19810 (org-inside-LaTeX-fragment-p)]
19811 ["Insert citation" org-reftex-citation t]
19812 "--"
19813 ["Template for BEAMER" (progn (require 'org-beamer)
19814 (org-insert-beamer-options-template)) t])
19815 "--"
19816 ("MobileOrg"
19817 ["Push Files and Views" org-mobile-push t]
19818 ["Get Captured and Flagged" org-mobile-pull t]
19819 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19820 "--"
19821 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19822 "--"
19823 ("Documentation"
19824 ["Show Version" org-version t]
19825 ["Info Documentation" org-info t])
19826 ("Customize"
19827 ["Browse Org Group" org-customize t]
19828 "--"
19829 ["Expand This Menu" org-create-customize-menu
19830 (fboundp 'customize-menu-create)])
19831 ["Send bug report" org-submit-bug-report t]
19832 "--"
19833 ("Refresh/Reload"
19834 ["Refresh setup current buffer" org-mode-restart t]
19835 ["Reload Org (after update)" org-reload t]
19836 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19839 (defun org-info (&optional node)
19840 "Read documentation for Org-mode in the info system.
19841 With optional NODE, go directly to that node."
19842 (interactive)
19843 (info (format "(org)%s" (or node ""))))
19845 ;;;###autoload
19846 (defun org-submit-bug-report ()
19847 "Submit a bug report on Org-mode via mail.
19849 Don't hesitate to report any problems or inaccurate documentation.
19851 If you don't have setup sending mail from (X)Emacs, please copy the
19852 output buffer into your mail program, as it gives us important
19853 information about your Org-mode version and configuration."
19854 (interactive)
19855 (require 'reporter)
19856 (org-load-modules-maybe)
19857 (org-require-autoloaded-modules)
19858 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19859 (reporter-submit-bug-report
19860 "emacs-orgmode@gnu.org"
19861 (org-version nil 'full)
19862 (let (list)
19863 (save-window-excursion
19864 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19865 (delete-other-windows)
19866 (erase-buffer)
19867 (insert "You are about to submit a bug report to the Org-mode mailing list.
19869 We would like to add your full Org-mode and Outline configuration to the
19870 bug report. This greatly simplifies the work of the maintainer and
19871 other experts on the mailing list.
19873 HOWEVER, some variables you have customized may contain private
19874 information. The names of customers, colleagues, or friends, might
19875 appear in the form of file names, tags, todo states, or search strings.
19876 If you answer yes to the prompt, you might want to check and remove
19877 such private information before sending the email.")
19878 (add-text-properties (point-min) (point-max) '(face org-warning))
19879 (when (yes-or-no-p "Include your Org-mode configuration ")
19880 (mapatoms
19881 (lambda (v)
19882 (and (boundp v)
19883 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19884 (or (and (symbol-value v)
19885 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19886 (and
19887 (get v 'custom-type) (get v 'standard-value)
19888 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19889 (push v list)))))
19890 (kill-buffer (get-buffer "*Warn about privacy*"))
19891 list))
19892 nil nil
19893 "Remember to cover the basics, that is, what you expected to happen and
19894 what in fact did happen. You don't know how to make a good report? See
19896 http://orgmode.org/manual/Feedback.html#Feedback
19898 Your bug report will be posted to the Org-mode mailing list.
19899 ------------------------------------------------------------------------")
19900 (save-excursion
19901 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19902 (replace-match "\\1Bug: \\3 [\\2]")))))
19905 (defun org-install-agenda-files-menu ()
19906 (let ((bl (buffer-list)))
19907 (save-excursion
19908 (while bl
19909 (set-buffer (pop bl))
19910 (if (derived-mode-p 'org-mode) (setq bl nil)))
19911 (when (derived-mode-p 'org-mode)
19912 (easy-menu-change
19913 '("Org") "File List for Agenda"
19914 (append
19915 (list
19916 ["Edit File List" (org-edit-agenda-file-list) t]
19917 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19918 ["Remove Current File from List" org-remove-file t]
19919 ["Cycle through agenda files" org-cycle-agenda-files t]
19920 ["Occur in all agenda files" org-occur-in-agenda-files t]
19921 "--")
19922 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19924 ;;;; Documentation
19926 (defun org-require-autoloaded-modules ()
19927 (interactive)
19928 (mapc 'require
19929 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19930 org-docbook org-exp org-html org-icalendar
19931 org-id org-latex
19932 org-publish org-remember org-table
19933 org-timer org-xoxo)))
19935 ;;;###autoload
19936 (defun org-reload (&optional uncompiled)
19937 "Reload all org lisp files.
19938 With prefix arg UNCOMPILED, load the uncompiled versions."
19939 (interactive "P")
19940 (require 'find-func)
19941 (let* ((file-re "^org\\(-.*\\)?\\.el")
19942 (dir-org (file-name-directory (org-find-library-dir "org")))
19943 (dir-org-contrib (ignore-errors
19944 (file-name-directory
19945 (org-find-library-dir "org-contribdir"))))
19946 (babel-files
19947 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19948 (append (list nil "comint" "eval" "exp" "keys"
19949 "lob" "ref" "table" "tangle")
19950 (delq nil
19951 (mapcar
19952 (lambda (lang)
19953 (when (cdr lang) (symbol-name (car lang))))
19954 org-babel-load-languages)))))
19955 (files
19956 (append babel-files
19957 (and dir-org-contrib
19958 (directory-files dir-org-contrib t file-re))
19959 (directory-files dir-org t file-re)))
19960 (remove-re (concat (if (featurep 'xemacs)
19961 "org-colview" "org-colview-xemacs")
19962 "\\'")))
19963 (setq files (mapcar 'file-name-sans-extension files))
19964 (setq files (mapcar
19965 (lambda (x) (if (string-match remove-re x) nil x))
19966 files))
19967 (setq files (delq nil files))
19968 (mapc
19969 (lambda (f)
19970 (when (featurep (intern (file-name-nondirectory f)))
19971 (if (and (not uncompiled)
19972 (file-exists-p (concat f ".elc")))
19973 (load (concat f ".elc") nil nil 'nosuffix)
19974 (load (concat f ".el") nil nil 'nosuffix))))
19975 files)
19976 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19977 (org-version nil 'full 'message))
19979 ;;;###autoload
19980 (defun org-customize ()
19981 "Call the customize function with org as argument."
19982 (interactive)
19983 (org-load-modules-maybe)
19984 (org-require-autoloaded-modules)
19985 (customize-browse 'org))
19987 (defun org-create-customize-menu ()
19988 "Create a full customization menu for Org-mode, insert it into the menu."
19989 (interactive)
19990 (org-load-modules-maybe)
19991 (org-require-autoloaded-modules)
19992 (if (fboundp 'customize-menu-create)
19993 (progn
19994 (easy-menu-change
19995 '("Org") "Customize"
19996 `(["Browse Org group" org-customize t]
19997 "--"
19998 ,(customize-menu-create 'org)
19999 ["Set" Custom-set t]
20000 ["Save" Custom-save t]
20001 ["Reset to Current" Custom-reset-current t]
20002 ["Reset to Saved" Custom-reset-saved t]
20003 ["Reset to Standard Settings" Custom-reset-standard t]))
20004 (message "\"Org\"-menu now contains full customization menu"))
20005 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20007 ;;;; Miscellaneous stuff
20009 ;;; Generally useful functions
20011 (defun org-get-at-bol (property)
20012 "Get text property PROPERTY at beginning of line."
20013 (get-text-property (point-at-bol) property))
20015 (defun org-find-text-property-in-string (prop s)
20016 "Return the first non-nil value of property PROP in string S."
20017 (or (get-text-property 0 prop s)
20018 (get-text-property (or (next-single-property-change 0 prop s) 0)
20019 prop s)))
20021 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20022 "Display the given MESSAGE as a warning."
20023 (if (fboundp 'display-warning)
20024 (display-warning 'org message
20025 (if (featurep 'xemacs) 'warning :warning))
20026 (let ((buf (get-buffer-create "*Org warnings*")))
20027 (with-current-buffer buf
20028 (goto-char (point-max))
20029 (insert "Warning (Org): " message)
20030 (unless (bolp)
20031 (newline)))
20032 (display-buffer buf)
20033 (sit-for 0))))
20035 (defun org-eval (form)
20036 "Eval FORM and return result."
20037 (condition-case error
20038 (eval form)
20039 (error (format "%%![Error: %s]" error))))
20041 (defun org-in-clocktable-p ()
20042 "Check if the cursor is in a clocktable."
20043 (let ((pos (point)) start)
20044 (save-excursion
20045 (end-of-line 1)
20046 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20047 (setq start (match-beginning 0))
20048 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20049 (>= (match-end 0) pos)
20050 start))))
20052 (defun org-in-commented-line ()
20053 "Is point in a line starting with `#'?"
20054 (equal (char-after (point-at-bol)) ?#))
20056 (defun org-in-indented-comment-line ()
20057 "Is point in a line starting with `#' after some white space?"
20058 (save-excursion
20059 (save-match-data
20060 (goto-char (point-at-bol))
20061 (looking-at "[ \t]*#"))))
20063 (defun org-in-verbatim-emphasis ()
20064 (save-match-data
20065 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20067 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20068 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20069 (if (and marker (marker-buffer marker)
20070 (buffer-live-p (marker-buffer marker)))
20071 (progn
20072 (org-pop-to-buffer-same-window (marker-buffer marker))
20073 (if (or (> marker (point-max)) (< marker (point-min)))
20074 (widen))
20075 (goto-char marker)
20076 (org-show-context 'org-goto))
20077 (if bookmark
20078 (bookmark-jump bookmark)
20079 (error "Cannot find location"))))
20081 (defun org-quote-csv-field (s)
20082 "Quote field for inclusion in CSV material."
20083 (if (string-match "[\",]" s)
20084 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20087 (defun org-force-self-insert (N)
20088 "Needed to enforce self-insert under remapping."
20089 (interactive "p")
20090 (self-insert-command N))
20092 (defun org-string-width (s)
20093 "Compute width of string, ignoring invisible characters.
20094 This ignores character with invisibility property `org-link', and also
20095 characters with property `org-cwidth', because these will become invisible
20096 upon the next fontification round."
20097 (let (b l)
20098 (when (or (eq t buffer-invisibility-spec)
20099 (assq 'org-link buffer-invisibility-spec))
20100 (while (setq b (text-property-any 0 (length s)
20101 'invisible 'org-link s))
20102 (setq s (concat (substring s 0 b)
20103 (substring s (or (next-single-property-change
20104 b 'invisible s) (length s)))))))
20105 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20106 (setq s (concat (substring s 0 b)
20107 (substring s (or (next-single-property-change
20108 b 'org-cwidth s) (length s))))))
20109 (setq l (string-width s) b -1)
20110 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20111 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20114 (defun org-shorten-string (s maxlength)
20115 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20116 If the string is shorter or has length MAXLENGTH, just return the
20117 original string. If it is longer, the functions finds a space in the
20118 string, breaks this string off at that locations and adds three dots
20119 as ellipsis. Including the ellipsis, the string will not be longer
20120 than MAXLENGTH. If finding a good breaking point in the string does
20121 not work, the string is just chopped off in the middle of a word
20122 if necessary."
20123 (if (<= (length s) maxlength)
20125 (let* ((n (max (- maxlength 4) 1))
20126 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20127 (if (string-match re s)
20128 (concat (match-string 1 s) "...")
20129 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20131 (defun org-get-indentation (&optional line)
20132 "Get the indentation of the current line, interpreting tabs.
20133 When LINE is given, assume it represents a line and compute its indentation."
20134 (if line
20135 (if (string-match "^ *" (org-remove-tabs line))
20136 (match-end 0))
20137 (save-excursion
20138 (beginning-of-line 1)
20139 (skip-chars-forward " \t")
20140 (current-column))))
20142 (defun org-get-string-indentation (s)
20143 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20144 (let ((n -1) (i 0) (w tab-width) c)
20145 (catch 'exit
20146 (while (< (setq n (1+ n)) (length s))
20147 (setq c (aref s n))
20148 (cond ((= c ?\ ) (setq i (1+ i)))
20149 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20150 (t (throw 'exit t)))))
20153 (defun org-remove-tabs (s &optional width)
20154 "Replace tabulators in S with spaces.
20155 Assumes that s is a single line, starting in column 0."
20156 (setq width (or width tab-width))
20157 (while (string-match "\t" s)
20158 (setq s (replace-match
20159 (make-string
20160 (- (* width (/ (+ (match-beginning 0) width) width))
20161 (match-beginning 0)) ?\ )
20162 t t s)))
20165 (defun org-fix-indentation (line ind)
20166 "Fix indentation in LINE.
20167 IND is a cons cell with target and minimum indentation.
20168 If the current indentation in LINE is smaller than the minimum,
20169 leave it alone. If it is larger than ind, set it to the target."
20170 (let* ((l (org-remove-tabs line))
20171 (i (org-get-indentation l))
20172 (i1 (car ind)) (i2 (cdr ind)))
20173 (if (>= i i2) (setq l (substring line i2)))
20174 (if (> i1 0)
20175 (concat (make-string i1 ?\ ) l)
20176 l)))
20178 (defun org-remove-indentation (code &optional n)
20179 "Remove the maximum common indentation from the lines in CODE.
20180 N may optionally be the number of spaces to remove."
20181 (with-temp-buffer
20182 (insert code)
20183 (org-do-remove-indentation n)
20184 (buffer-string)))
20186 (defun org-do-remove-indentation (&optional n)
20187 "Remove the maximum common indentation from the buffer."
20188 (untabify (point-min) (point-max))
20189 (let ((min 10000) re)
20190 (if n
20191 (setq min n)
20192 (goto-char (point-min))
20193 (while (re-search-forward "^ *[^ \n]" nil t)
20194 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20195 (unless (or (= min 0) (= min 10000))
20196 (setq re (format "^ \\{%d\\}" min))
20197 (goto-char (point-min))
20198 (while (re-search-forward re nil t)
20199 (replace-match "")
20200 (end-of-line 1))
20201 min)))
20203 (defun org-fill-template (template alist)
20204 "Find each %key of ALIST in TEMPLATE and replace it."
20205 (let ((case-fold-search nil)
20206 entry key value)
20207 (setq alist (sort (copy-sequence alist)
20208 (lambda (a b) (< (length (car a)) (length (car b))))))
20209 (while (setq entry (pop alist))
20210 (setq template
20211 (replace-regexp-in-string
20212 (concat "%" (regexp-quote (car entry)))
20213 (or (cdr entry) "") template t t)))
20214 template))
20216 (defun org-base-buffer (buffer)
20217 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20218 (if (not buffer)
20219 buffer
20220 (or (buffer-base-buffer buffer)
20221 buffer)))
20223 (defun org-trim (s)
20224 "Remove whitespace at beginning and end of string."
20225 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20226 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20229 (defun org-wrap (string &optional width lines)
20230 "Wrap string to either a number of lines, or a width in characters.
20231 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20232 that costs. If there is a word longer than WIDTH, the text is actually
20233 wrapped to the length of that word.
20234 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20235 many lines, whatever width that takes.
20236 The return value is a list of lines, without newlines at the end."
20237 (let* ((words (org-split-string string "[ \t\n]+"))
20238 (maxword (apply 'max (mapcar 'org-string-width words)))
20239 w ll)
20240 (cond (width
20241 (org-do-wrap words (max maxword width)))
20242 (lines
20243 (setq w maxword)
20244 (setq ll (org-do-wrap words maxword))
20245 (if (<= (length ll) lines)
20247 (setq ll words)
20248 (while (> (length ll) lines)
20249 (setq w (1+ w))
20250 (setq ll (org-do-wrap words w)))
20251 ll))
20252 (t (error "Cannot wrap this")))))
20254 (defun org-do-wrap (words width)
20255 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20256 (let (lines line)
20257 (while words
20258 (setq line (pop words))
20259 (while (and words (< (+ (length line) (length (car words))) width))
20260 (setq line (concat line " " (pop words))))
20261 (setq lines (push line lines)))
20262 (nreverse lines)))
20264 (defun org-split-string (string &optional separators)
20265 "Splits STRING into substrings at SEPARATORS.
20266 No empty strings are returned if there are matches at the beginning
20267 and end of string."
20268 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20269 (start 0)
20270 notfirst
20271 (list nil))
20272 (while (and (string-match rexp string
20273 (if (and notfirst
20274 (= start (match-beginning 0))
20275 (< start (length string)))
20276 (1+ start) start))
20277 (< (match-beginning 0) (length string)))
20278 (setq notfirst t)
20279 (or (eq (match-beginning 0) 0)
20280 (and (eq (match-beginning 0) (match-end 0))
20281 (eq (match-beginning 0) start))
20282 (setq list
20283 (cons (substring string start (match-beginning 0))
20284 list)))
20285 (setq start (match-end 0)))
20286 (or (eq start (length string))
20287 (setq list
20288 (cons (substring string start)
20289 list)))
20290 (nreverse list)))
20292 (defun org-quote-vert (s)
20293 "Replace \"|\" with \"\\vert\"."
20294 (while (string-match "|" s)
20295 (setq s (replace-match "\\vert" t t s)))
20298 (defun org-uuidgen-p (s)
20299 "Is S an ID created by UUIDGEN?"
20300 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20302 (defun org-in-src-block-p (&optional inside)
20303 "Whether point is in a code source block.
20304 When INSIDE is non-nil, don't consider we are within a src block
20305 when point is at #+BEGIN_SRC or #+END_SRC."
20306 (let ((case-fold-search t) ov)
20307 (or (and (setq ov (overlays-at (point)))
20308 (memq 'org-block-background
20309 (overlay-properties (car ov))))
20310 (and (not inside)
20311 (save-match-data
20312 (save-excursion
20313 (beginning-of-line)
20314 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20316 (defun org-context ()
20317 "Return a list of contexts of the current cursor position.
20318 If several contexts apply, all are returned.
20319 Each context entry is a list with a symbol naming the context, and
20320 two positions indicating start and end of the context. Possible
20321 contexts are:
20323 :headline anywhere in a headline
20324 :headline-stars on the leading stars in a headline
20325 :todo-keyword on a TODO keyword (including DONE) in a headline
20326 :tags on the TAGS in a headline
20327 :priority on the priority cookie in a headline
20328 :item on the first line of a plain list item
20329 :item-bullet on the bullet/number of a plain list item
20330 :checkbox on the checkbox in a plain list item
20331 :table in an org-mode table
20332 :table-special on a special filed in a table
20333 :table-table in a table.el table
20334 :clocktable in a clocktable
20335 :src-block in a source block
20336 :link on a hyperlink
20337 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20338 :target on a <<target>>
20339 :radio-target on a <<<radio-target>>>
20340 :latex-fragment on a LaTeX fragment
20341 :latex-preview on a LaTeX fragment with overlaid preview image
20343 This function expects the position to be visible because it uses font-lock
20344 faces as a help to recognize the following contexts: :table-special, :link,
20345 and :keyword."
20346 (let* ((f (get-text-property (point) 'face))
20347 (faces (if (listp f) f (list f)))
20348 (case-fold-search t)
20349 (p (point)) clist o)
20350 ;; First the large context
20351 (cond
20352 ((org-at-heading-p t)
20353 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20354 (when (progn
20355 (beginning-of-line 1)
20356 (looking-at org-todo-line-tags-regexp))
20357 (push (org-point-in-group p 1 :headline-stars) clist)
20358 (push (org-point-in-group p 2 :todo-keyword) clist)
20359 (push (org-point-in-group p 4 :tags) clist))
20360 (goto-char p)
20361 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20362 (if (looking-at "\\[#[A-Z0-9]\\]")
20363 (push (org-point-in-group p 0 :priority) clist)))
20365 ((org-at-item-p)
20366 (push (org-point-in-group p 2 :item-bullet) clist)
20367 (push (list :item (point-at-bol)
20368 (save-excursion (org-end-of-item) (point)))
20369 clist)
20370 (and (org-at-item-checkbox-p)
20371 (push (org-point-in-group p 0 :checkbox) clist)))
20373 ((org-at-table-p)
20374 (push (list :table (org-table-begin) (org-table-end)) clist)
20375 (if (memq 'org-formula faces)
20376 (push (list :table-special
20377 (previous-single-property-change p 'face)
20378 (next-single-property-change p 'face)) clist)))
20379 ((org-at-table-p 'any)
20380 (push (list :table-table) clist)))
20381 (goto-char p)
20383 (let ((case-fold-search t))
20384 ;; New the "medium" contexts: clocktables, source blocks
20385 (cond ((org-in-clocktable-p)
20386 (push (list :clocktable
20387 (and (or (looking-at "#\\+BEGIN: clocktable")
20388 (search-backward "#+BEGIN: clocktable" nil t))
20389 (match-beginning 0))
20390 (and (re-search-forward "#\\+END:?" nil t)
20391 (match-end 0))) clist))
20392 ((org-in-src-block-p)
20393 (push (list :src-block
20394 (and (or (looking-at "#\\+BEGIN_SRC")
20395 (search-backward "#+BEGIN_SRC" nil t))
20396 (match-beginning 0))
20397 (and (search-forward "#+END_SRC" nil t)
20398 (match-beginning 0))) clist))))
20399 (goto-char p)
20401 ;; Now the small context
20402 (cond
20403 ((org-at-timestamp-p)
20404 (push (org-point-in-group p 0 :timestamp) clist))
20405 ((memq 'org-link faces)
20406 (push (list :link
20407 (previous-single-property-change p 'face)
20408 (next-single-property-change p 'face)) clist))
20409 ((memq 'org-special-keyword faces)
20410 (push (list :keyword
20411 (previous-single-property-change p 'face)
20412 (next-single-property-change p 'face)) clist))
20413 ((org-at-target-p)
20414 (push (org-point-in-group p 0 :target) clist)
20415 (goto-char (1- (match-beginning 0)))
20416 (if (looking-at org-radio-target-regexp)
20417 (push (org-point-in-group p 0 :radio-target) clist))
20418 (goto-char p))
20419 ((setq o (car (delq nil
20420 (mapcar
20421 (lambda (x)
20422 (if (memq x org-latex-fragment-image-overlays) x))
20423 (overlays-at (point))))))
20424 (push (list :latex-fragment
20425 (overlay-start o) (overlay-end o)) clist)
20426 (push (list :latex-preview
20427 (overlay-start o) (overlay-end o)) clist))
20428 ((org-inside-LaTeX-fragment-p)
20429 ;; FIXME: positions wrong.
20430 (push (list :latex-fragment (point) (point)) clist)))
20432 (setq clist (nreverse (delq nil clist)))
20433 clist))
20435 ;; FIXME: Compare with at-regexp-p Do we need both?
20436 (defun org-in-regexp (re &optional nlines visually)
20437 "Check if point is inside a match of regexp.
20438 Normally only the current line is checked, but you can include NLINES extra
20439 lines both before and after point into the search.
20440 If VISUALLY is set, require that the cursor is not after the match but
20441 really on, so that the block visually is on the match."
20442 (catch 'exit
20443 (let ((pos (point))
20444 (eol (point-at-eol (+ 1 (or nlines 0))))
20445 (inc (if visually 1 0)))
20446 (save-excursion
20447 (beginning-of-line (- 1 (or nlines 0)))
20448 (while (re-search-forward re eol t)
20449 (if (and (<= (match-beginning 0) pos)
20450 (>= (+ inc (match-end 0)) pos))
20451 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20453 (defun org-at-regexp-p (regexp)
20454 "Is point inside a match of REGEXP in the current line?"
20455 (catch 'exit
20456 (save-excursion
20457 (let ((pos (point)) (end (point-at-eol)))
20458 (beginning-of-line 1)
20459 (while (re-search-forward regexp end t)
20460 (if (and (<= (match-beginning 0) pos)
20461 (>= (match-end 0) pos))
20462 (throw 'exit t)))
20463 nil))))
20465 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20466 "Non-nil when point is between matches of START-RE and END-RE.
20468 Also return a non-nil value when point is on one of the matches.
20470 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20471 buffer positions. Default values are the positions of headlines
20472 surrounding the point.
20474 The functions returns a cons cell whose car (resp. cdr) is the
20475 position before START-RE (resp. after END-RE)."
20476 (save-match-data
20477 (let ((pos (point))
20478 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20479 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20480 beg end)
20481 (save-excursion
20482 ;; Point is on a block when on START-RE or if START-RE can be
20483 ;; found before it...
20484 (and (or (org-at-regexp-p start-re)
20485 (re-search-backward start-re limit-up t))
20486 (setq beg (match-beginning 0))
20487 ;; ... and END-RE after it...
20488 (goto-char (match-end 0))
20489 (re-search-forward end-re limit-down t)
20490 (> (setq end (match-end 0)) pos)
20491 ;; ... without another START-RE in-between.
20492 (goto-char (match-beginning 0))
20493 (not (re-search-backward start-re (1+ beg) t))
20494 ;; Return value.
20495 (cons beg end))))))
20497 (defun org-in-block-p (names)
20498 "Non-nil when point belongs to a block whose name belongs to NAMES.
20500 NAMES is a list of strings containing names of blocks.
20502 Return first block name matched, or nil. Beware that in case of
20503 nested blocks, the returned name may not belong to the closest
20504 block from point."
20505 (save-match-data
20506 (catch 'exit
20507 (let ((case-fold-search t)
20508 (lim-up (save-excursion (outline-previous-heading)))
20509 (lim-down (save-excursion (outline-next-heading))))
20510 (mapc (lambda (name)
20511 (let ((n (regexp-quote name)))
20512 (when (org-between-regexps-p
20513 (concat "^[ \t]*#\\+begin_" n)
20514 (concat "^[ \t]*#\\+end_" n)
20515 lim-up lim-down)
20516 (throw 'exit n))))
20517 names))
20518 nil)))
20520 (defun org-occur-in-agenda-files (regexp &optional nlines)
20521 "Call `multi-occur' with buffers for all agenda files."
20522 (interactive "sOrg-files matching: \np")
20523 (let* ((files (org-agenda-files))
20524 (tnames (mapcar 'file-truename files))
20525 (extra org-agenda-text-search-extra-files)
20527 (when (eq (car extra) 'agenda-archives)
20528 (setq extra (cdr extra))
20529 (setq files (org-add-archive-files files)))
20530 (while (setq f (pop extra))
20531 (unless (member (file-truename f) tnames)
20532 (add-to-list 'files f 'append)
20533 (add-to-list 'tnames (file-truename f) 'append)))
20534 (multi-occur
20535 (mapcar (lambda (x)
20536 (with-current-buffer
20537 (or (get-file-buffer x) (find-file-noselect x))
20538 (widen)
20539 (current-buffer)))
20540 files)
20541 regexp)))
20543 (if (boundp 'occur-mode-find-occurrence-hook)
20544 ;; Emacs 23
20545 (add-hook 'occur-mode-find-occurrence-hook
20546 (lambda ()
20547 (when (derived-mode-p 'org-mode)
20548 (org-reveal))))
20549 ;; Emacs 22
20550 (defadvice occur-mode-goto-occurrence
20551 (after org-occur-reveal activate)
20552 (and (derived-mode-p 'org-mode) (org-reveal)))
20553 (defadvice occur-mode-goto-occurrence-other-window
20554 (after org-occur-reveal activate)
20555 (and (derived-mode-p 'org-mode) (org-reveal)))
20556 (defadvice occur-mode-display-occurrence
20557 (after org-occur-reveal activate)
20558 (when (derived-mode-p 'org-mode)
20559 (let ((pos (occur-mode-find-occurrence)))
20560 (with-current-buffer (marker-buffer pos)
20561 (save-excursion
20562 (goto-char pos)
20563 (org-reveal)))))))
20565 (defun org-occur-link-in-agenda-files ()
20566 "Create a link and search for it in the agendas.
20567 The link is not stored in `org-stored-links', it is just created
20568 for the search purpose."
20569 (interactive)
20570 (let ((link (condition-case nil
20571 (org-store-link nil)
20572 (error "Unable to create a link to here"))))
20573 (org-occur-in-agenda-files (regexp-quote link))))
20575 (defun org-uniquify (list)
20576 "Remove duplicate elements from LIST."
20577 (let (res)
20578 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20579 res))
20581 (defun org-delete-all (elts list)
20582 "Remove all elements in ELTS from LIST."
20583 (while elts
20584 (setq list (delete (pop elts) list)))
20585 list)
20587 (defun org-count (cl-item cl-seq)
20588 "Count the number of occurrences of ITEM in SEQ.
20589 Taken from `count' in cl-seq.el with all keyword arguments removed."
20590 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20591 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20592 (while (< cl-start cl-end)
20593 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20594 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20595 (setq cl-start (1+ cl-start)))
20596 cl-count))
20598 (defun org-remove-if (predicate seq)
20599 "Remove everything from SEQ that fulfills PREDICATE."
20600 (let (res e)
20601 (while seq
20602 (setq e (pop seq))
20603 (if (not (funcall predicate e)) (push e res)))
20604 (nreverse res)))
20606 (defun org-remove-if-not (predicate seq)
20607 "Remove everything from SEQ that does not fulfill PREDICATE."
20608 (let (res e)
20609 (while seq
20610 (setq e (pop seq))
20611 (if (funcall predicate e) (push e res)))
20612 (nreverse res)))
20614 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20615 "Reduce two-argument FUNCTION across SEQ.
20616 Taken from `reduce' in cl-seq.el with all keyword arguments but
20617 \":initial-value\" removed."
20618 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20619 (cadr (memq :initial-value cl-keys)))
20620 (cl-seq (pop cl-seq))
20621 (t (funcall cl-func)))))
20622 (while cl-seq
20623 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20624 cl-accum))
20626 (defun org-back-over-empty-lines ()
20627 "Move backwards over whitespace, to the beginning of the first empty line.
20628 Returns the number of empty lines passed."
20629 (let ((pos (point)))
20630 (if (cdr (assoc 'heading org-blank-before-new-entry))
20631 (skip-chars-backward " \t\n\r")
20632 (unless (eobp)
20633 (forward-line -1)))
20634 (beginning-of-line 2)
20635 (goto-char (min (point) pos))
20636 (count-lines (point) pos)))
20638 (defun org-skip-whitespace ()
20639 (skip-chars-forward " \t\n\r"))
20641 (defun org-point-in-group (point group &optional context)
20642 "Check if POINT is in match-group GROUP.
20643 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20644 match. If the match group does not exist or point is not inside it,
20645 return nil."
20646 (and (match-beginning group)
20647 (>= point (match-beginning group))
20648 (<= point (match-end group))
20649 (if context
20650 (list context (match-beginning group) (match-end group))
20651 t)))
20653 (defun org-switch-to-buffer-other-window (&rest args)
20654 "Switch to buffer in a second window on the current frame.
20655 In particular, do not allow pop-up frames.
20656 Returns the newly created buffer."
20657 (org-no-popups
20658 (apply 'switch-to-buffer-other-window args)))
20660 (defun org-combine-plists (&rest plists)
20661 "Create a single property list from all plists in PLISTS.
20662 The process starts by copying the first list, and then setting properties
20663 from the other lists. Settings in the last list are the most significant
20664 ones and overrule settings in the other lists."
20665 (let ((rtn (copy-sequence (pop plists)))
20666 p v ls)
20667 (while plists
20668 (setq ls (pop plists))
20669 (while ls
20670 (setq p (pop ls) v (pop ls))
20671 (setq rtn (plist-put rtn p v))))
20672 rtn))
20674 (defun org-replace-escapes (string table)
20675 "Replace %-escapes in STRING with values in TABLE.
20676 TABLE is an association list with keys like \"%a\" and string values.
20677 The sequences in STRING may contain normal field width and padding information,
20678 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20679 so values can contain further %-escapes if they are define later in TABLE."
20680 (let ((tbl (copy-alist table))
20681 (case-fold-search nil)
20682 (pchg 0)
20683 e re rpl)
20684 (while (setq e (pop tbl))
20685 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20686 (when (and (cdr e) (string-match re (cdr e)))
20687 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20688 (safe "SREF"))
20689 (add-text-properties 0 3 (list 'sref sref) safe)
20690 (setcdr e (replace-match safe t t (cdr e)))))
20691 (while (string-match re string)
20692 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20693 (cdr e)))
20694 (setq string (replace-match rpl t t string))))
20695 (while (setq pchg (next-property-change pchg string))
20696 (let ((sref (get-text-property pchg 'sref string)))
20697 (when (and sref (string-match "SREF" string pchg))
20698 (setq string (replace-match sref t t string)))))
20699 string))
20701 (defun org-sublist (list start end)
20702 "Return a section of LIST, from START to END.
20703 Counting starts at 1."
20704 (let (rtn (c start))
20705 (setq list (nthcdr (1- start) list))
20706 (while (and list (<= c end))
20707 (push (pop list) rtn)
20708 (setq c (1+ c)))
20709 (nreverse rtn)))
20711 (defun org-find-base-buffer-visiting (file)
20712 "Like `find-buffer-visiting' but always return the base buffer and
20713 not an indirect buffer."
20714 (let ((buf (or (get-file-buffer file)
20715 (find-buffer-visiting file))))
20716 (if buf
20717 (or (buffer-base-buffer buf) buf)
20718 nil)))
20720 (defun org-image-file-name-regexp (&optional extensions)
20721 "Return regexp matching the file names of images.
20722 If EXTENSIONS is given, only match these."
20723 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20724 (image-file-name-regexp)
20725 (let ((image-file-name-extensions
20726 (or extensions
20727 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20728 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20729 (concat "\\."
20730 (regexp-opt (nconc (mapcar 'upcase
20731 image-file-name-extensions)
20732 image-file-name-extensions)
20734 "\\'"))))
20736 (defun org-file-image-p (file &optional extensions)
20737 "Return non-nil if FILE is an image."
20738 (save-match-data
20739 (string-match (org-image-file-name-regexp extensions) file)))
20741 (defun org-get-cursor-date ()
20742 "Return the date at cursor in as a time.
20743 This works in the calendar and in the agenda, anywhere else it just
20744 returns the current time."
20745 (let (date day defd)
20746 (cond
20747 ((eq major-mode 'calendar-mode)
20748 (setq date (calendar-cursor-to-date)
20749 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20750 ((eq major-mode 'org-agenda-mode)
20751 (setq day (get-text-property (point) 'day))
20752 (if day
20753 (setq date (calendar-gregorian-from-absolute day)
20754 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20755 (nth 2 date))))))
20756 (or defd (current-time))))
20758 (defun org-mark-subtree (&optional up)
20759 "Mark the current subtree.
20760 This puts point at the start of the current subtree, and mark at
20761 the end. If a numeric prefix UP is given, move up into the
20762 hierarchy of headlines by UP levels before marking the subtree."
20763 (interactive "P")
20764 (org-with-limited-levels
20765 (cond ((org-at-heading-p) (beginning-of-line))
20766 ((org-before-first-heading-p) (error "Not in a subtree"))
20767 (t (outline-previous-visible-heading 1))))
20768 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20769 (if (org-called-interactively-p 'any)
20770 (call-interactively 'org-mark-element)
20771 (org-mark-element)))
20773 ;;; Indentation
20775 (defun org-indent-line ()
20776 "Indent line depending on context."
20777 (interactive)
20778 (let* ((pos (point))
20779 (itemp (org-at-item-p))
20780 (case-fold-search t)
20781 (org-drawer-regexp (or org-drawer-regexp "\000"))
20782 (inline-task-p (and (featurep 'org-inlinetask)
20783 (org-inlinetask-in-task-p)))
20784 (inline-re (and inline-task-p
20785 (org-inlinetask-outline-regexp)))
20786 column)
20787 (if (and orgstruct-is-++ (eq pos (point)))
20788 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20789 (indent-according-to-mode))
20790 (beginning-of-line 1)
20791 (cond
20792 ;; Headings
20793 ((looking-at org-outline-regexp) (setq column 0))
20794 ;; Included files
20795 ((looking-at "#\\+include:") (setq column 0))
20796 ;; Footnote definition
20797 ((looking-at org-footnote-definition-re) (setq column 0))
20798 ;; Literal examples
20799 ((looking-at "[ \t]*:\\( \\|$\\)")
20800 (setq column (org-get-indentation))) ; do nothing
20801 ;; Lists
20802 ((ignore-errors (goto-char (org-in-item-p)))
20803 (setq column (if itemp
20804 (org-get-indentation)
20805 (org-list-item-body-column (point))))
20806 (goto-char pos))
20807 ;; Drawers
20808 ((and (looking-at "[ \t]*:END:")
20809 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20810 (save-excursion
20811 (goto-char (1- (match-beginning 1)))
20812 (setq column (current-column))))
20813 ;; Special blocks
20814 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20815 (save-excursion
20816 (re-search-backward
20817 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20818 (setq column (org-get-indentation (match-string 0))))
20819 ((and (not (looking-at "[ \t]*#\\+begin_"))
20820 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20821 (save-excursion
20822 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20823 (setq column
20824 (cond ((equal (downcase (match-string 1)) "src")
20825 ;; src blocks: let `org-edit-src-exit' handle them
20826 (org-get-indentation))
20827 ((equal (downcase (match-string 1)) "example")
20828 (max (org-get-indentation)
20829 (org-get-indentation (match-string 0))))
20831 (org-get-indentation (match-string 0))))))
20832 ;; This line has nothing special, look at the previous relevant
20833 ;; line to compute indentation
20835 (beginning-of-line 0)
20836 (while (and (not (bobp))
20837 (not (looking-at org-table-line-regexp))
20838 (not (looking-at org-drawer-regexp))
20839 ;; When point started in an inline task, do not move
20840 ;; above task starting line.
20841 (not (and inline-task-p (looking-at inline-re)))
20842 ;; Skip drawers, blocks, empty lines, verbatim,
20843 ;; comments, tables, footnotes definitions, lists,
20844 ;; inline tasks.
20845 (or (and (looking-at "[ \t]*:END:")
20846 (re-search-backward org-drawer-regexp nil t))
20847 (and (looking-at "[ \t]*#\\+end_")
20848 (re-search-backward "[ \t]*#\\+begin_"nil t))
20849 (looking-at "[ \t]*[\n:#|]")
20850 (looking-at org-footnote-definition-re)
20851 (and (ignore-errors (goto-char (org-in-item-p)))
20852 (goto-char
20853 (org-list-get-top-point (org-list-struct))))
20854 (and (not inline-task-p)
20855 (featurep 'org-inlinetask)
20856 (org-inlinetask-in-task-p)
20857 (or (org-inlinetask-goto-beginning) t))))
20858 (beginning-of-line 0))
20859 (cond
20860 ;; There was an heading above.
20861 ((looking-at "\\*+[ \t]+")
20862 (if (not org-adapt-indentation)
20863 (setq column 0)
20864 (goto-char (match-end 0))
20865 (setq column (current-column))))
20866 ;; A drawer had started and is unfinished
20867 ((looking-at org-drawer-regexp)
20868 (goto-char (1- (match-beginning 1)))
20869 (setq column (current-column)))
20870 ;; Else, nothing noticeable found: get indentation and go on.
20871 (t (setq column (org-get-indentation))))))
20872 ;; Now apply indentation and move cursor accordingly
20873 (goto-char pos)
20874 (if (<= (current-column) (current-indentation))
20875 (org-indent-line-to column)
20876 (save-excursion (org-indent-line-to column)))
20877 ;; Special polishing for properties, see `org-property-format'
20878 (setq column (current-column))
20879 (beginning-of-line 1)
20880 (if (looking-at
20881 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20882 (replace-match (concat (match-string 1)
20883 (format org-property-format
20884 (match-string 2) (match-string 3)))
20885 t t))
20886 (org-move-to-column column))))
20888 (defun org-indent-drawer ()
20889 "Indent the drawer at point."
20890 (interactive)
20891 (let ((p (point))
20892 (e (and (save-excursion (re-search-forward ":END:" nil t))
20893 (match-end 0)))
20894 (folded
20895 (save-excursion
20896 (end-of-line)
20897 (when (overlays-at (point))
20898 (member 'invisible (overlay-properties
20899 (car (overlays-at (point)))))))))
20900 (when folded (org-cycle))
20901 (indent-for-tab-command)
20902 (while (and (move-beginning-of-line 2) (< (point) e))
20903 (indent-for-tab-command))
20904 (goto-char p)
20905 (when folded (org-cycle)))
20906 (message "Drawer at point indented"))
20908 (defun org-indent-block ()
20909 "Indent the block at point."
20910 (interactive)
20911 (let ((p (point))
20912 (case-fold-search t)
20913 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20914 (match-end 0)))
20915 (folded
20916 (save-excursion
20917 (end-of-line)
20918 (when (overlays-at (point))
20919 (member 'invisible (overlay-properties
20920 (car (overlays-at (point)))))))))
20921 (when folded (org-cycle))
20922 (indent-for-tab-command)
20923 (while (and (move-beginning-of-line 2) (< (point) e))
20924 (indent-for-tab-command))
20925 (goto-char p)
20926 (when folded (org-cycle)))
20927 (message "Block at point indented"))
20929 (defun org-indent-region (start end)
20930 "Indent region."
20931 (interactive "r")
20932 (save-excursion
20933 (let ((line-end (org-current-line end)))
20934 (goto-char start)
20935 (while (< (org-current-line) line-end)
20936 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20937 (t (call-interactively 'org-indent-line)))
20938 (move-beginning-of-line 2)))))
20941 ;;; Filling
20943 ;; We use our own fill-paragraph and auto-fill functions.
20945 ;; `org-fill-paragraph' relies on adaptive filling and context
20946 ;; checking. Appropriate `fill-prefix' is computed with
20947 ;; `org-adaptive-fill-function'.
20949 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20950 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20951 ;; `org-adaptive-fill-function' value. Internally,
20952 ;; `org-comment-line-break-function' breaks the line.
20954 ;; `org-setup-filling' installs filling and auto-filling related
20955 ;; variables during `org-mode' initialization.
20957 (defun org-setup-filling ()
20958 (interactive)
20959 ;; Prevent auto-fill from inserting unwanted new items.
20960 (when (boundp 'fill-nobreak-predicate)
20961 (org-set-local
20962 'fill-nobreak-predicate
20963 (org-uniquify
20964 (append fill-nobreak-predicate
20965 '(org-fill-paragraph-separate-nobreak-p
20966 org-fill-line-break-nobreak-p)))))
20967 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20968 (org-set-local 'auto-fill-inhibit-regexp nil)
20969 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20970 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20971 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20973 (defvar org-element-paragraph-separate) ; org-element.el
20974 (defun org-fill-paragraph-separate-nobreak-p ()
20975 "Non-nil when a line break at point would insert a new item."
20976 (looking-at (substring org-element-paragraph-separate 1)))
20978 (defun org-fill-line-break-nobreak-p ()
20979 "Non-nil when a line break at point would create an Org line break."
20980 (save-excursion
20981 (skip-chars-backward "[ \t]")
20982 (skip-chars-backward "\\\\")
20983 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20985 (declare-function message-in-body-p "message" ())
20986 (defvar org-element--affiliated-re) ; From org-element.el
20987 (defun org-adaptive-fill-function ()
20988 "Compute a fill prefix for the current line.
20989 Return fill prefix, as a string, or nil if current line isn't
20990 meant to be filled."
20991 (let (prefix)
20992 (when (and (derived-mode-p 'message-mode) (message-in-body-p))
20993 (save-excursion
20994 (beginning-of-line)
20995 (cond ((looking-at message-cite-prefix-regexp)
20996 (setq prefix (match-string-no-properties 0)))
20997 ((looking-at org-outline-regexp)
20998 (setq prefix "")))))
20999 (or prefix
21000 (org-with-wide-buffer
21001 (let* ((p (line-beginning-position))
21002 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21003 (type (org-element-type element))
21004 (post-affiliated
21005 (save-excursion
21006 (goto-char (org-element-property :begin element))
21007 (while (looking-at org-element--affiliated-re) (forward-line))
21008 (point))))
21009 (unless (< p post-affiliated)
21010 (case type
21011 (comment (looking-at "[ \t]*# ?") (match-string 0))
21012 (footnote-definition "")
21013 ((item plain-list)
21014 (make-string (org-list-item-body-column post-affiliated) ? ))
21015 (paragraph
21016 ;; Fill prefix is usually the same as the current line,
21017 ;; except if the paragraph is at the beginning of an item.
21018 (let ((parent (org-element-property :parent element)))
21019 (cond ((eq (org-element-type parent) 'item)
21020 (make-string (org-list-item-body-column
21021 (org-element-property :begin parent))
21022 ? ))
21023 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21024 (match-string 0))
21025 (t ""))))
21026 (comment-block
21027 ;; Only fill contents if P is within block boundaries.
21028 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21029 (forward-line)
21030 (point)))
21031 (cend (save-excursion
21032 (goto-char (org-element-property :end element))
21033 (skip-chars-backward " \r\t\n")
21034 (line-beginning-position))))
21035 (when (and (>= p cbeg) (< p cend))
21036 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21037 (match-string 0)
21038 "")))))))))))
21040 (declare-function message-goto-body "message" ())
21041 (defvar message-cite-prefix-regexp) ; From message.el
21042 (defvar org-element-all-objects) ; From org-element.el
21043 (defun org-fill-paragraph (&optional justify)
21044 "Fill element at point, when applicable.
21046 This function only applies to comment blocks, comments, example
21047 blocks and paragraphs. Also, as a special case, re-align table
21048 when point is at one.
21050 If JUSTIFY is non-nil (interactively, with prefix argument),
21051 justify as well. If `sentence-end-double-space' is non-nil, then
21052 period followed by one space does not end a sentence, so don't
21053 break a line there. The variable `fill-column' controls the
21054 width for filling.
21056 For convenience, when point is at a plain list, an item or
21057 a footnote definition, try to fill the first paragraph within."
21058 (interactive)
21059 (if (and (derived-mode-p 'message-mode)
21060 (or (not (message-in-body-p))
21061 (save-excursion (move-beginning-of-line 1)
21062 (looking-at message-cite-prefix-regexp))))
21063 ;; First ensure filling is correct in message-mode.
21064 (let ((fill-paragraph-function
21065 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21066 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21067 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21068 (paragraph-separate
21069 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21070 (fill-paragraph nil))
21071 (save-excursion
21072 ;; Move to end of line in order to get the first paragraph
21073 ;; within a plain list or a footnote definition.
21074 (end-of-line)
21075 (let ((element (org-element-at-point)))
21076 ;; First check if point is in a blank line at the beginning of
21077 ;; the buffer. In that case, ignore filling.
21078 (if (< (point) (org-element-property :begin element)) t
21079 (case (org-element-type element)
21080 ;; Use major mode filling function is src blocks.
21081 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21082 ;; Align Org tables, leave table.el tables as-is.
21083 (table-row (org-table-align) t)
21084 (table
21085 (when (eq (org-element-property :type element) 'org)
21086 (org-table-align))
21088 (paragraph
21089 ;; Paragraphs may contain `line-break' type objects.
21090 (let ((beg (max (point-min)
21091 (org-element-property :contents-begin element)))
21092 (end (min (point-max)
21093 (org-element-property :contents-end element))))
21094 ;; Do nothing if point is at an affiliated keyword.
21095 (if (< (point) beg) t
21096 (when (derived-mode-p 'message-mode)
21097 ;; In `message-mode', do not fill following
21098 ;; citation in current paragraph nor text before
21099 ;; message body.
21100 (let ((body-start (save-excursion (message-goto-body))))
21101 (when body-start (setq beg (max body-start beg))))
21102 (when (save-excursion
21103 (re-search-forward
21104 (concat "^" message-cite-prefix-regexp) end t))
21105 (setq end (match-beginning 0))))
21106 ;; Fill paragraph, taking line breaks into
21107 ;; consideration. For that, slice the paragraph
21108 ;; using line breaks as separators, and fill the
21109 ;; parts in reverse order to avoid messing with
21110 ;; markers.
21111 (save-excursion
21112 (goto-char end)
21113 (mapc
21114 (lambda (pos)
21115 (fill-region-as-paragraph pos (point) justify)
21116 (goto-char pos))
21117 ;; Find the list of ending positions for line
21118 ;; breaks in the current paragraph. Add paragraph
21119 ;; beginning to include first slice.
21120 (nreverse
21121 (cons
21123 (org-element-map
21124 (org-element--parse-objects
21125 beg end nil org-element-all-objects)
21126 'line-break
21127 (lambda (lb) (org-element-property :end lb)))))))
21128 t)))
21129 ;; Contents of `comment-block' type elements should be
21130 ;; filled as plain text, but only if point is within block
21131 ;; markers.
21132 (comment-block
21133 (let* ((case-fold-search t)
21134 (beg (save-excursion
21135 (goto-char (org-element-property :begin element))
21136 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21137 (forward-line)
21138 (point)))
21139 (end (save-excursion
21140 (goto-char (org-element-property :end element))
21141 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21142 (line-beginning-position))))
21143 (when (and (>= (point) beg) (< (point) end))
21144 (fill-region-as-paragraph
21145 (save-excursion
21146 (end-of-line)
21147 (re-search-backward "^[ \t]*$" beg 'move)
21148 (line-beginning-position))
21149 (save-excursion
21150 (beginning-of-line)
21151 (re-search-forward "^[ \t]*$" end 'move)
21152 (line-beginning-position))
21153 justify)))
21155 ;; Fill comments.
21156 (comment (fill-comment-paragraph justify))
21157 ;; Ignore every other element.
21158 (otherwise t)))))))
21160 (defun org-auto-fill-function ()
21161 "Auto-fill function."
21162 ;; Check if auto-filling is meaningful.
21163 (let ((fc (current-fill-column)))
21164 (when (and fc (> (current-column) fc))
21165 (let* ((fill-prefix (org-adaptive-fill-function))
21166 ;; Enforce empty fill prefix, if required. Otherwise, it
21167 ;; will be computed again.
21168 (adaptive-fill-mode (not (equal fill-prefix ""))))
21169 (when fill-prefix (do-auto-fill))))))
21171 (defun org-comment-line-break-function (&optional soft)
21172 "Break line at point and indent, continuing comment if within one.
21173 The inserted newline is marked hard if variable
21174 `use-hard-newlines' is true, unless optional argument SOFT is
21175 non-nil."
21176 (if soft (insert-and-inherit ?\n) (newline 1))
21177 (save-excursion (forward-char -1) (delete-horizontal-space))
21178 (delete-horizontal-space)
21179 (indent-to-left-margin)
21180 (insert-before-markers-and-inherit fill-prefix))
21183 ;;; Comments
21185 ;; Org comments syntax is quite complex. It requires the entire line
21186 ;; to be just a comment. Also, even with the right syntax at the
21187 ;; beginning of line, some some elements (i.e. verse-block or
21188 ;; example-block) don't accept comments. Usual Emacs comment commands
21189 ;; cannot cope with those requirements. Therefore, Org replaces them.
21191 ;; Org still relies on `comment-dwim', but cannot trust
21192 ;; `comment-only-p'. So, `comment-region-function' and
21193 ;; `uncomment-region-function' both point
21194 ;; to`org-comment-or-uncomment-region'. Eventually,
21195 ;; `org-insert-comment' takes care of insertion of comments at the
21196 ;; beginning of line.
21198 ;; `org-setup-comments-handling' install comments related variables
21199 ;; during `org-mode' initialization.
21201 (defun org-setup-comments-handling ()
21202 (interactive)
21203 (org-set-local 'comment-use-syntax nil)
21204 (org-set-local 'comment-start "# ")
21205 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21206 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21207 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21208 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21210 (defun org-insert-comment ()
21211 "Insert an empty comment above current line.
21212 If the line is empty, insert comment at its beginning."
21213 (beginning-of-line)
21214 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21215 (org-indent-line)
21216 (insert "# "))
21218 (defvar comment-empty-lines) ; From newcomment.el.
21219 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21220 "Comment or uncomment each non-blank line in the region.
21221 Uncomment each non-blank line between BEG and END if it only
21222 contains commented lines. Otherwise, comment them."
21223 (save-restriction
21224 ;; Restrict region
21225 (narrow-to-region (save-excursion (goto-char beg)
21226 (skip-chars-forward " \r\t\n" end)
21227 (line-beginning-position))
21228 (save-excursion (goto-char end)
21229 (skip-chars-backward " \r\t\n" beg)
21230 (line-end-position)))
21231 (let ((uncommentp
21232 ;; UNCOMMENTP is non-nil when every non blank line between
21233 ;; BEG and END is a comment.
21234 (save-excursion
21235 (goto-char (point-min))
21236 (while (and (not (eobp))
21237 (let ((element (org-element-at-point)))
21238 (and (eq (org-element-type element) 'comment)
21239 (goto-char (min (point-max)
21240 (org-element-property
21241 :end element)))))))
21242 (eobp))))
21243 (if uncommentp
21244 ;; Only blank lines and comments in region: uncomment it.
21245 (save-excursion
21246 (goto-char (point-min))
21247 (while (not (eobp))
21248 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21249 (replace-match "" nil nil nil 1))
21250 (forward-line)))
21251 ;; Comment each line in region.
21252 (let ((min-indent (point-max)))
21253 ;; First find the minimum indentation across all lines.
21254 (save-excursion
21255 (goto-char (point-min))
21256 (while (and (not (eobp)) (not (zerop min-indent)))
21257 (unless (looking-at "[ \t]*$")
21258 (setq min-indent (min min-indent (current-indentation))))
21259 (forward-line)))
21260 ;; Then loop over all lines.
21261 (save-excursion
21262 (goto-char (point-min))
21263 (while (not (eobp))
21264 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21265 (org-move-to-column min-indent t)
21266 (insert comment-start))
21267 (forward-line))))))))
21270 ;;; Other stuff.
21272 (defun org-toggle-fixed-width-section (arg)
21273 "Toggle the fixed-width export.
21274 If there is no active region, the QUOTE keyword at the current headline is
21275 inserted or removed. When present, it causes the text between this headline
21276 and the next to be exported as fixed-width text, and unmodified.
21277 If there is an active region, this command adds or removes a colon as the
21278 first character of this line. If the first character of a line is a colon,
21279 this line is also exported in fixed-width font."
21280 (interactive "P")
21281 (let* ((cc 0)
21282 (regionp (org-region-active-p))
21283 (beg (if regionp (region-beginning) (point)))
21284 (end (if regionp (region-end)))
21285 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21286 (case-fold-search nil)
21287 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21288 off)
21289 (if regionp
21290 (save-excursion
21291 (goto-char beg)
21292 (setq cc (current-column))
21293 (beginning-of-line 1)
21294 (setq off (looking-at re))
21295 (while (> nlines 0)
21296 (setq nlines (1- nlines))
21297 (beginning-of-line 1)
21298 (cond
21299 (arg
21300 (org-move-to-column cc t)
21301 (insert ": \n")
21302 (forward-line -1))
21303 ((and off (looking-at re))
21304 (replace-match "" t t nil 1))
21305 ((not off) (org-move-to-column cc t) (insert ": ")))
21306 (forward-line 1)))
21307 (save-excursion
21308 (org-back-to-heading)
21309 (cond
21310 ((looking-at (format org-heading-keyword-regexp-format
21311 org-quote-string))
21312 (goto-char (match-end 1))
21313 (looking-at (concat " +" org-quote-string))
21314 (replace-match "" t t)
21315 (when (eolp) (insert " ")))
21316 ((looking-at org-outline-regexp)
21317 (goto-char (match-end 0))
21318 (insert org-quote-string " ")))))))
21320 (defun org-reftex-citation ()
21321 "Use reftex-citation to insert a citation into the buffer.
21322 This looks for a line like
21324 #+BIBLIOGRAPHY: foo plain option:-d
21326 and derives from it that foo.bib is the bibliography file relevant
21327 for this document. It then installs the necessary environment for RefTeX
21328 to work in this buffer and calls `reftex-citation' to insert a citation
21329 into the buffer.
21331 Export of such citations to both LaTeX and HTML is handled by the contributed
21332 package org-exp-bibtex by Taru Karttunen."
21333 (interactive)
21334 (let ((reftex-docstruct-symbol 'rds)
21335 (reftex-cite-format "\\cite{%l}")
21336 rds bib)
21337 (save-excursion
21338 (save-restriction
21339 (widen)
21340 (let ((case-fold-search t)
21341 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21342 (if (not (save-excursion
21343 (or (re-search-forward re nil t)
21344 (re-search-backward re nil t))))
21345 (error "No bibliography defined in file")
21346 (setq bib (concat (match-string 1) ".bib")
21347 rds (list (list 'bib bib)))))))
21348 (call-interactively 'reftex-citation)))
21350 ;;;; Functions extending outline functionality
21352 (defun org-beginning-of-line (&optional arg)
21353 "Go to the beginning of the current line. If that is invisible, continue
21354 to a visible line beginning. This makes the function of C-a more intuitive.
21355 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21356 first attempt, and only move to after the tags when the cursor is already
21357 beyond the end of the headline."
21358 (interactive "P")
21359 (let ((pos (point))
21360 (special (if (consp org-special-ctrl-a/e)
21361 (car org-special-ctrl-a/e)
21362 org-special-ctrl-a/e))
21363 refpos)
21364 (if (org-bound-and-true-p visual-line-mode)
21365 (beginning-of-visual-line 1)
21366 (beginning-of-line 1))
21367 (if (and arg (fboundp 'move-beginning-of-line))
21368 (call-interactively 'move-beginning-of-line)
21369 (if (bobp)
21371 (backward-char 1)
21372 (if (org-truely-invisible-p)
21373 (while (and (not (bobp)) (org-truely-invisible-p))
21374 (backward-char 1)
21375 (beginning-of-line 1))
21376 (forward-char 1))))
21377 (when special
21378 (cond
21379 ((and (looking-at org-complex-heading-regexp)
21380 (= (char-after (match-end 1)) ?\ ))
21381 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21382 (point-at-eol)))
21383 (goto-char
21384 (if (eq special t)
21385 (cond ((> pos refpos) refpos)
21386 ((= pos (point)) refpos)
21387 (t (point)))
21388 (cond ((> pos (point)) (point))
21389 ((not (eq last-command this-command)) (point))
21390 (t refpos)))))
21391 ((org-at-item-p)
21392 ;; Being at an item and not looking at an the item means point
21393 ;; was previously moved to beginning of a visual line, which
21394 ;; doesn't contain the item. Therefore, do nothing special,
21395 ;; just stay here.
21396 (when (looking-at org-list-full-item-re)
21397 ;; Set special position at first white space character after
21398 ;; bullet, and check-box, if any.
21399 (let ((after-bullet
21400 (let ((box (match-end 3)))
21401 (if (not box) (match-end 1)
21402 (let ((after (char-after box)))
21403 (if (and after (= after ? )) (1+ box) box))))))
21404 ;; Special case: Move point to special position when
21405 ;; currently after it or at beginning of line.
21406 (if (eq special t)
21407 (when (or (> pos after-bullet) (= (point) pos))
21408 (goto-char after-bullet))
21409 ;; Reversed case: Move point to special position when
21410 ;; point was already at beginning of line and command is
21411 ;; repeated.
21412 (when (and (= (point) pos) (eq last-command this-command))
21413 (goto-char after-bullet))))))))
21414 (org-no-warnings
21415 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21417 (defun org-end-of-line (&optional arg)
21418 "Go to the end of the line.
21419 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21420 tags on the first attempt, and only move to after the tags when
21421 the cursor is already beyond the end of the headline."
21422 (interactive "P")
21423 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21424 org-special-ctrl-a/e))
21425 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21426 'end-of-visual-line)
21427 ((fboundp 'move-end-of-line) 'move-end-of-line)
21428 (t 'end-of-line))))
21429 (if (or (not special) arg) (call-interactively move-fun)
21430 (let* ((element (save-excursion (beginning-of-line)
21431 (org-element-at-point)))
21432 (type (org-element-type element)))
21433 (cond
21434 ((memq type '(headline inlinetask))
21435 (let ((pos (point)))
21436 (beginning-of-line 1)
21437 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21438 (if (eq special t)
21439 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21440 (goto-char (match-beginning 1))
21441 (goto-char (match-end 0)))
21442 (if (or (< pos (match-end 0))
21443 (not (eq this-command last-command)))
21444 (goto-char (match-end 0))
21445 (goto-char (match-beginning 1))))
21446 (call-interactively move-fun))))
21447 ((org-element-property :hiddenp element)
21448 ;; If element is hidden, `move-end-of-line' would put point
21449 ;; after it. Use `end-of-line' to stay on current line.
21450 (call-interactively 'end-of-line))
21451 (t (call-interactively move-fun)))))
21452 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21454 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21455 (define-key org-mode-map "\C-e" 'org-end-of-line)
21457 (defun org-backward-sentence (&optional arg)
21458 "Go to beginning of sentence, or beginning of table field.
21459 This will call `backward-sentence' or `org-table-beginning-of-field',
21460 depending on context."
21461 (interactive "P")
21462 (cond
21463 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21464 (t (call-interactively 'backward-sentence))))
21466 (defun org-forward-sentence (&optional arg)
21467 "Go to end of sentence, or end of table field.
21468 This will call `forward-sentence' or `org-table-end-of-field',
21469 depending on context."
21470 (interactive "P")
21471 (cond
21472 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21473 (t (call-interactively 'forward-sentence))))
21475 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21476 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21478 (defun org-kill-line (&optional arg)
21479 "Kill line, to tags or end of line."
21480 (interactive "P")
21481 (cond
21482 ((or (not org-special-ctrl-k)
21483 (bolp)
21484 (not (org-at-heading-p)))
21485 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21486 org-ctrl-k-protect-subtree)
21487 (if (or (eq org-ctrl-k-protect-subtree 'error)
21488 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21489 (error "C-k aborted - would kill hidden subtree")))
21490 (call-interactively
21491 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21492 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21493 (kill-region (point) (match-beginning 1))
21494 (org-set-tags nil t))
21495 (t (kill-region (point) (point-at-eol)))))
21497 (define-key org-mode-map "\C-k" 'org-kill-line)
21499 (defun org-yank (&optional arg)
21500 "Yank. If the kill is a subtree, treat it specially.
21501 This command will look at the current kill and check if is a single
21502 subtree, or a series of subtrees[1]. If it passes the test, and if the
21503 cursor is at the beginning of a line or after the stars of a currently
21504 empty headline, then the yank is handled specially. How exactly depends
21505 on the value of the following variables, both set by default.
21507 org-yank-folded-subtrees
21508 When set, the subtree(s) will be folded after insertion, but only
21509 if doing so would now swallow text after the yanked text.
21511 org-yank-adjusted-subtrees
21512 When set, the subtree will be promoted or demoted in order to
21513 fit into the local outline tree structure, which means that the level
21514 will be adjusted so that it becomes the smaller one of the two
21515 *visible* surrounding headings.
21517 Any prefix to this command will cause `yank' to be called directly with
21518 no special treatment. In particular, a simple \\[universal-argument] prefix \
21519 will just
21520 plainly yank the text as it is.
21522 \[1] The test checks if the first non-white line is a heading
21523 and if there are no other headings with fewer stars."
21524 (interactive "P")
21525 (org-yank-generic 'yank arg))
21527 (defun org-yank-generic (command arg)
21528 "Perform some yank-like command.
21530 This function implements the behavior described in the `org-yank'
21531 documentation. However, it has been generalized to work for any
21532 interactive command with similar behavior."
21534 ;; pretend to be command COMMAND
21535 (setq this-command command)
21537 (if arg
21538 (call-interactively command)
21540 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21541 (and (org-kill-is-subtree-p)
21542 (or (bolp)
21543 (and (looking-at "[ \t]*$")
21544 (string-match
21545 "\\`\\*+\\'"
21546 (buffer-substring (point-at-bol) (point)))))))
21547 swallowp)
21548 (cond
21549 ((and subtreep org-yank-folded-subtrees)
21550 (let ((beg (point))
21551 end)
21552 (if (and subtreep org-yank-adjusted-subtrees)
21553 (org-paste-subtree nil nil 'for-yank)
21554 (call-interactively command))
21556 (setq end (point))
21557 (goto-char beg)
21558 (when (and (bolp) subtreep
21559 (not (setq swallowp
21560 (org-yank-folding-would-swallow-text beg end))))
21561 (org-with-limited-levels
21562 (or (looking-at org-outline-regexp)
21563 (re-search-forward org-outline-regexp-bol end t))
21564 (while (and (< (point) end) (looking-at org-outline-regexp))
21565 (hide-subtree)
21566 (org-cycle-show-empty-lines 'folded)
21567 (condition-case nil
21568 (outline-forward-same-level 1)
21569 (error (goto-char end))))))
21570 (when swallowp
21571 (message
21572 "Inserted text not folded because that would swallow text"))
21574 (goto-char end)
21575 (skip-chars-forward " \t\n\r")
21576 (beginning-of-line 1)
21577 (push-mark beg 'nomsg)))
21578 ((and subtreep org-yank-adjusted-subtrees)
21579 (let ((beg (point-at-bol)))
21580 (org-paste-subtree nil nil 'for-yank)
21581 (push-mark beg 'nomsg)))
21583 (call-interactively command))))))
21585 (defun org-yank-folding-would-swallow-text (beg end)
21586 "Would hide-subtree at BEG swallow any text after END?"
21587 (let (level)
21588 (org-with-limited-levels
21589 (save-excursion
21590 (goto-char beg)
21591 (when (or (looking-at org-outline-regexp)
21592 (re-search-forward org-outline-regexp-bol end t))
21593 (setq level (org-outline-level)))
21594 (goto-char end)
21595 (skip-chars-forward " \t\r\n\v\f")
21596 (if (or (eobp)
21597 (and (bolp) (looking-at org-outline-regexp)
21598 (<= (org-outline-level) level)))
21599 nil ; Nothing would be swallowed
21600 t))))) ; something would swallow
21602 (define-key org-mode-map "\C-y" 'org-yank)
21604 (defun org-truely-invisible-p ()
21605 "Check if point is at a character currently not visible.
21606 This version does not only check the character property, but also
21607 `visible-mode'."
21608 ;; Early versions of noutline don't have `outline-invisible-p'.
21609 (if (org-bound-and-true-p visible-mode)
21611 (outline-invisible-p)))
21613 (defun org-invisible-p2 ()
21614 "Check if point is at a character currently not visible."
21615 (save-excursion
21616 (if (and (eolp) (not (bobp))) (backward-char 1))
21617 ;; Early versions of noutline don't have `outline-invisible-p'.
21618 (outline-invisible-p)))
21620 (defun org-back-to-heading (&optional invisible-ok)
21621 "Call `outline-back-to-heading', but provide a better error message."
21622 (condition-case nil
21623 (outline-back-to-heading invisible-ok)
21624 (error (error "Before first headline at position %d in buffer %s"
21625 (point) (current-buffer)))))
21627 (defun org-before-first-heading-p ()
21628 "Before first heading?"
21629 (save-excursion
21630 (end-of-line)
21631 (null (re-search-backward org-outline-regexp-bol nil t))))
21633 (defun org-at-heading-p (&optional ignored)
21634 (outline-on-heading-p t))
21635 ;; Compatibility alias with Org versions < 7.8.03
21636 (defalias 'org-on-heading-p 'org-at-heading-p)
21638 (defun org-at-comment-p nil
21639 "Is cursor in a line starting with a # character?"
21640 (save-excursion
21641 (beginning-of-line)
21642 (looking-at "^#")))
21644 (defun org-at-drawer-p nil
21645 "Is cursor at a drawer keyword?"
21646 (save-excursion
21647 (move-beginning-of-line 1)
21648 (looking-at org-drawer-regexp)))
21650 (defun org-at-block-p nil
21651 "Is cursor at a block keyword?"
21652 (save-excursion
21653 (move-beginning-of-line 1)
21654 (looking-at org-block-regexp)))
21656 (defun org-point-at-end-of-empty-headline ()
21657 "If point is at the end of an empty headline, return t, else nil.
21658 If the heading only contains a TODO keyword, it is still still considered
21659 empty."
21660 (and (looking-at "[ \t]*$")
21661 (when org-todo-line-regexp
21662 (save-excursion
21663 (beginning-of-line 1)
21664 (let ((case-fold-search nil))
21665 (looking-at org-todo-line-regexp)
21666 (string= (match-string 3) ""))))))
21668 (defun org-at-heading-or-item-p ()
21669 (or (org-at-heading-p) (org-at-item-p)))
21671 (defun org-at-target-p ()
21672 (or (org-in-regexp org-radio-target-regexp)
21673 (org-in-regexp org-target-regexp)))
21674 ;; Compatibility alias with Org versions < 7.8.03
21675 (defalias 'org-on-target-p 'org-at-target-p)
21677 (defun org-up-heading-all (arg)
21678 "Move to the heading line of which the present line is a subheading.
21679 This function considers both visible and invisible heading lines.
21680 With argument, move up ARG levels."
21681 (if (fboundp 'outline-up-heading-all)
21682 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21683 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21685 (defun org-up-heading-safe ()
21686 "Move to the heading line of which the present line is a subheading.
21687 This version will not throw an error. It will return the level of the
21688 headline found, or nil if no higher level is found.
21690 Also, this function will be a lot faster than `outline-up-heading',
21691 because it relies on stars being the outline starters. This can really
21692 make a significant difference in outlines with very many siblings."
21693 (let (start-level re)
21694 (org-back-to-heading t)
21695 (setq start-level (funcall outline-level))
21696 (if (equal start-level 1)
21698 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21699 (if (re-search-backward re nil t)
21700 (funcall outline-level)))))
21702 (defun org-first-sibling-p ()
21703 "Is this heading the first child of its parents?"
21704 (interactive)
21705 (let ((re org-outline-regexp-bol)
21706 level l)
21707 (unless (org-at-heading-p t)
21708 (error "Not at a heading"))
21709 (setq level (funcall outline-level))
21710 (save-excursion
21711 (if (not (re-search-backward re nil t))
21713 (setq l (funcall outline-level))
21714 (< l level)))))
21716 (defun org-goto-sibling (&optional previous)
21717 "Goto the next sibling, even if it is invisible.
21718 When PREVIOUS is set, go to the previous sibling instead. Returns t
21719 when a sibling was found. When none is found, return nil and don't
21720 move point."
21721 (let ((fun (if previous 're-search-backward 're-search-forward))
21722 (pos (point))
21723 (re org-outline-regexp-bol)
21724 level l)
21725 (when (condition-case nil (org-back-to-heading t) (error nil))
21726 (setq level (funcall outline-level))
21727 (catch 'exit
21728 (or previous (forward-char 1))
21729 (while (funcall fun re nil t)
21730 (setq l (funcall outline-level))
21731 (when (< l level) (goto-char pos) (throw 'exit nil))
21732 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21733 (goto-char pos)
21734 nil))))
21736 (defun org-show-siblings ()
21737 "Show all siblings of the current headline."
21738 (save-excursion
21739 (while (org-goto-sibling) (org-flag-heading nil)))
21740 (save-excursion
21741 (while (org-goto-sibling 'previous)
21742 (org-flag-heading nil))))
21744 (defun org-goto-first-child ()
21745 "Goto the first child, even if it is invisible.
21746 Return t when a child was found. Otherwise don't move point and
21747 return nil."
21748 (let (level (pos (point)) (re org-outline-regexp-bol))
21749 (when (condition-case nil (org-back-to-heading t) (error nil))
21750 (setq level (outline-level))
21751 (forward-char 1)
21752 (if (and (re-search-forward re nil t) (> (outline-level) level))
21753 (progn (goto-char (match-beginning 0)) t)
21754 (goto-char pos) nil))))
21756 (defun org-show-hidden-entry ()
21757 "Show an entry where even the heading is hidden."
21758 (save-excursion
21759 (org-show-entry)))
21761 (defun org-flag-heading (flag &optional entry)
21762 "Flag the current heading. FLAG non-nil means make invisible.
21763 When ENTRY is non-nil, show the entire entry."
21764 (save-excursion
21765 (org-back-to-heading t)
21766 ;; Check if we should show the entire entry
21767 (if entry
21768 (progn
21769 (org-show-entry)
21770 (save-excursion
21771 (and (outline-next-heading)
21772 (org-flag-heading nil))))
21773 (outline-flag-region (max (point-min) (1- (point)))
21774 (save-excursion (outline-end-of-heading) (point))
21775 flag))))
21777 (defun org-get-next-sibling ()
21778 "Move to next heading of the same level, and return point.
21779 If there is no such heading, return nil.
21780 This is like outline-next-sibling, but invisible headings are ok."
21781 (let ((level (funcall outline-level)))
21782 (outline-next-heading)
21783 (while (and (not (eobp)) (> (funcall outline-level) level))
21784 (outline-next-heading))
21785 (if (or (eobp) (< (funcall outline-level) level))
21787 (point))))
21789 (defun org-get-last-sibling ()
21790 "Move to previous heading of the same level, and return point.
21791 If there is no such heading, return nil."
21792 (let ((opoint (point))
21793 (level (funcall outline-level)))
21794 (outline-previous-heading)
21795 (when (and (/= (point) opoint) (outline-on-heading-p t))
21796 (while (and (> (funcall outline-level) level)
21797 (not (bobp)))
21798 (outline-previous-heading))
21799 (if (< (funcall outline-level) level)
21801 (point)))))
21803 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21804 "Goto to the end of a subtree."
21805 ;; This contains an exact copy of the original function, but it uses
21806 ;; `org-back-to-heading', to make it work also in invisible
21807 ;; trees. And is uses an invisible-ok argument.
21808 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21809 ;; Furthermore, when used inside Org, finding the end of a large subtree
21810 ;; with many children and grandchildren etc, this can be much faster
21811 ;; than the outline version.
21812 (org-back-to-heading invisible-ok)
21813 (let ((first t)
21814 (level (funcall outline-level)))
21815 (if (and (derived-mode-p 'org-mode) (< level 1000))
21816 ;; A true heading (not a plain list item), in Org-mode
21817 ;; This means we can easily find the end by looking
21818 ;; only for the right number of stars. Using a regexp to do
21819 ;; this is so much faster than using a Lisp loop.
21820 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21821 (forward-char 1)
21822 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21823 ;; something else, do it the slow way
21824 (while (and (not (eobp))
21825 (or first (> (funcall outline-level) level)))
21826 (setq first nil)
21827 (outline-next-heading)))
21828 (unless to-heading
21829 (if (memq (preceding-char) '(?\n ?\^M))
21830 (progn
21831 ;; Go to end of line before heading
21832 (forward-char -1)
21833 (if (memq (preceding-char) '(?\n ?\^M))
21834 ;; leave blank line before heading
21835 (forward-char -1))))))
21836 (point))
21838 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21839 "Use Org version in org-mode, for dramatic speed-up."
21840 (if (derived-mode-p 'org-mode)
21841 (progn
21842 (org-end-of-subtree nil t)
21843 (unless (eobp) (backward-char 1)))
21844 ad-do-it))
21846 (defun org-end-of-meta-data-and-drawers ()
21847 "Jump to the first text after meta data and drawers in the current entry.
21848 This will move over empty lines, lines with planning time stamps,
21849 clocking lines, and drawers."
21850 (org-back-to-heading t)
21851 (let ((end (save-excursion (outline-next-heading) (point)))
21852 (re (concat "\\(" org-drawer-regexp "\\)"
21853 "\\|" "[ \t]*" org-keyword-time-regexp)))
21854 (forward-line 1)
21855 (while (re-search-forward re end t)
21856 (if (not (match-end 1))
21857 ;; empty or planning line
21858 (forward-line 1)
21859 ;; a drawer, find the end
21860 (re-search-forward "^[ \t]*:END:" end 'move)
21861 (forward-line 1)))
21862 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21863 (point)))
21865 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21866 "Move forward to the arg'th subheading at same level as this one.
21867 Stop at the first and last subheadings of a superior heading.
21868 Normally this only looks at visible headings, but when INVISIBLE-OK is
21869 non-nil it will also look at invisible ones."
21870 (interactive "p")
21871 (org-back-to-heading invisible-ok)
21872 (org-at-heading-p)
21873 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21874 (re (format "^\\*\\{1,%d\\} " level))
21876 (forward-char 1)
21877 (while (> arg 0)
21878 (while (and (re-search-forward re nil 'move)
21879 (setq l (- (match-end 0) (match-beginning 0) 1))
21880 (= l level)
21881 (not invisible-ok)
21882 (progn (backward-char 1) (outline-invisible-p)))
21883 (if (< l level) (setq arg 1)))
21884 (setq arg (1- arg)))
21885 (beginning-of-line 1)))
21887 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21888 "Move backward to the arg'th subheading at same level as this one.
21889 Stop at the first and last subheadings of a superior heading."
21890 (interactive "p")
21891 (org-back-to-heading)
21892 (org-at-heading-p)
21893 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21894 (re (format "^\\*\\{1,%d\\} " level))
21896 (while (> arg 0)
21897 (while (and (re-search-backward re nil 'move)
21898 (setq l (- (match-end 0) (match-beginning 0) 1))
21899 (= l level)
21900 (not invisible-ok)
21901 (outline-invisible-p))
21902 (if (< l level) (setq arg 1)))
21903 (setq arg (1- arg)))))
21905 (defun org-forward-element ()
21906 "Move forward by one element.
21907 Move to the next element at the same level, when possible."
21908 (interactive)
21909 (cond ((eobp) (error "Cannot move further down"))
21910 ((org-with-limited-levels (org-at-heading-p))
21911 (let ((origin (point)))
21912 (org-forward-heading-same-level 1)
21913 (unless (org-with-limited-levels (org-at-heading-p))
21914 (goto-char origin)
21915 (error "Cannot move further down"))))
21917 (let* ((elem (org-element-at-point))
21918 (end (org-element-property :end elem))
21919 (parent (org-element-property :parent elem)))
21920 (if (and parent (= (org-element-property :contents-end parent) end))
21921 (goto-char (org-element-property :end parent))
21922 (goto-char end))))))
21924 (defun org-backward-element ()
21925 "Move backward by one element.
21926 Move to the previous element at the same level, when possible."
21927 (interactive)
21928 (cond ((bobp) (error "Cannot move further up"))
21929 ((org-with-limited-levels (org-at-heading-p))
21930 ;; At an headline, move to the previous one, if any, or stay
21931 ;; here.
21932 (let ((origin (point)))
21933 (org-backward-heading-same-level 1)
21934 (unless (org-with-limited-levels (org-at-heading-p))
21935 (goto-char origin)
21936 (error "Cannot move further up"))))
21938 (let* ((trail (org-element-at-point 'keep-trail))
21939 (elem (car trail))
21940 (prev-elem (nth 1 trail))
21941 (beg (org-element-property :begin elem)))
21942 (cond
21943 ;; Move to beginning of current element if point isn't
21944 ;; there already.
21945 ((/= (point) beg) (goto-char beg))
21946 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21947 ((org-before-first-heading-p) (goto-char (point-min)))
21948 (t (org-back-to-heading)))))))
21950 (defun org-up-element ()
21951 "Move to upper element."
21952 (interactive)
21953 (if (org-with-limited-levels (org-at-heading-p))
21954 (unless (org-up-heading-safe) (error "No surrounding element"))
21955 (let* ((elem (org-element-at-point))
21956 (parent (org-element-property :parent elem)))
21957 (if parent (goto-char (org-element-property :begin parent))
21958 (if (org-with-limited-levels (org-before-first-heading-p))
21959 (error "No surrounding element")
21960 (org-with-limited-levels (org-back-to-heading)))))))
21962 (defvar org-element-greater-elements)
21963 (defun org-down-element ()
21964 "Move to inner element."
21965 (interactive)
21966 (let ((element (org-element-at-point)))
21967 (cond
21968 ((memq (org-element-type element) '(plain-list table))
21969 (goto-char (org-element-property :contents-begin element))
21970 (forward-char))
21971 ((memq (org-element-type element) org-element-greater-elements)
21972 ;; If contents are hidden, first disclose them.
21973 (when (org-element-property :hiddenp element) (org-cycle))
21974 (goto-char (or (org-element-property :contents-begin element)
21975 (error "No content for this element"))))
21976 (t (error "No inner element")))))
21978 (defun org-drag-element-backward ()
21979 "Move backward element at point."
21980 (interactive)
21981 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21982 (let* ((trail (org-element-at-point 'keep-trail))
21983 (elem (car trail))
21984 (prev-elem (nth 1 trail)))
21985 ;; Error out if no previous element or previous element is
21986 ;; a parent of the current one.
21987 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21988 (error "Cannot drag element backward")
21989 (let ((pos (point)))
21990 (org-element-swap-A-B prev-elem elem)
21991 (goto-char (+ (org-element-property :begin prev-elem)
21992 (- pos (org-element-property :begin elem)))))))))
21994 (defun org-drag-element-forward ()
21995 "Move forward element at point."
21996 (interactive)
21997 (let* ((pos (point))
21998 (elem (org-element-at-point)))
21999 (when (= (point-max) (org-element-property :end elem))
22000 (error "Cannot drag element forward"))
22001 (goto-char (org-element-property :end elem))
22002 (let ((next-elem (org-element-at-point)))
22003 (when (or (org-element-nested-p elem next-elem)
22004 (and (eq (org-element-type next-elem) 'headline)
22005 (not (eq (org-element-type elem) 'headline))))
22006 (goto-char pos)
22007 (error "Cannot drag element forward"))
22008 ;; Compute new position of point: it's shifted by NEXT-ELEM
22009 ;; body's length (without final blanks) and by the length of
22010 ;; blanks between ELEM and NEXT-ELEM.
22011 (let ((size-next (- (save-excursion
22012 (goto-char (org-element-property :end next-elem))
22013 (skip-chars-backward " \r\t\n")
22014 (forward-line)
22015 ;; Small correction if buffer doesn't end
22016 ;; with a newline character.
22017 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22018 (org-element-property :begin next-elem)))
22019 (size-blank (- (org-element-property :end elem)
22020 (save-excursion
22021 (goto-char (org-element-property :end elem))
22022 (skip-chars-backward " \r\t\n")
22023 (forward-line)
22024 (point)))))
22025 (org-element-swap-A-B elem next-elem)
22026 (goto-char (+ pos size-next size-blank))))))
22028 (defun org-mark-element ()
22029 "Put point at beginning of this element, mark at end.
22031 Interactively, if this command is repeated or (in Transient Mark
22032 mode) if the mark is active, it marks the next element after the
22033 ones already marked."
22034 (interactive)
22035 (let (deactivate-mark)
22036 (if (and (org-called-interactively-p 'any)
22037 (or (and (eq last-command this-command) (mark t))
22038 (and transient-mark-mode mark-active)))
22039 (set-mark
22040 (save-excursion
22041 (goto-char (mark))
22042 (goto-char (org-element-property :end (org-element-at-point)))))
22043 (let ((element (org-element-at-point)))
22044 (end-of-line)
22045 (push-mark (org-element-property :end element) t t)
22046 (goto-char (org-element-property :begin element))))))
22048 (defun org-narrow-to-element ()
22049 "Narrow buffer to current element."
22050 (interactive)
22051 (let ((elem (org-element-at-point)))
22052 (cond
22053 ((eq (car elem) 'headline)
22054 (narrow-to-region
22055 (org-element-property :begin elem)
22056 (org-element-property :end elem)))
22057 ((memq (car elem) org-element-greater-elements)
22058 (narrow-to-region
22059 (org-element-property :contents-begin elem)
22060 (org-element-property :contents-end elem)))
22062 (narrow-to-region
22063 (org-element-property :begin elem)
22064 (org-element-property :end elem))))))
22066 (defun org-transpose-element ()
22067 "Transpose current and previous elements, keeping blank lines between.
22068 Point is moved after both elements."
22069 (interactive)
22070 (org-skip-whitespace)
22071 (let ((end (org-element-property :end (org-element-at-point))))
22072 (org-drag-element-backward)
22073 (goto-char end)))
22075 (defun org-unindent-buffer ()
22076 "Un-indent the visible part of the buffer.
22077 Relative indentation (between items, inside blocks, etc.) isn't
22078 modified."
22079 (interactive)
22080 (unless (eq major-mode 'org-mode)
22081 (error "Cannot un-indent a buffer not in Org mode"))
22082 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22083 unindent-tree ; For byte-compiler.
22084 (unindent-tree
22085 (function
22086 (lambda (contents)
22087 (mapc
22088 (lambda (element)
22089 (if (memq (org-element-type element) '(headline section))
22090 (funcall unindent-tree (org-element-contents element))
22091 (save-excursion
22092 (save-restriction
22093 (narrow-to-region
22094 (org-element-property :begin element)
22095 (org-element-property :end element))
22096 (org-do-remove-indentation)))))
22097 (reverse contents))))))
22098 (funcall unindent-tree (org-element-contents parse-tree))))
22100 (defun org-show-subtree ()
22101 "Show everything after this heading at deeper levels."
22102 (interactive)
22103 (outline-flag-region
22104 (point)
22105 (save-excursion
22106 (org-end-of-subtree t t))
22107 nil))
22109 (defun org-show-entry ()
22110 "Show the body directly following this heading.
22111 Show the heading too, if it is currently invisible."
22112 (interactive)
22113 (save-excursion
22114 (condition-case nil
22115 (progn
22116 (org-back-to-heading t)
22117 (outline-flag-region
22118 (max (point-min) (1- (point)))
22119 (save-excursion
22120 (if (re-search-forward
22121 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22122 (match-beginning 1)
22123 (point-max)))
22124 nil)
22125 (org-cycle-hide-drawers 'children))
22126 (error nil))))
22128 (defun org-make-options-regexp (kwds &optional extra)
22129 "Make a regular expression for keyword lines."
22130 (concat
22131 "^#\\+\\("
22132 (mapconcat 'regexp-quote kwds "\\|")
22133 (if extra (concat "\\|" extra))
22134 "\\):[ \t]*\\(.*\\)"))
22136 ;; Make isearch reveal the necessary context
22137 (defun org-isearch-end ()
22138 "Reveal context after isearch exits."
22139 (when isearch-success ; only if search was successful
22140 (if (featurep 'xemacs)
22141 ;; Under XEmacs, the hook is run in the correct place,
22142 ;; we directly show the context.
22143 (org-show-context 'isearch)
22144 ;; In Emacs the hook runs *before* restoring the overlays.
22145 ;; So we have to use a one-time post-command-hook to do this.
22146 ;; (Emacs 22 has a special variable, see function `org-mode')
22147 (unless (and (boundp 'isearch-mode-end-hook-quit)
22148 isearch-mode-end-hook-quit)
22149 ;; Only when the isearch was not quitted.
22150 (org-add-hook 'post-command-hook 'org-isearch-post-command
22151 'append 'local)))))
22153 (defun org-isearch-post-command ()
22154 "Remove self from hook, and show context."
22155 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22156 (org-show-context 'isearch))
22159 ;;;; Integration with and fixes for other packages
22161 ;;; Imenu support
22163 (defvar org-imenu-markers nil
22164 "All markers currently used by Imenu.")
22165 (make-variable-buffer-local 'org-imenu-markers)
22167 (defun org-imenu-new-marker (&optional pos)
22168 "Return a new marker for use by Imenu, and remember the marker."
22169 (let ((m (make-marker)))
22170 (move-marker m (or pos (point)))
22171 (push m org-imenu-markers)
22174 (defun org-imenu-get-tree ()
22175 "Produce the index for Imenu."
22176 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22177 (setq org-imenu-markers nil)
22178 (let* ((n org-imenu-depth)
22179 (re (concat "^" (org-get-limited-outline-regexp)))
22180 (subs (make-vector (1+ n) nil))
22181 (last-level 0)
22182 m level head)
22183 (save-excursion
22184 (save-restriction
22185 (widen)
22186 (goto-char (point-max))
22187 (while (re-search-backward re nil t)
22188 (setq level (org-reduced-level (funcall outline-level)))
22189 (when (and (<= level n)
22190 (looking-at org-complex-heading-regexp))
22191 (setq head (org-link-display-format
22192 (org-match-string-no-properties 4))
22193 m (org-imenu-new-marker))
22194 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22195 (if (>= level last-level)
22196 (push (cons head m) (aref subs level))
22197 (push (cons head (aref subs (1+ level))) (aref subs level))
22198 (loop for i from (1+ level) to n do (aset subs i nil)))
22199 (setq last-level level)))))
22200 (aref subs 1)))
22202 (eval-after-load "imenu"
22203 '(progn
22204 (add-hook 'imenu-after-jump-hook
22205 (lambda ()
22206 (if (derived-mode-p 'org-mode)
22207 (org-show-context 'org-goto))))))
22209 (defun org-link-display-format (link)
22210 "Replace a link with either the description, or the link target
22211 if no description is present"
22212 (save-match-data
22213 (if (string-match org-bracket-link-analytic-regexp link)
22214 (replace-match (if (match-end 5)
22215 (match-string 5 link)
22216 (concat (match-string 1 link)
22217 (match-string 3 link)))
22218 nil t link)
22219 link)))
22221 (defun org-toggle-link-display ()
22222 "Toggle the literal or descriptive display of links."
22223 (interactive)
22224 (if org-descriptive-links
22225 (progn (org-remove-from-invisibility-spec '(org-link))
22226 (org-restart-font-lock)
22227 (setq org-descriptive-links nil))
22228 (progn (add-to-invisibility-spec '(org-link))
22229 (org-restart-font-lock)
22230 (setq org-descriptive-links t))))
22232 ;; Speedbar support
22234 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22235 "Overlay marking the agenda restriction line in speedbar.")
22236 (overlay-put org-speedbar-restriction-lock-overlay
22237 'face 'org-agenda-restriction-lock)
22238 (overlay-put org-speedbar-restriction-lock-overlay
22239 'help-echo "Agendas are currently limited to this item.")
22240 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22242 (defun org-speedbar-set-agenda-restriction ()
22243 "Restrict future agenda commands to the location at point in speedbar.
22244 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22245 (interactive)
22246 (require 'org-agenda)
22247 (let (p m tp np dir txt)
22248 (cond
22249 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22250 'org-imenu t))
22251 (setq m (get-text-property p 'org-imenu-marker))
22252 (with-current-buffer (marker-buffer m)
22253 (goto-char m)
22254 (org-agenda-set-restriction-lock 'subtree)))
22255 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22256 'speedbar-function 'speedbar-find-file))
22257 (setq tp (previous-single-property-change
22258 (1+ p) 'speedbar-function)
22259 np (next-single-property-change
22260 tp 'speedbar-function)
22261 dir (speedbar-line-directory)
22262 txt (buffer-substring-no-properties (or tp (point-min))
22263 (or np (point-max))))
22264 (with-current-buffer (find-file-noselect
22265 (let ((default-directory dir))
22266 (expand-file-name txt)))
22267 (unless (derived-mode-p 'org-mode)
22268 (error "Cannot restrict to non-Org-mode file"))
22269 (org-agenda-set-restriction-lock 'file)))
22270 (t (error "Don't know how to restrict Org-mode's agenda")))
22271 (move-overlay org-speedbar-restriction-lock-overlay
22272 (point-at-bol) (point-at-eol))
22273 (setq current-prefix-arg nil)
22274 (org-agenda-maybe-redo)))
22276 (eval-after-load "speedbar"
22277 '(progn
22278 (speedbar-add-supported-extension ".org")
22279 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22280 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22281 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22282 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22283 (add-hook 'speedbar-visiting-tag-hook
22284 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22286 ;;; Fixes and Hacks for problems with other packages
22288 ;; Make flyspell not check words in links, to not mess up our keymap
22289 (defun org-mode-flyspell-verify ()
22290 "Don't let flyspell put overlays at active buttons, or on
22291 {todo,all-time,additional-option-like}-keywords."
22292 (let ((pos (max (1- (point)) (point-min)))
22293 (word (thing-at-point 'word)))
22294 (and (not (get-text-property pos 'keymap))
22295 (not (get-text-property pos 'org-no-flyspell))
22296 (not (member word org-todo-keywords-1))
22297 (not (member word org-all-time-keywords))
22298 (not (member word org-options-keywords))
22299 (not (member word (mapcar 'car org-startup-options)))
22300 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22302 (defun org-remove-flyspell-overlays-in (beg end)
22303 "Remove flyspell overlays in region."
22304 (and (org-bound-and-true-p flyspell-mode)
22305 (fboundp 'flyspell-delete-region-overlays)
22306 (flyspell-delete-region-overlays beg end))
22307 (add-text-properties beg end '(org-no-flyspell t)))
22309 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22310 (eval-after-load "bookmark"
22311 '(if (boundp 'bookmark-after-jump-hook)
22312 ;; We can use the hook
22313 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22314 ;; Hook not available, use advice
22315 (defadvice bookmark-jump (after org-make-visible activate)
22316 "Make the position visible."
22317 (org-bookmark-jump-unhide))))
22319 ;; Make sure saveplace shows the location if it was hidden
22320 (eval-after-load "saveplace"
22321 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22322 "Make the position visible."
22323 (org-bookmark-jump-unhide)))
22325 ;; Make sure ecb shows the location if it was hidden
22326 (eval-after-load "ecb"
22327 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22328 "Make hierarchy visible when jumping into location from ECB tree buffer."
22329 (if (derived-mode-p 'org-mode)
22330 (org-show-context))))
22332 (defun org-bookmark-jump-unhide ()
22333 "Unhide the current position, to show the bookmark location."
22334 (and (derived-mode-p 'org-mode)
22335 (or (outline-invisible-p)
22336 (save-excursion (goto-char (max (point-min) (1- (point))))
22337 (outline-invisible-p)))
22338 (org-show-context 'bookmark-jump)))
22340 ;; Make session.el ignore our circular variable
22341 (eval-after-load "session"
22342 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22344 ;;;; Experimental code
22346 (defun org-closed-in-range ()
22347 "Sparse tree of items closed in a certain time range.
22348 Still experimental, may disappear in the future."
22349 (interactive)
22350 ;; Get the time interval from the user.
22351 (let* ((time1 (org-float-time
22352 (org-read-date nil 'to-time nil "Starting date: ")))
22353 (time2 (org-float-time
22354 (org-read-date nil 'to-time nil "End date:")))
22355 ;; callback function
22356 (callback (lambda ()
22357 (let ((time
22358 (org-float-time
22359 (apply 'encode-time
22360 (org-parse-time-string
22361 (match-string 1))))))
22362 ;; check if time in interval
22363 (and (>= time time1) (<= time time2))))))
22364 ;; make tree, check each match with the callback
22365 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22367 ;;;; Finish up
22369 (provide 'org)
22371 (run-hooks 'org-load-hook)
22373 ;;; org.el ends here