When pasting a copied subtree, respect the whitelines before and after
[org-mode.git] / lisp / org.el
blobab1e2ad4799d5d447e1fee528d8a24a8d2048b69
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (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 :group 'org-edit-structure
1224 :type 'boolean)
1226 (defgroup org-sparse-trees nil
1227 "Options concerning sparse trees in Org-mode."
1228 :tag "Org Sparse Trees"
1229 :group 'org-structure)
1231 (defcustom org-highlight-sparse-tree-matches t
1232 "Non-nil means highlight all matches that define a sparse tree.
1233 The highlights will automatically disappear the next time the buffer is
1234 changed by an edit command."
1235 :group 'org-sparse-trees
1236 :type 'boolean)
1238 (defcustom org-remove-highlights-with-change t
1239 "Non-nil means any change to the buffer will remove temporary highlights.
1240 Such highlights are created by `org-occur' and `org-clock-display'.
1241 When nil, `C-c C-c needs to be used to get rid of the highlights.
1242 The highlights created by `org-preview-latex-fragment' always need
1243 `C-c C-c' to be removed."
1244 :group 'org-sparse-trees
1245 :group 'org-time
1246 :type 'boolean)
1249 (defcustom org-occur-hook '(org-first-headline-recenter)
1250 "Hook that is run after `org-occur' has constructed a sparse tree.
1251 This can be used to recenter the window to show as much of the structure
1252 as possible."
1253 :group 'org-sparse-trees
1254 :type 'hook)
1256 (defgroup org-imenu-and-speedbar nil
1257 "Options concerning imenu and speedbar in Org-mode."
1258 :tag "Org Imenu and Speedbar"
1259 :group 'org-structure)
1261 (defcustom org-imenu-depth 2
1262 "The maximum level for Imenu access to Org-mode headlines.
1263 This also applied for speedbar access."
1264 :group 'org-imenu-and-speedbar
1265 :type 'integer)
1267 (defgroup org-table nil
1268 "Options concerning tables in Org-mode."
1269 :tag "Org Table"
1270 :group 'org)
1272 (defcustom org-enable-table-editor 'optimized
1273 "Non-nil means lines starting with \"|\" are handled by the table editor.
1274 When nil, such lines will be treated like ordinary lines.
1276 When equal to the symbol `optimized', the table editor will be optimized to
1277 do the following:
1278 - Automatic overwrite mode in front of whitespace in table fields.
1279 This makes the structure of the table stay in tact as long as the edited
1280 field does not exceed the column width.
1281 - Minimize the number of realigns. Normally, the table is aligned each time
1282 TAB or RET are pressed to move to another field. With optimization this
1283 happens only if changes to a field might have changed the column width.
1284 Optimization requires replacing the functions `self-insert-command',
1285 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1286 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1287 very good at guessing when a re-align will be necessary, but you can always
1288 force one with \\[org-ctrl-c-ctrl-c].
1290 If you would like to use the optimized version in Org-mode, but the
1291 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1293 This variable can be used to turn on and off the table editor during a session,
1294 but in order to toggle optimization, a restart is required.
1296 See also the variable `org-table-auto-blank-field'."
1297 :group 'org-table
1298 :type '(choice
1299 (const :tag "off" nil)
1300 (const :tag "on" t)
1301 (const :tag "on, optimized" optimized)))
1303 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1304 (version<= emacs-version "24.1"))
1305 "Non-nil means cluster self-insert commands for undo when possible.
1306 If this is set, then, like in the Emacs command loop, 20 consecutive
1307 characters will be undone together.
1308 This is configurable, because there is some impact on typing performance."
1309 :group 'org-table
1310 :type 'boolean)
1312 (defcustom org-table-tab-recognizes-table.el t
1313 "Non-nil means TAB will automatically notice a table.el table.
1314 When it sees such a table, it moves point into it and - if necessary -
1315 calls `table-recognize-table'."
1316 :group 'org-table-editing
1317 :type 'boolean)
1319 (defgroup org-link nil
1320 "Options concerning links in Org-mode."
1321 :tag "Org Link"
1322 :group 'org)
1324 (defvar org-link-abbrev-alist-local nil
1325 "Buffer-local version of `org-link-abbrev-alist', which see.
1326 The value of this is taken from the #+LINK lines.")
1327 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1329 (defcustom org-link-abbrev-alist nil
1330 "Alist of link abbreviations.
1331 The car of each element is a string, to be replaced at the start of a link.
1332 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1333 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1335 [[linkkey:tag][description]]
1337 The 'linkkey' must be a word word, starting with a letter, followed
1338 by letters, numbers, '-' or '_'.
1340 If REPLACE is a string, the tag will simply be appended to create the link.
1341 If the string contains \"%s\", the tag will be inserted there. If the string
1342 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1343 at that point (see the function `url-hexify-string'). If the string contains
1344 the specifier \"%(my-function)\", then the custom function `my-function' will
1345 be invoked: this function takes the tag as its only argument and must return
1346 a string.
1348 REPLACE may also be a function that will be called with the tag as the
1349 only argument to create the link, which should be returned as a string.
1351 See the manual for examples."
1352 :group 'org-link
1353 :type '(repeat
1354 (cons
1355 (string :tag "Protocol")
1356 (choice
1357 (string :tag "Format")
1358 (function)))))
1360 (defcustom org-descriptive-links t
1361 "Non-nil means Org will display descriptive links.
1362 E.g. [[http://orgmode.org][Org website]] will be displayed as
1363 \"Org Website\", hiding the link itself and just displaying its
1364 description. When set to `nil', Org will display the full links
1365 literally.
1367 You can interactively set the value of this variable by calling
1368 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1369 :group 'org-link
1370 :type 'boolean)
1372 (defcustom org-link-file-path-type 'adaptive
1373 "How the path name in file links should be stored.
1374 Valid values are:
1376 relative Relative to the current directory, i.e. the directory of the file
1377 into which the link is being inserted.
1378 absolute Absolute path, if possible with ~ for home directory.
1379 noabbrev Absolute path, no abbreviation of home directory.
1380 adaptive Use relative path for files in the current directory and sub-
1381 directories of it. For other files, use an absolute path."
1382 :group 'org-link
1383 :type '(choice
1384 (const relative)
1385 (const absolute)
1386 (const noabbrev)
1387 (const adaptive)))
1389 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1390 "Types of links that should be activated in Org-mode files.
1391 This is a list of symbols, each leading to the activation of a certain link
1392 type. In principle, it does not hurt to turn on most link types - there may
1393 be a small gain when turning off unused link types. The types are:
1395 bracket The recommended [[link][description]] or [[link]] links with hiding.
1396 angle Links in angular brackets that may contain whitespace like
1397 <bbdb:Carsten Dominik>.
1398 plain Plain links in normal text, no whitespace, like http://google.com.
1399 radio Text that is matched by a radio target, see manual for details.
1400 tag Tag settings in a headline (link to tag search).
1401 date Time stamps (link to calendar).
1402 footnote Footnote labels.
1404 Changing this variable requires a restart of Emacs to become effective."
1405 :group 'org-link
1406 :type '(set :greedy t
1407 (const :tag "Double bracket links" bracket)
1408 (const :tag "Angular bracket links" angle)
1409 (const :tag "Plain text links" plain)
1410 (const :tag "Radio target matches" radio)
1411 (const :tag "Tags" tag)
1412 (const :tag "Timestamps" date)
1413 (const :tag "Footnotes" footnote)))
1415 (defcustom org-make-link-description-function nil
1416 "Function to use for generating link descriptions from links.
1417 When nil, the link location will be used. This function must take
1418 two parameters: the first one is the link, the second one is the
1419 description generated by `org-insert-link'. The function should
1420 return the description to use."
1421 :group 'org-link
1422 :type 'function)
1424 (defgroup org-link-store nil
1425 "Options concerning storing links in Org-mode."
1426 :tag "Org Store Link"
1427 :group 'org-link)
1429 (defcustom org-url-hexify-p t
1430 "When non-nil, hexify URL when creating a link."
1431 :type 'boolean
1432 :version "24.3"
1433 :group 'org-link-store)
1435 (defcustom org-email-link-description-format "Email %c: %.30s"
1436 "Format of the description part of a link to an email or usenet message.
1437 The following %-escapes will be replaced by corresponding information:
1439 %F full \"From\" field
1440 %f name, taken from \"From\" field, address if no name
1441 %T full \"To\" field
1442 %t first name in \"To\" field, address if no name
1443 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1444 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1445 %s subject
1446 %d date
1447 %m message-id.
1449 You may use normal field width specification between the % and the letter.
1450 This is for example useful to limit the length of the subject.
1452 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1453 :group 'org-link-store
1454 :type 'string)
1456 (defcustom org-from-is-user-regexp
1457 (let (r1 r2)
1458 (when (and user-mail-address (not (string= user-mail-address "")))
1459 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1460 (when (and user-full-name (not (string= user-full-name "")))
1461 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1462 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1463 "Regexp matched against the \"From:\" header of an email or usenet message.
1464 It should match if the message is from the user him/herself."
1465 :group 'org-link-store
1466 :type 'regexp)
1468 (defcustom org-context-in-file-links t
1469 "Non-nil means file links from `org-store-link' contain context.
1470 A search string will be added to the file name with :: as separator and
1471 used to find the context when the link is activated by the command
1472 `org-open-at-point'. When this option is t, the entire active region
1473 will be placed in the search string of the file link. If set to a
1474 positive integer, only the first n lines of context will be stored.
1476 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1477 negates this setting for the duration of the command."
1478 :group 'org-link-store
1479 :type '(choice boolean integer))
1481 (defcustom org-keep-stored-link-after-insertion nil
1482 "Non-nil means keep link in list for entire session.
1484 The command `org-store-link' adds a link pointing to the current
1485 location to an internal list. These links accumulate during a session.
1486 The command `org-insert-link' can be used to insert links into any
1487 Org-mode file (offering completion for all stored links). When this
1488 option is nil, every link which has been inserted once using \\[org-insert-link]
1489 will be removed from the list, to make completing the unused links
1490 more efficient."
1491 :group 'org-link-store
1492 :type 'boolean)
1494 (defgroup org-link-follow nil
1495 "Options concerning following links in Org-mode."
1496 :tag "Org Follow Link"
1497 :group 'org-link)
1499 (defcustom org-link-translation-function nil
1500 "Function to translate links with different syntax to Org syntax.
1501 This can be used to translate links created for example by the Planner
1502 or emacs-wiki packages to Org syntax.
1503 The function must accept two parameters, a TYPE containing the link
1504 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1505 which is everything after the link protocol. It should return a cons
1506 with possibly modified values of type and path.
1507 Org contains a function for this, so if you set this variable to
1508 `org-translate-link-from-planner', you should be able follow many
1509 links created by planner."
1510 :group 'org-link-follow
1511 :type 'function)
1513 (defcustom org-follow-link-hook nil
1514 "Hook that is run after a link has been followed."
1515 :group 'org-link-follow
1516 :type 'hook)
1518 (defcustom org-tab-follows-link nil
1519 "Non-nil means on links TAB will follow the link.
1520 Needs to be set before org.el is loaded.
1521 This really should not be used, it does not make sense, and the
1522 implementation is bad."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-return-follows-link nil
1527 "Non-nil means on links RET will follow the link."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mouse-1-follows-link
1532 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1533 "Non-nil means mouse-1 on a link will follow the link.
1534 A longer mouse click will still set point. Does not work on XEmacs.
1535 Needs to be set before org.el is loaded."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mark-ring-length 4
1540 "Number of different positions to be recorded in the ring.
1541 Changing this requires a restart of Emacs to work correctly."
1542 :group 'org-link-follow
1543 :type 'integer)
1545 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1546 "Non-nil means internal links in Org files must exactly match a headline.
1547 When nil, the link search tries to match a phrase with all words
1548 in the search text."
1549 :group 'org-link-follow
1550 :version "24.1"
1551 :type '(choice
1552 (const :tag "Use fuzzy text search" nil)
1553 (const :tag "Match only exact headline" t)
1554 (const :tag "Match exact headline or query to create it"
1555 query-to-create)))
1557 (defcustom org-link-frame-setup
1558 '((vm . vm-visit-folder-other-frame)
1559 (vm-imap . vm-visit-imap-folder-other-frame)
1560 (gnus . org-gnus-no-new-news)
1561 (file . find-file-other-window)
1562 (wl . wl-other-frame))
1563 "Setup the frame configuration for following links.
1564 When following a link with Emacs, it may often be useful to display
1565 this link in another window or frame. This variable can be used to
1566 set this up for the different types of links.
1567 For VM, use any of
1568 `vm-visit-folder'
1569 `vm-visit-folder-other-window'
1570 `vm-visit-folder-other-frame'
1571 For Gnus, use any of
1572 `gnus'
1573 `gnus-other-frame'
1574 `org-gnus-no-new-news'
1575 For FILE, use any of
1576 `find-file'
1577 `find-file-other-window'
1578 `find-file-other-frame'
1579 For Wanderlust use any of
1580 `wl'
1581 `wl-other-frame'
1582 For the calendar, use the variable `calendar-setup'.
1583 For BBDB, it is currently only possible to display the matches in
1584 another window."
1585 :group 'org-link-follow
1586 :type '(list
1587 (cons (const vm)
1588 (choice
1589 (const vm-visit-folder)
1590 (const vm-visit-folder-other-window)
1591 (const vm-visit-folder-other-frame)))
1592 (cons (const gnus)
1593 (choice
1594 (const gnus)
1595 (const gnus-other-frame)
1596 (const org-gnus-no-new-news)))
1597 (cons (const file)
1598 (choice
1599 (const find-file)
1600 (const find-file-other-window)
1601 (const find-file-other-frame)))
1602 (cons (const wl)
1603 (choice
1604 (const wl)
1605 (const wl-other-frame)))))
1607 (defcustom org-display-internal-link-with-indirect-buffer nil
1608 "Non-nil means use indirect buffer to display infile links.
1609 Activating internal links (from one location in a file to another location
1610 in the same file) normally just jumps to the location. When the link is
1611 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1612 is displayed in
1613 another window. When this option is set, the other window actually displays
1614 an indirect buffer clone of the current buffer, to avoid any visibility
1615 changes to the current buffer."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-open-non-existing-files nil
1620 "Non-nil means `org-open-file' will open non-existing files.
1621 When nil, an error will be generated.
1622 This variable applies only to external applications because they
1623 might choke on non-existing files. If the link is to a file that
1624 will be opened in Emacs, the variable is ignored."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-directory-means-index-dot-org nil
1629 "Non-nil means a link to a directory really means to index.org.
1630 When nil, following a directory link will run dired or open a finder/explorer
1631 window on that directory."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1636 "Function and arguments to call for following mailto links.
1637 This is a list with the first element being a Lisp function, and the
1638 remaining elements being arguments to the function. In string arguments,
1639 %a will be replaced by the address, and %s will be replaced by the subject
1640 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1644 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1645 (const :tag "message-mail" (message-mail "%a" "%s"))
1646 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1648 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1649 "Non-nil means ask for confirmation before executing shell links.
1650 Shell links can be dangerous: just think about a link
1652 [[shell:rm -rf ~/*][Google Search]]
1654 This link would show up in your Org-mode document as \"Google Search\",
1655 but really it would remove your entire home directory.
1656 Therefore we advise against setting this variable to nil.
1657 Just change it to `y-or-n-p' if you want to confirm with a
1658 single keystroke rather than having to type \"yes\"."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1662 (const :tag "with y-or-n (faster)" y-or-n-p)
1663 (const :tag "no confirmation (dangerous)" nil)))
1664 (put 'org-confirm-shell-link-function
1665 'safe-local-variable
1666 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1668 (defcustom org-confirm-shell-link-not-regexp ""
1669 "A regexp to skip confirmation for shell links."
1670 :group 'org-link-follow
1671 :version "24.1"
1672 :type 'regexp)
1674 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1675 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1676 Elisp links can be dangerous: just think about a link
1678 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1680 This link would show up in your Org-mode document as \"Google Search\",
1681 but really it would remove your entire home directory.
1682 Therefore we advise against setting this variable to nil.
1683 Just change it to `y-or-n-p' if you want to confirm with a
1684 single keystroke rather than having to type \"yes\"."
1685 :group 'org-link-follow
1686 :type '(choice
1687 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1688 (const :tag "with y-or-n (faster)" y-or-n-p)
1689 (const :tag "no confirmation (dangerous)" nil)))
1690 (put 'org-confirm-shell-link-function
1691 'safe-local-variable
1692 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1694 (defcustom org-confirm-elisp-link-not-regexp ""
1695 "A regexp to skip confirmation for Elisp links."
1696 :group 'org-link-follow
1697 :version "24.1"
1698 :type 'regexp)
1700 (defconst org-file-apps-defaults-gnu
1701 '((remote . emacs)
1702 (system . mailcap)
1703 (t . mailcap))
1704 "Default file applications on a UNIX or GNU/Linux system.
1705 See `org-file-apps'.")
1707 (defconst org-file-apps-defaults-macosx
1708 '((remote . emacs)
1709 (t . "open %s")
1710 (system . "open %s")
1711 ("ps.gz" . "gv %s")
1712 ("eps.gz" . "gv %s")
1713 ("dvi" . "xdvi %s")
1714 ("fig" . "xfig %s"))
1715 "Default file applications on a MacOS X system.
1716 The system \"open\" is known as a default, but we use X11 applications
1717 for some files for which the OS does not have a good default.
1718 See `org-file-apps'.")
1720 (defconst org-file-apps-defaults-windowsnt
1721 (list
1722 '(remote . emacs)
1723 (cons t
1724 (list (if (featurep 'xemacs)
1725 'mswindows-shell-execute
1726 'w32-shell-execute)
1727 "open" 'file))
1728 (cons 'system
1729 (list (if (featurep 'xemacs)
1730 'mswindows-shell-execute
1731 'w32-shell-execute)
1732 "open" 'file)))
1733 "Default file applications on a Windows NT system.
1734 The system \"open\" is used for most files.
1735 See `org-file-apps'.")
1737 (defcustom org-file-apps
1739 (auto-mode . emacs)
1740 ("\\.mm\\'" . default)
1741 ("\\.x?html?\\'" . default)
1742 ("\\.pdf\\'" . default)
1744 "External applications for opening `file:path' items in a document.
1745 Org-mode uses system defaults for different file types, but
1746 you can use this variable to set the application for a given file
1747 extension. The entries in this list are cons cells where the car identifies
1748 files and the cdr the corresponding command. Possible values for the
1749 file identifier are
1750 \"string\" A string as a file identifier can be interpreted in different
1751 ways, depending on its contents:
1753 - Alphanumeric characters only:
1754 Match links with this file extension.
1755 Example: (\"pdf\" . \"evince %s\")
1756 to open PDFs with evince.
1758 - Regular expression: Match links where the
1759 filename matches the regexp. If you want to
1760 use groups here, use shy groups.
1762 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1763 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1764 to open *.html and *.xhtml with firefox.
1766 - Regular expression which contains (non-shy) groups:
1767 Match links where the whole link, including \"::\", and
1768 anything after that, matches the regexp.
1769 In a custom command string, %1, %2, etc. are replaced with
1770 the parts of the link that were matched by the groups.
1771 For backwards compatibility, if a command string is given
1772 that does not use any of the group matches, this case is
1773 handled identically to the second one (i.e. match against
1774 file name only).
1775 In a custom lisp form, you can access the group matches with
1776 (match-string n link).
1778 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1779 to open [[file:document.pdf::5]] with evince at page 5.
1781 `directory' Matches a directory
1782 `remote' Matches a remote file, accessible through tramp or efs.
1783 Remote files most likely should be visited through Emacs
1784 because external applications cannot handle such paths.
1785 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1786 so all files Emacs knows how to handle. Using this with
1787 command `emacs' will open most files in Emacs. Beware that this
1788 will also open html files inside Emacs, unless you add
1789 (\"html\" . default) to the list as well.
1790 t Default for files not matched by any of the other options.
1791 `system' The system command to open files, like `open' on Windows
1792 and Mac OS X, and mailcap under GNU/Linux. This is the command
1793 that will be selected if you call `C-c C-o' with a double
1794 \\[universal-argument] \\[universal-argument] prefix.
1796 Possible values for the command are:
1797 `emacs' The file will be visited by the current Emacs process.
1798 `default' Use the default application for this file type, which is the
1799 association for t in the list, most likely in the system-specific
1800 part.
1801 This can be used to overrule an unwanted setting in the
1802 system-specific variable.
1803 `system' Use the system command for opening files, like \"open\".
1804 This command is specified by the entry whose car is `system'.
1805 Most likely, the system-specific version of this variable
1806 does define this command, but you can overrule/replace it
1807 here.
1808 string A command to be executed by a shell; %s will be replaced
1809 by the path to the file.
1810 sexp A Lisp form which will be evaluated. The file path will
1811 be available in the Lisp variable `file'.
1812 For more examples, see the system specific constants
1813 `org-file-apps-defaults-macosx'
1814 `org-file-apps-defaults-windowsnt'
1815 `org-file-apps-defaults-gnu'."
1816 :group 'org-link-follow
1817 :type '(repeat
1818 (cons (choice :value ""
1819 (string :tag "Extension")
1820 (const :tag "System command to open files" system)
1821 (const :tag "Default for unrecognized files" t)
1822 (const :tag "Remote file" remote)
1823 (const :tag "Links to a directory" directory)
1824 (const :tag "Any files that have Emacs modes"
1825 auto-mode))
1826 (choice :value ""
1827 (const :tag "Visit with Emacs" emacs)
1828 (const :tag "Use default" default)
1829 (const :tag "Use the system command" system)
1830 (string :tag "Command")
1831 (sexp :tag "Lisp form")))))
1833 (defcustom org-doi-server-url "http://dx.doi.org/"
1834 "The URL of the DOI server."
1835 :type 'string
1836 :version "24.3"
1837 :group 'org-link-follow)
1839 (defgroup org-refile nil
1840 "Options concerning refiling entries in Org-mode."
1841 :tag "Org Refile"
1842 :group 'org)
1844 (defcustom org-directory "~/org"
1845 "Directory with org files.
1846 This is just a default location to look for Org files. There is no need
1847 at all to put your files into this directory. It is only used in the
1848 following situations:
1850 1. When a capture template specifies a target file that is not an
1851 absolute path. The path will then be interpreted relative to
1852 `org-directory'
1853 2. When a capture note is filed away in an interactive way (when exiting the
1854 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1855 with `org-directory' as the default path."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :group 'org-capture
1859 :type 'directory)
1861 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1862 "Default target for storing notes.
1863 Used as a fall back file for org-remember.el and org-capture.el, for
1864 templates that do not specify a target file."
1865 :group 'org-refile
1866 :group 'org-remember
1867 :group 'org-capture
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-capture
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax that
2101 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2102 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords. In this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called
2188 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2189 `C-u t' in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have
2195 actually been assigned by the user, i.e. if keywords in the configuration
2196 are followed by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `org-state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Each function gets as its single argument a property list, see
2240 `org-trigger-hook' for more information about this list.
2242 If any of the functions in this hook returns nil, the state change
2243 is blocked.")
2245 (defvar org-trigger-hook nil
2246 "Hook for functions that are triggered by a state change.
2248 Each function gets as its single argument a property list with at least
2249 the following elements:
2251 (:type type-of-change :position pos-at-entry-start
2252 :from old-state :to new-state)
2254 Depending on the type, more properties may be present.
2256 This mechanism is currently implemented for:
2258 TODO state changes
2259 ------------------
2260 :type todo-state-change
2261 :from previous state (keyword as a string), or nil, or a symbol
2262 'todo' or 'done', to indicate the general type of state.
2263 :to new state, like in :from")
2265 (defcustom org-enforce-todo-dependencies nil
2266 "Non-nil means undone TODO entries will block switching the parent to DONE.
2267 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2268 be blocked if any prior sibling is not yet done.
2269 Finally, if the parent is blocked because of ordered siblings of its own,
2270 the child will also be blocked."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-children-or-siblings-or-parent)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-enforce-todo-checkbox-dependencies nil
2282 "Non-nil means unchecked boxes will block switching the parent to DONE.
2283 When this is nil, checkboxes have no influence on switching TODO states.
2284 When non-nil, you first need to check off all check boxes before the TODO
2285 entry can be switched to DONE.
2286 This variable needs to be set before org.el is loaded, and you need to
2287 restart Emacs after a change to make the change effective. The only way
2288 to change is while Emacs is running is through the customize interface."
2289 :set (lambda (var val)
2290 (set var val)
2291 (if val
2292 (add-hook 'org-blocker-hook
2293 'org-block-todo-from-checkboxes)
2294 (remove-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)))
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-treat-insert-todo-heading-as-state-change nil
2300 "Non-nil means inserting a TODO heading is treated as state change.
2301 So when the command \\[org-insert-todo-heading] is used, state change
2302 logging will apply if appropriate. When nil, the new TODO item will
2303 be inserted directly, and no logging will take place."
2304 :group 'org-todo
2305 :type 'boolean)
2307 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2308 "Non-nil means switching TODO states with S-cursor counts as state change.
2309 This is the default behavior. However, setting this to nil allows a
2310 convenient way to select a TODO state and bypass any logging associated
2311 with that."
2312 :group 'org-todo
2313 :type 'boolean)
2315 (defcustom org-todo-state-tags-triggers nil
2316 "Tag changes that should be triggered by TODO state changes.
2317 This is a list. Each entry is
2319 (state-change (tag . flag) .......)
2321 State-change can be a string with a state, and empty string to indicate the
2322 state that has no TODO keyword, or it can be one of the symbols `todo'
2323 or `done', meaning any not-done or done state, respectively."
2324 :group 'org-todo
2325 :group 'org-tags
2326 :type '(repeat
2327 (cons (choice :tag "When changing to"
2328 (const :tag "Not-done state" todo)
2329 (const :tag "Done state" done)
2330 (string :tag "State"))
2331 (repeat
2332 (cons :tag "Tag action"
2333 (string :tag "Tag")
2334 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2336 (defcustom org-log-done nil
2337 "Information to record when a task moves to the DONE state.
2339 Possible values are:
2341 nil Don't add anything, just change the keyword
2342 time Add a time stamp to the task
2343 note Prompt for a note and add it with template `org-log-note-headings'
2345 This option can also be set with on a per-file-basis with
2347 #+STARTUP: nologdone
2348 #+STARTUP: logdone
2349 #+STARTUP: lognotedone
2351 You can have local logging settings for a subtree by setting the LOGGING
2352 property to one or more of these keywords."
2353 :group 'org-todo
2354 :group 'org-progress
2355 :type '(choice
2356 (const :tag "No logging" nil)
2357 (const :tag "Record CLOSED timestamp" time)
2358 (const :tag "Record CLOSED timestamp with note." note)))
2360 ;; Normalize old uses of org-log-done.
2361 (cond
2362 ((eq org-log-done t) (setq org-log-done 'time))
2363 ((and (listp org-log-done) (memq 'done org-log-done))
2364 (setq org-log-done 'note)))
2366 (defcustom org-log-reschedule nil
2367 "Information to record when the scheduling date of a tasks is modified.
2369 Possible values are:
2371 nil Don't add anything, just change the date
2372 time Add a time stamp to the task
2373 note Prompt for a note and add it with template `org-log-note-headings'
2375 This option can also be set with on a per-file-basis with
2377 #+STARTUP: nologreschedule
2378 #+STARTUP: logreschedule
2379 #+STARTUP: lognotereschedule"
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type '(choice
2383 (const :tag "No logging" nil)
2384 (const :tag "Record timestamp" time)
2385 (const :tag "Record timestamp with note." note)))
2387 (defcustom org-log-redeadline nil
2388 "Information to record when the deadline date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologredeadline
2399 #+STARTUP: logredeadline
2400 #+STARTUP: lognoteredeadline
2402 You can have local logging settings for a subtree by setting the LOGGING
2403 property to one or more of these keywords."
2404 :group 'org-todo
2405 :group 'org-progress
2406 :type '(choice
2407 (const :tag "No logging" nil)
2408 (const :tag "Record timestamp" time)
2409 (const :tag "Record timestamp with note." note)))
2411 (defcustom org-log-note-clock-out nil
2412 "Non-nil means record a note when clocking out of an item.
2413 This can also be configured on a per-file basis by adding one of
2414 the following lines anywhere in the buffer:
2416 #+STARTUP: lognoteclock-out
2417 #+STARTUP: nolognoteclock-out"
2418 :group 'org-todo
2419 :group 'org-progress
2420 :type 'boolean)
2422 (defcustom org-log-done-with-time t
2423 "Non-nil means the CLOSED time stamp will contain date and time.
2424 When nil, only the date will be recorded."
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-log-note-headings
2429 '((done . "CLOSING NOTE %t")
2430 (state . "State %-12s from %-12S %t")
2431 (note . "Note taken on %t")
2432 (reschedule . "Rescheduled from %S on %t")
2433 (delschedule . "Not scheduled, was %S on %t")
2434 (redeadline . "New deadline from %S on %t")
2435 (deldeadline . "Removed deadline, was %S on %t")
2436 (refile . "Refiled on %t")
2437 (clock-out . ""))
2438 "Headings for notes added to entries.
2439 The value is an alist, with the car being a symbol indicating the note
2440 context, and the cdr is the heading to be used. The heading may also be the
2441 empty string.
2442 %t in the heading will be replaced by a time stamp.
2443 %T will be an active time stamp instead the default inactive one
2444 %d will be replaced by a short-format time stamp.
2445 %D will be replaced by an active short-format time stamp.
2446 %s will be replaced by the new TODO state, in double quotes.
2447 %S will be replaced by the old TODO state, in double quotes.
2448 %u will be replaced by the user name.
2449 %U will be replaced by the full user name.
2451 In fact, it is not a good idea to change the `state' entry, because
2452 agenda log mode depends on the format of these entries."
2453 :group 'org-todo
2454 :group 'org-progress
2455 :type '(list :greedy t
2456 (cons (const :tag "Heading when closing an item" done) string)
2457 (cons (const :tag
2458 "Heading when changing todo state (todo sequence only)"
2459 state) string)
2460 (cons (const :tag "Heading when just taking a note" note) string)
2461 (cons (const :tag "Heading when clocking out" clock-out) string)
2462 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2463 (cons (const :tag "Heading when rescheduling" reschedule) string)
2464 (cons (const :tag "Heading when changing deadline" redeadline) string)
2465 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2466 (cons (const :tag "Heading when refiling" refile) string)))
2468 (unless (assq 'note org-log-note-headings)
2469 (push '(note . "%t") org-log-note-headings))
2471 (defcustom org-log-into-drawer nil
2472 "Non-nil means insert state change notes and time stamps into a drawer.
2473 When nil, state changes notes will be inserted after the headline and
2474 any scheduling and clock lines, but not inside a drawer.
2476 The value of this variable should be the name of the drawer to use.
2477 LOGBOOK is proposed as the default drawer for this purpose, you can
2478 also set this to a string to define the drawer of your choice.
2480 A value of t is also allowed, representing \"LOGBOOK\".
2482 If this variable is set, `org-log-state-notes-insert-after-drawers'
2483 will be ignored.
2485 You can set the property LOG_INTO_DRAWER to overrule this setting for
2486 a subtree."
2487 :group 'org-todo
2488 :group 'org-progress
2489 :type '(choice
2490 (const :tag "Not into a drawer" nil)
2491 (const :tag "LOGBOOK" t)
2492 (string :tag "Other")))
2494 (if (fboundp 'defvaralias)
2495 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2497 (defun org-log-into-drawer ()
2498 "Return the value of `org-log-into-drawer', but let properties overrule.
2499 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2500 used instead of the default value."
2501 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2502 (cond
2503 ((not p) org-log-into-drawer)
2504 ((equal p "nil") nil)
2505 ((equal p "t") "LOGBOOK")
2506 (t p))))
2508 (defcustom org-log-state-notes-insert-after-drawers nil
2509 "Non-nil means insert state change notes after any drawers in entry.
2510 Only the drawers that *immediately* follow the headline and the
2511 deadline/scheduled line are skipped.
2512 When nil, insert notes right after the heading and perhaps the line
2513 with deadline/scheduling if present.
2515 This variable will have no effect if `org-log-into-drawer' is
2516 set."
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type 'boolean)
2521 (defcustom org-log-states-order-reversed t
2522 "Non-nil means the latest state note will be directly after heading.
2523 When nil, the state change notes will be ordered according to time."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type 'boolean)
2528 (defcustom org-todo-repeat-to-state nil
2529 "The TODO state to which a repeater should return the repeating task.
2530 By default this is the first task in a TODO sequence, or the previous state
2531 in a TODO_TYP set. But you can specify another task here.
2532 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2533 :group 'org-todo
2534 :version "24.1"
2535 :type '(choice (const :tag "Head of sequence" nil)
2536 (string :tag "Specific state")))
2538 (defcustom org-log-repeat 'time
2539 "Non-nil means record moving through the DONE state when triggering repeat.
2540 An auto-repeating task is immediately switched back to TODO when
2541 marked DONE. If you are not logging state changes (by adding \"@\"
2542 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2543 record a closing note, there will be no record of the task moving
2544 through DONE. This variable forces taking a note anyway.
2546 nil Don't force a record
2547 time Record a time stamp
2548 note Prompt for a note and add it with template `org-log-note-headings'
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: nologrepeat
2553 #+STARTUP: logrepeat
2554 #+STARTUP: lognoterepeat
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "Don't force a record" nil)
2562 (const :tag "Force recording the DONE state" time)
2563 (const :tag "Force recording a note with the DONE state" note)))
2566 (defgroup org-priorities nil
2567 "Priorities in Org-mode."
2568 :tag "Org Priorities"
2569 :group 'org-todo)
2571 (defcustom org-enable-priority-commands t
2572 "Non-nil means priority commands are active.
2573 When nil, these commands will be disabled, so that you never accidentally
2574 set a priority."
2575 :group 'org-priorities
2576 :type 'boolean)
2578 (defcustom org-highest-priority ?A
2579 "The highest priority of TODO items. A character like ?A, ?B etc.
2580 Must have a smaller ASCII number than `org-lowest-priority'."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-lowest-priority ?C
2585 "The lowest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a larger ASCII number than `org-highest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-default-priority ?B
2591 "The default priority of TODO items.
2592 This is the priority an item gets if no explicit priority is given.
2593 When starting to cycle on an empty priority the first step in the cycle
2594 depends on `org-priority-start-cycle-with-default'. The resulting first
2595 step priority must not exceed the range from `org-highest-priority' to
2596 `org-lowest-priority' which means that `org-default-priority' has to be
2597 in this range exclusive or inclusive the range boundaries. Else the
2598 first step refuses to set the default and the second will fall back
2599 to (depending on the command used) the highest or lowest priority."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-priority-start-cycle-with-default t
2604 "Non-nil means start with default priority when starting to cycle.
2605 When this is nil, the first step in the cycle will be (depending on the
2606 command used) one higher or lower than the default priority.
2607 See also `org-default-priority'."
2608 :group 'org-priorities
2609 :type 'boolean)
2611 (defcustom org-get-priority-function nil
2612 "Function to extract the priority from a string.
2613 The string is normally the headline. If this is nil Org computes the
2614 priority from the priority cookie like [#A] in the headline. It returns
2615 an integer, increasing by 1000 for each priority level.
2616 The user can set a different function here, which should take a string
2617 as an argument and return the numeric priority."
2618 :group 'org-priorities
2619 :version "24.1"
2620 :type 'function)
2622 (defgroup org-time nil
2623 "Options concerning time stamps and deadlines in Org-mode."
2624 :tag "Org Time"
2625 :group 'org)
2627 (defcustom org-insert-labeled-timestamps-at-point nil
2628 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2629 When nil, these labeled time stamps are forces into the second line of an
2630 entry, just after the headline. When scheduling from the global TODO list,
2631 the time stamp will always be forced into the second line."
2632 :group 'org-time
2633 :type 'boolean)
2635 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2636 "Formats for `format-time-string' which are used for time stamps.
2637 It is not recommended to change this constant.")
2639 (defcustom org-time-stamp-rounding-minutes '(0 5)
2640 "Number of minutes to round time stamps to.
2641 These are two values, the first applies when first creating a time stamp.
2642 The second applies when changing it with the commands `S-up' and `S-down'.
2643 When changing the time stamp, this means that it will change in steps
2644 of N minutes, as given by the second value.
2646 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2647 numbers should be factors of 60, so for example 5, 10, 15.
2649 When this is larger than 1, you can still force an exact time stamp by using
2650 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2651 and by using a prefix arg to `S-up/down' to specify the exact number
2652 of minutes to shift."
2653 :group 'org-time
2654 :get #'(lambda (var) ; Make sure both elements are there
2655 (if (integerp (default-value var))
2656 (list (default-value var) 5)
2657 (default-value var)))
2658 :type '(list
2659 (integer :tag "when inserting times")
2660 (integer :tag "when modifying times")))
2662 ;; Normalize old customizations of this variable.
2663 (when (integerp org-time-stamp-rounding-minutes)
2664 (setq org-time-stamp-rounding-minutes
2665 (list org-time-stamp-rounding-minutes
2666 org-time-stamp-rounding-minutes)))
2668 (defcustom org-display-custom-times nil
2669 "Non-nil means overlay custom formats over all time stamps.
2670 The formats are defined through the variable `org-time-stamp-custom-formats'.
2671 To turn this on on a per-file basis, insert anywhere in the file:
2672 #+STARTUP: customtime"
2673 :group 'org-time
2674 :set 'set-default
2675 :type 'sexp)
2676 (make-variable-buffer-local 'org-display-custom-times)
2678 (defcustom org-time-stamp-custom-formats
2679 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2680 "Custom formats for time stamps. See `format-time-string' for the syntax.
2681 These are overlaid over the default ISO format if the variable
2682 `org-display-custom-times' is set. Time like %H:%M should be at the
2683 end of the second format. The custom formats are also honored by export
2684 commands, if custom time display is turned on at the time of export."
2685 :group 'org-time
2686 :type 'sexp)
2688 (defun org-time-stamp-format (&optional long inactive)
2689 "Get the right format for a time string."
2690 (let ((f (if long (cdr org-time-stamp-formats)
2691 (car org-time-stamp-formats))))
2692 (if inactive
2693 (concat "[" (substring f 1 -1) "]")
2694 f)))
2696 (defcustom org-time-clocksum-format "%d:%02d"
2697 "The format string used when creating CLOCKSUM lines.
2698 This is also used when org-mode generates a time duration."
2699 :group 'org-time
2700 :type 'string)
2702 (defcustom org-time-clocksum-use-fractional nil
2703 "If non-nil, \\[org-clock-display] uses fractional times.
2704 org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'boolean)
2708 (defcustom org-time-clocksum-fractional-format "%.2f"
2709 "The format string used when creating CLOCKSUM lines, or when
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-deadline-warning-days 14
2715 "No. of days before expiration during which a deadline becomes active.
2716 This variable governs the display in sparse trees and in the agenda.
2717 When 0 or negative, it means use this number (the absolute value of it)
2718 even if a deadline has a different individual lead time specified.
2720 Custom commands can set this variable in the options section."
2721 :group 'org-time
2722 :group 'org-agenda-daily/weekly
2723 :type 'integer)
2725 (defcustom org-read-date-prefer-future t
2726 "Non-nil means assume future for incomplete date input from user.
2727 This affects the following situations:
2728 1. The user gives a month but not a year.
2729 For example, if it is April and you enter \"feb 2\", this will be read
2730 as Feb 2, *next* year. \"May 5\", however, will be this year.
2731 2. The user gives a day, but no month.
2732 For example, if today is the 15th, and you enter \"3\", Org-mode will
2733 read this as the third of *next* month. However, if you enter \"17\",
2734 it will be considered as *this* month.
2736 If you set this variable to the symbol `time', then also the following
2737 will work:
2739 3. If the user gives a time.
2740 If the time is before now, it will be interpreted as tomorrow.
2742 Currently none of this works for ISO week specifications.
2744 When this option is nil, the current day, month and year will always be
2745 used as defaults.
2747 See also `org-agenda-jump-prefer-future'."
2748 :group 'org-time
2749 :type '(choice
2750 (const :tag "Never" nil)
2751 (const :tag "Check month and day" t)
2752 (const :tag "Check month, day, and time" time)))
2754 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2755 "Should the agenda jump command prefer the future for incomplete dates?
2756 The default is to do the same as configured in `org-read-date-prefer-future'.
2757 But you can also set a deviating value here.
2758 This may t or nil, or the symbol `org-read-date-prefer-future'."
2759 :group 'org-agenda
2760 :group 'org-time
2761 :version "24.1"
2762 :type '(choice
2763 (const :tag "Use org-read-date-prefer-future"
2764 org-read-date-prefer-future)
2765 (const :tag "Never" nil)
2766 (const :tag "Always" t)))
2768 (defcustom org-read-date-force-compatible-dates t
2769 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2771 Depending on the system Emacs is running on, certain dates cannot
2772 be represented with the type used internally to represent time.
2773 Dates between 1970-1-1 and 2038-1-1 can always be represented
2774 correctly. Some systems allow for earlier dates, some for later,
2775 some for both. One way to find out it to insert any date into an
2776 Org buffer, putting the cursor on the year and hitting S-up and
2777 S-down to test the range.
2779 When this variable is set to t, the date/time prompt will not let
2780 you specify dates outside the 1970-2037 range, so it is certain that
2781 these dates will work in whatever version of Emacs you are
2782 running, and also that you can move a file from one Emacs implementation
2783 to another. WHenever Org is forcing the year for you, it will display
2784 a message and beep.
2786 When this variable is nil, Org will check if the date is
2787 representable in the specific Emacs implementation you are using.
2788 If not, it will force a year, usually the current year, and beep
2789 to remind you. Currently this setting is not recommended because
2790 the likelihood that you will open your Org files in an Emacs that
2791 has limited date range is not negligible.
2793 A workaround for this problem is to use diary sexp dates for time
2794 stamps outside of this range."
2795 :group 'org-time
2796 :version "24.1"
2797 :type 'boolean)
2799 (defcustom org-read-date-display-live t
2800 "Non-nil means display current interpretation of date prompt live.
2801 This display will be in an overlay, in the minibuffer."
2802 :group 'org-time
2803 :type 'boolean)
2805 (defcustom org-read-date-popup-calendar t
2806 "Non-nil means pop up a calendar when prompting for a date.
2807 In the calendar, the date can be selected with mouse-1. However, the
2808 minibuffer will also be active, and you can simply enter the date as well.
2809 When nil, only the minibuffer will be available."
2810 :group 'org-time
2811 :type 'boolean)
2812 (if (fboundp 'defvaralias)
2813 (defvaralias 'org-popup-calendar-for-date-prompt
2814 'org-read-date-popup-calendar))
2816 (defcustom org-read-date-minibuffer-setup-hook nil
2817 "Hook to be used to set up keys for the date/time interface.
2818 Add key definitions to `minibuffer-local-map', which will be a temporary
2819 copy."
2820 :group 'org-time
2821 :type 'hook)
2823 (defcustom org-extend-today-until 0
2824 "The hour when your day really ends. Must be an integer.
2825 This has influence for the following applications:
2826 - When switching the agenda to \"today\". It it is still earlier than
2827 the time given here, the day recognized as TODAY is actually yesterday.
2828 - When a date is read from the user and it is still before the time given
2829 here, the current date and time will be assumed to be yesterday, 23:59.
2830 Also, timestamps inserted in capture templates follow this rule.
2832 IMPORTANT: This is a feature whose implementation is and likely will
2833 remain incomplete. Really, it is only here because past midnight seems to
2834 be the favorite working time of John Wiegley :-)"
2835 :group 'org-time
2836 :type 'integer)
2838 (defcustom org-use-effective-time nil
2839 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2840 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2841 \"effective time\" of any timestamps between midnight and 8am will be
2842 23:59 of the previous day."
2843 :group 'org-time
2844 :version "24.1"
2845 :type 'boolean)
2847 (defcustom org-edit-timestamp-down-means-later nil
2848 "Non-nil means S-down will increase the time in a time stamp.
2849 When nil, S-up will increase."
2850 :group 'org-time
2851 :type 'boolean)
2853 (defcustom org-calendar-follow-timestamp-change t
2854 "Non-nil means make the calendar window follow timestamp changes.
2855 When a timestamp is modified and the calendar window is visible, it will be
2856 moved to the new date."
2857 :group 'org-time
2858 :type 'boolean)
2860 (defgroup org-tags nil
2861 "Options concerning tags in Org-mode."
2862 :tag "Org Tags"
2863 :group 'org)
2865 (defcustom org-tag-alist nil
2866 "List of tags allowed in Org-mode files.
2867 When this list is nil, Org-mode will base TAG input on what is already in the
2868 buffer.
2869 The value of this variable is an alist, the car of each entry must be a
2870 keyword as a string, the cdr may be a character that is used to select
2871 that tag through the fast-tag-selection interface.
2872 See the manual for details."
2873 :group 'org-tags
2874 :type '(repeat
2875 (choice
2876 (cons (string :tag "Tag name")
2877 (character :tag "Access char"))
2878 (list :tag "Start radio group"
2879 (const :startgroup)
2880 (option (string :tag "Group description")))
2881 (list :tag "End radio group"
2882 (const :endgroup)
2883 (option (string :tag "Group description")))
2884 (const :tag "New line" (:newline)))))
2886 (defcustom org-tag-persistent-alist nil
2887 "List of tags that will always appear in all Org-mode files.
2888 This is in addition to any in buffer settings or customizations
2889 of `org-tag-alist'.
2890 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2891 The value of this variable is an alist, the car of each entry must be a
2892 keyword as a string, the cdr may be a character that is used to select
2893 that tag through the fast-tag-selection interface.
2894 See the manual for details.
2895 To disable these tags on a per-file basis, insert anywhere in the file:
2896 #+STARTUP: noptag"
2897 :group 'org-tags
2898 :type '(repeat
2899 (choice
2900 (cons (string :tag "Tag name")
2901 (character :tag "Access char"))
2902 (const :tag "Start radio group" (:startgroup))
2903 (const :tag "End radio group" (:endgroup))
2904 (const :tag "New line" (:newline)))))
2906 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2907 "If non-nil, always offer completion for all tags of all agenda files.
2908 Instead of customizing this variable directly, you might want to
2909 set it locally for capture buffers, because there no list of
2910 tags in that file can be created dynamically (there are none).
2912 (add-hook 'org-capture-mode-hook
2913 (lambda ()
2914 (set (make-local-variable
2915 'org-complete-tags-always-offer-all-agenda-tags)
2916 t)))"
2917 :group 'org-tags
2918 :version "24.1"
2919 :type 'boolean)
2921 (defvar org-file-tags nil
2922 "List of tags that can be inherited by all entries in the file.
2923 The tags will be inherited if the variable `org-use-tag-inheritance'
2924 says they should be.
2925 This variable is populated from #+FILETAGS lines.")
2927 (defcustom org-use-fast-tag-selection 'auto
2928 "Non-nil means use fast tag selection scheme.
2929 This is a special interface to select and deselect tags with single keys.
2930 When nil, fast selection is never used.
2931 When the symbol `auto', fast selection is used if and only if selection
2932 characters for tags have been configured, either through the variable
2933 `org-tag-alist' or through a #+TAGS line in the buffer.
2934 When t, fast selection is always used and selection keys are assigned
2935 automatically if necessary."
2936 :group 'org-tags
2937 :type '(choice
2938 (const :tag "Always" t)
2939 (const :tag "Never" nil)
2940 (const :tag "When selection characters are configured" 'auto)))
2942 (defcustom org-fast-tag-selection-single-key nil
2943 "Non-nil means fast tag selection exits after first change.
2944 When nil, you have to press RET to exit it.
2945 During fast tag selection, you can toggle this flag with `C-c'.
2946 This variable can also have the value `expert'. In this case, the window
2947 displaying the tags menu is not even shown, until you press C-c again."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "No" nil)
2951 (const :tag "Yes" t)
2952 (const :tag "Expert" expert)))
2954 (defvar org-fast-tag-selection-include-todo nil
2955 "Non-nil means fast tags selection interface will also offer TODO states.
2956 This is an undocumented feature, you should not rely on it.")
2958 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2959 "The column to which tags should be indented in a headline.
2960 If this number is positive, it specifies the column. If it is negative,
2961 it means that the tags should be flushright to that column. For example,
2962 -80 works well for a normal 80 character screen.
2963 When 0, place tags directly after headline text, with only one space in
2964 between."
2965 :group 'org-tags
2966 :type 'integer)
2968 (defcustom org-auto-align-tags t
2969 "Non-nil keeps tags aligned when modifying headlines.
2970 Some operations (i.e. demoting) change the length of a headline and
2971 therefore shift the tags around. With this option turned on, after
2972 each such operation the tags are again aligned to `org-tags-column'."
2973 :group 'org-tags
2974 :type 'boolean)
2976 (defcustom org-use-tag-inheritance t
2977 "Non-nil means tags in levels apply also for sublevels.
2978 When nil, only the tags directly given in a specific line apply there.
2979 This may also be a list of tags that should be inherited, or a regexp that
2980 matches tags that should be inherited. Additional control is possible
2981 with the variable `org-tags-exclude-from-inheritance' which gives an
2982 explicit list of tags to be excluded from inheritance., even if the value of
2983 `org-use-tag-inheritance' would select it for inheritance.
2985 If this option is t, a match early-on in a tree can lead to a large
2986 number of matches in the subtree when constructing the agenda or creating
2987 a sparse tree. If you only want to see the first match in a tree during
2988 a search, check out the variable `org-tags-match-list-sublevels'."
2989 :group 'org-tags
2990 :type '(choice
2991 (const :tag "Not" nil)
2992 (const :tag "Always" t)
2993 (repeat :tag "Specific tags" (string :tag "Tag"))
2994 (regexp :tag "Tags matched by regexp")))
2996 (defcustom org-tags-exclude-from-inheritance nil
2997 "List of tags that should never be inherited.
2998 This is a way to exclude a few tags from inheritance. For way to do
2999 the opposite, to actively allow inheritance for selected tags,
3000 see the variable `org-use-tag-inheritance'."
3001 :group 'org-tags
3002 :type '(repeat (string :tag "Tag")))
3004 (defun org-tag-inherit-p (tag)
3005 "Check if TAG is one that should be inherited."
3006 (cond
3007 ((member tag org-tags-exclude-from-inheritance) nil)
3008 ((eq org-use-tag-inheritance t) t)
3009 ((not org-use-tag-inheritance) nil)
3010 ((stringp org-use-tag-inheritance)
3011 (string-match org-use-tag-inheritance tag))
3012 ((listp org-use-tag-inheritance)
3013 (member tag org-use-tag-inheritance))
3014 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3016 (defcustom org-tags-match-list-sublevels t
3017 "Non-nil means list also sublevels of headlines matching a search.
3018 This variable applies to tags/property searches, and also to stuck
3019 projects because this search is based on a tags match as well.
3021 When set to the symbol `indented', sublevels are indented with
3022 leading dots.
3024 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3025 the sublevels of a headline matching a tag search often also match
3026 the same search. Listing all of them can create very long lists.
3027 Setting this variable to nil causes subtrees of a match to be skipped.
3029 This variable is semi-obsolete and probably should always be true. It
3030 is better to limit inheritance to certain tags using the variables
3031 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3032 :group 'org-tags
3033 :type '(choice
3034 (const :tag "No, don't list them" nil)
3035 (const :tag "Yes, do list them" t)
3036 (const :tag "List them, indented with leading dots" indented)))
3038 (defcustom org-tags-sort-function nil
3039 "When set, tags are sorted using this function as a comparator."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No sorting" nil)
3043 (const :tag "Alphabetical" string<)
3044 (const :tag "Reverse alphabetical" string>)
3045 (function :tag "Custom function" nil)))
3047 (defvar org-tags-history nil
3048 "History of minibuffer reads for tags.")
3049 (defvar org-last-tags-completion-table nil
3050 "The last used completion table for tags.")
3051 (defvar org-after-tags-change-hook nil
3052 "Hook that is run after the tags in a line have changed.")
3054 (defgroup org-properties nil
3055 "Options concerning properties in Org-mode."
3056 :tag "Org Properties"
3057 :group 'org)
3059 (defcustom org-property-format "%-10s %s"
3060 "How property key/value pairs should be formatted by `indent-line'.
3061 When `indent-line' hits a property definition, it will format the line
3062 according to this format, mainly to make sure that the values are
3063 lined-up with respect to each other."
3064 :group 'org-properties
3065 :type 'string)
3067 (defcustom org-properties-postprocess-alist nil
3068 "Alist of properties and functions to adjust inserted values.
3069 Elements of this alist must be of the form
3071 ([string] [function])
3073 where [string] must be a property name and [function] must be a
3074 lambda expression: this lambda expression must take one argument,
3075 the value to adjust, and return the new value as a string.
3077 For example, this element will allow the property \"Remaining\"
3078 to be updated wrt the relation between the \"Effort\" property
3079 and the clock summary:
3081 ((\"Remaining\" (lambda(value)
3082 (let ((clocksum (org-clock-sum-current-item))
3083 (effort (org-duration-string-to-minutes
3084 (org-entry-get (point) \"Effort\"))))
3085 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3086 :group 'org-properties
3087 :version "24.1"
3088 :type '(alist :key-type (string :tag "Property")
3089 :value-type (function :tag "Function")))
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-insert-diary-entry-key [?i]
3287 "The key to be installed in `calendar-mode-map' for adding diary entries.
3288 This option is irrelevant until `org-agenda-diary-file' has been configured
3289 to point to an Org-mode file. When that is the case, the command
3290 `org-agenda-diary-entry' will be bound to the key given here, by default
3291 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3292 if you want to continue doing this, you need to change this to a different
3293 key."
3294 :group 'org-agenda
3295 :type 'sexp)
3297 (defcustom org-agenda-diary-file 'diary-file
3298 "File to which to add new entries with the `i' key in agenda and calendar.
3299 When this is the symbol `diary-file', the functionality in the Emacs
3300 calendar will be used to add entries to the `diary-file'. But when this
3301 points to a file, `org-agenda-diary-entry' will be used instead."
3302 :group 'org-agenda
3303 :type '(choice
3304 (const :tag "The standard Emacs diary file" diary-file)
3305 (file :tag "Special Org file diary entries")))
3307 (eval-after-load "calendar"
3308 '(progn
3309 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3310 'org-calendar-goto-agenda)
3311 (add-hook 'calendar-mode-hook
3312 (lambda ()
3313 (unless (eq org-agenda-diary-file 'diary-file)
3314 (define-key calendar-mode-map
3315 org-calendar-insert-diary-entry-key
3316 'org-agenda-diary-entry))))))
3318 (defgroup org-latex nil
3319 "Options for embedding LaTeX code into Org-mode."
3320 :tag "Org LaTeX"
3321 :group 'org)
3323 (defcustom org-format-latex-options
3324 '(:foreground default :background default :scale 1.0
3325 :html-foreground "Black" :html-background "Transparent"
3326 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3327 "Options for creating images from LaTeX fragments.
3328 This is a property list with the following properties:
3329 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3330 `default' means use the foreground of the default face.
3331 :background the background color, or \"Transparent\".
3332 `default' means use the background of the default face.
3333 :scale a scaling factor for the size of the images, to get more pixels
3334 :html-foreground, :html-background, :html-scale
3335 the same numbers for HTML export.
3336 :matchers a list indicating which matchers should be used to
3337 find LaTeX fragments. Valid members of this list are:
3338 \"begin\" find environments
3339 \"$1\" find single characters surrounded by $.$
3340 \"$\" find math expressions surrounded by $...$
3341 \"$$\" find math expressions surrounded by $$....$$
3342 \"\\(\" find math expressions surrounded by \\(...\\)
3343 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3344 :group 'org-latex
3345 :type 'plist)
3347 (defcustom org-format-latex-signal-error t
3348 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3349 When nil, just push out a message."
3350 :group 'org-latex
3351 :version "24.1"
3352 :type 'boolean)
3354 (defcustom org-latex-to-mathml-jar-file nil
3355 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3356 Use this to specify additional executable file say a jar file.
3358 When using MathToWeb as the converter, specify the full-path to
3359 your mathtoweb.jar file."
3360 :group 'org-latex
3361 :version "24.1"
3362 :type '(choice
3363 (const :tag "None" nil)
3364 (file :tag "JAR file" :must-match t)))
3366 (defcustom org-latex-to-mathml-convert-command nil
3367 "Command to convert LaTeX fragments to MathML.
3368 Replace format-specifiers in the command as noted below and use
3369 `shell-command' to convert LaTeX to MathML.
3370 %j: Executable file in fully expanded form as specified by
3371 `org-latex-to-mathml-jar-file'.
3372 %I: Input LaTeX file in fully expanded form
3373 %o: Output MathML file
3374 This command is used by `org-create-math-formula'.
3376 When using MathToWeb as the converter, set this to
3377 \"java -jar %j -unicode -force -df %o %I\"."
3378 :group 'org-latex
3379 :version "24.1"
3380 :type '(choice
3381 (const :tag "None" nil)
3382 (string :tag "\nShell command")))
3384 (defcustom org-latex-create-formula-image-program 'dvipng
3385 "Program to convert LaTeX fragments with.
3387 dvipng Process the LaTeX fragments to dvi file, then convert
3388 dvi files to png files using dvipng.
3389 This will also include processing of non-math environments.
3390 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3391 to convert pdf files to png files"
3392 :group 'org-latex
3393 :version "24.1"
3394 :type '(choice
3395 (const :tag "dvipng" dvipng)
3396 (const :tag "imagemagick" imagemagick)))
3398 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3399 "Path to store latex preview images. A relative path here creates many
3400 directories relative to the processed org files paths. An absolute path
3401 puts all preview images at the same place."
3402 :group 'org-latex
3403 :version "24.3"
3404 :type 'string)
3406 (defun org-format-latex-mathml-available-p ()
3407 "Return t if `org-latex-to-mathml-convert-command' is usable."
3408 (save-match-data
3409 (when (and (boundp 'org-latex-to-mathml-convert-command)
3410 org-latex-to-mathml-convert-command)
3411 (let ((executable (car (split-string
3412 org-latex-to-mathml-convert-command))))
3413 (when (executable-find executable)
3414 (if (string-match
3415 "%j" org-latex-to-mathml-convert-command)
3416 (file-readable-p org-latex-to-mathml-jar-file)
3417 t))))))
3419 (defcustom org-format-latex-header "\\documentclass{article}
3420 \\usepackage[usenames]{color}
3421 \\usepackage{amsmath}
3422 \\usepackage[mathscr]{eucal}
3423 \\pagestyle{empty} % do not remove
3424 \[PACKAGES]
3425 \[DEFAULT-PACKAGES]
3426 % The settings below are copied from fullpage.sty
3427 \\setlength{\\textwidth}{\\paperwidth}
3428 \\addtolength{\\textwidth}{-3cm}
3429 \\setlength{\\oddsidemargin}{1.5cm}
3430 \\addtolength{\\oddsidemargin}{-2.54cm}
3431 \\setlength{\\evensidemargin}{\\oddsidemargin}
3432 \\setlength{\\textheight}{\\paperheight}
3433 \\addtolength{\\textheight}{-\\headheight}
3434 \\addtolength{\\textheight}{-\\headsep}
3435 \\addtolength{\\textheight}{-\\footskip}
3436 \\addtolength{\\textheight}{-3cm}
3437 \\setlength{\\topmargin}{1.5cm}
3438 \\addtolength{\\topmargin}{-2.54cm}"
3439 "The document header used for processing LaTeX fragments.
3440 It is imperative that this header make sure that no page number
3441 appears on the page. The package defined in the variables
3442 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3443 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3444 will be appended."
3445 :group 'org-latex
3446 :type 'string)
3448 (defvar org-format-latex-header-extra nil)
3450 (defun org-set-packages-alist (var val)
3451 "Set the packages alist and make sure it has 3 elements per entry."
3452 (set var (mapcar (lambda (x)
3453 (if (and (consp x) (= (length x) 2))
3454 (list (car x) (nth 1 x) t)
3456 val)))
3458 (defun org-get-packages-alist (var)
3460 "Get the packages alist and make sure it has 3 elements per entry."
3461 (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 (default-value var)))
3467 ;; The following variables are defined here because is it also used
3468 ;; when formatting latex fragments. Originally it was part of the
3469 ;; LaTeX exporter, which is why the name includes "export".
3470 (defcustom org-export-latex-default-packages-alist
3471 '(("AUTO" "inputenc" t)
3472 ("T1" "fontenc" t)
3473 ("" "fixltx2e" nil)
3474 ("" "graphicx" t)
3475 ("" "longtable" nil)
3476 ("" "float" nil)
3477 ("" "wrapfig" nil)
3478 ("" "soul" t)
3479 ("" "textcomp" t)
3480 ("" "marvosym" t)
3481 ("" "wasysym" t)
3482 ("" "latexsym" t)
3483 ("" "amssymb" t)
3484 ("" "hyperref" nil)
3485 "\\tolerance=1000"
3487 "Alist of default packages to be inserted in the header.
3488 Change this only if one of the packages here causes an incompatibility
3489 with another package you are using.
3490 The packages in this list are needed by one part or another of Org-mode
3491 to function properly.
3493 - inputenc, fontenc: for basic font and character selection
3494 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3495 for interpreting the entities in `org-entities'. You can skip some of these
3496 packages if you don't use any of the symbols in it.
3497 - graphicx: for including images
3498 - float, wrapfig: for figure placement
3499 - longtable: for long tables
3500 - hyperref: for cross references
3502 Therefore you should not modify this variable unless you know what you
3503 are doing. The one reason to change it anyway is that you might be loading
3504 some other package that conflicts with one of the default packages.
3505 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3506 If SNIPPET-FLAG is t, the package also needs to be included when
3507 compiling LaTeX snippets into images for inclusion into HTML."
3508 :group 'org-export-latex
3509 :set 'org-set-packages-alist
3510 :get 'org-get-packages-alist
3511 :version "24.1"
3512 :type '(repeat
3513 (choice
3514 (list :tag "options/package pair"
3515 (string :tag "options")
3516 (string :tag "package")
3517 (boolean :tag "Snippet"))
3518 (string :tag "A line of LaTeX"))))
3520 (defcustom org-export-latex-packages-alist nil
3521 "Alist of packages to be inserted in every LaTeX header.
3522 These will be inserted after `org-export-latex-default-packages-alist'.
3523 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3524 SNIPPET-FLAG, when t, indicates that this package is also needed when
3525 turning LaTeX snippets into images for inclusion into HTML.
3526 Make sure that you only list packages here which:
3527 - you want in every file
3528 - do not conflict with the default packages in
3529 `org-export-latex-default-packages-alist'
3530 - do not conflict with the setup in `org-format-latex-header'."
3531 :group 'org-export-latex
3532 :set 'org-set-packages-alist
3533 :get 'org-get-packages-alist
3534 :type '(repeat
3535 (choice
3536 (list :tag "options/package pair"
3537 (string :tag "options")
3538 (string :tag "package")
3539 (boolean :tag "Snippet"))
3540 (string :tag "A line of LaTeX"))))
3543 (defgroup org-appearance nil
3544 "Settings for Org-mode appearance."
3545 :tag "Org Appearance"
3546 :group 'org)
3548 (defcustom org-level-color-stars-only nil
3549 "Non-nil means fontify only the stars in each headline.
3550 When nil, the entire headline is fontified.
3551 Changing it requires restart of `font-lock-mode' to become effective
3552 also in regions already fontified."
3553 :group 'org-appearance
3554 :type 'boolean)
3556 (defcustom org-hide-leading-stars nil
3557 "Non-nil means hide the first N-1 stars in a headline.
3558 This works by using the face `org-hide' for these stars. This
3559 face is white for a light background, and black for a dark
3560 background. You may have to customize the face `org-hide' to
3561 make this work.
3562 Changing it requires restart of `font-lock-mode' to become effective
3563 also in regions already fontified.
3564 You may also set this on a per-file basis by adding one of the following
3565 lines to the buffer:
3567 #+STARTUP: hidestars
3568 #+STARTUP: showstars"
3569 :group 'org-appearance
3570 :type 'boolean)
3572 (defcustom org-hidden-keywords nil
3573 "List of symbols corresponding to keywords to be hidden the org buffer.
3574 For example, a value '(title) for this list will make the document's title
3575 appear in the buffer without the initial #+TITLE: keyword."
3576 :group 'org-appearance
3577 :version "24.1"
3578 :type '(set (const :tag "#+AUTHOR" author)
3579 (const :tag "#+DATE" date)
3580 (const :tag "#+EMAIL" email)
3581 (const :tag "#+TITLE" title)))
3583 (defcustom org-custom-properties nil
3584 "List of properties (as strings) with a special meaning.
3585 The default use of these custom properties is to let the user
3586 hide them with `org-toggle-custom-properties-visibility'."
3587 :group 'org-properties
3588 :group 'org-appearance
3589 :version "24.3"
3590 :type '(repeat (string :tag "Property Name")))
3592 (defcustom org-fontify-done-headline nil
3593 "Non-nil means change the face of a headline if it is marked DONE.
3594 Normally, only the TODO/DONE keyword indicates the state of a headline.
3595 When this is non-nil, the headline after the keyword is set to the
3596 `org-headline-done' as an additional indication."
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-fontify-emphasized-text t
3601 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3602 Changing this variable requires a restart of Emacs to take effect."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-fontify-whole-heading-line nil
3607 "Non-nil means fontify the whole line for headings.
3608 This is useful when setting a background color for the
3609 org-level-* faces."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-highlight-latex-fragments-and-specials nil
3614 "Non-nil means fontify what is treated specially by the exporters."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-hide-emphasis-markers nil
3619 "Non-nil mean font-lock should hide the emphasis marker characters."
3620 :group 'org-appearance
3621 :type 'boolean)
3623 (defcustom org-pretty-entities nil
3624 "Non-nil means show entities as UTF8 characters.
3625 When nil, the \\name form remains in the buffer."
3626 :group 'org-appearance
3627 :version "24.1"
3628 :type 'boolean)
3630 (defcustom org-pretty-entities-include-sub-superscripts t
3631 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3632 :group 'org-appearance
3633 :version "24.1"
3634 :type 'boolean)
3636 (defvar org-emph-re nil
3637 "Regular expression for matching emphasis.
3638 After a match, the match groups contain these elements:
3639 0 The match of the full regular expression, including the characters
3640 before and after the proper match
3641 1 The character before the proper match, or empty at beginning of line
3642 2 The proper match, including the leading and trailing markers
3643 3 The leading marker like * or /, indicating the type of highlighting
3644 4 The text between the emphasis markers, not including the markers
3645 5 The character after the match, empty at the end of a line")
3646 (defvar org-verbatim-re nil
3647 "Regular expression for matching verbatim text.")
3648 (defvar org-emphasis-regexp-components) ; defined just below
3649 (defvar org-emphasis-alist) ; defined just below
3650 (defun org-set-emph-re (var val)
3651 "Set variable and compute the emphasis regular expression."
3652 (set var val)
3653 (when (and (boundp 'org-emphasis-alist)
3654 (boundp 'org-emphasis-regexp-components)
3655 org-emphasis-alist org-emphasis-regexp-components)
3656 (let* ((e org-emphasis-regexp-components)
3657 (pre (car e))
3658 (post (nth 1 e))
3659 (border (nth 2 e))
3660 (body (nth 3 e))
3661 (nl (nth 4 e))
3662 (body1 (concat body "*?"))
3663 (markers (mapconcat 'car org-emphasis-alist ""))
3664 (vmarkers (mapconcat
3665 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3666 org-emphasis-alist "")))
3667 ;; make sure special characters appear at the right position in the class
3668 (if (string-match "\\^" markers)
3669 (setq markers (concat (replace-match "" t t markers) "^")))
3670 (if (string-match "-" markers)
3671 (setq markers (concat (replace-match "" t t markers) "-")))
3672 (if (string-match "\\^" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3674 (if (string-match "-" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3676 (if (> nl 0)
3677 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3678 (int-to-string nl) "\\}")))
3679 ;; Make the regexp
3680 (setq org-emph-re
3681 (concat "\\([" pre "]\\|^\\)"
3682 "\\("
3683 "\\([" markers "]\\)"
3684 "\\("
3685 "[^" border "]\\|"
3686 "[^" border "]"
3687 body1
3688 "[^" border "]"
3689 "\\)"
3690 "\\3\\)"
3691 "\\([" post "]\\|$\\)"))
3692 (setq org-verbatim-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" vmarkers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)")))))
3705 (defcustom org-emphasis-regexp-components
3706 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3707 "Components used to build the regular expression for emphasis.
3708 This is a list with five entries. Terminology: In an emphasis string
3709 like \" *strong word* \", we call the initial space PREMATCH, the final
3710 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3711 and \"trong wor\" is the body. The different components in this variable
3712 specify what is allowed/forbidden in each part:
3714 pre Chars allowed as prematch. Beginning of line will be allowed too.
3715 post Chars allowed as postmatch. End of line will be allowed too.
3716 border The chars *forbidden* as border characters.
3717 body-regexp A regexp like \".\" to match a body character. Don't use
3718 non-shy groups here, and don't allow newline here.
3719 newline The maximum number of newlines allowed in an emphasis exp.
3721 Use customize to modify this, or restart Emacs after changing it."
3722 :group 'org-appearance
3723 :set 'org-set-emph-re
3724 :type '(list
3725 (sexp :tag "Allowed chars in pre ")
3726 (sexp :tag "Allowed chars in post ")
3727 (sexp :tag "Forbidden chars in border ")
3728 (sexp :tag "Regexp for body ")
3729 (integer :tag "number of newlines allowed")
3730 (option (boolean :tag "Please ignore this button"))))
3732 (defcustom org-emphasis-alist
3733 `(("*" bold "<b>" "</b>")
3734 ("/" italic "<i>" "</i>")
3735 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3736 ("=" org-code "<code>" "</code>" verbatim)
3737 ("~" org-verbatim "<code>" "</code>" verbatim)
3738 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3739 "<del>" "</del>")
3741 "Special syntax for emphasized text.
3742 Text starting and ending with a special character will be emphasized, for
3743 example *bold*, _underlined_ and /italic/. This variable sets the marker
3744 characters, the face to be used by font-lock for highlighting in Org-mode
3745 Emacs buffers, and the HTML tags to be used for this.
3746 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3747 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3748 Use customize to modify this, or restart Emacs after changing it."
3749 :group 'org-appearance
3750 :set 'org-set-emph-re
3751 :type '(repeat
3752 (list
3753 (string :tag "Marker character")
3754 (choice
3755 (face :tag "Font-lock-face")
3756 (plist :tag "Face property list"))
3757 (string :tag "HTML start tag")
3758 (string :tag "HTML end tag")
3759 (option (const verbatim)))))
3761 (defvar org-protecting-blocks
3762 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3763 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3764 This is needed for font-lock setup.")
3766 ;;; Miscellaneous options
3768 (defgroup org-completion nil
3769 "Completion in Org-mode."
3770 :tag "Org Completion"
3771 :group 'org)
3773 (defcustom org-completion-use-ido nil
3774 "Non-nil means use ido completion wherever possible.
3775 Note that `ido-mode' must be active for this variable to be relevant.
3776 If you decide to turn this variable on, you might well want to turn off
3777 `org-outline-path-complete-in-steps'.
3778 See also `org-completion-use-iswitchb'."
3779 :group 'org-completion
3780 :type 'boolean)
3782 (defcustom org-completion-use-iswitchb nil
3783 "Non-nil means use iswitchb completion wherever possible.
3784 Note that `iswitchb-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 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-fallback-command 'hippie-expand
3792 "The expansion command called by \\[pcomplete] in normal context.
3793 Normal means, no org-mode-specific context."
3794 :group 'org-completion
3795 :type 'function)
3797 ;;; Functions and variables from their packages
3798 ;; Declared here to avoid compiler warnings
3800 ;; XEmacs only
3801 (defvar outline-mode-menu-heading)
3802 (defvar outline-mode-menu-show)
3803 (defvar outline-mode-menu-hide)
3804 (defvar zmacs-regions) ; XEmacs regions
3806 ;; Emacs only
3807 (defvar mark-active)
3809 ;; Various packages
3810 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3811 (declare-function calendar-forward-day "cal-move" (arg))
3812 (declare-function calendar-goto-date "cal-move" (date))
3813 (declare-function calendar-goto-today "cal-move" ())
3814 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3815 (defvar calc-embedded-close-formula)
3816 (defvar calc-embedded-open-formula)
3817 (declare-function cdlatex-tab "ext:cdlatex" ())
3818 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3819 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3820 (defvar font-lock-unfontify-region-function)
3821 (declare-function iswitchb-read-buffer "iswitchb"
3822 (prompt &optional default require-match start matches-set))
3823 (defvar iswitchb-temp-buflist)
3824 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3825 (defvar org-agenda-tags-todo-honor-ignore-options)
3826 (declare-function org-agenda-skip "org-agenda" ())
3827 (declare-function
3828 org-agenda-format-item "org-agenda"
3829 (extra txt &optional category tags dotime noprefix remove-re habitp))
3830 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3831 (declare-function org-agenda-change-all-lines "org-agenda"
3832 (newhead hdmarker &optional fixface just-this))
3833 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3834 (declare-function org-agenda-maybe-redo "org-agenda" ())
3835 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3836 (beg end))
3837 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3839 "org-agenda" (&optional end))
3840 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3841 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3844 (declare-function org-indent-mode "org-indent" (&optional arg))
3845 (declare-function parse-time-string "parse-time" (string))
3846 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3847 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3848 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3849 (defvar remember-data-file)
3850 (defvar texmathp-why)
3851 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3852 (declare-function table--at-cell-p "table" (position &optional object at-column))
3854 (defvar w3m-current-url)
3855 (defvar w3m-current-title)
3857 (defvar org-latex-regexps)
3859 ;;; Autoload and prepare some org modules
3861 ;; Some table stuff that needs to be defined here, because it is used
3862 ;; by the functions setting up org-mode or checking for table context.
3864 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3865 "Detect an org-type or table-type table.")
3866 (defconst org-table-line-regexp "^[ \t]*|"
3867 "Detect an org-type table line.")
3868 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3869 "Detect an org-type table line.")
3870 (defconst org-table-hline-regexp "^[ \t]*|-"
3871 "Detect an org-type table hline.")
3872 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3873 "Detect a table-type table hline.")
3874 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3875 "Detect the first line outside a table when searching from within it.
3876 This works for both table types.")
3878 ;; Autoload the functions in org-table.el that are needed by functions here.
3880 (eval-and-compile
3881 (org-autoload "org-table"
3882 '(org-table-begin org-table-blank-field org-table-end)))
3884 ;;;###autoload
3885 (defun turn-on-orgtbl ()
3886 "Unconditionally turn on `orgtbl-mode'."
3887 (require 'org-table)
3888 (orgtbl-mode 1))
3890 (defun org-at-table-p (&optional table-type)
3891 "Return t if the cursor is inside an org-type table.
3892 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3893 (if org-enable-table-editor
3894 (save-excursion
3895 (beginning-of-line 1)
3896 (looking-at (if table-type org-table-any-line-regexp
3897 org-table-line-regexp)))
3898 nil))
3899 (defsubst org-table-p () (org-at-table-p))
3901 (defun org-at-table.el-p ()
3902 "Return t if and only if we are at a table.el table."
3903 (and (org-at-table-p 'any)
3904 (save-excursion
3905 (goto-char (org-table-begin 'any))
3906 (looking-at org-table1-hline-regexp))))
3907 (defun org-table-recognize-table.el ()
3908 "If there is a table.el table nearby, recognize it and move into it."
3909 (if org-table-tab-recognizes-table.el
3910 (if (org-at-table.el-p)
3911 (progn
3912 (beginning-of-line 1)
3913 (if (looking-at org-table-dataline-regexp)
3915 (if (looking-at org-table1-hline-regexp)
3916 (progn
3917 (beginning-of-line 2)
3918 (if (looking-at org-table-any-border-regexp)
3919 (beginning-of-line -1)))))
3920 (if (re-search-forward "|" (org-table-end t) t)
3921 (progn
3922 (require 'table)
3923 (if (table--at-cell-p (point))
3925 (message "recognizing table.el table...")
3926 (table-recognize-table)
3927 (message "recognizing table.el table...done")))
3928 (error "This should not happen"))
3930 nil)
3931 nil))
3933 (defun org-at-table-hline-p ()
3934 "Return t if the cursor is inside a hline in a table."
3935 (if org-enable-table-editor
3936 (save-excursion
3937 (beginning-of-line 1)
3938 (looking-at org-table-hline-regexp))
3939 nil))
3941 (defvar org-table-clean-did-remove-column nil)
3943 (defun org-table-map-tables (function &optional quietly)
3944 "Apply FUNCTION to the start of all tables in the buffer."
3945 (save-excursion
3946 (save-restriction
3947 (widen)
3948 (goto-char (point-min))
3949 (while (re-search-forward org-table-any-line-regexp nil t)
3950 (unless quietly
3951 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3952 (beginning-of-line 1)
3953 (when (and (looking-at org-table-line-regexp)
3954 ;; Exclude tables in src/example/verbatim/clocktable blocks
3955 (not (org-in-block-p '("src" "example"))))
3956 (save-excursion (funcall function))
3957 (or (looking-at org-table-line-regexp)
3958 (forward-char 1)))
3959 (re-search-forward org-table-any-border-regexp nil 1))))
3960 (unless quietly (message "Mapping tables: done")))
3962 ;; Declare and autoload functions from org-exp.el & Co
3964 (declare-function org-default-export-plist "org-exp")
3965 (declare-function org-infile-export-plist "org-exp")
3966 (declare-function org-get-current-options "org-exp")
3968 ;; Declare and autoload functions from org-agenda.el
3970 (eval-and-compile
3971 (org-autoload "org-agenda"
3972 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3974 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3975 (declare-function org-clock-update-mode-line "org-clock" ())
3976 (declare-function org-resolve-clocks "org-clock"
3977 (&optional also-non-dangling-p prompt last-valid))
3978 (defvar org-clock-start-time)
3979 (defvar org-clock-marker (make-marker)
3980 "Marker recording the last clock-in.")
3981 (defvar org-clock-hd-marker (make-marker)
3982 "Marker recording the last clock-in, but the headline position.")
3983 (defvar org-clock-heading ""
3984 "The heading of the current clock entry.")
3985 (defun org-clock-is-active ()
3986 "Return non-nil if clock is currently running.
3987 The return value is actually the clock marker."
3988 (marker-buffer org-clock-marker))
3990 (eval-and-compile
3991 (org-autoload "org-clock" '(org-clock-remove-overlays
3992 org-clock-update-time-maybe
3993 org-clocktable-shift)))
3995 (defun org-check-running-clock ()
3996 "Check if the current buffer contains the running clock.
3997 If yes, offer to stop it and to save the buffer with the changes."
3998 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3999 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4000 (buffer-name))))
4001 (org-clock-out)
4002 (when (y-or-n-p "Save changed buffer?")
4003 (save-buffer))))
4005 (defun org-clocktable-try-shift (dir n)
4006 "Check if this line starts a clock table, if yes, shift the time block."
4007 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4008 (org-clocktable-shift dir n)))
4010 ;;;###autoload
4011 (defun org-clock-persistence-insinuate ()
4012 "Set up hooks for clock persistence."
4013 (require 'org-clock)
4014 (add-hook 'org-mode-hook 'org-clock-load)
4015 (add-hook 'kill-emacs-hook 'org-clock-save))
4017 ;; Define the variable already here, to make sure we have it.
4018 (defvar org-indent-mode nil
4019 "Non-nil if Org-Indent mode is enabled.
4020 Use the command `org-indent-mode' to change this variable.")
4022 ;; Autoload archiving code
4023 ;; The stuff that is needed for cycling and tags has to be defined here.
4025 (defgroup org-archive nil
4026 "Options concerning archiving in Org-mode."
4027 :tag "Org Archive"
4028 :group 'org-structure)
4030 (defcustom org-archive-location "%s_archive::"
4031 "The location where subtrees should be archived.
4033 The value of this variable is a string, consisting of two parts,
4034 separated by a double-colon. The first part is a filename and
4035 the second part is a headline.
4037 When the filename is omitted, archiving happens in the same file.
4038 %s in the filename will be replaced by the current file
4039 name (without the directory part). Archiving to a different file
4040 is useful to keep archived entries from contributing to the
4041 Org-mode Agenda.
4043 The archived entries will be filed as subtrees of the specified
4044 headline. When the headline is omitted, the subtrees are simply
4045 filed away at the end of the file, as top-level entries. Also in
4046 the heading you can use %s to represent the file name, this can be
4047 useful when using the same archive for a number of different files.
4049 Here are a few examples:
4050 \"%s_archive::\"
4051 If the current file is Projects.org, archive in file
4052 Projects.org_archive, as top-level trees. This is the default.
4054 \"::* Archived Tasks\"
4055 Archive in the current file, under the top-level headline
4056 \"* Archived Tasks\".
4058 \"~/org/archive.org::\"
4059 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4061 \"~/org/archive.org::* From %s\"
4062 Archive in file ~/org/archive.org (absolute path), under headlines
4063 \"From FILENAME\" where file name is the current file name.
4065 \"~/org/datetree.org::datetree/* Finished Tasks\"
4066 The \"datetree/\" string is special, signifying to archive
4067 items to the datetree. Items are placed in either the CLOSED
4068 date of the item, or the current date if there is no CLOSED date.
4069 The heading will be a subentry to the current date. There doesn't
4070 need to be a heading, but there always needs to be a slash after
4071 datetree. For example, to store archived items directly in the
4072 datetree, use \"~/org/datetree.org::datetree/\".
4074 \"basement::** Finished Tasks\"
4075 Archive in file ./basement (relative path), as level 3 trees
4076 below the level 2 heading \"** Finished Tasks\".
4078 You may set this option on a per-file basis by adding to the buffer a
4079 line like
4081 #+ARCHIVE: basement::** Finished Tasks
4083 You may also define it locally for a subtree by setting an ARCHIVE property
4084 in the entry. If such a property is found in an entry, or anywhere up
4085 the hierarchy, it will be used."
4086 :group 'org-archive
4087 :type 'string)
4089 (defcustom org-archive-tag "ARCHIVE"
4090 "The tag that marks a subtree as archived.
4091 An archived subtree does not open during visibility cycling, and does
4092 not contribute to the agenda listings.
4093 After changing this, font-lock must be restarted in the relevant buffers to
4094 get the proper fontification."
4095 :group 'org-archive
4096 :group 'org-keywords
4097 :type 'string)
4099 (defcustom org-agenda-skip-archived-trees t
4100 "Non-nil means the agenda will skip any items located in archived trees.
4101 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4102 variable is no longer recommended, you should leave it at the value t.
4103 Instead, use the key `v' to cycle the archives-mode in the agenda."
4104 :group 'org-archive
4105 :group 'org-agenda-skip
4106 :type 'boolean)
4108 (defcustom org-columns-skip-archived-trees t
4109 "Non-nil means ignore archived trees when creating column view."
4110 :group 'org-archive
4111 :group 'org-properties
4112 :type 'boolean)
4114 (defcustom org-cycle-open-archived-trees nil
4115 "Non-nil means `org-cycle' will open archived trees.
4116 An archived tree is a tree marked with the tag ARCHIVE.
4117 When nil, archived trees will stay folded. You can still open them with
4118 normal outline commands like `show-all', but not with the cycling commands."
4119 :group 'org-archive
4120 :group 'org-cycle
4121 :type 'boolean)
4123 (defcustom org-sparse-tree-open-archived-trees nil
4124 "Non-nil means sparse tree construction shows matches in archived trees.
4125 When nil, matches in these trees are highlighted, but the trees are kept in
4126 collapsed state."
4127 :group 'org-archive
4128 :group 'org-sparse-trees
4129 :type 'boolean)
4131 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4132 "The default date type when building a sparse tree.
4133 When this is nil, a date is a scheduled or a deadline timestamp.
4134 Otherwise, these types are allowed:
4136 all: all timestamps
4137 active: only active timestamps (<...>)
4138 inactive: only inactive timestamps (<...)
4139 scheduled: only scheduled timestamps
4140 deadline: only deadline timestamps"
4141 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4142 (const :tag "All timestamps" all)
4143 (const :tag "Only active timestamps" active)
4144 (const :tag "Only inactive timestamps" inactive)
4145 (const :tag "Only scheduled timestamps" scheduled)
4146 (const :tag "Only deadline timestamps" deadline))
4147 :version "24.3"
4148 :group 'org-sparse-trees)
4150 (defun org-cycle-hide-archived-subtrees (state)
4151 "Re-hide all archived subtrees after a visibility state change."
4152 (when (and (not org-cycle-open-archived-trees)
4153 (not (memq state '(overview folded))))
4154 (save-excursion
4155 (let* ((globalp (memq state '(contents all)))
4156 (beg (if globalp (point-min) (point)))
4157 (end (if globalp (point-max) (org-end-of-subtree t))))
4158 (org-hide-archived-subtrees beg end)
4159 (goto-char beg)
4160 (if (looking-at (concat ".*:" org-archive-tag ":"))
4161 (message "%s" (substitute-command-keys
4162 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4164 (defun org-force-cycle-archived ()
4165 "Cycle subtree even if it is archived."
4166 (interactive)
4167 (setq this-command 'org-cycle)
4168 (let ((org-cycle-open-archived-trees t))
4169 (call-interactively 'org-cycle)))
4171 (defun org-hide-archived-subtrees (beg end)
4172 "Re-hide all archived subtrees after a visibility state change."
4173 (save-excursion
4174 (let* ((re (concat ":" org-archive-tag ":")))
4175 (goto-char beg)
4176 (while (re-search-forward re end t)
4177 (when (org-at-heading-p)
4178 (org-flag-subtree t)
4179 (org-end-of-subtree t))))))
4181 (declare-function outline-end-of-heading "outline" ())
4182 (declare-function outline-flag-region "outline" (from to flag))
4183 (defun org-flag-subtree (flag)
4184 (save-excursion
4185 (org-back-to-heading t)
4186 (outline-end-of-heading)
4187 (outline-flag-region (point)
4188 (progn (org-end-of-subtree t) (point))
4189 flag)))
4191 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4193 (eval-and-compile
4194 (org-autoload "org-archive"
4195 '(org-add-archive-files)))
4197 ;; Autoload Column View Code
4199 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4200 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4201 (declare-function org-columns-compute "org-colview" (property))
4203 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4204 '(org-columns-number-to-string
4205 org-columns-get-format-and-top-level
4206 org-columns-compute
4207 org-columns-remove-overlays))
4209 ;; Autoload ID code
4211 (declare-function org-id-store-link "org-id")
4212 (declare-function org-id-locations-load "org-id")
4213 (declare-function org-id-locations-save "org-id")
4214 (defvar org-id-track-globally)
4215 (org-autoload "org-id"
4216 '(org-id-new
4217 org-id-copy
4218 org-id-get-with-outline-path-completion
4219 org-id-get-with-outline-drilling))
4221 ;;; Variables for pre-computed regular expressions, all buffer local
4223 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4224 "Matches first line of a hidden block.")
4225 (make-variable-buffer-local 'org-drawer-regexp)
4226 (defvar org-todo-regexp nil
4227 "Matches any of the TODO state keywords.")
4228 (make-variable-buffer-local 'org-todo-regexp)
4229 (defvar org-not-done-regexp nil
4230 "Matches any of the TODO state keywords except the last one.")
4231 (make-variable-buffer-local 'org-not-done-regexp)
4232 (defvar org-not-done-heading-regexp nil
4233 "Matches a TODO headline that is not done.")
4234 (make-variable-buffer-local 'org-not-done-regexp)
4235 (defvar org-todo-line-regexp nil
4236 "Matches a headline and puts TODO state into group 2 if present.")
4237 (make-variable-buffer-local 'org-todo-line-regexp)
4238 (defvar org-complex-heading-regexp nil
4239 "Matches a headline and puts everything into groups:
4240 group 1: the stars
4241 group 2: The todo keyword, maybe
4242 group 3: Priority cookie
4243 group 4: True headline
4244 group 5: Tags")
4245 (make-variable-buffer-local 'org-complex-heading-regexp)
4246 (defvar org-complex-heading-regexp-format nil
4247 "Printf format to make regexp to match an exact headline.
4248 This regexp will match the headline of any node which has the
4249 exact headline text that is put into the format, but may have any
4250 TODO state, priority and tags.")
4251 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4252 (defvar org-todo-line-tags-regexp nil
4253 "Matches a headline and puts TODO state into group 2 if present.
4254 Also put tags into group 4 if tags are present.")
4255 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4256 (defvar org-ds-keyword-length 12
4257 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4258 (make-variable-buffer-local 'org-ds-keyword-length)
4259 (defvar org-deadline-regexp nil
4260 "Matches the DEADLINE keyword.")
4261 (make-variable-buffer-local 'org-deadline-regexp)
4262 (defvar org-deadline-time-regexp nil
4263 "Matches the DEADLINE keyword together with a time stamp.")
4264 (make-variable-buffer-local 'org-deadline-time-regexp)
4265 (defvar org-deadline-line-regexp nil
4266 "Matches the DEADLINE keyword and the rest of the line.")
4267 (make-variable-buffer-local 'org-deadline-line-regexp)
4268 (defvar org-scheduled-regexp nil
4269 "Matches the SCHEDULED keyword.")
4270 (make-variable-buffer-local 'org-scheduled-regexp)
4271 (defvar org-scheduled-time-regexp nil
4272 "Matches the SCHEDULED keyword together with a time stamp.")
4273 (make-variable-buffer-local 'org-scheduled-time-regexp)
4274 (defvar org-closed-time-regexp nil
4275 "Matches the CLOSED keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-closed-time-regexp)
4278 (defvar org-keyword-time-regexp nil
4279 "Matches any of the 4 keywords, together with the time stamp.")
4280 (make-variable-buffer-local 'org-keyword-time-regexp)
4281 (defvar org-keyword-time-not-clock-regexp nil
4282 "Matches any of the 3 keywords, together with the time stamp.")
4283 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4284 (defvar org-maybe-keyword-time-regexp nil
4285 "Matches a timestamp, possibly preceded by a keyword.")
4286 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4287 (defvar org-all-time-keywords nil
4288 "List of time keywords.")
4289 (make-variable-buffer-local 'org-all-time-keywords)
4291 (defconst org-plain-time-of-day-regexp
4292 (concat
4293 "\\(\\<[012]?[0-9]"
4294 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4295 "\\(--?"
4296 "\\(\\<[012]?[0-9]"
4297 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4298 "\\)?")
4299 "Regular expression to match a plain time or time range.
4300 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4301 groups carry important information:
4302 0 the full match
4303 1 the first time, range or not
4304 8 the second time, if it is a range.")
4306 (defconst org-plain-time-extension-regexp
4307 (concat
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4311 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4312 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4313 groups carry important information:
4314 0 the full match
4315 7 hours of duration
4316 9 minutes of duration")
4318 (defconst org-stamp-time-of-day-regexp
4319 (concat
4320 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4321 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4322 "\\(--?"
4323 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4324 "Regular expression to match a timestamp time or time range.
4325 After a match, the following groups carry important information:
4326 0 the full match
4327 1 date plus weekday, for back referencing to make sure both times are on the same day
4328 2 the first time, range or not
4329 4 the second time, if it is a range.")
4331 (defconst org-startup-options
4332 '(("fold" org-startup-folded t)
4333 ("overview" org-startup-folded t)
4334 ("nofold" org-startup-folded nil)
4335 ("showall" org-startup-folded nil)
4336 ("showeverything" org-startup-folded showeverything)
4337 ("content" org-startup-folded content)
4338 ("indent" org-startup-indented t)
4339 ("noindent" org-startup-indented nil)
4340 ("hidestars" org-hide-leading-stars t)
4341 ("showstars" org-hide-leading-stars nil)
4342 ("odd" org-odd-levels-only t)
4343 ("oddeven" org-odd-levels-only nil)
4344 ("align" org-startup-align-all-tables t)
4345 ("noalign" org-startup-align-all-tables nil)
4346 ("inlineimages" org-startup-with-inline-images t)
4347 ("noinlineimages" org-startup-with-inline-images nil)
4348 ("customtime" org-display-custom-times t)
4349 ("logdone" org-log-done time)
4350 ("lognotedone" org-log-done note)
4351 ("nologdone" org-log-done nil)
4352 ("lognoteclock-out" org-log-note-clock-out t)
4353 ("nolognoteclock-out" org-log-note-clock-out nil)
4354 ("logrepeat" org-log-repeat state)
4355 ("lognoterepeat" org-log-repeat note)
4356 ("nologrepeat" org-log-repeat nil)
4357 ("logreschedule" org-log-reschedule time)
4358 ("lognotereschedule" org-log-reschedule note)
4359 ("nologreschedule" org-log-reschedule nil)
4360 ("logredeadline" org-log-redeadline time)
4361 ("lognoteredeadline" org-log-redeadline note)
4362 ("nologredeadline" org-log-redeadline nil)
4363 ("logrefile" org-log-refile time)
4364 ("lognoterefile" org-log-refile note)
4365 ("nologrefile" org-log-refile nil)
4366 ("fninline" org-footnote-define-inline t)
4367 ("nofninline" org-footnote-define-inline nil)
4368 ("fnlocal" org-footnote-section nil)
4369 ("fnauto" org-footnote-auto-label t)
4370 ("fnprompt" org-footnote-auto-label nil)
4371 ("fnconfirm" org-footnote-auto-label confirm)
4372 ("fnplain" org-footnote-auto-label plain)
4373 ("fnadjust" org-footnote-auto-adjust t)
4374 ("nofnadjust" org-footnote-auto-adjust nil)
4375 ("constcgs" constants-unit-system cgs)
4376 ("constSI" constants-unit-system SI)
4377 ("noptag" org-tag-persistent-alist nil)
4378 ("hideblocks" org-hide-block-startup t)
4379 ("nohideblocks" org-hide-block-startup nil)
4380 ("beamer" org-startup-with-beamer-mode t)
4381 ("entitiespretty" org-pretty-entities t)
4382 ("entitiesplain" org-pretty-entities nil))
4383 "Variable associated with STARTUP options for org-mode.
4384 Each element is a list of three items: the startup options (as written
4385 in the #+STARTUP line), the corresponding variable, and the value to set
4386 this variable to if the option is found. An optional forth element PUSH
4387 means to push this value onto the list in the variable.")
4389 (defun org-update-property-plist (key val props)
4390 "Update PROPS with KEY and VAL."
4391 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4392 (key (if appending (substring key 0 (- (length key) 1)) key))
4393 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4394 (previous (cdr (assoc key props))))
4395 (if appending
4396 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4397 (cons (cons key val) remainder))))
4399 (defconst org-block-regexp
4400 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4401 "Regular expression for hiding blocks.")
4402 (defconst org-heading-keyword-regexp-format
4403 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4404 "Printf format for a regexp matching an headline with some keyword.
4405 This regexp will match the headline of any node which has the
4406 exact keyword that is put into the format. The keyword isn't in
4407 any group by default, but the stars and the body are.")
4408 (defconst org-heading-keyword-maybe-regexp-format
4409 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4410 "Printf format for a regexp matching an headline, possibly with some keyword.
4411 This regexp can match any headline with the specified keyword, or
4412 without a keyword. The keyword isn't in any group by default,
4413 but the stars and the body are.")
4415 (defun org-set-regexps-and-options ()
4416 "Precompute regular expressions for current buffer."
4417 (when (derived-mode-p 'org-mode)
4418 (org-set-local 'org-todo-kwd-alist nil)
4419 (org-set-local 'org-todo-key-alist nil)
4420 (org-set-local 'org-todo-key-trigger nil)
4421 (org-set-local 'org-todo-keywords-1 nil)
4422 (org-set-local 'org-done-keywords nil)
4423 (org-set-local 'org-todo-heads nil)
4424 (org-set-local 'org-todo-sets nil)
4425 (org-set-local 'org-todo-log-states nil)
4426 (org-set-local 'org-file-properties nil)
4427 (org-set-local 'org-file-tags nil)
4428 (let ((re (org-make-options-regexp
4429 '("CATEGORY" "TODO" "COLUMNS"
4430 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4431 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4432 "OPTIONS")
4433 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4434 (splitre "[ \t]+")
4435 (scripts org-use-sub-superscripts)
4436 kwds kws0 kwsa key log value cat arch tags const links hw dws
4437 tail sep kws1 prio props ftags drawers beamer-p
4438 ext-setup-or-nil setup-contents (start 0))
4439 (save-excursion
4440 (save-restriction
4441 (widen)
4442 (goto-char (point-min))
4443 (while (or (and ext-setup-or-nil
4444 (string-match re ext-setup-or-nil start)
4445 (setq start (match-end 0)))
4446 (and (setq ext-setup-or-nil nil start 0)
4447 (re-search-forward re nil t)))
4448 (setq key (upcase (match-string 1 ext-setup-or-nil))
4449 value (org-match-string-no-properties 2 ext-setup-or-nil))
4450 (if (stringp value) (setq value (org-trim value)))
4451 (cond
4452 ((equal key "CATEGORY")
4453 (setq cat value))
4454 ((member key '("SEQ_TODO" "TODO"))
4455 (push (cons 'sequence (org-split-string value splitre)) kwds))
4456 ((equal key "TYP_TODO")
4457 (push (cons 'type (org-split-string value splitre)) kwds))
4458 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4459 ;; general TODO-like setup
4460 (push (cons (intern (downcase (match-string 1 key)))
4461 (org-split-string value splitre)) kwds))
4462 ((equal key "TAGS")
4463 (setq tags (append tags (if tags '("\\n") nil)
4464 (org-split-string value splitre))))
4465 ((equal key "COLUMNS")
4466 (org-set-local 'org-columns-default-format value))
4467 ((equal key "LINK")
4468 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4469 (push (cons (match-string 1 value)
4470 (org-trim (match-string 2 value)))
4471 links)))
4472 ((equal key "PRIORITIES")
4473 (setq prio (org-split-string value " +")))
4474 ((equal key "PROPERTY")
4475 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4476 (setq props (org-update-property-plist (match-string 1 value)
4477 (match-string 2 value)
4478 props))))
4479 ((equal key "FILETAGS")
4480 (when (string-match "\\S-" value)
4481 (setq ftags
4482 (append
4483 ftags
4484 (apply 'append
4485 (mapcar (lambda (x) (org-split-string x ":"))
4486 (org-split-string value)))))))
4487 ((equal key "DRAWERS")
4488 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4489 ((equal key "CONSTANTS")
4490 (setq const (append const (org-split-string value splitre))))
4491 ((equal key "STARTUP")
4492 (let ((opts (org-split-string value splitre))
4493 l var val)
4494 (while (setq l (pop opts))
4495 (when (setq l (assoc l org-startup-options))
4496 (setq var (nth 1 l) val (nth 2 l))
4497 (if (not (nth 3 l))
4498 (set (make-local-variable var) val)
4499 (if (not (listp (symbol-value var)))
4500 (set (make-local-variable var) nil))
4501 (set (make-local-variable var) (symbol-value var))
4502 (add-to-list var val))))))
4503 ((equal key "ARCHIVE")
4504 (setq arch value)
4505 (remove-text-properties 0 (length arch)
4506 '(face t fontified t) arch))
4507 ((equal key "LATEX_CLASS")
4508 (setq beamer-p (equal value "beamer")))
4509 ((equal key "OPTIONS")
4510 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4511 (setq scripts (read (match-string 2 value)))))
4512 ((equal key "SETUPFILE")
4513 (setq setup-contents (org-file-contents
4514 (expand-file-name
4515 (org-remove-double-quotes value))
4516 'noerror))
4517 (if (not ext-setup-or-nil)
4518 (setq ext-setup-or-nil setup-contents start 0)
4519 (setq ext-setup-or-nil
4520 (concat (substring ext-setup-or-nil 0 start)
4521 "\n" setup-contents "\n"
4522 (substring ext-setup-or-nil start)))))))
4523 ;; search for property blocks
4524 (goto-char (point-min))
4525 (while (re-search-forward org-block-regexp nil t)
4526 (when (equal "PROPERTY" (upcase (match-string 1)))
4527 (setq value (replace-regexp-in-string
4528 "[\n\r]" " " (match-string 4)))
4529 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4530 (setq props (org-update-property-plist (match-string 1 value)
4531 (match-string 2 value)
4532 props)))))))
4533 (org-set-local 'org-use-sub-superscripts scripts)
4534 (when cat
4535 (org-set-local 'org-category (intern cat))
4536 (push (cons "CATEGORY" cat) props))
4537 (when prio
4538 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4539 (setq prio (mapcar 'string-to-char prio))
4540 (org-set-local 'org-highest-priority (nth 0 prio))
4541 (org-set-local 'org-lowest-priority (nth 1 prio))
4542 (org-set-local 'org-default-priority (nth 2 prio)))
4543 (and props (org-set-local 'org-file-properties (nreverse props)))
4544 (and ftags (org-set-local 'org-file-tags
4545 (mapcar 'org-add-prop-inherited ftags)))
4546 (and drawers (org-set-local 'org-drawers drawers))
4547 (and arch (org-set-local 'org-archive-location arch))
4548 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4549 ;; Process the TODO keywords
4550 (unless kwds
4551 ;; Use the global values as if they had been given locally.
4552 (setq kwds (default-value 'org-todo-keywords))
4553 (if (stringp (car kwds))
4554 (setq kwds (list (cons org-todo-interpretation
4555 (default-value 'org-todo-keywords)))))
4556 (setq kwds (reverse kwds)))
4557 (setq kwds (nreverse kwds))
4558 (let (inter kws kw)
4559 (while (setq kws (pop kwds))
4560 (let ((kws (or
4561 (run-hook-with-args-until-success
4562 'org-todo-setup-filter-hook kws)
4563 kws)))
4564 (setq inter (pop kws) sep (member "|" kws)
4565 kws0 (delete "|" (copy-sequence kws))
4566 kwsa nil
4567 kws1 (mapcar
4568 (lambda (x)
4569 ;; 1 2
4570 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4571 (progn
4572 (setq kw (match-string 1 x)
4573 key (and (match-end 2) (match-string 2 x))
4574 log (org-extract-log-state-settings x))
4575 (push (cons kw (and key (string-to-char key))) kwsa)
4576 (and log (push log org-todo-log-states))
4578 (error "Invalid TODO keyword %s" x)))
4579 kws0)
4580 kwsa (if kwsa (append '((:startgroup))
4581 (nreverse kwsa)
4582 '((:endgroup))))
4583 hw (car kws1)
4584 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4585 tail (list inter hw (car dws) (org-last dws))))
4586 (add-to-list 'org-todo-heads hw 'append)
4587 (push kws1 org-todo-sets)
4588 (setq org-done-keywords (append org-done-keywords dws nil))
4589 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4590 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4591 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4592 (setq org-todo-sets (nreverse org-todo-sets)
4593 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4594 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4595 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4596 ;; Process the constants
4597 (when const
4598 (let (e cst)
4599 (while (setq e (pop const))
4600 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4601 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4602 (setq org-table-formula-constants-local cst)))
4604 ;; Process the tags.
4605 (when tags
4606 (let (e tgs)
4607 (while (setq e (pop tags))
4608 (cond
4609 ((equal e "{") (push '(:startgroup) tgs))
4610 ((equal e "}") (push '(:endgroup) tgs))
4611 ((equal e "\\n") (push '(:newline) tgs))
4612 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4613 (push (cons (match-string 1 e)
4614 (string-to-char (match-string 2 e)))
4615 tgs))
4616 (t (push (list e) tgs))))
4617 (org-set-local 'org-tag-alist nil)
4618 (while (setq e (pop tgs))
4619 (or (and (stringp (car e))
4620 (assoc (car e) org-tag-alist))
4621 (push e org-tag-alist)))))
4623 ;; Compute the regular expressions and other local variables.
4624 ;; Using `org-outline-regexp-bol' would complicate them much,
4625 ;; because of the fixed white space at the end of that string.
4626 (if (not org-done-keywords)
4627 (setq org-done-keywords (and org-todo-keywords-1
4628 (list (org-last org-todo-keywords-1)))))
4629 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4630 (length org-scheduled-string)
4631 (length org-clock-string)
4632 (length org-closed-string)))
4633 org-drawer-regexp
4634 (concat "^[ \t]*:\\("
4635 (mapconcat 'regexp-quote org-drawers "\\|")
4636 "\\):[ \t]*$")
4637 org-not-done-keywords
4638 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4639 org-todo-regexp
4640 (concat "\\("
4641 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4642 "\\)")
4643 org-not-done-regexp
4644 (concat "\\("
4645 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4646 "\\)")
4647 org-not-done-heading-regexp
4648 (format org-heading-keyword-regexp-format org-not-done-regexp)
4649 org-todo-line-regexp
4650 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4651 org-complex-heading-regexp
4652 (concat "^\\(\\*+\\)"
4653 "\\(?: +" org-todo-regexp "\\)?"
4654 "\\(?: +\\(\\[#.\\]\\)\\)?"
4655 "\\(?: +\\(.*?\\)\\)??"
4656 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4657 "[ \t]*$")
4658 org-complex-heading-regexp-format
4659 (concat "^\\(\\*+\\)"
4660 "\\(?: +" org-todo-regexp "\\)?"
4661 "\\(?: +\\(\\[#.\\]\\)\\)?"
4662 "\\(?: +"
4663 ;; Stats cookies can be stuck to body.
4664 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4665 "\\(%s\\)"
4666 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4667 "\\)"
4668 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4669 "[ \t]*$")
4670 org-todo-line-tags-regexp
4671 (concat "^\\(\\*+\\)"
4672 "\\(?: +" org-todo-regexp "\\)?"
4673 "\\(?: +\\(.*?\\)\\)??"
4674 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4675 "[ \t]*$")
4676 org-deadline-regexp (concat "\\<" org-deadline-string)
4677 org-deadline-time-regexp
4678 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4679 org-deadline-line-regexp
4680 (concat "\\<\\(" org-deadline-string "\\).*")
4681 org-scheduled-regexp
4682 (concat "\\<" org-scheduled-string)
4683 org-scheduled-time-regexp
4684 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4685 org-closed-time-regexp
4686 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4687 org-keyword-time-regexp
4688 (concat "\\<\\(" org-scheduled-string
4689 "\\|" org-deadline-string
4690 "\\|" org-closed-string
4691 "\\|" org-clock-string "\\)"
4692 " *[[<]\\([^]>]+\\)[]>]")
4693 org-keyword-time-not-clock-regexp
4694 (concat "\\<\\(" org-scheduled-string
4695 "\\|" org-deadline-string
4696 "\\|" org-closed-string
4697 "\\)"
4698 " *[[<]\\([^]>]+\\)[]>]")
4699 org-maybe-keyword-time-regexp
4700 (concat "\\(\\<\\(" org-scheduled-string
4701 "\\|" org-deadline-string
4702 "\\|" org-closed-string
4703 "\\|" org-clock-string "\\)\\)?"
4704 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4705 org-all-time-keywords
4706 (mapcar (lambda (w) (substring w 0 -1))
4707 (list org-scheduled-string org-deadline-string
4708 org-clock-string org-closed-string))
4710 (org-compute-latex-and-specials-regexp)
4711 (org-set-font-lock-defaults))))
4713 (defun org-file-contents (file &optional noerror)
4714 "Return the contents of FILE, as a string."
4715 (if (or (not file)
4716 (not (file-readable-p file)))
4717 (if noerror
4718 (progn
4719 (message "Cannot read file \"%s\"" file)
4720 (ding) (sit-for 2)
4722 (error "Cannot read file \"%s\"" file))
4723 (with-temp-buffer
4724 (insert-file-contents file)
4725 (buffer-string))))
4727 (defun org-extract-log-state-settings (x)
4728 "Extract the log state setting from a TODO keyword string.
4729 This will extract info from a string like \"WAIT(w@/!)\"."
4730 (let (kw key log1 log2)
4731 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4732 (setq kw (match-string 1 x)
4733 key (and (match-end 2) (match-string 2 x))
4734 log1 (and (match-end 3) (match-string 3 x))
4735 log2 (and (match-end 4) (match-string 4 x)))
4736 (and (or log1 log2)
4737 (list kw
4738 (and log1 (if (equal log1 "!") 'time 'note))
4739 (and log2 (if (equal log2 "!") 'time 'note)))))))
4741 (defun org-remove-keyword-keys (list)
4742 "Remove a pair of parenthesis at the end of each string in LIST."
4743 (mapcar (lambda (x)
4744 (if (string-match "(.*)$" x)
4745 (substring x 0 (match-beginning 0))
4747 list))
4749 (defun org-assign-fast-keys (alist)
4750 "Assign fast keys to a keyword-key alist.
4751 Respect keys that are already there."
4752 (let (new e (alt ?0))
4753 (while (setq e (pop alist))
4754 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4755 (cdr e)) ;; Key already assigned.
4756 (push e new)
4757 (let ((clist (string-to-list (downcase (car e))))
4758 (used (append new alist)))
4759 (when (= (car clist) ?@)
4760 (pop clist))
4761 (while (and clist (rassoc (car clist) used))
4762 (pop clist))
4763 (unless clist
4764 (while (rassoc alt used)
4765 (incf alt)))
4766 (push (cons (car e) (or (car clist) alt)) new))))
4767 (nreverse new)))
4769 ;;; Some variables used in various places
4771 (defvar org-window-configuration nil
4772 "Used in various places to store a window configuration.")
4773 (defvar org-selected-window nil
4774 "Used in various places to store a window configuration.")
4775 (defvar org-finish-function nil
4776 "Function to be called when `C-c C-c' is used.
4777 This is for getting out of special buffers like capture.")
4780 ;; FIXME: Occasionally check by commenting these, to make sure
4781 ;; no other functions uses these, forgetting to let-bind them.
4782 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4783 (defvar org-last-state)
4784 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4786 ;; Defined somewhere in this file, but used before definition.
4787 (defvar org-entities) ;; defined in org-entities.el
4788 (defvar org-struct-menu)
4789 (defvar org-org-menu)
4790 (defvar org-tbl-menu)
4792 ;;;; Define the Org-mode
4794 ;; We use a before-change function to check if a table might need
4795 ;; an update.
4796 (defvar org-table-may-need-update t
4797 "Indicates that a table might need an update.
4798 This variable is set by `org-before-change-function'.
4799 `org-table-align' sets it back to nil.")
4800 (defun org-before-change-function (beg end)
4801 "Every change indicates that a table might need an update."
4802 (setq org-table-may-need-update t))
4803 (defvar org-mode-map)
4804 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4805 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4806 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4807 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4808 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4809 (defvar org-table-buffer-is-an nil)
4811 (defvar bidi-paragraph-direction)
4812 (defvar buffer-face-mode-face)
4814 (require 'outline)
4815 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4816 (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"))
4817 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4819 ;; Other stuff we need.
4820 (require 'time-date)
4821 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4822 (require 'easymenu)
4823 (require 'overlay)
4825 (require 'org-macs)
4826 (require 'org-entities)
4827 ;; (require 'org-compat) moved higher up in the file before it is first used
4828 (require 'org-faces)
4829 (require 'org-list)
4830 (require 'org-pcomplete)
4831 (require 'org-src)
4832 (require 'org-footnote)
4834 ;; babel
4835 (require 'ob)
4836 (require 'ob-table)
4837 (require 'ob-lob)
4838 (require 'ob-ref)
4839 (require 'ob-tangle)
4840 (require 'ob-comint)
4841 (require 'ob-keys)
4843 ;;;###autoload
4844 (define-derived-mode org-mode outline-mode "Org"
4845 "Outline-based notes management and organizer, alias
4846 \"Carsten's outline-mode for keeping track of everything.\"
4848 Org-mode develops organizational tasks around a NOTES file which
4849 contains information about projects as plain text. Org-mode is
4850 implemented on top of outline-mode, which is ideal to keep the content
4851 of large files well structured. It supports ToDo items, deadlines and
4852 time stamps, which magically appear in the diary listing of the Emacs
4853 calendar. Tables are easily created with a built-in table editor.
4854 Plain text URL-like links connect to websites, emails (VM), Usenet
4855 messages (Gnus), BBDB entries, and any files related to the project.
4856 For printing and sharing of notes, an Org-mode file (or a part of it)
4857 can be exported as a structured ASCII or HTML file.
4859 The following commands are available:
4861 \\{org-mode-map}"
4863 ;; Get rid of Outline menus, they are not needed
4864 ;; Need to do this here because define-derived-mode sets up
4865 ;; the keymap so late. Still, it is a waste to call this each time
4866 ;; we switch another buffer into org-mode.
4867 (if (featurep 'xemacs)
4868 (when (boundp 'outline-mode-menu-heading)
4869 ;; Assume this is Greg's port, it uses easymenu
4870 (easy-menu-remove outline-mode-menu-heading)
4871 (easy-menu-remove outline-mode-menu-show)
4872 (easy-menu-remove outline-mode-menu-hide))
4873 (define-key org-mode-map [menu-bar headings] 'undefined)
4874 (define-key org-mode-map [menu-bar hide] 'undefined)
4875 (define-key org-mode-map [menu-bar show] 'undefined))
4877 (org-load-modules-maybe)
4878 (easy-menu-add org-org-menu)
4879 (easy-menu-add org-tbl-menu)
4880 (org-install-agenda-files-menu)
4881 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4882 (add-to-invisibility-spec '(org-cwidth))
4883 (add-to-invisibility-spec '(org-hide-block . t))
4884 (when (featurep 'xemacs)
4885 (org-set-local 'line-move-ignore-invisible t))
4886 (org-set-local 'outline-regexp org-outline-regexp)
4887 (org-set-local 'outline-level 'org-outline-level)
4888 (setq bidi-paragraph-direction 'left-to-right)
4889 (when (and org-ellipsis
4890 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4891 (fboundp 'make-glyph-code))
4892 (unless org-display-table
4893 (setq org-display-table (make-display-table)))
4894 (set-display-table-slot
4895 org-display-table 4
4896 (vconcat (mapcar
4897 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4898 org-ellipsis)))
4899 (if (stringp org-ellipsis) org-ellipsis "..."))))
4900 (setq buffer-display-table org-display-table))
4901 (org-set-regexps-and-options)
4902 (when (and org-tag-faces (not org-tags-special-faces-re))
4903 ;; tag faces set outside customize.... force initialization.
4904 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4905 ;; Calc embedded
4906 (org-set-local 'calc-embedded-open-mode "# ")
4907 (modify-syntax-entry ?@ "w")
4908 (if org-startup-truncated (setq truncate-lines t))
4909 (org-set-local 'font-lock-unfontify-region-function
4910 'org-unfontify-region)
4911 ;; Activate before-change-function
4912 (org-set-local 'org-table-may-need-update t)
4913 (org-add-hook 'before-change-functions 'org-before-change-function nil
4914 'local)
4915 ;; Check for running clock before killing a buffer
4916 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4917 ;; Indentation.
4918 (org-set-local 'indent-line-function 'org-indent-line)
4919 (org-set-local 'indent-region-function 'org-indent-region)
4920 ;; Initialize radio targets.
4921 (org-update-radio-target-regexp)
4922 ;; Filling and auto-filling.
4923 (org-setup-filling)
4924 ;; Comments.
4925 (org-setup-comments-handling)
4926 ;; Beginning/end of defun
4927 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4928 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4929 ;; Next error for sparse trees
4930 (org-set-local 'next-error-function 'org-occur-next-match)
4931 ;; Make sure dependence stuff works reliably, even for users who set it
4932 ;; too late :-(
4933 (if org-enforce-todo-dependencies
4934 (add-hook 'org-blocker-hook
4935 'org-block-todo-from-children-or-siblings-or-parent)
4936 (remove-hook 'org-blocker-hook
4937 'org-block-todo-from-children-or-siblings-or-parent))
4938 (if org-enforce-todo-checkbox-dependencies
4939 (add-hook 'org-blocker-hook
4940 'org-block-todo-from-checkboxes)
4941 (remove-hook 'org-blocker-hook
4942 'org-block-todo-from-checkboxes))
4944 ;; Align options lines
4945 (org-set-local
4946 'align-mode-rules-list
4947 '((org-in-buffer-settings
4948 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4949 (modes . '(org-mode)))))
4951 ;; Imenu
4952 (org-set-local 'imenu-create-index-function
4953 'org-imenu-get-tree)
4955 ;; Make isearch reveal context
4956 (if (or (featurep 'xemacs)
4957 (not (boundp 'outline-isearch-open-invisible-function)))
4958 ;; Emacs 21 and XEmacs make use of the hook
4959 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4960 ;; Emacs 22 deals with this through a special variable
4961 (org-set-local 'outline-isearch-open-invisible-function
4962 (lambda (&rest ignore) (org-show-context 'isearch))))
4964 ;; Turn on org-beamer-mode?
4965 (and org-startup-with-beamer-mode (org-beamer-mode))
4967 ;; Setup the pcomplete hooks
4968 (set (make-local-variable 'pcomplete-command-completion-function)
4969 'org-pcomplete-initial)
4970 (set (make-local-variable 'pcomplete-command-name-function)
4971 'org-command-at-point)
4972 (set (make-local-variable 'pcomplete-default-completion-function)
4973 'ignore)
4974 (set (make-local-variable 'pcomplete-parse-arguments-function)
4975 'org-parse-arguments)
4976 (set (make-local-variable 'pcomplete-termination-string) "")
4977 (when (>= emacs-major-version 23)
4978 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4980 ;; If empty file that did not turn on org-mode automatically, make it to.
4981 (if (and org-insert-mode-line-in-empty-file
4982 (org-called-interactively-p 'any)
4983 (= (point-min) (point-max)))
4984 (insert "# -*- mode: org -*-\n\n"))
4985 (unless org-inhibit-startup
4986 (when org-startup-align-all-tables
4987 (let ((bmp (buffer-modified-p)))
4988 (org-table-map-tables 'org-table-align 'quietly)
4989 (set-buffer-modified-p bmp)))
4990 (when org-startup-with-inline-images
4991 (org-display-inline-images))
4992 (when org-startup-indented
4993 (require 'org-indent)
4994 (org-indent-mode 1))
4995 (unless org-inhibit-startup-visibility-stuff
4996 (org-set-startup-visibility)))
4997 ;; Try to set org-hide correctly
4998 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5000 (when (fboundp 'abbrev-table-put)
5001 (abbrev-table-put org-mode-abbrev-table
5002 :parents (list text-mode-abbrev-table)))
5004 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5007 (defun org-find-invisible-foreground ()
5008 (let ((candidates (remove
5009 "unspecified-bg"
5010 (nconc
5011 (list (face-background 'default)
5012 (face-background 'org-default))
5013 (mapcar
5014 (lambda (alist)
5015 (when (boundp alist)
5016 (cdr (assoc 'background-color (symbol-value alist)))))
5017 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5018 (list (face-foreground 'org-hide))))))
5019 (car (remove nil candidates))))
5021 (defun org-current-time ()
5022 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5023 (if (> (car org-time-stamp-rounding-minutes) 1)
5024 (let ((r (car org-time-stamp-rounding-minutes))
5025 (time (decode-time)))
5026 (apply 'encode-time
5027 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5028 (nthcdr 2 time))))
5029 (current-time)))
5031 (defun org-today ()
5032 "Return today date, considering `org-extend-today-until'."
5033 (time-to-days
5034 (time-subtract (current-time)
5035 (list 0 (* 3600 org-extend-today-until) 0))))
5037 ;;;; Font-Lock stuff, including the activators
5039 (defvar org-mouse-map (make-sparse-keymap))
5040 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5041 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5042 (when org-mouse-1-follows-link
5043 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5044 (when org-tab-follows-link
5045 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5046 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5048 (require 'font-lock)
5050 (defconst org-non-link-chars "]\t\n\r<>")
5051 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5052 "shell" "elisp" "doi" "message"))
5053 (defvar org-link-types-re nil
5054 "Matches a link that has a url-like prefix like \"http:\"")
5055 (defvar org-link-re-with-space nil
5056 "Matches a link with spaces, optional angular brackets around it.")
5057 (defvar org-link-re-with-space2 nil
5058 "Matches a link with spaces, optional angular brackets around it.")
5059 (defvar org-link-re-with-space3 nil
5060 "Matches a link with spaces, only for internal part in bracket links.")
5061 (defvar org-angle-link-re nil
5062 "Matches link with angular brackets, spaces are allowed.")
5063 (defvar org-plain-link-re nil
5064 "Matches plain link, without spaces.")
5065 (defvar org-bracket-link-regexp nil
5066 "Matches a link in double brackets.")
5067 (defvar org-bracket-link-analytic-regexp nil
5068 "Regular expression used to analyze links.
5069 Here is what the match groups contain after a match:
5070 1: http:
5071 2: http
5072 3: path
5073 4: [desc]
5074 5: desc")
5075 (defvar org-bracket-link-analytic-regexp++ nil
5076 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5077 (defvar org-any-link-re nil
5078 "Regular expression matching any link.")
5080 (defcustom org-match-sexp-depth 3
5081 "Number of stacked braces for sub/superscript matching.
5082 This has to be set before loading org.el to be effective."
5083 :group 'org-export-translation ; ??????????????????????????/
5084 :type 'integer)
5086 (defun org-create-multibrace-regexp (left right n)
5087 "Create a regular expression which will match a balanced sexp.
5088 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5089 as single character strings.
5090 The regexp returned will match the entire expression including the
5091 delimiters. It will also define a single group which contains the
5092 match except for the outermost delimiters. The maximum depth of
5093 stacked delimiters is N. Escaping delimiters is not possible."
5094 (let* ((nothing (concat "[^" left right "]*?"))
5095 (or "\\|")
5096 (re nothing)
5097 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5098 (while (> n 1)
5099 (setq n (1- n)
5100 re (concat re or next)
5101 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5102 (concat left "\\(" re "\\)" right)))
5104 (defvar org-match-substring-regexp
5105 (concat
5106 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5107 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5108 "\\|"
5109 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5110 "\\|"
5111 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5112 "The regular expression matching a sub- or superscript.")
5114 (defvar org-match-substring-with-braces-regexp
5115 (concat
5116 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5117 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5118 "\\)")
5119 "The regular expression matching a sub- or superscript, forcing braces.")
5121 (defun org-make-link-regexps ()
5122 "Update the link regular expressions.
5123 This should be called after the variable `org-link-types' has changed."
5124 (setq org-link-types-re
5125 (concat
5126 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5127 org-link-re-with-space
5128 (concat
5129 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5130 "\\([^" org-non-link-chars " ]"
5131 "[^" org-non-link-chars "]*"
5132 "[^" org-non-link-chars " ]\\)>?")
5133 org-link-re-with-space2
5134 (concat
5135 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5136 "\\([^" org-non-link-chars " ]"
5137 "[^\t\n\r]*"
5138 "[^" org-non-link-chars " ]\\)>?")
5139 org-link-re-with-space3
5140 (concat
5141 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5142 "\\([^" org-non-link-chars " ]"
5143 "[^\t\n\r]*\\)")
5144 org-angle-link-re
5145 (concat
5146 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5147 "\\([^" org-non-link-chars " ]"
5148 "[^" org-non-link-chars "]*"
5149 "\\)>")
5150 org-plain-link-re
5151 (concat
5152 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5153 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5154 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5155 org-bracket-link-regexp
5156 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5157 org-bracket-link-analytic-regexp
5158 (concat
5159 "\\[\\["
5160 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5161 "\\([^]]+\\)"
5162 "\\]"
5163 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5164 "\\]")
5165 org-bracket-link-analytic-regexp++
5166 (concat
5167 "\\[\\["
5168 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5169 "\\([^]]+\\)"
5170 "\\]"
5171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5172 "\\]")
5173 org-any-link-re
5174 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5175 org-angle-link-re "\\)\\|\\("
5176 org-plain-link-re "\\)")))
5178 (org-make-link-regexps)
5180 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5181 "Regular expression for fast time stamp matching.")
5182 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5183 "Regular expression for fast time stamp matching.")
5184 (defconst org-ts-regexp0
5185 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5186 "Regular expression matching time strings for analysis.
5187 This one does not require the space after the date, so it can be used
5188 on a string that terminates immediately after the date.")
5189 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5190 "Regular expression matching time strings for analysis.")
5191 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5192 "Regular expression matching time stamps, with groups.")
5193 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5194 "Regular expression matching time stamps (also [..]), with groups.")
5195 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5196 "Regular expression matching a time stamp range.")
5197 (defconst org-tr-regexp-both
5198 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5199 "Regular expression matching a time stamp range.")
5200 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5201 org-ts-regexp "\\)?")
5202 "Regular expression matching a time stamp or time stamp range.")
5203 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5204 org-ts-regexp-both "\\)?")
5205 "Regular expression matching a time stamp or time stamp range.
5206 The time stamps may be either active or inactive.")
5208 (defvar org-emph-face nil)
5210 (defun org-do-emphasis-faces (limit)
5211 "Run through the buffer and add overlays to emphasized strings."
5212 (let (rtn a)
5213 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5214 (if (not (= (char-after (match-beginning 3))
5215 (char-after (match-beginning 4))))
5216 (progn
5217 (setq rtn t)
5218 (setq a (assoc (match-string 3) org-emphasis-alist))
5219 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5220 'face
5221 (nth 1 a))
5222 (and (nth 4 a)
5223 (org-remove-flyspell-overlays-in
5224 (match-beginning 0) (match-end 0)))
5225 (add-text-properties (match-beginning 2) (match-end 2)
5226 '(font-lock-multiline t org-emphasis t))
5227 (when org-hide-emphasis-markers
5228 (add-text-properties (match-end 4) (match-beginning 5)
5229 '(invisible org-link))
5230 (add-text-properties (match-beginning 3) (match-end 3)
5231 '(invisible org-link)))))
5232 (backward-char 1))
5233 rtn))
5235 (defun org-emphasize (&optional char)
5236 "Insert or change an emphasis, i.e. a font like bold or italic.
5237 If there is an active region, change that region to a new emphasis.
5238 If there is no region, just insert the marker characters and position
5239 the cursor between them.
5240 CHAR should be either the marker character, or the first character of the
5241 HTML tag associated with that emphasis. If CHAR is a space, the means
5242 to remove the emphasis of the selected region.
5243 If char is not given (for example in an interactive call) it
5244 will be prompted for."
5245 (interactive)
5246 (let ((eal org-emphasis-alist) e det
5247 (erc org-emphasis-regexp-components)
5248 (prompt "")
5249 (string "") beg end move tag c s)
5250 (if (org-region-active-p)
5251 (setq beg (region-beginning) end (region-end)
5252 string (buffer-substring beg end))
5253 (setq move t))
5255 (while (setq e (pop eal))
5256 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5257 c (aref tag 0))
5258 (push (cons c (string-to-char (car e))) det)
5259 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5260 (substring tag 1)))))
5261 (setq det (nreverse det))
5262 (unless char
5263 (message "%s" (concat "Emphasis marker or tag:" prompt))
5264 (setq char (read-char-exclusive)))
5265 (setq char (or (cdr (assoc char det)) char))
5266 (if (equal char ?\ )
5267 (setq s "" move nil)
5268 (unless (assoc (char-to-string char) org-emphasis-alist)
5269 (error "No such emphasis marker: \"%c\"" char))
5270 (setq s (char-to-string char)))
5271 (while (and (> (length string) 1)
5272 (equal (substring string 0 1) (substring string -1))
5273 (assoc (substring string 0 1) org-emphasis-alist))
5274 (setq string (substring string 1 -1)))
5275 (setq string (concat s string s))
5276 (if beg (delete-region beg end))
5277 (unless (or (bolp)
5278 (string-match (concat "[" (nth 0 erc) "\n]")
5279 (char-to-string (char-before (point)))))
5280 (insert " "))
5281 (unless (or (eobp)
5282 (string-match (concat "[" (nth 1 erc) "\n]")
5283 (char-to-string (char-after (point)))))
5284 (insert " ") (backward-char 1))
5285 (insert string)
5286 (and move (backward-char 1))))
5288 (defconst org-nonsticky-props
5289 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5291 (defsubst org-rear-nonsticky-at (pos)
5292 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5294 (defun org-activate-plain-links (limit)
5295 "Run through the buffer and add overlays to links."
5296 (catch 'exit
5297 (let (f)
5298 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5299 (not (org-in-src-block-p)))
5300 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5301 (setq f (get-text-property (match-beginning 0) 'face))
5302 (unless (or (org-in-src-block-p)
5303 (eq f 'org-tag)
5304 (and (listp f) (memq 'org-tag f)))
5305 (add-text-properties (match-beginning 0) (match-end 0)
5306 (list 'mouse-face 'highlight
5307 'face 'org-link
5308 'keymap org-mouse-map))
5309 (org-rear-nonsticky-at (match-end 0)))
5310 t))))
5312 (defun org-activate-code (limit)
5313 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5314 (progn
5315 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5316 (remove-text-properties (match-beginning 0) (match-end 0)
5317 '(display t invisible t intangible t))
5318 t)))
5320 (defcustom org-src-fontify-natively nil
5321 "When non-nil, fontify code in code blocks."
5322 :type 'boolean
5323 :version "24.1"
5324 :group 'org-appearance
5325 :group 'org-babel)
5327 (defcustom org-allow-promoting-top-level-subtree nil
5328 "When non-nil, allow promoting a top level subtree.
5329 The leading star of the top level headline will be replaced
5330 by a #."
5331 :type 'boolean
5332 :version "24.1"
5333 :group 'org-appearance)
5335 (defun org-fontify-meta-lines-and-blocks (limit)
5336 (condition-case nil
5337 (org-fontify-meta-lines-and-blocks-1 limit)
5338 (error (message "org-mode fontification error"))))
5340 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5341 "Fontify #+ lines and blocks, in the correct ways."
5342 (let ((case-fold-search t))
5343 (if (re-search-forward
5344 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5345 limit t)
5346 (let ((beg (match-beginning 0))
5347 (block-start (match-end 0))
5348 (block-end nil)
5349 (lang (match-string 7))
5350 (beg1 (line-beginning-position 2))
5351 (dc1 (downcase (match-string 2)))
5352 (dc3 (downcase (match-string 3)))
5353 end end1 quoting block-type ovl)
5354 (cond
5355 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5356 ;; a single line of backend-specific content
5357 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5358 (remove-text-properties (match-beginning 0) (match-end 0)
5359 '(display t invisible t intangible t))
5360 (add-text-properties (match-beginning 1) (match-end 3)
5361 '(font-lock-fontified t face org-meta-line))
5362 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5363 '(font-lock-fontified t face org-block))
5364 ; for backend-specific code
5366 ((and (match-end 4) (equal dc3 "+begin"))
5367 ;; Truly a block
5368 (setq block-type (downcase (match-string 5))
5369 quoting (member block-type org-protecting-blocks))
5370 (when (re-search-forward
5371 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5372 nil t) ;; on purpose, we look further than LIMIT
5373 (setq end (min (point-max) (match-end 0))
5374 end1 (min (point-max) (1- (match-beginning 0))))
5375 (setq block-end (match-beginning 0))
5376 (when quoting
5377 (remove-text-properties beg end
5378 '(display t invisible t intangible t)))
5379 (add-text-properties
5380 beg end
5381 '(font-lock-fontified t font-lock-multiline t))
5382 (add-text-properties beg beg1 '(face org-meta-line))
5383 (add-text-properties end1 (min (point-max) (1+ end))
5384 '(face org-meta-line)) ; for end_src
5385 (cond
5386 ((and lang (not (string= lang "")) org-src-fontify-natively)
5387 (org-src-font-lock-fontify-block lang block-start block-end)
5388 ;; remove old background overlays
5389 (mapc (lambda (ov)
5390 (if (eq (overlay-get ov 'face) 'org-block-background)
5391 (delete-overlay ov)))
5392 (overlays-at (/ (+ beg1 block-end) 2)))
5393 ;; add a background overlay
5394 (setq ovl (make-overlay beg1 block-end))
5395 (overlay-put ovl 'face 'org-block-background)
5396 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5397 (quoting
5398 (add-text-properties beg1 (min (point-max) (1+ end1))
5399 '(face org-block))) ; end of source block
5400 ((not org-fontify-quote-and-verse-blocks))
5401 ((string= block-type "quote")
5402 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5403 ((string= block-type "verse")
5404 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5405 (add-text-properties beg beg1 '(face org-block-begin-line))
5406 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5407 '(face org-block-end-line))
5409 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5410 (add-text-properties
5411 beg (match-end 3)
5412 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5413 '(font-lock-fontified t invisible t)
5414 '(font-lock-fontified t face org-document-info-keyword)))
5415 (add-text-properties
5416 (match-beginning 6) (match-end 6)
5417 (if (string-equal dc1 "+title:")
5418 '(font-lock-fontified t face org-document-title)
5419 '(font-lock-fontified t face org-document-info))))
5420 ((or (equal dc1 "+results")
5421 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5422 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5423 "+call:" "+header:" "+headers:" "+name:"))
5424 (and (match-end 4) (equal dc3 "+attr")))
5425 (add-text-properties
5426 beg (match-end 0)
5427 '(font-lock-fontified t face org-meta-line))
5429 ((member dc3 '(" " ""))
5430 (add-text-properties
5431 beg (match-end 0)
5432 '(font-lock-fontified t face font-lock-comment-face)))
5433 ((not (member (char-after beg) '(?\ ?\t)))
5434 ;; just any other in-buffer setting, but not indented
5435 (add-text-properties
5436 beg (match-end 0)
5437 '(font-lock-fontified t face org-meta-line))
5439 (t nil))))))
5441 (defun org-activate-angle-links (limit)
5442 "Run through the buffer and add overlays to links."
5443 (if (and (re-search-forward org-angle-link-re limit t)
5444 (not (org-in-src-block-p)))
5445 (progn
5446 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5447 (add-text-properties (match-beginning 0) (match-end 0)
5448 (list 'mouse-face 'highlight
5449 'keymap org-mouse-map))
5450 (org-rear-nonsticky-at (match-end 0))
5451 t)))
5453 (defun org-activate-footnote-links (limit)
5454 "Run through the buffer and add overlays to footnotes."
5455 (let ((fn (org-footnote-next-reference-or-definition limit)))
5456 (when fn
5457 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5458 (org-remove-flyspell-overlays-in beg end)
5459 (add-text-properties beg end
5460 (list 'mouse-face 'highlight
5461 'keymap org-mouse-map
5462 'help-echo
5463 (if (= (point-at-bol) beg)
5464 "Footnote definition"
5465 "Footnote reference")
5466 'font-lock-fontified t
5467 'font-lock-multiline t
5468 'face 'org-footnote))))))
5470 (defun org-activate-bracket-links (limit)
5471 "Run through the buffer and add overlays to bracketed links."
5472 (if (and (re-search-forward org-bracket-link-regexp limit t)
5473 (not (org-in-src-block-p)))
5474 (let* ((help (concat "LINK: "
5475 (org-match-string-no-properties 1)))
5476 ;; FIXME: above we should remove the escapes.
5477 ;; but that requires another match, protecting match data,
5478 ;; a lot of overhead for font-lock.
5479 (ip (org-maybe-intangible
5480 (list 'invisible 'org-link
5481 'keymap org-mouse-map 'mouse-face 'highlight
5482 'font-lock-multiline t 'help-echo help)))
5483 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5484 'font-lock-multiline t 'help-echo help)))
5485 ;; We need to remove the invisible property here. Table narrowing
5486 ;; may have made some of this invisible.
5487 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5488 (remove-text-properties (match-beginning 0) (match-end 0)
5489 '(invisible nil))
5490 (if (match-end 3)
5491 (progn
5492 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5493 (org-rear-nonsticky-at (match-beginning 3))
5494 (add-text-properties (match-beginning 3) (match-end 3) vp)
5495 (org-rear-nonsticky-at (match-end 3))
5496 (add-text-properties (match-end 3) (match-end 0) ip)
5497 (org-rear-nonsticky-at (match-end 0)))
5498 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5499 (org-rear-nonsticky-at (match-beginning 1))
5500 (add-text-properties (match-beginning 1) (match-end 1) vp)
5501 (org-rear-nonsticky-at (match-end 1))
5502 (add-text-properties (match-end 1) (match-end 0) ip)
5503 (org-rear-nonsticky-at (match-end 0)))
5504 t)))
5506 (defun org-activate-dates (limit)
5507 "Run through the buffer and add overlays to dates."
5508 (if (re-search-forward org-tsr-regexp-both limit t)
5509 (progn
5510 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5511 (add-text-properties (match-beginning 0) (match-end 0)
5512 (list 'mouse-face 'highlight
5513 'keymap org-mouse-map))
5514 (org-rear-nonsticky-at (match-end 0))
5515 (when org-display-custom-times
5516 (if (match-end 3)
5517 (org-display-custom-time (match-beginning 3) (match-end 3)))
5518 (org-display-custom-time (match-beginning 1) (match-end 1)))
5519 t)))
5521 (defvar org-target-link-regexp nil
5522 "Regular expression matching radio targets in plain text.")
5523 (make-variable-buffer-local 'org-target-link-regexp)
5524 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5525 "Regular expression matching a link target.")
5526 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5527 "Regular expression matching a radio target.")
5528 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5529 "Regular expression matching any target.")
5531 (defun org-activate-target-links (limit)
5532 "Run through the buffer and add overlays to target matches."
5533 (when org-target-link-regexp
5534 (let ((case-fold-search t))
5535 (if (re-search-forward org-target-link-regexp limit t)
5536 (progn
5537 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5538 (add-text-properties (match-beginning 0) (match-end 0)
5539 (list 'mouse-face 'highlight
5540 'keymap org-mouse-map
5541 'help-echo "Radio target link"
5542 'org-linked-text t))
5543 (org-rear-nonsticky-at (match-end 0))
5544 t)))))
5546 (defun org-update-radio-target-regexp ()
5547 "Find all radio targets in this file and update the regular expression."
5548 (interactive)
5549 (when (memq 'radio org-activate-links)
5550 (setq org-target-link-regexp
5551 (org-make-target-link-regexp (org-all-targets 'radio)))
5552 (org-restart-font-lock)))
5554 (defun org-hide-wide-columns (limit)
5555 (let (s e)
5556 (setq s (text-property-any (point) (or limit (point-max))
5557 'org-cwidth t))
5558 (when s
5559 (setq e (next-single-property-change s 'org-cwidth))
5560 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5561 (goto-char e)
5562 t)))
5564 (defvar org-latex-and-specials-regexp nil
5565 "Regular expression for highlighting export special stuff.")
5566 (defvar org-match-substring-regexp)
5567 (defvar org-match-substring-with-braces-regexp)
5569 ;; This should be with the exporter code, but we also use if for font-locking
5570 (defconst org-export-html-special-string-regexps
5571 '(("\\\\-" . "&shy;")
5572 ("---\\([^-]\\)" . "&mdash;\\1")
5573 ("--\\([^-]\\)" . "&ndash;\\1")
5574 ("\\.\\.\\." . "&hellip;"))
5575 "Regular expressions for special string conversion.")
5578 (defun org-compute-latex-and-specials-regexp ()
5579 "Compute regular expression for stuff treated specially by exporters."
5580 (if (not org-highlight-latex-fragments-and-specials)
5581 (org-set-local 'org-latex-and-specials-regexp nil)
5582 (require 'org-exp)
5583 (let*
5584 ((matchers (plist-get org-format-latex-options :matchers))
5585 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5586 org-latex-regexps)))
5587 (org-export-allow-BIND nil)
5588 (options (org-combine-plists (org-default-export-plist)
5589 (org-infile-export-plist)))
5590 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5591 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5592 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5593 (org-export-html-expand (plist-get options :expand-quoted-html))
5594 (org-export-with-special-strings (plist-get options :special-strings))
5595 (re-sub
5596 (cond
5597 ((equal org-export-with-sub-superscripts '{})
5598 (list org-match-substring-with-braces-regexp))
5599 (org-export-with-sub-superscripts
5600 (list org-match-substring-regexp))))
5601 (re-latex
5602 (if org-export-with-LaTeX-fragments
5603 (mapcar (lambda (x) (nth 1 x)) latexs)))
5604 (re-macros
5605 (if org-export-with-TeX-macros
5606 (list (concat "\\\\"
5607 (regexp-opt
5608 (append
5610 (delq nil
5611 (mapcar 'car-safe
5612 (append org-entities-user
5613 org-entities)))
5614 (if (boundp 'org-latex-entities)
5615 (mapcar (lambda (x)
5616 (or (car-safe x) x))
5617 org-latex-entities)
5618 nil))
5619 'words))) ; FIXME
5621 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5622 (re-special (if org-export-with-special-strings
5623 (mapcar (lambda (x) (car x))
5624 org-export-html-special-string-regexps)))
5625 (re-rest
5626 (delq nil
5627 (list
5628 (if org-export-html-expand "@<[^>\n]+>")
5629 ))))
5630 (org-set-local
5631 'org-latex-and-specials-regexp
5632 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5633 re-rest) "\\|")))))
5635 (defun org-do-latex-and-special-faces (limit)
5636 "Run through the buffer and add overlays to links."
5637 (when org-latex-and-specials-regexp
5638 (let (rtn d)
5639 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5640 limit t))
5641 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5642 'face))
5643 '(org-code org-verbatim underline)))
5644 (progn
5645 (setq rtn t
5646 d (cond ((member (char-after (1+ (match-beginning 0)))
5647 '(?_ ?^)) 1)
5648 (t 0)))
5649 (font-lock-prepend-text-property
5650 (+ d (match-beginning 0)) (match-end 0)
5651 'face 'org-latex-and-export-specials)
5652 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5653 '(font-lock-multiline t)))))
5654 rtn)))
5656 (defun org-restart-font-lock ()
5657 "Restart `font-lock-mode', to force refontification."
5658 (when (and (boundp 'font-lock-mode) font-lock-mode)
5659 (font-lock-mode -1)
5660 (font-lock-mode 1)))
5662 (defun org-all-targets (&optional radio)
5663 "Return a list of all targets in this file.
5664 With optional argument RADIO, only find radio targets."
5665 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5666 rtn)
5667 (save-excursion
5668 (goto-char (point-min))
5669 (while (re-search-forward re nil t)
5670 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5671 rtn)))
5673 (defun org-make-target-link-regexp (targets)
5674 "Make regular expression matching all strings in TARGETS.
5675 The regular expression finds the targets also if there is a line break
5676 between words."
5677 (and targets
5678 (concat
5679 "\\<\\("
5680 (mapconcat
5681 (lambda (x)
5682 (setq x (regexp-quote x))
5683 (while (string-match " +" x)
5684 (setq x (replace-match "\\s-+" t t x)))
5686 targets
5687 "\\|")
5688 "\\)\\>")))
5690 (defun org-activate-tags (limit)
5691 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5692 (progn
5693 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5694 (add-text-properties (match-beginning 1) (match-end 1)
5695 (list 'mouse-face 'highlight
5696 'keymap org-mouse-map))
5697 (org-rear-nonsticky-at (match-end 1))
5698 t)))
5700 (defun org-outline-level ()
5701 "Compute the outline level of the heading at point.
5702 This function assumes that the cursor is at the beginning of a line matched
5703 by `outline-regexp'. Otherwise it returns garbage.
5704 If this is called at a normal headline, the level is the number of stars.
5705 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5706 (save-excursion
5707 (looking-at org-outline-regexp)
5708 (1- (- (match-end 0) (match-beginning 0)))))
5710 (defvar org-font-lock-keywords nil)
5712 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5713 "Regular expression matching a property line.")
5715 (defvar org-font-lock-hook nil
5716 "Functions to be called for special font lock stuff.")
5718 (defvar org-font-lock-set-keywords-hook nil
5719 "Functions that can manipulate `org-font-lock-extra-keywords'.
5720 This is called after `org-font-lock-extra-keywords' is defined, but before
5721 it is installed to be used by font lock. This can be useful if something
5722 needs to be inserted at a specific position in the font-lock sequence.")
5724 (defun org-font-lock-hook (limit)
5725 "Run `org-font-lock-hook' within LIMIT."
5726 (run-hook-with-args 'org-font-lock-hook limit))
5728 (defun org-set-font-lock-defaults ()
5729 "Set font lock defaults for the current buffer."
5730 (let* ((em org-fontify-emphasized-text)
5731 (lk org-activate-links)
5732 (org-font-lock-extra-keywords
5733 (list
5734 ;; Call the hook
5735 '(org-font-lock-hook)
5736 ;; Headlines
5737 `(,(if org-fontify-whole-heading-line
5738 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5739 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5740 (1 (org-get-level-face 1))
5741 (2 (org-get-level-face 2))
5742 (3 (org-get-level-face 3)))
5743 ;; Table lines
5744 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5745 (1 'org-table t))
5746 ;; Table internals
5747 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5748 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5749 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5750 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5751 ;; Drawers
5752 (list org-drawer-regexp '(0 'org-special-keyword t))
5753 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5754 ;; Properties
5755 (list org-property-re
5756 '(1 'org-special-keyword t)
5757 '(3 'org-property-value t))
5758 ;; Links
5759 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5760 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5761 (if (memq 'plain lk) '(org-activate-plain-links))
5762 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5763 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5764 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5765 (if (memq 'footnote lk) '(org-activate-footnote-links))
5766 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5767 '(org-hide-wide-columns (0 nil append))
5768 ;; TODO keyword
5769 (list (format org-heading-keyword-regexp-format
5770 org-todo-regexp)
5771 '(2 (org-get-todo-face 2) t))
5772 ;; DONE
5773 (if org-fontify-done-headline
5774 (list (format org-heading-keyword-regexp-format
5775 (concat
5776 "\\(?:"
5777 (mapconcat 'regexp-quote org-done-keywords "\\|")
5778 "\\)"))
5779 '(2 'org-headline-done t))
5780 nil)
5781 ;; Priorities
5782 '(org-font-lock-add-priority-faces)
5783 ;; Tags
5784 '(org-font-lock-add-tag-faces)
5785 ;; Special keywords
5786 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5787 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5788 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5789 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5790 ;; Emphasis
5791 (if em
5792 (if (featurep 'xemacs)
5793 '(org-do-emphasis-faces (0 nil append))
5794 '(org-do-emphasis-faces)))
5795 ;; Checkboxes
5796 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5797 1 'org-checkbox prepend)
5798 (if (cdr (assq 'checkbox org-list-automatic-rules))
5799 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5800 (0 (org-get-checkbox-statistics-face) t)))
5801 ;; Description list items
5802 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5803 1 'org-list-dt prepend)
5804 ;; ARCHIVEd headings
5805 (list (concat
5806 org-outline-regexp-bol
5807 "\\(.*:" org-archive-tag ":.*\\)")
5808 '(1 'org-archived prepend))
5809 ;; Specials
5810 '(org-do-latex-and-special-faces)
5811 '(org-fontify-entities)
5812 '(org-raise-scripts)
5813 ;; Code
5814 '(org-activate-code (1 'org-code t))
5815 ;; COMMENT
5816 (list (format org-heading-keyword-regexp-format
5817 (concat "\\("
5818 org-comment-string "\\|" org-quote-string
5819 "\\)"))
5820 '(2 'org-special-keyword t))
5821 ;; Blocks and meta lines
5822 '(org-fontify-meta-lines-and-blocks)
5824 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5825 (run-hooks 'org-font-lock-set-keywords-hook)
5826 ;; Now set the full font-lock-keywords
5827 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5828 (org-set-local 'font-lock-defaults
5829 '(org-font-lock-keywords t nil nil backward-paragraph))
5830 (kill-local-variable 'font-lock-keywords) nil))
5832 (defun org-toggle-pretty-entities ()
5833 "Toggle the composition display of entities as UTF8 characters."
5834 (interactive)
5835 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5836 (org-restart-font-lock)
5837 (if org-pretty-entities
5838 (message "Entities are displayed as UTF8 characters")
5839 (save-restriction
5840 (widen)
5841 (org-decompose-region (point-min) (point-max))
5842 (message "Entities are displayed plain"))))
5844 (defvar org-custom-properties-overlays nil
5845 "List of overlays used for custom properties.")
5846 (make-variable-buffer-local 'org-custom-properties-overlays)
5848 (defun org-toggle-custom-properties-visibility ()
5849 "Display or hide properties in `org-custom-properties'."
5850 (interactive)
5851 (if org-custom-properties-overlays
5852 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5853 (setq org-custom-properties-overlays nil))
5854 (unless (not org-custom-properties)
5855 (save-excursion
5856 (save-restriction
5857 (widen)
5858 (goto-char (point-min))
5859 (while (re-search-forward org-property-re nil t)
5860 (mapc (lambda(p)
5861 (when (equal p (substring (match-string 1) 1 -1))
5862 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5863 (overlay-put o 'invisible t)
5864 (overlay-put o 'org-custom-property t)
5865 (push o org-custom-properties-overlays))))
5866 org-custom-properties)))))))
5868 (defun org-fontify-entities (limit)
5869 "Find an entity to fontify."
5870 (let (ee)
5871 (when org-pretty-entities
5872 (catch 'match
5873 (while (re-search-forward
5874 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5875 limit t)
5876 (if (and (not (org-in-indented-comment-line))
5877 (setq ee (org-entity-get (match-string 1)))
5878 (= (length (nth 6 ee)) 1))
5879 (let*
5880 ((end (if (equal (match-string 2) "{}")
5881 (match-end 2)
5882 (match-end 1))))
5883 (add-text-properties
5884 (match-beginning 0) end
5885 (list 'font-lock-fontified t))
5886 (compose-region (match-beginning 0) end
5887 (nth 6 ee) nil)
5888 (backward-char 1)
5889 (throw 'match t))))
5890 nil))))
5892 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5893 "Fontify string S like in Org-mode."
5894 (with-temp-buffer
5895 (insert s)
5896 (let ((org-odd-levels-only odd-levels))
5897 (org-mode)
5898 (font-lock-fontify-buffer)
5899 (buffer-string))))
5901 (defvar org-m nil)
5902 (defvar org-l nil)
5903 (defvar org-f nil)
5904 (defun org-get-level-face (n)
5905 "Get the right face for match N in font-lock matching of headlines."
5906 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5907 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5908 (if org-cycle-level-faces
5909 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5910 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5911 (cond
5912 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5913 ((eq n 2) org-f)
5914 (t (if org-level-color-stars-only nil org-f))))
5917 (defun org-get-todo-face (kwd)
5918 "Get the right face for a TODO keyword KWD.
5919 If KWD is a number, get the corresponding match group."
5920 (if (numberp kwd) (setq kwd (match-string kwd)))
5921 (or (org-face-from-face-or-color
5922 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5923 (and (member kwd org-done-keywords) 'org-done)
5924 'org-todo))
5926 (defun org-face-from-face-or-color (context inherit face-or-color)
5927 "Create a face list that inherits INHERIT, but sets the foreground color.
5928 When FACE-OR-COLOR is not a string, just return it."
5929 (if (stringp face-or-color)
5930 (list :inherit inherit
5931 (cdr (assoc context org-faces-easy-properties))
5932 face-or-color)
5933 face-or-color))
5935 (defun org-font-lock-add-tag-faces (limit)
5936 "Add the special tag faces."
5937 (when (and org-tag-faces org-tags-special-faces-re)
5938 (while (re-search-forward org-tags-special-faces-re limit t)
5939 (add-text-properties (match-beginning 1) (match-end 1)
5940 (list 'face (org-get-tag-face 1)
5941 'font-lock-fontified t))
5942 (backward-char 1))))
5944 (defun org-font-lock-add-priority-faces (limit)
5945 "Add the special priority faces."
5946 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5947 (when (save-match-data (org-at-heading-p))
5948 (add-text-properties
5949 (match-beginning 0) (match-end 0)
5950 (list 'face (or (org-face-from-face-or-color
5951 'priority 'org-special-keyword
5952 (cdr (assoc (char-after (match-beginning 1))
5953 org-priority-faces)))
5954 'org-special-keyword)
5955 'font-lock-fontified t)))))
5957 (defun org-get-tag-face (kwd)
5958 "Get the right face for a TODO keyword KWD.
5959 If KWD is a number, get the corresponding match group."
5960 (if (numberp kwd) (setq kwd (match-string kwd)))
5961 (or (org-face-from-face-or-color
5962 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5963 'org-tag))
5965 (defun org-unfontify-region (beg end &optional maybe_loudly)
5966 "Remove fontification and activation overlays from links."
5967 (font-lock-default-unfontify-region beg end)
5968 (let* ((buffer-undo-list t)
5969 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5970 (inhibit-modification-hooks t)
5971 deactivate-mark buffer-file-name buffer-file-truename)
5972 (org-decompose-region beg end)
5973 (remove-text-properties beg end
5974 '(mouse-face t keymap t org-linked-text t
5975 invisible t intangible t
5976 org-no-flyspell t org-emphasis t))
5977 (org-remove-font-lock-display-properties beg end)))
5979 (defconst org-script-display '(((raise -0.3) (height 0.7))
5980 ((raise 0.3) (height 0.7))
5981 ((raise -0.5))
5982 ((raise 0.5)))
5983 "Display properties for showing superscripts and subscripts.")
5985 (defun org-remove-font-lock-display-properties (beg end)
5986 "Remove specific display properties that have been added by font lock.
5987 The will remove the raise properties that are used to show superscripts
5988 and subscripts."
5989 (let (next prop)
5990 (while (< beg end)
5991 (setq next (next-single-property-change beg 'display nil end)
5992 prop (get-text-property beg 'display))
5993 (if (member prop org-script-display)
5994 (put-text-property beg next 'display nil))
5995 (setq beg next))))
5997 (defun org-raise-scripts (limit)
5998 "Add raise properties to sub/superscripts."
5999 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6000 (if (re-search-forward
6001 (if (eq org-use-sub-superscripts t)
6002 org-match-substring-regexp
6003 org-match-substring-with-braces-regexp)
6004 limit t)
6005 (let* ((pos (point)) table-p comment-p
6006 (mpos (match-beginning 3))
6007 (emph-p (get-text-property mpos 'org-emphasis))
6008 (link-p (get-text-property mpos 'mouse-face))
6009 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6010 (goto-char (point-at-bol))
6011 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6012 comment-p (org-looking-at-p "[ \t]*#"))
6013 (goto-char pos)
6014 ;; FIXME: Should we go back one character here, for a_b^c
6015 ;; (goto-char (1- pos)) ;????????????????????
6016 (if (or comment-p emph-p link-p keyw-p)
6018 (put-text-property (match-beginning 3) (match-end 0)
6019 'display
6020 (if (equal (char-after (match-beginning 2)) ?^)
6021 (nth (if table-p 3 1) org-script-display)
6022 (nth (if table-p 2 0) org-script-display)))
6023 (add-text-properties (match-beginning 2) (match-end 2)
6024 (list 'invisible t
6025 'org-dwidth t 'org-dwidth-n 1))
6026 (if (and (eq (char-after (match-beginning 3)) ?{)
6027 (eq (char-before (match-end 3)) ?}))
6028 (progn
6029 (add-text-properties
6030 (match-beginning 3) (1+ (match-beginning 3))
6031 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6032 (add-text-properties
6033 (1- (match-end 3)) (match-end 3)
6034 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6035 t)))))
6037 ;;;; Visibility cycling, including org-goto and indirect buffer
6039 ;;; Cycling
6041 (defvar org-cycle-global-status nil)
6042 (make-variable-buffer-local 'org-cycle-global-status)
6043 (defvar org-cycle-subtree-status nil)
6044 (make-variable-buffer-local 'org-cycle-subtree-status)
6046 (defvar org-inlinetask-min-level)
6048 ;;;###autoload
6049 (defun org-cycle (&optional arg)
6050 "TAB-action and visibility cycling for Org-mode.
6052 This is the command invoked in Org-mode by the TAB key. Its main purpose
6053 is outline visibility cycling, but it also invokes other actions
6054 in special contexts.
6056 - When this function is called with a prefix argument, rotate the entire
6057 buffer through 3 states (global cycling)
6058 1. OVERVIEW: Show only top-level headlines.
6059 2. CONTENTS: Show all headlines of all levels, but no body text.
6060 3. SHOW ALL: Show everything.
6061 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6062 determined by the variable `org-startup-folded', and by any VISIBILITY
6063 properties in the buffer.
6064 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6065 including any drawers.
6067 - When inside a table, re-align the table and move to the next field.
6069 - When point is at the beginning of a headline, rotate the subtree started
6070 by this line through 3 different states (local cycling)
6071 1. FOLDED: Only the main headline is shown.
6072 2. CHILDREN: The main headline and the direct children are shown.
6073 From this state, you can move to one of the children
6074 and zoom in further.
6075 3. SUBTREE: Show the entire subtree, including body text.
6076 If there is no subtree, switch directly from CHILDREN to FOLDED.
6078 - When point is at the beginning of an empty headline and the variable
6079 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6080 of the headline by demoting and promoting it to likely levels. This
6081 speeds up creation document structure by pressing TAB once or several
6082 times right after creating a new headline.
6084 - When there is a numeric prefix, go up to a heading with level ARG, do
6085 a `show-subtree' and return to the previous cursor position. If ARG
6086 is negative, go up that many levels.
6088 - When point is not at the beginning of a headline, execute the global
6089 binding for TAB, which is re-indenting the line. See the option
6090 `org-cycle-emulate-tab' for details.
6092 - Special case: if point is at the beginning of the buffer and there is
6093 no headline in line 1, this function will act as if called with prefix arg
6094 (C-u TAB, same as S-TAB) also when called without prefix arg.
6095 But only if also the variable `org-cycle-global-at-bob' is t."
6096 (interactive "P")
6097 (org-load-modules-maybe)
6098 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6099 (and org-cycle-level-after-item/entry-creation
6100 (or (org-cycle-level)
6101 (org-cycle-item-indentation))))
6102 (let* ((limit-level
6103 (or org-cycle-max-level
6104 (and (boundp 'org-inlinetask-min-level)
6105 org-inlinetask-min-level
6106 (1- org-inlinetask-min-level))))
6107 (nstars (and limit-level
6108 (if org-odd-levels-only
6109 (and limit-level (1- (* limit-level 2)))
6110 limit-level)))
6111 (org-outline-regexp
6112 (if (not (derived-mode-p 'org-mode))
6113 outline-regexp
6114 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6115 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6116 (not (looking-at org-outline-regexp))))
6117 (org-cycle-hook
6118 (if bob-special
6119 (delq 'org-optimize-window-after-visibility-change
6120 (copy-sequence org-cycle-hook))
6121 org-cycle-hook))
6122 (pos (point)))
6124 (if (or bob-special (equal arg '(4)))
6125 ;; special case: use global cycling
6126 (setq arg t))
6128 (cond
6130 ((equal arg '(16))
6131 (setq last-command 'dummy)
6132 (org-set-startup-visibility)
6133 (message "Startup visibility, plus VISIBILITY properties"))
6135 ((equal arg '(64))
6136 (show-all)
6137 (message "Entire buffer visible, including drawers"))
6139 ;; Table: enter it or move to the next field.
6140 ((org-at-table-p 'any)
6141 (if (org-at-table.el-p)
6142 (message "Use C-c ' to edit table.el tables")
6143 (if arg (org-table-edit-field t)
6144 (org-table-justify-field-maybe)
6145 (call-interactively 'org-table-next-field))))
6147 ((run-hook-with-args-until-success
6148 'org-tab-after-check-for-table-hook))
6150 ;; Global cycling: delegate to `org-cycle-internal-global'.
6151 ((eq arg t) (org-cycle-internal-global))
6153 ;; Drawers: delegate to `org-flag-drawer'.
6154 ((and org-drawers org-drawer-regexp
6155 (save-excursion
6156 (beginning-of-line 1)
6157 (looking-at org-drawer-regexp)))
6158 (org-flag-drawer ; toggle block visibility
6159 (not (get-char-property (match-end 0) 'invisible))))
6161 ;; Show-subtree, ARG levels up from here.
6162 ((integerp arg)
6163 (save-excursion
6164 (org-back-to-heading)
6165 (outline-up-heading (if (< arg 0) (- arg)
6166 (- (funcall outline-level) arg)))
6167 (org-show-subtree)))
6169 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6170 ((and (featurep 'org-inlinetask)
6171 (org-inlinetask-at-task-p)
6172 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6173 (org-inlinetask-toggle-visibility))
6175 ((org-try-cdlatex-tab))
6177 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6178 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6179 (save-excursion (beginning-of-line 1)
6180 (looking-at org-outline-regexp)))
6181 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6182 (org-cycle-internal-local))
6184 ;; From there: TAB emulation and template completion.
6185 (buffer-read-only (org-back-to-heading))
6187 ((run-hook-with-args-until-success
6188 'org-tab-after-check-for-cycling-hook))
6190 ((org-try-structure-completion))
6192 ((run-hook-with-args-until-success
6193 'org-tab-before-tab-emulation-hook))
6195 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6196 (or (not (bolp))
6197 (not (looking-at org-outline-regexp))))
6198 (call-interactively (global-key-binding "\t")))
6200 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6201 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6202 (or (and (eq org-cycle-emulate-tab 'white)
6203 (= (match-end 0) (point-at-eol)))
6204 (and (eq org-cycle-emulate-tab 'whitestart)
6205 (>= (match-end 0) pos))))
6207 (eq org-cycle-emulate-tab t))
6208 (call-interactively (global-key-binding "\t")))
6210 (t (save-excursion
6211 (org-back-to-heading)
6212 (org-cycle)))))))
6214 (defun org-cycle-internal-global ()
6215 "Do the global cycling action."
6216 ;; Hack to avoid display of messages for .org attachments in Gnus
6217 (let ((ga (string-match "\\*fontification" (buffer-name))))
6218 (cond
6219 ((and (eq last-command this-command)
6220 (eq org-cycle-global-status 'overview))
6221 ;; We just created the overview - now do table of contents
6222 ;; This can be slow in very large buffers, so indicate action
6223 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6224 (unless ga (message "CONTENTS..."))
6225 (org-content)
6226 (unless ga (message "CONTENTS...done"))
6227 (setq org-cycle-global-status 'contents)
6228 (run-hook-with-args 'org-cycle-hook 'contents))
6230 ((and (eq last-command this-command)
6231 (eq org-cycle-global-status 'contents))
6232 ;; We just showed the table of contents - now show everything
6233 (run-hook-with-args 'org-pre-cycle-hook 'all)
6234 (show-all)
6235 (unless ga (message "SHOW ALL"))
6236 (setq org-cycle-global-status 'all)
6237 (run-hook-with-args 'org-cycle-hook 'all))
6240 ;; Default action: go to overview
6241 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6242 (org-overview)
6243 (unless ga (message "OVERVIEW"))
6244 (setq org-cycle-global-status 'overview)
6245 (run-hook-with-args 'org-cycle-hook 'overview)))))
6247 (defun org-cycle-internal-local ()
6248 "Do the local cycling action."
6249 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6250 ;; First, determine end of headline (EOH), end of subtree or item
6251 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6252 (save-excursion
6253 (if (org-at-item-p)
6254 (progn
6255 (beginning-of-line)
6256 (setq struct (org-list-struct))
6257 (setq eoh (point-at-eol))
6258 (setq eos (org-list-get-item-end-before-blank (point) struct))
6259 (setq has-children (org-list-has-child-p (point) struct)))
6260 (org-back-to-heading)
6261 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6262 (setq eos (save-excursion
6263 (org-end-of-subtree t)
6264 (unless (eobp)
6265 (skip-chars-forward " \t\n"))
6266 (if (eobp) (point) (1- (point)))))
6267 (setq has-children
6268 (or (save-excursion
6269 (let ((level (funcall outline-level)))
6270 (outline-next-heading)
6271 (and (org-at-heading-p t)
6272 (> (funcall outline-level) level))))
6273 (save-excursion
6274 (org-list-search-forward (org-item-beginning-re) eos t)))))
6275 ;; Determine end invisible part of buffer (EOL)
6276 (beginning-of-line 2)
6277 ;; XEmacs doesn't have `next-single-char-property-change'
6278 (if (featurep 'xemacs)
6279 (while (and (not (eobp)) ;; this is like `next-line'
6280 (get-char-property (1- (point)) 'invisible))
6281 (beginning-of-line 2))
6282 (while (and (not (eobp)) ;; this is like `next-line'
6283 (get-char-property (1- (point)) 'invisible))
6284 (goto-char (next-single-char-property-change (point) 'invisible))
6285 (and (eolp) (beginning-of-line 2))))
6286 (setq eol (point)))
6287 ;; Find out what to do next and set `this-command'
6288 (cond
6289 ((= eos eoh)
6290 ;; Nothing is hidden behind this heading
6291 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6292 (message "EMPTY ENTRY")
6293 (setq org-cycle-subtree-status nil)
6294 (save-excursion
6295 (goto-char eos)
6296 (outline-next-heading)
6297 (if (outline-invisible-p) (org-flag-heading nil))))
6298 ((and (or (>= eol eos)
6299 (not (string-match "\\S-" (buffer-substring eol eos))))
6300 (or has-children
6301 (not (setq children-skipped
6302 org-cycle-skip-children-state-if-no-children))))
6303 ;; Entire subtree is hidden in one line: children view
6304 (run-hook-with-args 'org-pre-cycle-hook 'children)
6305 (if (org-at-item-p)
6306 (org-list-set-item-visibility (point-at-bol) struct 'children)
6307 (org-show-entry)
6308 (org-with-limited-levels (show-children))
6309 ;; FIXME: This slows down the func way too much.
6310 ;; How keep drawers hidden in subtree anyway?
6311 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6312 ;; (org-cycle-hide-drawers 'subtree))
6314 ;; Fold every list in subtree to top-level items.
6315 (when (eq org-cycle-include-plain-lists 'integrate)
6316 (save-excursion
6317 (org-back-to-heading)
6318 (while (org-list-search-forward (org-item-beginning-re) eos t)
6319 (beginning-of-line 1)
6320 (let* ((struct (org-list-struct))
6321 (prevs (org-list-prevs-alist struct))
6322 (end (org-list-get-bottom-point struct)))
6323 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6324 (org-list-get-all-items (point) struct prevs))
6325 (goto-char end))))))
6326 (message "CHILDREN")
6327 (save-excursion
6328 (goto-char eos)
6329 (outline-next-heading)
6330 (if (outline-invisible-p) (org-flag-heading nil)))
6331 (setq org-cycle-subtree-status 'children)
6332 (run-hook-with-args 'org-cycle-hook 'children))
6333 ((or children-skipped
6334 (and (eq last-command this-command)
6335 (eq org-cycle-subtree-status 'children)))
6336 ;; We just showed the children, or no children are there,
6337 ;; now show everything.
6338 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6339 (outline-flag-region eoh eos nil)
6340 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6341 (setq org-cycle-subtree-status 'subtree)
6342 (run-hook-with-args 'org-cycle-hook 'subtree))
6344 ;; Default action: hide the subtree.
6345 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6346 (outline-flag-region eoh eos t)
6347 (message "FOLDED")
6348 (setq org-cycle-subtree-status 'folded)
6349 (run-hook-with-args 'org-cycle-hook 'folded)))))
6351 ;;;###autoload
6352 (defun org-global-cycle (&optional arg)
6353 "Cycle the global visibility. For details see `org-cycle'.
6354 With \\[universal-argument] prefix arg, switch to startup visibility.
6355 With a numeric prefix, show all headlines up to that level."
6356 (interactive "P")
6357 (let ((org-cycle-include-plain-lists
6358 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6359 (cond
6360 ((integerp arg)
6361 (show-all)
6362 (hide-sublevels arg)
6363 (setq org-cycle-global-status 'contents))
6364 ((equal arg '(4))
6365 (org-set-startup-visibility)
6366 (message "Startup visibility, plus VISIBILITY properties."))
6368 (org-cycle '(4))))))
6370 (defun org-set-startup-visibility ()
6371 "Set the visibility required by startup options and properties."
6372 (cond
6373 ((eq org-startup-folded t)
6374 (org-cycle '(4)))
6375 ((eq org-startup-folded 'content)
6376 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6377 (org-cycle '(4)) (org-cycle '(4)))))
6378 (unless (eq org-startup-folded 'showeverything)
6379 (if org-hide-block-startup (org-hide-block-all))
6380 (org-set-visibility-according-to-property 'no-cleanup)
6381 (org-cycle-hide-archived-subtrees 'all)
6382 (org-cycle-hide-drawers 'all)
6383 (org-cycle-show-empty-lines t)))
6385 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6386 "Switch subtree visibilities according to :VISIBILITY: property."
6387 (interactive)
6388 (let (org-show-entry-below state)
6389 (save-excursion
6390 (goto-char (point-min))
6391 (while (re-search-forward
6392 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6393 nil t)
6394 (setq state (match-string 1))
6395 (save-excursion
6396 (org-back-to-heading t)
6397 (hide-subtree)
6398 (org-reveal)
6399 (cond
6400 ((equal state '("fold" "folded"))
6401 (hide-subtree))
6402 ((equal state "children")
6403 (org-show-hidden-entry)
6404 (show-children))
6405 ((equal state "content")
6406 (save-excursion
6407 (save-restriction
6408 (org-narrow-to-subtree)
6409 (org-content))))
6410 ((member state '("all" "showall"))
6411 (show-subtree)))))
6412 (unless no-cleanup
6413 (org-cycle-hide-archived-subtrees 'all)
6414 (org-cycle-hide-drawers 'all)
6415 (org-cycle-show-empty-lines 'all)))))
6417 ;; This function uses outline-regexp instead of the more fundamental
6418 ;; org-outline-regexp so that org-cycle-global works outside of Org
6419 ;; buffers, where outline-regexp is needed.
6420 (defun org-overview ()
6421 "Switch to overview mode, showing only top-level headlines.
6422 Really, this shows all headlines with level equal or greater than the level
6423 of the first headline in the buffer. This is important, because if the
6424 first headline is not level one, then (hide-sublevels 1) gives confusing
6425 results."
6426 (interactive)
6427 (let ((level (save-excursion
6428 (goto-char (point-min))
6429 (if (re-search-forward (concat "^" outline-regexp) nil t)
6430 (progn
6431 (goto-char (match-beginning 0))
6432 (funcall outline-level))))))
6433 (and level (hide-sublevels level))))
6435 (defun org-content (&optional arg)
6436 "Show all headlines in the buffer, like a table of contents.
6437 With numerical argument N, show content up to level N."
6438 (interactive "P")
6439 (save-excursion
6440 ;; Visit all headings and show their offspring
6441 (and (integerp arg) (org-overview))
6442 (goto-char (point-max))
6443 (catch 'exit
6444 (while (and (progn (condition-case nil
6445 (outline-previous-visible-heading 1)
6446 (error (goto-char (point-min))))
6448 (looking-at org-outline-regexp))
6449 (if (integerp arg)
6450 (show-children (1- arg))
6451 (show-branches))
6452 (if (bobp) (throw 'exit nil))))))
6455 (defun org-optimize-window-after-visibility-change (state)
6456 "Adjust the window after a change in outline visibility.
6457 This function is the default value of the hook `org-cycle-hook'."
6458 (when (get-buffer-window (current-buffer))
6459 (cond
6460 ((eq state 'content) nil)
6461 ((eq state 'all) nil)
6462 ((eq state 'folded) nil)
6463 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6464 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6466 (defun org-remove-empty-overlays-at (pos)
6467 "Remove outline overlays that do not contain non-white stuff."
6468 (mapc
6469 (lambda (o)
6470 (and (eq 'outline (overlay-get o 'invisible))
6471 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6472 (overlay-end o))))
6473 (delete-overlay o)))
6474 (overlays-at pos)))
6476 (defun org-clean-visibility-after-subtree-move ()
6477 "Fix visibility issues after moving a subtree."
6478 ;; First, find a reasonable region to look at:
6479 ;; Start two siblings above, end three below
6480 (let* ((beg (save-excursion
6481 (and (org-get-last-sibling)
6482 (org-get-last-sibling))
6483 (point)))
6484 (end (save-excursion
6485 (and (org-get-next-sibling)
6486 (org-get-next-sibling)
6487 (org-get-next-sibling))
6488 (if (org-at-heading-p)
6489 (point-at-eol)
6490 (point))))
6491 (level (looking-at "\\*+"))
6492 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6493 (save-excursion
6494 (save-restriction
6495 (narrow-to-region beg end)
6496 (when re
6497 ;; Properly fold already folded siblings
6498 (goto-char (point-min))
6499 (while (re-search-forward re nil t)
6500 (if (and (not (outline-invisible-p))
6501 (save-excursion
6502 (goto-char (point-at-eol)) (outline-invisible-p)))
6503 (hide-entry))))
6504 (org-cycle-show-empty-lines 'overview)
6505 (org-cycle-hide-drawers 'overview)))))
6507 (defun org-cycle-show-empty-lines (state)
6508 "Show empty lines above all visible headlines.
6509 The region to be covered depends on STATE when called through
6510 `org-cycle-hook'. Lisp program can use t for STATE to get the
6511 entire buffer covered. Note that an empty line is only shown if there
6512 are at least `org-cycle-separator-lines' empty lines before the headline."
6513 (when (not (= org-cycle-separator-lines 0))
6514 (save-excursion
6515 (let* ((n (abs org-cycle-separator-lines))
6516 (re (cond
6517 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6518 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6519 (t (let ((ns (number-to-string (- n 2))))
6520 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6521 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6522 beg end b e)
6523 (cond
6524 ((memq state '(overview contents t))
6525 (setq beg (point-min) end (point-max)))
6526 ((memq state '(children folded))
6527 (setq beg (point) end (progn (org-end-of-subtree t t)
6528 (beginning-of-line 2)
6529 (point)))))
6530 (when beg
6531 (goto-char beg)
6532 (while (re-search-forward re end t)
6533 (unless (get-char-property (match-end 1) 'invisible)
6534 (setq e (match-end 1))
6535 (if (< org-cycle-separator-lines 0)
6536 (setq b (save-excursion
6537 (goto-char (match-beginning 0))
6538 (org-back-over-empty-lines)
6539 (if (save-excursion
6540 (goto-char (max (point-min) (1- (point))))
6541 (org-at-heading-p))
6542 (1- (point))
6543 (point))))
6544 (setq b (match-beginning 1)))
6545 (outline-flag-region b e nil)))))))
6546 ;; Never hide empty lines at the end of the file.
6547 (save-excursion
6548 (goto-char (point-max))
6549 (outline-previous-heading)
6550 (outline-end-of-heading)
6551 (if (and (looking-at "[ \t\n]+")
6552 (= (match-end 0) (point-max)))
6553 (outline-flag-region (point) (match-end 0) nil))))
6555 (defun org-show-empty-lines-in-parent ()
6556 "Move to the parent and re-show empty lines before visible headlines."
6557 (save-excursion
6558 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6559 (org-cycle-show-empty-lines context))))
6561 (defun org-files-list ()
6562 "Return `org-agenda-files' list, plus all open org-mode files.
6563 This is useful for operations that need to scan all of a user's
6564 open and agenda-wise Org files."
6565 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6566 (dolist (buf (buffer-list))
6567 (with-current-buffer buf
6568 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6569 (let ((file (expand-file-name (buffer-file-name))))
6570 (unless (member file files)
6571 (push file files))))))
6572 files))
6574 (defsubst org-entry-beginning-position ()
6575 "Return the beginning position of the current entry."
6576 (save-excursion (outline-back-to-heading t) (point)))
6578 (defsubst org-entry-end-position ()
6579 "Return the end position of the current entry."
6580 (save-excursion (outline-next-heading) (point)))
6582 (defun org-cycle-hide-drawers (state)
6583 "Re-hide all drawers after a visibility state change."
6584 (when (and (derived-mode-p 'org-mode)
6585 (not (memq state '(overview folded contents))))
6586 (save-excursion
6587 (let* ((globalp (memq state '(contents all)))
6588 (beg (if globalp (point-min) (point)))
6589 (end (if globalp (point-max)
6590 (if (eq state 'children)
6591 (save-excursion (outline-next-heading) (point))
6592 (org-end-of-subtree t)))))
6593 (goto-char beg)
6594 (while (re-search-forward org-drawer-regexp end t)
6595 (org-flag-drawer t))))))
6597 (defun org-flag-drawer (flag)
6598 "When FLAG is non-nil, hide the drawer we are within.
6599 Otherwise make it visible."
6600 (save-excursion
6601 (beginning-of-line 1)
6602 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6603 (let ((b (match-end 0)))
6604 (if (re-search-forward
6605 "^[ \t]*:END:"
6606 (save-excursion (outline-next-heading) (point)) t)
6607 (outline-flag-region b (point-at-eol) flag)
6608 (error ":END: line missing at position %s" b))))))
6610 (defun org-subtree-end-visible-p ()
6611 "Is the end of the current subtree visible?"
6612 (pos-visible-in-window-p
6613 (save-excursion (org-end-of-subtree t) (point))))
6615 (defun org-first-headline-recenter (&optional N)
6616 "Move cursor to the first headline and recenter the headline.
6617 Optional argument N means put the headline into the Nth line of the window."
6618 (goto-char (point-min))
6619 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6620 (beginning-of-line)
6621 (recenter (prefix-numeric-value N))))
6623 ;;; Saving and restoring visibility
6625 (defun org-outline-overlay-data (&optional use-markers)
6626 "Return a list of the locations of all outline overlays.
6627 These are overlays with the `invisible' property value `outline'.
6628 The return value is a list of cons cells, with start and stop
6629 positions for each overlay.
6630 If USE-MARKERS is set, return the positions as markers."
6631 (let (beg end)
6632 (save-excursion
6633 (save-restriction
6634 (widen)
6635 (delq nil
6636 (mapcar (lambda (o)
6637 (when (eq (overlay-get o 'invisible) 'outline)
6638 (setq beg (overlay-start o)
6639 end (overlay-end o))
6640 (and beg end (> end beg)
6641 (if use-markers
6642 (cons (move-marker (make-marker) beg)
6643 (move-marker (make-marker) end))
6644 (cons beg end)))))
6645 (overlays-in (point-min) (point-max))))))))
6647 (defun org-set-outline-overlay-data (data)
6648 "Create visibility overlays for all positions in DATA.
6649 DATA should have been made by `org-outline-overlay-data'."
6650 (let (o)
6651 (save-excursion
6652 (save-restriction
6653 (widen)
6654 (show-all)
6655 (mapc (lambda (c)
6656 (outline-flag-region (car c) (cdr c) t))
6657 data)))))
6659 ;;; Folding of blocks
6661 (defvar org-hide-block-overlays nil
6662 "Overlays hiding blocks.")
6663 (make-variable-buffer-local 'org-hide-block-overlays)
6665 (defun org-block-map (function &optional start end)
6666 "Call FUNCTION at the head of all source blocks in the current buffer.
6667 Optional arguments START and END can be used to limit the range."
6668 (let ((start (or start (point-min)))
6669 (end (or end (point-max))))
6670 (save-excursion
6671 (goto-char start)
6672 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6673 (save-excursion
6674 (save-match-data
6675 (goto-char (match-beginning 0))
6676 (funcall function)))))))
6678 (defun org-hide-block-toggle-all ()
6679 "Toggle the visibility of all blocks in the current buffer."
6680 (org-block-map #'org-hide-block-toggle))
6682 (defun org-hide-block-all ()
6683 "Fold all blocks in the current buffer."
6684 (interactive)
6685 (org-show-block-all)
6686 (org-block-map #'org-hide-block-toggle-maybe))
6688 (defun org-show-block-all ()
6689 "Unfold all blocks in the current buffer."
6690 (interactive)
6691 (mapc 'delete-overlay org-hide-block-overlays)
6692 (setq org-hide-block-overlays nil))
6694 (defun org-hide-block-toggle-maybe ()
6695 "Toggle visibility of block at point."
6696 (interactive)
6697 (let ((case-fold-search t))
6698 (if (save-excursion
6699 (beginning-of-line 1)
6700 (looking-at org-block-regexp))
6701 (progn (org-hide-block-toggle)
6702 t) ;; to signal that we took action
6703 nil))) ;; to signal that we did not
6705 (defun org-hide-block-toggle (&optional force)
6706 "Toggle the visibility of the current block."
6707 (interactive)
6708 (save-excursion
6709 (beginning-of-line)
6710 (if (re-search-forward org-block-regexp nil t)
6711 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6712 (end (match-end 0)) ;; end of entire body
6714 (if (memq t (mapcar (lambda (overlay)
6715 (eq (overlay-get overlay 'invisible)
6716 'org-hide-block))
6717 (overlays-at start)))
6718 (if (or (not force) (eq force 'off))
6719 (mapc (lambda (ov)
6720 (when (member ov org-hide-block-overlays)
6721 (setq org-hide-block-overlays
6722 (delq ov org-hide-block-overlays)))
6723 (when (eq (overlay-get ov 'invisible)
6724 'org-hide-block)
6725 (delete-overlay ov)))
6726 (overlays-at start)))
6727 (setq ov (make-overlay start end))
6728 (overlay-put ov 'invisible 'org-hide-block)
6729 ;; make the block accessible to isearch
6730 (overlay-put
6731 ov 'isearch-open-invisible
6732 (lambda (ov)
6733 (when (member ov org-hide-block-overlays)
6734 (setq org-hide-block-overlays
6735 (delq ov org-hide-block-overlays)))
6736 (when (eq (overlay-get ov 'invisible)
6737 'org-hide-block)
6738 (delete-overlay ov))))
6739 (push ov org-hide-block-overlays)))
6740 (error "Not looking at a source block"))))
6742 ;; org-tab-after-check-for-cycling-hook
6743 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6744 ;; Remove overlays when changing major mode
6745 (add-hook 'org-mode-hook
6746 (lambda () (org-add-hook 'change-major-mode-hook
6747 'org-show-block-all 'append 'local)))
6749 ;;; Org-goto
6751 (defvar org-goto-window-configuration nil)
6752 (defvar org-goto-marker nil)
6753 (defvar org-goto-map
6754 (let ((map (make-sparse-keymap)))
6755 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6756 (while (setq cmd (pop cmds))
6757 (substitute-key-definition cmd cmd map global-map)))
6758 (suppress-keymap map)
6759 (org-defkey map "\C-m" 'org-goto-ret)
6760 (org-defkey map [(return)] 'org-goto-ret)
6761 (org-defkey map [(left)] 'org-goto-left)
6762 (org-defkey map [(right)] 'org-goto-right)
6763 (org-defkey map [(control ?g)] 'org-goto-quit)
6764 (org-defkey map "\C-i" 'org-cycle)
6765 (org-defkey map [(tab)] 'org-cycle)
6766 (org-defkey map [(down)] 'outline-next-visible-heading)
6767 (org-defkey map [(up)] 'outline-previous-visible-heading)
6768 (if org-goto-auto-isearch
6769 (if (fboundp 'define-key-after)
6770 (define-key-after map [t] 'org-goto-local-auto-isearch)
6771 nil)
6772 (org-defkey map "q" 'org-goto-quit)
6773 (org-defkey map "n" 'outline-next-visible-heading)
6774 (org-defkey map "p" 'outline-previous-visible-heading)
6775 (org-defkey map "f" 'outline-forward-same-level)
6776 (org-defkey map "b" 'outline-backward-same-level)
6777 (org-defkey map "u" 'outline-up-heading))
6778 (org-defkey map "/" 'org-occur)
6779 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6780 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6781 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6782 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6783 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6784 map))
6786 (defconst org-goto-help
6787 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6788 RET=jump to location [Q]uit and return to previous location
6789 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6791 (defvar org-goto-start-pos) ; dynamically scoped parameter
6793 ;; FIXME: Docstring does not mention both interfaces
6794 (defun org-goto (&optional alternative-interface)
6795 "Look up a different location in the current file, keeping current visibility.
6797 When you want look-up or go to a different location in a
6798 document, the fastest way is often to fold the entire buffer and
6799 then dive into the tree. This method has the disadvantage, that
6800 the previous location will be folded, which may not be what you
6801 want.
6803 This command works around this by showing a copy of the current
6804 buffer in an indirect buffer, in overview mode. You can dive
6805 into the tree in that copy, use org-occur and incremental search
6806 to find a location. When pressing RET or `Q', the command
6807 returns to the original buffer in which the visibility is still
6808 unchanged. After RET it will also jump to the location selected
6809 in the indirect buffer and expose the headline hierarchy above.
6811 With a prefix argument, use the alternative interface: e.g. if
6812 `org-goto-interface' is 'outline use 'outline-path-completion."
6813 (interactive "P")
6814 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6815 (org-refile-use-outline-path t)
6816 (org-refile-target-verify-function nil)
6817 (interface
6818 (if (not alternative-interface)
6819 org-goto-interface
6820 (if (eq org-goto-interface 'outline)
6821 'outline-path-completion
6822 'outline)))
6823 (org-goto-start-pos (point))
6824 (selected-point
6825 (if (eq interface 'outline)
6826 (car (org-get-location (current-buffer) org-goto-help))
6827 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6828 (org-refile-check-position pa)
6829 (nth 3 pa)))))
6830 (if selected-point
6831 (progn
6832 (org-mark-ring-push org-goto-start-pos)
6833 (goto-char selected-point)
6834 (if (or (outline-invisible-p) (org-invisible-p2))
6835 (org-show-context 'org-goto)))
6836 (message "Quit"))))
6838 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6839 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6840 (defvar org-goto-local-auto-isearch-map) ; defined below
6842 (defun org-get-location (buf help)
6843 "Let the user select a location in the Org-mode buffer BUF.
6844 This function uses a recursive edit. It returns the selected position
6845 or nil."
6846 (org-no-popups
6847 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6848 (isearch-hide-immediately nil)
6849 (isearch-search-fun-function
6850 (lambda () 'org-goto-local-search-headings))
6851 (org-goto-selected-point org-goto-exit-command))
6852 (save-excursion
6853 (save-window-excursion
6854 (delete-other-windows)
6855 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6856 (org-pop-to-buffer-same-window
6857 (condition-case nil
6858 (make-indirect-buffer (current-buffer) "*org-goto*")
6859 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6860 (with-output-to-temp-buffer "*Help*"
6861 (princ help))
6862 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6863 (setq buffer-read-only nil)
6864 (let ((org-startup-truncated t)
6865 (org-startup-folded nil)
6866 (org-startup-align-all-tables nil))
6867 (org-mode)
6868 (org-overview))
6869 (setq buffer-read-only t)
6870 (if (and (boundp 'org-goto-start-pos)
6871 (integer-or-marker-p org-goto-start-pos))
6872 (let ((org-show-hierarchy-above t)
6873 (org-show-siblings t)
6874 (org-show-following-heading t))
6875 (goto-char org-goto-start-pos)
6876 (and (outline-invisible-p) (org-show-context)))
6877 (goto-char (point-min)))
6878 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6879 (message "Select location and press RET")
6880 (use-local-map org-goto-map)
6881 (recursive-edit)
6883 (kill-buffer "*org-goto*")
6884 (cons org-goto-selected-point org-goto-exit-command))))
6886 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6887 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6888 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6889 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6891 (defun org-goto-local-search-headings (string bound noerror)
6892 "Search and make sure that any matches are in headlines."
6893 (catch 'return
6894 (while (if isearch-forward
6895 (search-forward string bound noerror)
6896 (search-backward string bound noerror))
6897 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6898 (and (member :headline context)
6899 (not (member :tags context))))
6900 (throw 'return (point))))))
6902 (defun org-goto-local-auto-isearch ()
6903 "Start isearch."
6904 (interactive)
6905 (goto-char (point-min))
6906 (let ((keys (this-command-keys)))
6907 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6908 (isearch-mode t)
6909 (isearch-process-search-char (string-to-char keys)))))
6911 (defun org-goto-ret (&optional arg)
6912 "Finish `org-goto' by going to the new location."
6913 (interactive "P")
6914 (setq org-goto-selected-point (point)
6915 org-goto-exit-command 'return)
6916 (throw 'exit nil))
6918 (defun org-goto-left ()
6919 "Finish `org-goto' by going to the new location."
6920 (interactive)
6921 (if (org-at-heading-p)
6922 (progn
6923 (beginning-of-line 1)
6924 (setq org-goto-selected-point (point)
6925 org-goto-exit-command 'left)
6926 (throw 'exit nil))
6927 (error "Not on a heading")))
6929 (defun org-goto-right ()
6930 "Finish `org-goto' by going to the new location."
6931 (interactive)
6932 (if (org-at-heading-p)
6933 (progn
6934 (setq org-goto-selected-point (point)
6935 org-goto-exit-command 'right)
6936 (throw 'exit nil))
6937 (error "Not on a heading")))
6939 (defun org-goto-quit ()
6940 "Finish `org-goto' without cursor motion."
6941 (interactive)
6942 (setq org-goto-selected-point nil)
6943 (setq org-goto-exit-command 'quit)
6944 (throw 'exit nil))
6946 ;;; Indirect buffer display of subtrees
6948 (defvar org-indirect-dedicated-frame nil
6949 "This is the frame being used for indirect tree display.")
6950 (defvar org-last-indirect-buffer nil)
6952 (defun org-tree-to-indirect-buffer (&optional arg)
6953 "Create indirect buffer and narrow it to current subtree.
6954 With a numerical prefix ARG, go up to this level and then take that tree.
6955 If ARG is negative, go up that many levels.
6957 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6958 indirect buffer previously made with this command, to avoid proliferation of
6959 indirect buffers. However, when you call the command with a \
6960 \\[universal-argument] prefix, or
6961 when `org-indirect-buffer-display' is `new-frame', the last buffer
6962 is kept so that you can work with several indirect buffers at the same time.
6963 If `org-indirect-buffer-display' is `dedicated-frame', the \
6964 \\[universal-argument] prefix also
6965 requests that a new frame be made for the new buffer, so that the dedicated
6966 frame is not changed."
6967 (interactive "P")
6968 (let ((cbuf (current-buffer))
6969 (cwin (selected-window))
6970 (pos (point))
6971 beg end level heading ibuf)
6972 (save-excursion
6973 (org-back-to-heading t)
6974 (when (numberp arg)
6975 (setq level (org-outline-level))
6976 (if (< arg 0) (setq arg (+ level arg)))
6977 (while (> (setq level (org-outline-level)) arg)
6978 (org-up-heading-safe)))
6979 (setq beg (point)
6980 heading (org-get-heading))
6981 (org-end-of-subtree t t)
6982 (if (org-at-heading-p) (backward-char 1))
6983 (setq end (point)))
6984 (if (and (buffer-live-p org-last-indirect-buffer)
6985 (not (eq org-indirect-buffer-display 'new-frame))
6986 (not arg))
6987 (kill-buffer org-last-indirect-buffer))
6988 (setq ibuf (org-get-indirect-buffer cbuf)
6989 org-last-indirect-buffer ibuf)
6990 (cond
6991 ((or (eq org-indirect-buffer-display 'new-frame)
6992 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6993 (select-frame (make-frame))
6994 (delete-other-windows)
6995 (org-pop-to-buffer-same-window ibuf)
6996 (org-set-frame-title heading))
6997 ((eq org-indirect-buffer-display 'dedicated-frame)
6998 (raise-frame
6999 (select-frame (or (and org-indirect-dedicated-frame
7000 (frame-live-p org-indirect-dedicated-frame)
7001 org-indirect-dedicated-frame)
7002 (setq org-indirect-dedicated-frame (make-frame)))))
7003 (delete-other-windows)
7004 (org-pop-to-buffer-same-window ibuf)
7005 (org-set-frame-title (concat "Indirect: " heading)))
7006 ((eq org-indirect-buffer-display 'current-window)
7007 (org-pop-to-buffer-same-window ibuf))
7008 ((eq org-indirect-buffer-display 'other-window)
7009 (pop-to-buffer ibuf))
7010 (t (error "Invalid value")))
7011 (if (featurep 'xemacs)
7012 (save-excursion (org-mode) (turn-on-font-lock)))
7013 (narrow-to-region beg end)
7014 (show-all)
7015 (goto-char pos)
7016 (run-hook-with-args 'org-cycle-hook 'all)
7017 (and (window-live-p cwin) (select-window cwin))))
7019 (defun org-get-indirect-buffer (&optional buffer)
7020 (setq buffer (or buffer (current-buffer)))
7021 (let ((n 1) (base (buffer-name buffer)) bname)
7022 (while (buffer-live-p
7023 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7024 (setq n (1+ n)))
7025 (condition-case nil
7026 (make-indirect-buffer buffer bname 'clone)
7027 (error (make-indirect-buffer buffer bname)))))
7029 (defun org-set-frame-title (title)
7030 "Set the title of the current frame to the string TITLE."
7031 ;; FIXME: how to name a single frame in XEmacs???
7032 (unless (featurep 'xemacs)
7033 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7035 ;;;; Structure editing
7037 ;;; Inserting headlines
7039 (defun org-previous-line-empty-p ()
7040 (save-excursion
7041 (and (not (bobp))
7042 (or (beginning-of-line 0) t)
7043 (save-match-data
7044 (looking-at "[ \t]*$")))))
7046 (defun org-insert-heading (&optional force-heading invisible-ok)
7047 "Insert a new heading or item with same depth at point.
7048 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7049 If point is at the beginning of a headline, insert a sibling before the
7050 current headline. If point is not at the beginning, split the line,
7051 create the new headline with the text in the current line after point
7052 \(but see also the variable `org-M-RET-may-split-line').
7054 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7055 This is important for non-interactive uses of the command."
7056 (interactive "P")
7057 (if (or (= (buffer-size) 0)
7058 (and (not (save-excursion
7059 (and (ignore-errors (org-back-to-heading invisible-ok))
7060 (org-at-heading-p))))
7061 (or force-heading (not (org-in-item-p)))))
7062 (progn
7063 (insert "\n* ")
7064 (run-hooks 'org-insert-heading-hook))
7065 (when (or force-heading (not (org-insert-item)))
7066 (let* ((empty-line-p nil)
7067 (level nil)
7068 (on-heading (org-at-heading-p))
7069 (head (save-excursion
7070 (condition-case nil
7071 (progn
7072 (org-back-to-heading invisible-ok)
7073 (when (and (not on-heading)
7074 (featurep 'org-inlinetask)
7075 (integerp org-inlinetask-min-level)
7076 (>= (length (match-string 0))
7077 org-inlinetask-min-level))
7078 ;; Find a heading level before the inline task
7079 (while (and (setq level (org-up-heading-safe))
7080 (>= level org-inlinetask-min-level)))
7081 (if (org-at-heading-p)
7082 (org-back-to-heading invisible-ok)
7083 (error "This should not happen")))
7084 (setq empty-line-p (org-previous-line-empty-p))
7085 (match-string 0))
7086 (error "*"))))
7087 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7088 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7089 pos hide-previous previous-pos)
7090 (cond
7091 ((and (org-at-heading-p) (bolp)
7092 (or (bobp)
7093 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7094 ;; insert before the current line
7095 (open-line (if blank 2 1)))
7096 ((and (bolp)
7097 (not org-insert-heading-respect-content)
7098 (or (bobp)
7099 (save-excursion
7100 (backward-char 1) (not (outline-invisible-p)))))
7101 ;; insert right here
7102 nil)
7104 ;; somewhere in the line
7105 (save-excursion
7106 (setq previous-pos (point-at-bol))
7107 (end-of-line)
7108 (setq hide-previous (outline-invisible-p)))
7109 (and org-insert-heading-respect-content (org-show-subtree))
7110 (let ((split
7111 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7112 (save-excursion
7113 (let ((p (point)))
7114 (goto-char (point-at-bol))
7115 (and (looking-at org-complex-heading-regexp)
7116 (match-beginning 4)
7117 (> p (match-beginning 4)))))))
7118 tags pos)
7119 (cond
7120 (org-insert-heading-respect-content
7121 (org-end-of-subtree nil t)
7122 (when (featurep 'org-inlinetask)
7123 (while (and (not (eobp))
7124 (looking-at "\\(\\*+\\)[ \t]+")
7125 (>= (length (match-string 1))
7126 org-inlinetask-min-level))
7127 (org-end-of-subtree nil t)))
7128 (or (bolp) (newline))
7129 (or (org-previous-line-empty-p)
7130 (and blank (newline)))
7131 (open-line 1))
7132 ((org-at-heading-p)
7133 (when hide-previous
7134 (show-children)
7135 (org-show-entry))
7136 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7137 (setq tags (and (match-end 2) (match-string 2)))
7138 (and (match-end 1)
7139 (delete-region (match-beginning 1) (match-end 1)))
7140 (setq pos (point-at-bol))
7141 (or split (end-of-line 1))
7142 (delete-horizontal-space)
7143 (if (string-match "\\`\\*+\\'"
7144 (buffer-substring (point-at-bol) (point)))
7145 (insert " "))
7146 (newline (if blank 2 1))
7147 (when tags
7148 (save-excursion
7149 (goto-char pos)
7150 (end-of-line 1)
7151 (insert " " tags)
7152 (org-set-tags nil 'align))))
7154 (or split (end-of-line 1))
7155 (newline (if blank 2 1)))))))
7156 (insert head) (just-one-space)
7157 (setq pos (point))
7158 (end-of-line 1)
7159 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7160 (when (and org-insert-heading-respect-content hide-previous)
7161 (save-excursion
7162 (goto-char previous-pos)
7163 (hide-subtree)))
7164 (run-hooks 'org-insert-heading-hook)))))
7166 (defun org-get-heading (&optional no-tags no-todo)
7167 "Return the heading of the current entry, without the stars.
7168 When NO-TAGS is non-nil, don't include tags.
7169 When NO-TODO is non-nil, don't include TODO keywords."
7170 (save-excursion
7171 (org-back-to-heading t)
7172 (cond
7173 ((and no-tags no-todo)
7174 (looking-at org-complex-heading-regexp)
7175 (match-string 4))
7176 (no-tags
7177 (looking-at (concat org-outline-regexp
7178 "\\(.*?\\)"
7179 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7180 (match-string 1))
7181 (no-todo
7182 (looking-at org-todo-line-regexp)
7183 (match-string 3))
7184 (t (looking-at org-heading-regexp)
7185 (match-string 2)))))
7187 (defun org-heading-components ()
7188 "Return the components of the current heading.
7189 This is a list with the following elements:
7190 - the level as an integer
7191 - the reduced level, different if `org-odd-levels-only' is set.
7192 - the TODO keyword, or nil
7193 - the priority character, like ?A, or nil if no priority is given
7194 - the headline text itself, or the tags string if no headline text
7195 - the tags string, or nil."
7196 (save-excursion
7197 (org-back-to-heading t)
7198 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7199 (list (length (match-string 1))
7200 (org-reduced-level (length (match-string 1)))
7201 (org-match-string-no-properties 2)
7202 (and (match-end 3) (aref (match-string 3) 2))
7203 (org-match-string-no-properties 4)
7204 (org-match-string-no-properties 5)))))
7206 (defun org-get-entry ()
7207 "Get the entry text, after heading, entire subtree."
7208 (save-excursion
7209 (org-back-to-heading t)
7210 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7212 (defun org-insert-heading-after-current ()
7213 "Insert a new heading with same level as current, after current subtree."
7214 (interactive)
7215 (org-back-to-heading)
7216 (org-insert-heading)
7217 (org-move-subtree-down)
7218 (end-of-line 1))
7220 (defun org-insert-heading-respect-content ()
7221 (interactive)
7222 (let ((org-insert-heading-respect-content t))
7223 (org-insert-heading t)))
7225 (defun org-insert-todo-heading-respect-content (&optional force-state)
7226 (interactive "P")
7227 (let ((org-insert-heading-respect-content t))
7228 (org-insert-todo-heading force-state t)))
7230 (defun org-insert-todo-heading (arg &optional force-heading)
7231 "Insert a new heading with the same level and TODO state as current heading.
7232 If the heading has no TODO state, or if the state is DONE, use the first
7233 state (TODO by default). Also with prefix arg, force first state."
7234 (interactive "P")
7235 (when (or force-heading (not (org-insert-item 'checkbox)))
7236 (org-insert-heading force-heading)
7237 (save-excursion
7238 (org-back-to-heading)
7239 (outline-previous-heading)
7240 (looking-at org-todo-line-regexp))
7241 (let*
7242 ((new-mark-x
7243 (if (or arg
7244 (not (match-beginning 2))
7245 (member (match-string 2) org-done-keywords))
7246 (car org-todo-keywords-1)
7247 (match-string 2)))
7248 (new-mark
7250 (run-hook-with-args-until-success
7251 'org-todo-get-default-hook new-mark-x nil)
7252 new-mark-x)))
7253 (beginning-of-line 1)
7254 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7255 (if org-treat-insert-todo-heading-as-state-change
7256 (org-todo new-mark)
7257 (insert new-mark " "))))
7258 (when org-provide-todo-statistics
7259 (org-update-parent-todo-statistics))))
7261 (defun org-insert-subheading (arg)
7262 "Insert a new subheading and demote it.
7263 Works for outline headings and for plain lists alike."
7264 (interactive "P")
7265 (org-insert-heading arg)
7266 (cond
7267 ((org-at-heading-p) (org-do-demote))
7268 ((org-at-item-p) (org-indent-item))))
7270 (defun org-insert-todo-subheading (arg)
7271 "Insert a new subheading with TODO keyword or checkbox and demote it.
7272 Works for outline headings and for plain lists alike."
7273 (interactive "P")
7274 (org-insert-todo-heading arg)
7275 (cond
7276 ((org-at-heading-p) (org-do-demote))
7277 ((org-at-item-p) (org-indent-item))))
7279 ;;; Promotion and Demotion
7281 (defvar org-after-demote-entry-hook nil
7282 "Hook run after an entry has been demoted.
7283 The cursor will be at the beginning of the entry.
7284 When a subtree is being demoted, the hook will be called for each node.")
7286 (defvar org-after-promote-entry-hook nil
7287 "Hook run after an entry has been promoted.
7288 The cursor will be at the beginning of the entry.
7289 When a subtree is being promoted, the hook will be called for each node.")
7291 (defun org-promote-subtree ()
7292 "Promote the entire subtree.
7293 See also `org-promote'."
7294 (interactive)
7295 (save-excursion
7296 (org-with-limited-levels (org-map-tree 'org-promote)))
7297 (org-fix-position-after-promote))
7299 (defun org-demote-subtree ()
7300 "Demote the entire subtree. See `org-demote'.
7301 See also `org-promote'."
7302 (interactive)
7303 (save-excursion
7304 (org-with-limited-levels (org-map-tree 'org-demote)))
7305 (org-fix-position-after-promote))
7308 (defun org-do-promote ()
7309 "Promote the current heading higher up the tree.
7310 If the region is active in `transient-mark-mode', promote all headings
7311 in the region."
7312 (interactive)
7313 (save-excursion
7314 (if (org-region-active-p)
7315 (org-map-region 'org-promote (region-beginning) (region-end))
7316 (org-promote)))
7317 (org-fix-position-after-promote))
7319 (defun org-do-demote ()
7320 "Demote the current heading lower down the tree.
7321 If the region is active in `transient-mark-mode', demote all headings
7322 in the region."
7323 (interactive)
7324 (save-excursion
7325 (if (org-region-active-p)
7326 (org-map-region 'org-demote (region-beginning) (region-end))
7327 (org-demote)))
7328 (org-fix-position-after-promote))
7330 (defun org-fix-position-after-promote ()
7331 "Make sure that after pro/demotion cursor position is right."
7332 (let ((pos (point)))
7333 (when (save-excursion
7334 (beginning-of-line 1)
7335 (looking-at org-todo-line-regexp)
7336 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7337 (cond ((eobp) (insert " "))
7338 ((eolp) (insert " "))
7339 ((equal (char-after) ?\ ) (forward-char 1))))))
7341 (defun org-current-level ()
7342 "Return the level of the current entry, or nil if before the first headline.
7343 The level is the number of stars at the beginning of the headline."
7344 (save-excursion
7345 (org-with-limited-levels
7346 (if (ignore-errors (org-back-to-heading t))
7347 (funcall outline-level)))))
7349 (defun org-get-previous-line-level ()
7350 "Return the outline depth of the last headline before the current line.
7351 Returns 0 for the first headline in the buffer, and nil if before the
7352 first headline."
7353 (let ((current-level (org-current-level))
7354 (prev-level (when (> (line-number-at-pos) 1)
7355 (save-excursion
7356 (beginning-of-line 0)
7357 (org-current-level)))))
7358 (cond ((null current-level) nil) ; Before first headline
7359 ((null prev-level) 0) ; At first headline
7360 (prev-level))))
7362 (defun org-reduced-level (l)
7363 "Compute the effective level of a heading.
7364 This takes into account the setting of `org-odd-levels-only'."
7365 (cond
7366 ((zerop l) 0)
7367 (org-odd-levels-only (1+ (floor (/ l 2))))
7368 (t l)))
7370 (defun org-level-increment ()
7371 "Return the number of stars that will be added or removed at a
7372 time to headlines when structure editing, based on the value of
7373 `org-odd-levels-only'."
7374 (if org-odd-levels-only 2 1))
7376 (defun org-get-valid-level (level &optional change)
7377 "Rectify a level change under the influence of `org-odd-levels-only'
7378 LEVEL is a current level, CHANGE is by how much the level should be
7379 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7380 even level numbers will become the next higher odd number."
7381 (if org-odd-levels-only
7382 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7383 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7384 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7385 (max 1 (+ level (or change 0)))))
7387 (if (boundp 'define-obsolete-function-alias)
7388 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7389 (define-obsolete-function-alias 'org-get-legal-level
7390 'org-get-valid-level)
7391 (define-obsolete-function-alias 'org-get-legal-level
7392 'org-get-valid-level "23.1")))
7394 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7395 ;; ̀org-with-limited-levels'
7396 (defun org-promote ()
7397 "Promote the current heading higher up the tree.
7398 If the region is active in `transient-mark-mode', promote all headings
7399 in the region."
7400 (org-back-to-heading t)
7401 (let* ((level (save-match-data (funcall outline-level)))
7402 (after-change-functions (remove 'flyspell-after-change-function
7403 after-change-functions))
7404 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7405 (diff (abs (- level (length up-head) -1))))
7406 (cond ((and (= level 1) org-called-with-limited-levels
7407 org-allow-promoting-top-level-subtree)
7408 (replace-match "# " nil t))
7409 ((= level 1)
7410 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7411 (t (replace-match up-head nil t)))
7412 ;; Fixup tag positioning
7413 (unless (= level 1)
7414 (and org-auto-align-tags (org-set-tags nil t))
7415 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7416 (run-hooks 'org-after-promote-entry-hook)))
7418 (defun org-demote ()
7419 "Demote the current heading lower down the tree.
7420 If the region is active in `transient-mark-mode', demote all headings
7421 in the region."
7422 (org-back-to-heading t)
7423 (let* ((level (save-match-data (funcall outline-level)))
7424 (after-change-functions (remove 'flyspell-after-change-function
7425 after-change-functions))
7426 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7427 (diff (abs (- level (length down-head) -1))))
7428 (replace-match down-head nil t)
7429 ;; Fixup tag positioning
7430 (and org-auto-align-tags (org-set-tags nil t))
7431 (if org-adapt-indentation (org-fixup-indentation diff))
7432 (run-hooks 'org-after-demote-entry-hook)))
7434 (defun org-cycle-level ()
7435 "Cycle the level of an empty headline through possible states.
7436 This goes first to child, then to parent, level, then up the hierarchy.
7437 After top level, it switches back to sibling level."
7438 (interactive)
7439 (let ((org-adapt-indentation nil))
7440 (when (org-point-at-end-of-empty-headline)
7441 (setq this-command 'org-cycle-level) ; Only needed for caching
7442 (let ((cur-level (org-current-level))
7443 (prev-level (org-get-previous-line-level)))
7444 (cond
7445 ;; If first headline in file, promote to top-level.
7446 ((= prev-level 0)
7447 (loop repeat (/ (- cur-level 1) (org-level-increment))
7448 do (org-do-promote)))
7449 ;; If same level as prev, demote one.
7450 ((= prev-level cur-level)
7451 (org-do-demote))
7452 ;; If parent is top-level, promote to top level if not already.
7453 ((= prev-level 1)
7454 (loop repeat (/ (- cur-level 1) (org-level-increment))
7455 do (org-do-promote)))
7456 ;; If top-level, return to prev-level.
7457 ((= cur-level 1)
7458 (loop repeat (/ (- prev-level 1) (org-level-increment))
7459 do (org-do-demote)))
7460 ;; If less than prev-level, promote one.
7461 ((< cur-level prev-level)
7462 (org-do-promote))
7463 ;; If deeper than prev-level, promote until higher than
7464 ;; prev-level.
7465 ((> cur-level prev-level)
7466 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7467 do (org-do-promote))))
7468 t))))
7470 (defun org-map-tree (fun)
7471 "Call FUN for every heading underneath the current one."
7472 (org-back-to-heading)
7473 (let ((level (funcall outline-level)))
7474 (save-excursion
7475 (funcall fun)
7476 (while (and (progn
7477 (outline-next-heading)
7478 (> (funcall outline-level) level))
7479 (not (eobp)))
7480 (funcall fun)))))
7482 (defun org-map-region (fun beg end)
7483 "Call FUN for every heading between BEG and END."
7484 (let ((org-ignore-region t))
7485 (save-excursion
7486 (setq end (copy-marker end))
7487 (goto-char beg)
7488 (if (and (re-search-forward org-outline-regexp-bol nil t)
7489 (< (point) end))
7490 (funcall fun))
7491 (while (and (progn
7492 (outline-next-heading)
7493 (< (point) end))
7494 (not (eobp)))
7495 (funcall fun)))))
7497 (defvar org-property-end-re) ; silence byte-compiler
7498 (defun org-fixup-indentation (diff)
7499 "Change the indentation in the current entry by DIFF.
7500 However, if any line in the current entry has no indentation, or if it
7501 would end up with no indentation after the change, nothing at all is done."
7502 (save-excursion
7503 (let ((end (save-excursion (outline-next-heading)
7504 (point-marker)))
7505 (prohibit (if (> diff 0)
7506 "^\\S-"
7507 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7508 col)
7509 (unless (save-excursion (end-of-line 1)
7510 (re-search-forward prohibit end t))
7511 (while (and (< (point) end)
7512 (re-search-forward "^[ \t]+" end t))
7513 (goto-char (match-end 0))
7514 (setq col (current-column))
7515 (if (< diff 0) (replace-match ""))
7516 (org-indent-to-column (+ diff col))))
7517 (move-marker end nil))))
7519 (defun org-convert-to-odd-levels ()
7520 "Convert an org-mode file with all levels allowed to one with odd levels.
7521 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7522 level 5 etc."
7523 (interactive)
7524 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7525 (let ((outline-level 'org-outline-level)
7526 (org-odd-levels-only nil) n)
7527 (save-excursion
7528 (goto-char (point-min))
7529 (while (re-search-forward "^\\*\\*+ " nil t)
7530 (setq n (- (length (match-string 0)) 2))
7531 (while (>= (setq n (1- n)) 0)
7532 (org-demote))
7533 (end-of-line 1))))))
7535 (defun org-convert-to-oddeven-levels ()
7536 "Convert an org-mode file with only odd levels to one with odd/even levels.
7537 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7538 file contains a section with an even level, conversion would
7539 destroy the structure of the file. An error is signaled in this
7540 case."
7541 (interactive)
7542 (goto-char (point-min))
7543 ;; First check if there are no even levels
7544 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7545 (org-show-context t)
7546 (error "Not all levels are odd in this file. Conversion not possible"))
7547 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7548 (let ((outline-regexp org-outline-regexp)
7549 (outline-level 'org-outline-level)
7550 (org-odd-levels-only nil) n)
7551 (save-excursion
7552 (goto-char (point-min))
7553 (while (re-search-forward "^\\*\\*+ " nil t)
7554 (setq n (/ (1- (length (match-string 0))) 2))
7555 (while (>= (setq n (1- n)) 0)
7556 (org-promote))
7557 (end-of-line 1))))))
7559 (defun org-tr-level (n)
7560 "Make N odd if required."
7561 (if org-odd-levels-only (1+ (/ n 2)) n))
7563 ;;; Vertical tree motion, cutting and pasting of subtrees
7565 (defun org-move-subtree-up (&optional arg)
7566 "Move the current subtree up past ARG headlines of the same level."
7567 (interactive "p")
7568 (org-move-subtree-down (- (prefix-numeric-value arg))))
7570 (defun org-move-subtree-down (&optional arg)
7571 "Move the current subtree down past ARG headlines of the same level."
7572 (interactive "p")
7573 (setq arg (prefix-numeric-value arg))
7574 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7575 'org-get-last-sibling))
7576 (ins-point (make-marker))
7577 (cnt (abs arg))
7578 (col (current-column))
7579 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7580 ;; Select the tree
7581 (org-back-to-heading)
7582 (setq beg0 (point))
7583 (save-excursion
7584 (setq ne-beg (org-back-over-empty-lines))
7585 (setq beg (point)))
7586 (save-match-data
7587 (save-excursion (outline-end-of-heading)
7588 (setq folded (outline-invisible-p)))
7589 (outline-end-of-subtree))
7590 (outline-next-heading)
7591 (setq ne-end (org-back-over-empty-lines))
7592 (setq end (point))
7593 (goto-char beg0)
7594 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7595 ;; include less whitespace
7596 (save-excursion
7597 (goto-char beg)
7598 (forward-line (- ne-beg ne-end))
7599 (setq beg (point))))
7600 ;; Find insertion point, with error handling
7601 (while (> cnt 0)
7602 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7603 (progn (goto-char beg0)
7604 (error "Cannot move past superior level or buffer limit")))
7605 (setq cnt (1- cnt)))
7606 (if (> arg 0)
7607 ;; Moving forward - still need to move over subtree
7608 (progn (org-end-of-subtree t t)
7609 (save-excursion
7610 (org-back-over-empty-lines)
7611 (or (bolp) (newline)))))
7612 (setq ne-ins (org-back-over-empty-lines))
7613 (move-marker ins-point (point))
7614 (setq txt (buffer-substring beg end))
7615 (org-save-markers-in-region beg end)
7616 (delete-region beg end)
7617 (org-remove-empty-overlays-at beg)
7618 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7619 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7620 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7621 (let ((bbb (point)))
7622 (insert-before-markers txt)
7623 (org-reinstall-markers-in-region bbb)
7624 (move-marker ins-point bbb))
7625 (or (bolp) (insert "\n"))
7626 (setq ins-end (point))
7627 (goto-char ins-point)
7628 (org-skip-whitespace)
7629 (when (and (< arg 0)
7630 (org-first-sibling-p)
7631 (> ne-ins ne-beg))
7632 ;; Move whitespace back to beginning
7633 (save-excursion
7634 (goto-char ins-end)
7635 (let ((kill-whole-line t))
7636 (kill-line (- ne-ins ne-beg)) (point)))
7637 (insert (make-string (- ne-ins ne-beg) ?\n)))
7638 (move-marker ins-point nil)
7639 (if folded
7640 (hide-subtree)
7641 (org-show-entry)
7642 (show-children)
7643 (org-cycle-hide-drawers 'children))
7644 (org-clean-visibility-after-subtree-move)
7645 ;; move back to the initial column we were at
7646 (move-to-column col)))
7648 (defvar org-subtree-clip ""
7649 "Clipboard for cut and paste of subtrees.
7650 This is actually only a copy of the kill, because we use the normal kill
7651 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7653 (defvar org-subtree-clip-folded nil
7654 "Was the last copied subtree folded?
7655 This is used to fold the tree back after pasting.")
7657 (defun org-cut-subtree (&optional n)
7658 "Cut the current subtree into the clipboard.
7659 With prefix arg N, cut this many sequential subtrees.
7660 This is a short-hand for marking the subtree and then cutting it."
7661 (interactive "p")
7662 (org-copy-subtree n 'cut))
7664 (defun org-copy-subtree (&optional n cut force-store-markers)
7665 "Cut the current subtree into the clipboard.
7666 With prefix arg N, cut this many sequential subtrees.
7667 This is a short-hand for marking the subtree and then copying it.
7668 If CUT is non-nil, actually cut the subtree.
7669 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7670 of some markers in the region, even if CUT is non-nil. This is
7671 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7672 (interactive "p")
7673 (let (beg end folded (beg0 (point)))
7674 (if (org-called-interactively-p 'any)
7675 (org-back-to-heading nil) ; take what looks like a subtree
7676 (org-back-to-heading t)) ; take what is really there
7677 (setq beg (point))
7678 (skip-chars-forward " \t\r\n")
7679 (save-match-data
7680 (save-excursion (outline-end-of-heading)
7681 (setq folded (outline-invisible-p)))
7682 (condition-case nil
7683 (org-forward-heading-same-level (1- n) t)
7684 (error nil))
7685 (org-end-of-subtree t t))
7686 (setq end (point))
7687 (goto-char beg0)
7688 (when (> end beg)
7689 (setq org-subtree-clip-folded folded)
7690 (when (or cut force-store-markers)
7691 (org-save-markers-in-region beg end))
7692 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7693 (setq org-subtree-clip (current-kill 0))
7694 (message "%s: Subtree(s) with %d characters"
7695 (if cut "Cut" "Copied")
7696 (length org-subtree-clip)))))
7698 (defun org-paste-subtree (&optional level tree for-yank)
7699 "Paste the clipboard as a subtree, with modification of headline level.
7700 The entire subtree is promoted or demoted in order to match a new headline
7701 level.
7703 If the cursor is at the beginning of a headline, the same level as
7704 that headline is used to paste the tree
7706 If not, the new level is derived from the *visible* headings
7707 before and after the insertion point, and taken to be the inferior headline
7708 level of the two. So if the previous visible heading is level 3 and the
7709 next is level 4 (or vice versa), level 4 will be used for insertion.
7710 This makes sure that the subtree remains an independent subtree and does
7711 not swallow low level entries.
7713 You can also force a different level, either by using a numeric prefix
7714 argument, or by inserting the heading marker by hand. For example, if the
7715 cursor is after \"*****\", then the tree will be shifted to level 5.
7717 If optional TREE is given, use this text instead of the kill ring.
7719 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7720 move back over whitespace before inserting, and move point to the end of
7721 the inserted text when done."
7722 (interactive "P")
7723 (setq tree (or tree (and kill-ring (current-kill 0))))
7724 (unless (org-kill-is-subtree-p tree)
7725 (error "%s"
7726 (substitute-command-keys
7727 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7728 (org-with-limited-levels
7729 (let* ((visp (not (outline-invisible-p)))
7730 (txt tree)
7731 (^re_ "\\(\\*+\\)[ \t]*")
7732 (old-level (if (string-match org-outline-regexp-bol txt)
7733 (- (match-end 0) (match-beginning 0) 1)
7734 -1))
7735 (force-level (cond (level (prefix-numeric-value level))
7736 ((and (looking-at "[ \t]*$")
7737 (string-match
7738 "^\\*+$" (buffer-substring
7739 (point-at-bol) (point))))
7740 (- (match-end 1) (match-beginning 1)))
7741 ((and (bolp)
7742 (looking-at org-outline-regexp))
7743 (- (match-end 0) (point) 1))))
7744 (previous-level (save-excursion
7745 (condition-case nil
7746 (progn
7747 (outline-previous-visible-heading 1)
7748 (if (looking-at ^re_)
7749 (- (match-end 0) (match-beginning 0) 1)
7751 (error 1))))
7752 (next-level (save-excursion
7753 (condition-case nil
7754 (progn
7755 (or (looking-at org-outline-regexp)
7756 (outline-next-visible-heading 1))
7757 (if (looking-at ^re_)
7758 (- (match-end 0) (match-beginning 0) 1)
7760 (error 1))))
7761 (new-level (or force-level (max previous-level next-level)))
7762 (shift (if (or (= old-level -1)
7763 (= new-level -1)
7764 (= old-level new-level))
7766 (- new-level old-level)))
7767 (delta (if (> shift 0) -1 1))
7768 (func (if (> shift 0) 'org-demote 'org-promote))
7769 (org-odd-levels-only nil)
7770 beg end newend)
7771 ;; Remove the forced level indicator
7772 (if force-level
7773 (delete-region (point-at-bol) (point)))
7774 ;; Paste
7775 (beginning-of-line (if (bolp) 1 2))
7776 (setq beg (point))
7777 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7778 (insert-before-markers txt)
7779 (unless (string-match "\n\\'" txt) (insert "\n"))
7780 (setq newend (point))
7781 (org-reinstall-markers-in-region beg)
7782 (setq end (point))
7783 (goto-char beg)
7784 (skip-chars-forward " \t\n\r")
7785 (setq beg (point))
7786 (if (and (outline-invisible-p) visp)
7787 (save-excursion (outline-show-heading)))
7788 ;; Shift if necessary
7789 (unless (= shift 0)
7790 (save-restriction
7791 (narrow-to-region beg end)
7792 (while (not (= shift 0))
7793 (org-map-region func (point-min) (point-max))
7794 (setq shift (+ delta shift)))
7795 (goto-char (point-min))
7796 (setq newend (point-max))))
7797 (when (or (org-called-interactively-p 'interactive) for-yank)
7798 (message "Clipboard pasted as level %d subtree" new-level))
7799 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7800 kill-ring
7801 (eq org-subtree-clip (current-kill 0))
7802 org-subtree-clip-folded)
7803 ;; The tree was folded before it was killed/copied
7804 (hide-subtree))
7805 (and for-yank (goto-char newend)))))
7807 (defun org-kill-is-subtree-p (&optional txt)
7808 "Check if the current kill is an outline subtree, or a set of trees.
7809 Returns nil if kill does not start with a headline, or if the first
7810 headline level is not the largest headline level in the tree.
7811 So this will actually accept several entries of equal levels as well,
7812 which is OK for `org-paste-subtree'.
7813 If optional TXT is given, check this string instead of the current kill."
7814 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7815 (re (org-get-limited-outline-regexp))
7816 (^re (concat "^" re))
7817 (start-level (and kill
7818 (string-match
7819 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7820 kill)
7821 (- (match-end 2) (match-beginning 2) 1)))
7822 (start (1+ (or (match-beginning 2) -1))))
7823 (if (not start-level)
7824 (progn
7825 nil) ;; does not even start with a heading
7826 (catch 'exit
7827 (while (setq start (string-match ^re kill (1+ start)))
7828 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7829 (throw 'exit nil)))
7830 t))))
7832 (defvar org-markers-to-move nil
7833 "Markers that should be moved with a cut-and-paste operation.
7834 Those markers are stored together with their positions relative to
7835 the start of the region.")
7837 (defun org-save-markers-in-region (beg end)
7838 "Check markers in region.
7839 If these markers are between BEG and END, record their position relative
7840 to BEG, so that after moving the block of text, we can put the markers back
7841 into place.
7842 This function gets called just before an entry or tree gets cut from the
7843 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7844 called immediately, to move the markers with the entries."
7845 (setq org-markers-to-move nil)
7846 (when (featurep 'org-clock)
7847 (org-clock-save-markers-for-cut-and-paste beg end))
7848 (when (featurep 'org-agenda)
7849 (org-agenda-save-markers-for-cut-and-paste beg end)))
7851 (defun org-check-and-save-marker (marker beg end)
7852 "Check if MARKER is between BEG and END.
7853 If yes, remember the marker and the distance to BEG."
7854 (when (and (marker-buffer marker)
7855 (equal (marker-buffer marker) (current-buffer)))
7856 (if (and (>= marker beg) (< marker end))
7857 (push (cons marker (- marker beg)) org-markers-to-move))))
7859 (defun org-reinstall-markers-in-region (beg)
7860 "Move all remembered markers to their position relative to BEG."
7861 (mapc (lambda (x)
7862 (move-marker (car x) (+ beg (cdr x))))
7863 org-markers-to-move)
7864 (setq org-markers-to-move nil))
7866 (defun org-narrow-to-subtree ()
7867 "Narrow buffer to the current subtree."
7868 (interactive)
7869 (save-excursion
7870 (save-match-data
7871 (org-with-limited-levels
7872 (narrow-to-region
7873 (progn (org-back-to-heading t) (point))
7874 (progn (org-end-of-subtree t t)
7875 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7876 (point)))))))
7878 (defun org-narrow-to-block ()
7879 "Narrow buffer to the current block."
7880 (interactive)
7881 (let* ((case-fold-search t)
7882 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7883 "^[ \t]*#\\+end_.*")))
7884 (if blockp
7885 (narrow-to-region (car blockp) (cdr blockp))
7886 (error "Not in a block"))))
7888 (eval-when-compile
7889 (defvar org-property-drawer-re))
7891 (defvar org-property-start-re) ;; defined below
7892 (defun org-clone-subtree-with-time-shift (n &optional shift)
7893 "Clone the task (subtree) at point N times.
7894 The clones will be inserted as siblings.
7896 In interactive use, the user will be prompted for the number of
7897 clones to be produced, and for a time SHIFT, which may be a
7898 repeater as used in time stamps, for example `+3d'.
7900 When a valid repeater is given and the entry contains any time
7901 stamps, the clones will become a sequence in time, with time
7902 stamps in the subtree shifted for each clone produced. If SHIFT
7903 is nil or the empty string, time stamps will be left alone. The
7904 ID property of the original subtree is removed.
7906 If the original subtree did contain time stamps with a repeater,
7907 the following will happen:
7908 - the repeater will be removed in each clone
7909 - an additional clone will be produced, with the current, unshifted
7910 date(s) in the entry.
7911 - the original entry will be placed *after* all the clones, with
7912 repeater intact.
7913 - the start days in the repeater in the original entry will be shifted
7914 to past the last clone.
7915 In this way you can spell out a number of instances of a repeating task,
7916 and still retain the repeater to cover future instances of the task."
7917 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7918 (let (beg end template task idprop
7919 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7920 (drawer-re org-drawer-regexp))
7921 (if (not (and (integerp n) (> n 0)))
7922 (error "Invalid number of replications %s" n))
7923 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7924 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7925 shift)))
7926 (error "Invalid shift specification %s" shift))
7927 (when doshift
7928 (setq shift-n (string-to-number (match-string 1 shift))
7929 shift-what (cdr (assoc (match-string 2 shift)
7930 '(("d" . day) ("w" . week)
7931 ("m" . month) ("y" . year))))))
7932 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7933 (setq nmin 1 nmax n)
7934 (org-back-to-heading t)
7935 (setq beg (point))
7936 (setq idprop (org-entry-get nil "ID"))
7937 (org-end-of-subtree t t)
7938 (or (bolp) (insert "\n"))
7939 (setq end (point))
7940 (setq template (buffer-substring beg end))
7941 (when (and doshift
7942 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7943 (delete-region beg end)
7944 (setq end beg)
7945 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7946 (goto-char end)
7947 (loop for n from nmin to nmax do
7948 ;; prepare clone
7949 (with-temp-buffer
7950 (insert template)
7951 (org-mode)
7952 (goto-char (point-min))
7953 (org-show-subtree)
7954 (and idprop (if org-clone-delete-id
7955 (org-entry-delete nil "ID")
7956 (org-id-get-create t)))
7957 (unless (= n 0)
7958 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7959 (kill-whole-line))
7960 (goto-char (point-min))
7961 (while (re-search-forward drawer-re nil t)
7962 (mapc (lambda (d)
7963 (org-remove-empty-drawer-at d (point))) org-drawers)))
7964 (goto-char (point-min))
7965 (when doshift
7966 (while (re-search-forward org-ts-regexp-both nil t)
7967 (org-timestamp-change (* n shift-n) shift-what))
7968 (unless (= n n-no-remove)
7969 (goto-char (point-min))
7970 (while (re-search-forward org-ts-regexp nil t)
7971 (save-excursion
7972 (goto-char (match-beginning 0))
7973 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7974 (delete-region (match-beginning 1) (match-end 1)))))))
7975 (setq task (buffer-string)))
7976 (insert task))
7977 (goto-char beg)))
7979 ;;; Outline Sorting
7981 (defun org-sort (with-case)
7982 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7983 Optional argument WITH-CASE means sort case-sensitively."
7984 (interactive "P")
7985 (cond
7986 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7987 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7989 (org-call-with-arg 'org-sort-entries with-case))))
7991 (defun org-sort-remove-invisible (s)
7992 (remove-text-properties 0 (length s) org-rm-props s)
7993 (while (string-match org-bracket-link-regexp s)
7994 (setq s (replace-match (if (match-end 2)
7995 (match-string 3 s)
7996 (match-string 1 s)) t t s)))
7999 (defvar org-priority-regexp) ; defined later in the file
8001 (defvar org-after-sorting-entries-or-items-hook nil
8002 "Hook that is run after a bunch of entries or items have been sorted.
8003 When children are sorted, the cursor is in the parent line when this
8004 hook gets called. When a region or a plain list is sorted, the cursor
8005 will be in the first entry of the sorted region/list.")
8007 (defun org-sort-entries
8008 (&optional with-case sorting-type getkey-func compare-func property)
8009 "Sort entries on a certain level of an outline tree.
8010 If there is an active region, the entries in the region are sorted.
8011 Else, if the cursor is before the first entry, sort the top-level items.
8012 Else, the children of the entry at point are sorted.
8014 Sorting can be alphabetically, numerically, by date/time as given by
8015 a time stamp, by a property or by priority.
8017 The command prompts for the sorting type unless it has been given to the
8018 function through the SORTING-TYPE argument, which needs to be a character,
8019 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8020 precise meaning of each character:
8022 n Numerically, by converting the beginning of the entry/item to a number.
8023 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8024 o By order of TODO keywords.
8025 t By date/time, either the first active time stamp in the entry, or, if
8026 none exist, by the first inactive one.
8027 s By the scheduled date/time.
8028 d By deadline date/time.
8029 c By creation time, which is assumed to be the first inactive time stamp
8030 at the beginning of a line.
8031 p By priority according to the cookie.
8032 r By the value of a property.
8034 Capital letters will reverse the sort order.
8036 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8037 called with point at the beginning of the record. It must return either
8038 a string or a number that should serve as the sorting key for that record.
8040 Comparing entries ignores case by default. However, with an optional argument
8041 WITH-CASE, the sorting considers case as well."
8042 (interactive "P")
8043 (let ((case-func (if with-case 'identity 'downcase))
8044 (cmstr
8045 ;; The clock marker is lost when using `sort-subr', let's
8046 ;; store the clocking string.
8047 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8048 (save-excursion
8049 (goto-char org-clock-marker)
8050 (looking-back "^.*") (match-string-no-properties 0))))
8051 start beg end stars re re2
8052 txt what tmp)
8053 ;; Find beginning and end of region to sort
8054 (cond
8055 ((org-region-active-p)
8056 ;; we will sort the region
8057 (setq end (region-end)
8058 what "region")
8059 (goto-char (region-beginning))
8060 (if (not (org-at-heading-p)) (outline-next-heading))
8061 (setq start (point)))
8062 ((or (org-at-heading-p)
8063 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8064 ;; we will sort the children of the current headline
8065 (org-back-to-heading)
8066 (setq start (point)
8067 end (progn (org-end-of-subtree t t)
8068 (or (bolp) (insert "\n"))
8069 (org-back-over-empty-lines)
8070 (point))
8071 what "children")
8072 (goto-char start)
8073 (show-subtree)
8074 (outline-next-heading))
8076 ;; we will sort the top-level entries in this file
8077 (goto-char (point-min))
8078 (or (org-at-heading-p) (outline-next-heading))
8079 (setq start (point))
8080 (goto-char (point-max))
8081 (beginning-of-line 1)
8082 (when (looking-at ".*?\\S-")
8083 ;; File ends in a non-white line
8084 (end-of-line 1)
8085 (insert "\n"))
8086 (setq end (point-max))
8087 (setq what "top-level")
8088 (goto-char start)
8089 (show-all)))
8091 (setq beg (point))
8092 (if (>= beg end) (error "Nothing to sort"))
8094 (looking-at "\\(\\*+\\)")
8095 (setq stars (match-string 1)
8096 re (concat "^" (regexp-quote stars) " +")
8097 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8098 txt (buffer-substring beg end))
8099 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8100 (if (and (not (equal stars "*")) (string-match re2 txt))
8101 (error "Region to sort contains a level above the first entry"))
8103 (unless sorting-type
8104 (message
8105 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8106 [t]ime [s]cheduled [d]eadline [c]reated
8107 A/N/P/R/O/F/T/S/D/C means reversed:"
8108 what)
8109 (setq sorting-type (read-char-exclusive))
8111 (and (= (downcase sorting-type) ?f)
8112 (setq getkey-func
8113 (org-icompleting-read "Sort using function: "
8114 obarray 'fboundp t nil nil))
8115 (setq getkey-func (intern getkey-func)))
8117 (and (= (downcase sorting-type) ?r)
8118 (setq property
8119 (org-icompleting-read "Property: "
8120 (mapcar 'list (org-buffer-property-keys t))
8121 nil t))))
8123 (message "Sorting entries...")
8125 (save-restriction
8126 (narrow-to-region start end)
8127 (let ((dcst (downcase sorting-type))
8128 (case-fold-search nil)
8129 (now (current-time)))
8130 (sort-subr
8131 (/= dcst sorting-type)
8132 ;; This function moves to the beginning character of the "record" to
8133 ;; be sorted.
8134 (lambda nil
8135 (if (re-search-forward re nil t)
8136 (goto-char (match-beginning 0))
8137 (goto-char (point-max))))
8138 ;; This function moves to the last character of the "record" being
8139 ;; sorted.
8140 (lambda nil
8141 (save-match-data
8142 (condition-case nil
8143 (outline-forward-same-level 1)
8144 (error
8145 (goto-char (point-max))))))
8146 ;; This function returns the value that gets sorted against.
8147 (lambda nil
8148 (cond
8149 ((= dcst ?n)
8150 (if (looking-at org-complex-heading-regexp)
8151 (string-to-number (match-string 4))
8152 nil))
8153 ((= dcst ?a)
8154 (if (looking-at org-complex-heading-regexp)
8155 (funcall case-func (match-string 4))
8156 nil))
8157 ((= dcst ?t)
8158 (let ((end (save-excursion (outline-next-heading) (point))))
8159 (if (or (re-search-forward org-ts-regexp end t)
8160 (re-search-forward org-ts-regexp-both end t))
8161 (org-time-string-to-seconds (match-string 0))
8162 (org-float-time now))))
8163 ((= dcst ?c)
8164 (let ((end (save-excursion (outline-next-heading) (point))))
8165 (if (re-search-forward
8166 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8167 end t)
8168 (org-time-string-to-seconds (match-string 0))
8169 (org-float-time now))))
8170 ((= dcst ?s)
8171 (let ((end (save-excursion (outline-next-heading) (point))))
8172 (if (re-search-forward org-scheduled-time-regexp end t)
8173 (org-time-string-to-seconds (match-string 1))
8174 (org-float-time now))))
8175 ((= dcst ?d)
8176 (let ((end (save-excursion (outline-next-heading) (point))))
8177 (if (re-search-forward org-deadline-time-regexp end t)
8178 (org-time-string-to-seconds (match-string 1))
8179 (org-float-time now))))
8180 ((= dcst ?p)
8181 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8182 (string-to-char (match-string 2))
8183 org-default-priority))
8184 ((= dcst ?r)
8185 (or (org-entry-get nil property) ""))
8186 ((= dcst ?o)
8187 (if (looking-at org-complex-heading-regexp)
8188 (- 9999 (length (member (match-string 2)
8189 org-todo-keywords-1)))))
8190 ((= dcst ?f)
8191 (if getkey-func
8192 (progn
8193 (setq tmp (funcall getkey-func))
8194 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8195 tmp)
8196 (error "Invalid key function `%s'" getkey-func)))
8197 (t (error "Invalid sorting type `%c'" sorting-type))))
8199 (cond
8200 ((= dcst ?a) 'string<)
8201 ((= dcst ?f) compare-func)
8202 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8203 (run-hooks 'org-after-sorting-entries-or-items-hook)
8204 ;; Reset the clock marker if needed
8205 (when cmstr
8206 (save-excursion
8207 (goto-char start)
8208 (search-forward cmstr nil t)
8209 (move-marker org-clock-marker (point))))
8210 (message "Sorting entries...done")))
8212 (defun org-do-sort (table what &optional with-case sorting-type)
8213 "Sort TABLE of WHAT according to SORTING-TYPE.
8214 The user will be prompted for the SORTING-TYPE if the call to this
8215 function does not specify it. WHAT is only for the prompt, to indicate
8216 what is being sorted. The sorting key will be extracted from
8217 the car of the elements of the table.
8218 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8219 (unless sorting-type
8220 (message
8221 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8222 what)
8223 (setq sorting-type (read-char-exclusive)))
8224 (let ((dcst (downcase sorting-type))
8225 extractfun comparefun)
8226 ;; Define the appropriate functions
8227 (cond
8228 ((= dcst ?n)
8229 (setq extractfun 'string-to-number
8230 comparefun (if (= dcst sorting-type) '< '>)))
8231 ((= dcst ?a)
8232 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8233 (lambda(x) (downcase (org-sort-remove-invisible x))))
8234 comparefun (if (= dcst sorting-type)
8235 'string<
8236 (lambda (a b) (and (not (string< a b))
8237 (not (string= a b)))))))
8238 ((= dcst ?t)
8239 (setq extractfun
8240 (lambda (x)
8241 (if (or (string-match org-ts-regexp x)
8242 (string-match org-ts-regexp-both x))
8243 (org-float-time
8244 (org-time-string-to-time (match-string 0 x)))
8246 comparefun (if (= dcst sorting-type) '< '>)))
8247 (t (error "Invalid sorting type `%c'" sorting-type)))
8249 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8250 table)
8251 (lambda (a b) (funcall comparefun (car a) (car b))))))
8254 ;;; The orgstruct minor mode
8256 ;; Define a minor mode which can be used in other modes in order to
8257 ;; integrate the org-mode structure editing commands.
8259 ;; This is really a hack, because the org-mode structure commands use
8260 ;; keys which normally belong to the major mode. Here is how it
8261 ;; works: The minor mode defines all the keys necessary to operate the
8262 ;; structure commands, but wraps the commands into a function which
8263 ;; tests if the cursor is currently at a headline or a plain list
8264 ;; item. If that is the case, the structure command is used,
8265 ;; temporarily setting many Org-mode variables like regular
8266 ;; expressions for filling etc. However, when any of those keys is
8267 ;; used at a different location, function uses `key-binding' to look
8268 ;; up if the key has an associated command in another currently active
8269 ;; keymap (minor modes, major mode, global), and executes that
8270 ;; command. There might be problems if any of the keys is otherwise
8271 ;; used as a prefix key.
8273 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8274 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8275 ;; addresses this by checking explicitly for both bindings.
8277 (defvar orgstruct-mode-map (make-sparse-keymap)
8278 "Keymap for the minor `orgstruct-mode'.")
8280 (defvar org-local-vars nil
8281 "List of local variables, for use by `orgstruct-mode'.")
8283 ;;;###autoload
8284 (define-minor-mode orgstruct-mode
8285 "Toggle the minor mode `orgstruct-mode'.
8286 This mode is for using Org-mode structure commands in other
8287 modes. The following keys behave as if Org-mode were active, if
8288 the cursor is on a headline, or on a plain list item (both as
8289 defined by Org-mode).
8291 M-up Move entry/item up
8292 M-down Move entry/item down
8293 M-left Promote
8294 M-right Demote
8295 M-S-up Move entry/item up
8296 M-S-down Move entry/item down
8297 M-S-left Promote subtree
8298 M-S-right Demote subtree
8299 M-q Fill paragraph and items like in Org-mode
8300 C-c ^ Sort entries
8301 C-c - Cycle list bullet
8302 TAB Cycle item visibility
8303 M-RET Insert new heading/item
8304 S-M-RET Insert new TODO heading / Checkbox item
8305 C-c C-c Set tags / toggle checkbox"
8306 nil " OrgStruct" nil
8307 (org-load-modules-maybe)
8308 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8310 ;;;###autoload
8311 (defun turn-on-orgstruct ()
8312 "Unconditionally turn on `orgstruct-mode'."
8313 (orgstruct-mode 1))
8315 (defvar org-fb-vars nil)
8316 (make-variable-buffer-local 'org-fb-vars)
8317 (defun orgstruct++-mode (&optional arg)
8318 "Toggle `orgstruct-mode', the enhanced version of it.
8319 In addition to setting orgstruct-mode, this also exports all
8320 indentation and autofilling variables from org-mode into the
8321 buffer. It will also recognize item context in multiline items."
8322 (interactive "P")
8323 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8324 (if (< arg 1)
8325 (progn (orgstruct-mode -1)
8326 (mapc (lambda(v)
8327 (org-set-local (car v)
8328 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8329 org-fb-vars))
8330 (orgstruct-mode 1)
8331 (setq org-fb-vars nil)
8332 (let (var val)
8333 (mapc
8334 (lambda (x)
8335 (when (string-match
8336 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8337 (symbol-name (car x)))
8338 (setq var (car x) val (nth 1 x))
8339 (push (list var `(quote ,(eval var))) org-fb-vars)
8340 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8341 org-local-vars)
8342 (org-set-local 'orgstruct-is-++ t))))
8344 (defvar orgstruct-is-++ nil
8345 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8346 (make-variable-buffer-local 'orgstruct-is-++)
8348 ;;;###autoload
8349 (defun turn-on-orgstruct++ ()
8350 "Unconditionally turn on `orgstruct++-mode'."
8351 (orgstruct++-mode 1))
8353 (defun orgstruct-error ()
8354 "Error when there is no default binding for a structure key."
8355 (interactive)
8356 (error "This key has no function outside structure elements"))
8358 (defun orgstruct-setup ()
8359 "Setup orgstruct keymaps."
8360 (let ((nfunc 0)
8361 (bindings
8362 (list
8363 '([(meta up)] org-metaup)
8364 '([(meta down)] org-metadown)
8365 '([(meta left)] org-metaleft)
8366 '([(meta right)] org-metaright)
8367 '([(meta shift up)] org-shiftmetaup)
8368 '([(meta shift down)] org-shiftmetadown)
8369 '([(meta shift left)] org-shiftmetaleft)
8370 '([(meta shift right)] org-shiftmetaright)
8371 '([?\e (up)] org-metaup)
8372 '([?\e (down)] org-metadown)
8373 '([?\e (left)] org-metaleft)
8374 '([?\e (right)] org-metaright)
8375 '([?\e (shift up)] org-shiftmetaup)
8376 '([?\e (shift down)] org-shiftmetadown)
8377 '([?\e (shift left)] org-shiftmetaleft)
8378 '([?\e (shift right)] org-shiftmetaright)
8379 '([(shift up)] org-shiftup)
8380 '([(shift down)] org-shiftdown)
8381 '([(shift left)] org-shiftleft)
8382 '([(shift right)] org-shiftright)
8383 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8384 '("\M-q" fill-paragraph)
8385 '("\C-c^" org-sort)
8386 '("\C-c-" org-cycle-list-bullet)))
8387 elt key fun cmd)
8388 (while (setq elt (pop bindings))
8389 (setq nfunc (1+ nfunc))
8390 (setq key (org-key (car elt))
8391 fun (nth 1 elt)
8392 cmd (orgstruct-make-binding fun nfunc key))
8393 (org-defkey orgstruct-mode-map key cmd))
8395 ;; Prevent an error for users who forgot to make autoloads
8396 (require 'org-element)
8398 ;; Special treatment needed for TAB and RET
8399 (org-defkey orgstruct-mode-map [(tab)]
8400 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8401 (org-defkey orgstruct-mode-map "\C-i"
8402 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8404 (org-defkey orgstruct-mode-map "\M-\C-m"
8405 (orgstruct-make-binding 'org-insert-heading 105
8406 "\M-\C-m" [(meta return)]))
8407 (org-defkey orgstruct-mode-map [(meta return)]
8408 (orgstruct-make-binding 'org-insert-heading 106
8409 [(meta return)] "\M-\C-m"))
8411 (org-defkey orgstruct-mode-map [(shift meta return)]
8412 (orgstruct-make-binding 'org-insert-todo-heading 107
8413 [(meta return)] "\M-\C-m"))
8415 (org-defkey orgstruct-mode-map "\e\C-m"
8416 (orgstruct-make-binding 'org-insert-heading 108
8417 "\e\C-m" [?\e (return)]))
8418 (org-defkey orgstruct-mode-map [?\e (return)]
8419 (orgstruct-make-binding 'org-insert-heading 109
8420 [?\e (return)] "\e\C-m"))
8421 (org-defkey orgstruct-mode-map [?\e (shift return)]
8422 (orgstruct-make-binding 'org-insert-todo-heading 110
8423 [?\e (return)] "\e\C-m"))
8425 (unless org-local-vars
8426 (setq org-local-vars (org-get-local-variables)))
8430 (defun orgstruct-make-binding (fun n &rest keys)
8431 "Create a function for binding in the structure minor mode.
8432 FUN is the command to call inside a table. N is used to create a unique
8433 command name. KEYS are keys that should be checked in for a command
8434 to execute outside of tables."
8435 (eval
8436 (list 'defun
8437 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8438 '(arg)
8439 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8440 "Outside of structure, run the binding of `"
8441 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8442 "'.")
8443 '(interactive "p")
8444 (list 'if
8445 `(org-context-p 'headline 'item
8446 (and orgstruct-is-++
8447 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8448 'item-body))
8449 (list 'org-run-like-in-org-mode (list 'quote fun))
8450 (list 'let '(orgstruct-mode)
8451 (list 'call-interactively
8452 (append '(or)
8453 (mapcar (lambda (k)
8454 (list 'key-binding k))
8455 keys)
8456 '('orgstruct-error))))))))
8458 (defun org-contextualize-keys (alist contexts)
8459 "Return valid elements in ALIST depending on CONTEXTS.
8461 `org-agenda-custom-commands' or `org-capture-templates' are the
8462 values used for ALIST, and `org-agenda-custom-commands-contexts'
8463 or `org-capture-templates-contexts' are the associated contexts
8464 definitions."
8465 (let ((contexts
8466 ;; normalize contexts
8467 (mapcar
8468 (lambda(c) (cond ((listp (cadr c))
8469 (list (car c) (car c) (cadr c)))
8470 ((string= "" (cadr c))
8471 (list (car c) (car c) (caddr c)))
8472 (t c))) contexts))
8473 (a alist) c r s)
8474 ;; loop over all commands or templates
8475 (while (setq c (pop a))
8476 (let (vrules repl)
8477 (cond
8478 ((not (assoc (car c) contexts))
8479 (push c r))
8480 ((and (assoc (car c) contexts)
8481 (setq vrules (org-contextualize-validate-key
8482 (car c) contexts)))
8483 (mapc (lambda (vr)
8484 (when (not (equal (car vr) (cadr vr)))
8485 (setq repl vr))) vrules)
8486 (if (not repl) (push c r)
8487 (push (cadr repl) s)
8488 (push
8489 (cons (car c)
8490 (cdr (or (assoc (cadr repl) alist)
8491 (error "Undefined key `%s' as contextual replacement for `%s'"
8492 (cadr repl) (car c)))))
8493 r))))))
8494 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8495 (delq
8497 (delete-dups
8498 (mapcar (lambda (x)
8499 (let ((tpl (car x)))
8500 (when (not (delq
8502 (mapcar (lambda(y)
8503 (equal y tpl)) s))) x)))
8504 (reverse r))))))
8506 (defun org-contextualize-validate-key (key contexts)
8507 "Check CONTEXTS for agenda or capture KEY."
8508 (let (r rr res)
8509 (while (setq r (pop contexts))
8510 (mapc
8511 (lambda (rr)
8512 (when
8513 (and (equal key (car r))
8514 (if (functionp rr) (funcall rr)
8515 (or (and (eq (car rr) 'in-file)
8516 (buffer-file-name)
8517 (string-match (cdr rr) (buffer-file-name)))
8518 (and (eq (car rr) 'in-mode)
8519 (string-match (cdr rr) (symbol-name major-mode)))
8520 (when (and (eq (car rr) 'not-in-file)
8521 (buffer-file-name))
8522 (not (string-match (cdr rr) (buffer-file-name))))
8523 (when (eq (car rr) 'not-in-mode)
8524 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8525 (push r res)))
8526 (car (last r))))
8527 (delete-dups (delq nil res))))
8529 (defun org-context-p (&rest contexts)
8530 "Check if local context is any of CONTEXTS.
8531 Possible values in the list of contexts are `table', `headline', and `item'."
8532 (let ((pos (point)))
8533 (goto-char (point-at-bol))
8534 (prog1 (or (and (memq 'table contexts)
8535 (looking-at "[ \t]*|"))
8536 (and (memq 'headline contexts)
8537 (looking-at org-outline-regexp))
8538 (and (memq 'item contexts)
8539 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8540 (and (memq 'item-body contexts)
8541 (org-in-item-p)))
8542 (goto-char pos))))
8544 (defun org-get-local-variables ()
8545 "Return a list of all local variables in an Org mode buffer."
8546 (let (varlist)
8547 (with-current-buffer (get-buffer-create "*Org tmp*")
8548 (erase-buffer)
8549 (org-mode)
8550 (setq varlist (buffer-local-variables)))
8551 (kill-buffer "*Org tmp*")
8552 (delq nil
8553 (mapcar
8554 (lambda (x)
8555 (setq x
8556 (if (symbolp x)
8557 (list x)
8558 (list (car x) (list 'quote (cdr x)))))
8559 (if (string-match
8560 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8561 (symbol-name (car x)))
8562 x nil))
8563 varlist))))
8565 (defun org-clone-local-variables (from-buffer &optional regexp)
8566 "Clone local variables from FROM-BUFFER.
8567 Optional argument REGEXP selects variables to clone."
8568 (mapc
8569 (lambda (pair)
8570 (and (symbolp (car pair))
8571 (or (null regexp)
8572 (string-match regexp (symbol-name (car pair))))
8573 (set (make-local-variable (car pair))
8574 (cdr pair))))
8575 (buffer-local-variables from-buffer)))
8577 ;;;###autoload
8578 (defun org-run-like-in-org-mode (cmd)
8579 "Run a command, pretending that the current buffer is in Org-mode.
8580 This will temporarily bind local variables that are typically bound in
8581 Org-mode to the values they have in Org-mode, and then interactively
8582 call CMD."
8583 (org-load-modules-maybe)
8584 (unless org-local-vars
8585 (setq org-local-vars (org-get-local-variables)))
8586 (eval (list 'let org-local-vars
8587 (list 'call-interactively (list 'quote cmd)))))
8589 ;;;; Archiving
8591 (defun org-get-category (&optional pos force-refresh)
8592 "Get the category applying to position POS."
8593 (save-match-data
8594 (if force-refresh (org-refresh-category-properties))
8595 (let ((pos (or pos (point))))
8596 (or (get-text-property pos 'org-category)
8597 (progn (org-refresh-category-properties)
8598 (get-text-property pos 'org-category))))))
8600 (defun org-refresh-category-properties ()
8601 "Refresh category text properties in the buffer."
8602 (let ((case-fold-search t)
8603 (inhibit-read-only t)
8604 (def-cat (cond
8605 ((null org-category)
8606 (if buffer-file-name
8607 (file-name-sans-extension
8608 (file-name-nondirectory buffer-file-name))
8609 "???"))
8610 ((symbolp org-category) (symbol-name org-category))
8611 (t org-category)))
8612 beg end cat pos optionp)
8613 (org-unmodified
8614 (save-excursion
8615 (save-restriction
8616 (widen)
8617 (goto-char (point-min))
8618 (put-text-property (point) (point-max) 'org-category def-cat)
8619 (while (re-search-forward
8620 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8621 (setq pos (match-end 0)
8622 optionp (equal (char-after (match-beginning 0)) ?#)
8623 cat (org-trim (match-string 2)))
8624 (if optionp
8625 (setq beg (point-at-bol) end (point-max))
8626 (org-back-to-heading t)
8627 (setq beg (point) end (org-end-of-subtree t t)))
8628 (put-text-property beg end 'org-category cat)
8629 (put-text-property beg end 'org-category-position beg)
8630 (goto-char pos)))))))
8633 ;;;; Link Stuff
8635 ;;; Link abbreviations
8637 (defun org-link-expand-abbrev (link)
8638 "Apply replacements as defined in `org-link-abbrev-alist'."
8639 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8640 (let* ((key (match-string 1 link))
8641 (as (or (assoc key org-link-abbrev-alist-local)
8642 (assoc key org-link-abbrev-alist)))
8643 (tag (and (match-end 2) (match-string 3 link)))
8644 rpl)
8645 (if (not as)
8646 link
8647 (setq rpl (cdr as))
8648 (cond
8649 ((symbolp rpl) (funcall rpl tag))
8650 ((string-match "%(\\([^)]+\\))" rpl)
8651 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8652 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8653 ((string-match "%h" rpl)
8654 (replace-match (url-hexify-string (or tag "")) t t rpl))
8655 (t (concat rpl tag)))))
8656 link))
8658 ;;; Storing and inserting links
8660 (defvar org-insert-link-history nil
8661 "Minibuffer history for links inserted with `org-insert-link'.")
8663 (defvar org-stored-links nil
8664 "Contains the links stored with `org-store-link'.")
8666 (defvar org-store-link-plist nil
8667 "Plist with info about the most recently link created with `org-store-link'.")
8669 (defvar org-link-protocols nil
8670 "Link protocols added to Org-mode using `org-add-link-type'.")
8672 (defvar org-store-link-functions nil
8673 "List of functions that are called to create and store a link.
8674 Each function will be called in turn until one returns a non-nil
8675 value. Each function should check if it is responsible for creating
8676 this link (for example by looking at the major mode).
8677 If not, it must exit and return nil.
8678 If yes, it should return a non-nil value after a calling
8679 `org-store-link-props' with a list of properties and values.
8680 Special properties are:
8682 :type The link prefix, like \"http\". This must be given.
8683 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8684 This is obligatory as well.
8685 :description Optional default description for the second pair
8686 of brackets in an Org-mode link. The user can still change
8687 this when inserting this link into an Org-mode buffer.
8689 In addition to these, any additional properties can be specified
8690 and then used in capture templates.")
8692 (defun org-add-link-type (type &optional follow export)
8693 "Add TYPE to the list of `org-link-types'.
8694 Re-compute all regular expressions depending on `org-link-types'
8696 FOLLOW and EXPORT are two functions.
8698 FOLLOW should take the link path as the single argument and do whatever
8699 is necessary to follow the link, for example find a file or display
8700 a mail message.
8702 EXPORT should format the link path for export to one of the export formats.
8703 It should be a function accepting three arguments:
8705 path the path of the link, the text after the prefix (like \"http:\")
8706 desc the description of the link, if any, or a description added by
8707 org-export-normalize-links if there is none
8708 format the export format, a symbol like `html' or `latex' or `ascii'..
8710 The function may use the FORMAT information to return different values
8711 depending on the format. The return value will be put literally into
8712 the exported file. If the return value is nil, this means Org should
8713 do what it normally does with links which do not have EXPORT defined.
8715 Org-mode has a built-in default for exporting links. If you are happy with
8716 this default, there is no need to define an export function for the link
8717 type. For a simple example of an export function, see `org-bbdb.el'."
8718 (add-to-list 'org-link-types type t)
8719 (org-make-link-regexps)
8720 (if (assoc type org-link-protocols)
8721 (setcdr (assoc type org-link-protocols) (list follow export))
8722 (push (list type follow export) org-link-protocols)))
8724 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8725 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8727 ;;;###autoload
8728 (defun org-store-link (arg)
8729 "\\<org-mode-map>Store an org-link to the current location.
8730 This link is added to `org-stored-links' and can later be inserted
8731 into an org-buffer with \\[org-insert-link].
8733 For some link types, a prefix arg is interpreted:
8734 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8735 For file links, arg negates `org-context-in-file-links'."
8736 (interactive "P")
8737 (org-load-modules-maybe)
8738 (setq org-store-link-plist nil) ; reset
8739 (org-with-limited-levels
8740 (let (link cpltxt desc description search txt custom-id agenda-link)
8741 (cond
8743 ((run-hook-with-args-until-success 'org-store-link-functions)
8744 (setq link (plist-get org-store-link-plist :link)
8745 desc (or (plist-get org-store-link-plist :description) link)))
8747 ((org-src-edit-buffer-p)
8748 (let (label gc)
8749 (while (or (not label)
8750 (save-excursion
8751 (save-restriction
8752 (widen)
8753 (goto-char (point-min))
8754 (re-search-forward
8755 (regexp-quote (format org-coderef-label-format label))
8756 nil t))))
8757 (when label (message "Label exists already") (sit-for 2))
8758 (setq label (read-string "Code line label: " label)))
8759 (end-of-line 1)
8760 (setq link (format org-coderef-label-format label))
8761 (setq gc (- 79 (length link)))
8762 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8763 (insert link)
8764 (setq link (concat "(" label ")") desc nil)))
8766 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8767 ;; We are in the agenda, link to referenced location
8768 (let ((m (or (get-text-property (point) 'org-hd-marker)
8769 (get-text-property (point) 'org-marker))))
8770 (when m
8771 (org-with-point-at m
8772 (setq agenda-link
8773 (if (org-called-interactively-p 'any)
8774 (call-interactively 'org-store-link)
8775 (org-store-link nil)))))))
8777 ((eq major-mode 'calendar-mode)
8778 (let ((cd (calendar-cursor-to-date)))
8779 (setq link
8780 (format-time-string
8781 (car org-time-stamp-formats)
8782 (apply 'encode-time
8783 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8784 nil nil nil))))
8785 (org-store-link-props :type "calendar" :date cd)))
8787 ((eq major-mode 'help-mode)
8788 (setq link (concat "help:" (save-excursion
8789 (goto-char (point-min))
8790 (looking-at "^[^ ]+")
8791 (match-string 0))))
8792 (org-store-link-props :type "help"))
8794 ((eq major-mode 'w3-mode)
8795 (setq cpltxt (if (and (buffer-name)
8796 (not (string-match "Untitled" (buffer-name))))
8797 (buffer-name)
8798 (url-view-url t))
8799 link (url-view-url t))
8800 (org-store-link-props :type "w3" :url (url-view-url t)))
8802 ((eq major-mode 'w3m-mode)
8803 (setq cpltxt (or w3m-current-title w3m-current-url)
8804 link w3m-current-url)
8805 (org-store-link-props :type "w3m" :url (url-view-url t)))
8807 ((setq search (run-hook-with-args-until-success
8808 'org-create-file-search-functions))
8809 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8810 "::" search))
8811 (setq cpltxt (or description link)))
8813 ((eq major-mode 'image-mode)
8814 (setq cpltxt (concat "file:"
8815 (abbreviate-file-name buffer-file-name))
8816 link cpltxt)
8817 (org-store-link-props :type "image" :file buffer-file-name))
8819 ((eq major-mode 'dired-mode)
8820 ;; link to the file in the current line
8821 (let ((file (dired-get-filename nil t)))
8822 (setq file (if file
8823 (abbreviate-file-name
8824 (expand-file-name (dired-get-filename nil t)))
8825 ;; otherwise, no file so use current directory.
8826 default-directory))
8827 (setq cpltxt (concat "file:" file)
8828 link cpltxt)))
8830 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8831 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8832 (cond
8833 ((org-in-regexp "<<\\(.*?\\)>>")
8834 (setq cpltxt
8835 (concat "file:"
8836 (abbreviate-file-name
8837 (buffer-file-name (buffer-base-buffer)))
8838 "::" (match-string 1))
8839 link cpltxt))
8840 ((and (featurep 'org-id)
8841 (or (eq org-link-to-org-use-id t)
8842 (and (org-called-interactively-p 'any)
8843 (or (eq org-link-to-org-use-id 'create-if-interactive)
8844 (and (eq org-link-to-org-use-id
8845 'create-if-interactive-and-no-custom-id)
8846 (not custom-id))))
8847 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8848 ;; We can make a link using the ID.
8849 (setq link (condition-case nil
8850 (prog1 (org-id-store-link)
8851 (setq desc (plist-get org-store-link-plist :description)))
8852 (error
8853 ;; probably before first headline, link to file only
8854 (concat "file:"
8855 (abbreviate-file-name
8856 (buffer-file-name (buffer-base-buffer))))))))
8858 ;; Just link to current headline
8859 (setq cpltxt (concat "file:"
8860 (abbreviate-file-name
8861 (buffer-file-name (buffer-base-buffer)))))
8862 ;; Add a context search string
8863 (when (org-xor org-context-in-file-links arg)
8864 (setq txt (cond
8865 ((org-at-heading-p) nil)
8866 ((org-region-active-p)
8867 (buffer-substring (region-beginning) (region-end)))))
8868 (when (or (null txt) (string-match "\\S-" txt))
8869 (setq cpltxt
8870 (concat cpltxt "::"
8871 (condition-case nil
8872 (org-make-org-heading-search-string txt)
8873 (error "")))
8874 desc (or (nth 4 (ignore-errors
8875 (org-heading-components))) "NONE"))))
8876 (if (string-match "::\\'" cpltxt)
8877 (setq cpltxt (substring cpltxt 0 -2)))
8878 (setq link cpltxt))))
8880 ((buffer-file-name (buffer-base-buffer))
8881 ;; Just link to this file here.
8882 (setq cpltxt (concat "file:"
8883 (abbreviate-file-name
8884 (buffer-file-name (buffer-base-buffer)))))
8885 ;; Add a context string
8886 (when (org-xor org-context-in-file-links arg)
8887 (setq txt (if (org-region-active-p)
8888 (buffer-substring (region-beginning) (region-end))
8889 (buffer-substring (point-at-bol) (point-at-eol))))
8890 ;; Only use search option if there is some text.
8891 (when (string-match "\\S-" txt)
8892 (setq cpltxt
8893 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8894 desc "NONE")))
8895 (setq link cpltxt))
8897 ((org-called-interactively-p 'interactive)
8898 (error "Cannot link to a buffer which is not visiting a file"))
8900 (t (setq link nil)))
8902 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8903 (setq link (or link cpltxt)
8904 desc (or desc cpltxt))
8905 (if (equal desc "NONE") (setq desc nil))
8907 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8908 (progn
8909 (setq org-stored-links
8910 (cons (list link desc) org-stored-links))
8911 (message "Stored: %s" (or desc link))
8912 (when custom-id
8913 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8914 "::#" custom-id))
8915 (setq org-stored-links
8916 (cons (list link desc) org-stored-links))))
8917 (or agenda-link (and link (org-make-link-string link desc)))))))
8919 (defun org-store-link-props (&rest plist)
8920 "Store link properties, extract names and addresses."
8921 (let (x adr)
8922 (when (setq x (plist-get plist :from))
8923 (setq adr (mail-extract-address-components x))
8924 (setq plist (plist-put plist :fromname (car adr)))
8925 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8926 (when (setq x (plist-get plist :to))
8927 (setq adr (mail-extract-address-components x))
8928 (setq plist (plist-put plist :toname (car adr)))
8929 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8930 (let ((from (plist-get plist :from))
8931 (to (plist-get plist :to)))
8932 (when (and from to org-from-is-user-regexp)
8933 (setq plist
8934 (plist-put plist :fromto
8935 (if (string-match org-from-is-user-regexp from)
8936 (concat "to %t")
8937 (concat "from %f"))))))
8938 (setq org-store-link-plist plist))
8940 (defun org-add-link-props (&rest plist)
8941 "Add these properties to the link property list."
8942 (let (key value)
8943 (while plist
8944 (setq key (pop plist) value (pop plist))
8945 (setq org-store-link-plist
8946 (plist-put org-store-link-plist key value)))))
8948 (defun org-email-link-description (&optional fmt)
8949 "Return the description part of an email link.
8950 This takes information from `org-store-link-plist' and formats it
8951 according to FMT (default from `org-email-link-description-format')."
8952 (setq fmt (or fmt org-email-link-description-format))
8953 (let* ((p org-store-link-plist)
8954 (to (plist-get p :toaddress))
8955 (from (plist-get p :fromaddress))
8956 (table
8957 (list
8958 (cons "%c" (plist-get p :fromto))
8959 (cons "%F" (plist-get p :from))
8960 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8961 (cons "%T" (plist-get p :to))
8962 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8963 (cons "%s" (plist-get p :subject))
8964 (cons "%d" (plist-get p :date))
8965 (cons "%m" (plist-get p :message-id)))))
8966 (when (string-match "%c" fmt)
8967 ;; Check if the user wrote this message
8968 (if (and org-from-is-user-regexp from to
8969 (save-match-data (string-match org-from-is-user-regexp from)))
8970 (setq fmt (replace-match "to %t" t t fmt))
8971 (setq fmt (replace-match "from %f" t t fmt))))
8972 (org-replace-escapes fmt table)))
8974 (defun org-make-org-heading-search-string (&optional string heading)
8975 "Make search string for STRING or current headline."
8976 (interactive)
8977 (let ((s (or string (org-get-heading)))
8978 (lines org-context-in-file-links))
8979 (unless (and string (not heading))
8980 ;; We are using a headline, clean up garbage in there.
8981 (if (string-match org-todo-regexp s)
8982 (setq s (replace-match "" t t s)))
8983 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8984 (setq s (replace-match "" t t s)))
8985 (setq s (org-trim s))
8986 (if (string-match (concat "^\\(" org-quote-string "\\|"
8987 org-comment-string "\\)") s)
8988 (setq s (replace-match "" t t s)))
8989 (while (string-match org-ts-regexp s)
8990 (setq s (replace-match "" t t s))))
8991 (or string (setq s (concat "*" s))) ; Add * for headlines
8992 (when (and string (integerp lines) (> lines 0))
8993 (let ((slines (org-split-string s "\n")))
8994 (when (< lines (length slines))
8995 (setq s (mapconcat
8996 'identity
8997 (reverse (nthcdr (- (length slines) lines)
8998 (reverse slines))) "\n")))))
8999 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9001 (defun org-make-link-string (link &optional description)
9002 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9003 (unless (string-match "\\S-" link)
9004 (error "Empty link"))
9005 (when (and description
9006 (stringp description)
9007 (not (string-match "\\S-" description)))
9008 (setq description nil))
9009 (when (stringp description)
9010 ;; Remove brackets from the description, they are fatal.
9011 (while (string-match "\\[" description)
9012 (setq description (replace-match "{" t t description)))
9013 (while (string-match "\\]" description)
9014 (setq description (replace-match "}" t t description))))
9015 (when (equal link description)
9016 ;; No description needed, it is identical
9017 (setq description nil))
9018 (when (and (not description)
9019 (not (string-match (org-image-file-name-regexp) link))
9020 (not (equal link (org-link-escape link))))
9021 (setq description (org-extract-attributes link)))
9022 (setq link
9023 (cond ((string-match (org-image-file-name-regexp) link) link)
9024 ((string-match org-link-types-re link)
9025 (concat (match-string 1 link)
9026 (org-link-escape (substring link (match-end 1)))))
9027 (t (org-link-escape link))))
9028 (concat "[[" link "]"
9029 (if description (concat "[" description "]") "")
9030 "]"))
9032 (defconst org-link-escape-chars
9033 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9034 "List of characters that should be escaped in link.
9035 This is the list that is used for internal purposes.")
9037 (defconst org-link-escape-chars-browser
9038 '(?\ )
9039 "List of escapes for characters that are problematic in links.
9040 This is the list that is used before handing over to the browser.")
9042 (defun org-link-escape (text &optional table merge)
9043 "Return percent escaped representation of TEXT.
9044 TEXT is a string with the text to escape.
9045 Optional argument TABLE is a list with characters that should be
9046 escaped. When nil, `org-link-escape-chars' is used.
9047 If optional argument MERGE is set, merge TABLE into
9048 `org-link-escape-chars'."
9049 (cond
9050 ((and table merge)
9051 (mapc (lambda (defchr)
9052 (unless (member defchr table)
9053 (setq table (cons defchr table)))) org-link-escape-chars))
9054 ((null table)
9055 (setq table org-link-escape-chars)))
9056 (mapconcat
9057 (lambda (char)
9058 (if (or (member char table)
9059 (and (or (< char 32) (= char 37) (> char 126))
9060 org-url-hexify-p))
9061 (mapconcat (lambda (sequence-element)
9062 (format "%%%.2X" sequence-element))
9063 (or (encode-coding-char char 'utf-8)
9064 (error "Unable to percent escape character: %s"
9065 (char-to-string char))) "")
9066 (char-to-string char))) text ""))
9068 (defun org-link-unescape (str)
9069 "Unhex hexified Unicode strings as returned from the JavaScript function
9070 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9071 (unless (and (null str) (string= "" str))
9072 (let ((pos 0) (case-fold-search t) unhexed)
9073 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9074 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9075 (setq str (replace-match unhexed t t str))
9076 (setq pos (+ pos (length unhexed))))))
9077 str)
9079 (defun org-link-unescape-compound (hex)
9080 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9081 Note: this function also decodes single byte encodings like
9082 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9083 (save-match-data
9084 (let* ((bytes (cdr (split-string hex "%")))
9085 (ret "")
9086 (eat 0)
9087 (sum 0))
9088 (while bytes
9089 (let* ((val (string-to-number (pop bytes) 16))
9090 (shift-xor
9091 (if (= 0 eat)
9092 (cond
9093 ((>= val 252) (cons 6 252))
9094 ((>= val 248) (cons 5 248))
9095 ((>= val 240) (cons 4 240))
9096 ((>= val 224) (cons 3 224))
9097 ((>= val 192) (cons 2 192))
9098 (t (cons 0 0)))
9099 (cons 6 128))))
9100 (if (>= val 192) (setq eat (car shift-xor)))
9101 (setq val (logxor val (cdr shift-xor)))
9102 (setq sum (+ (lsh sum (car shift-xor)) val))
9103 (if (> eat 0) (setq eat (- eat 1)))
9104 (cond
9105 ((= 0 eat) ;multi byte
9106 (setq ret (concat ret (org-char-to-string sum)))
9107 (setq sum 0))
9108 ((not bytes) ; single byte(s)
9109 (setq ret (org-link-unescape-single-byte-sequence hex))))
9110 )) ;; end (while bytes
9111 ret )))
9113 (defun org-link-unescape-single-byte-sequence (hex)
9114 "Unhexify hex-encoded single byte character sequences."
9115 (mapconcat (lambda (byte)
9116 (char-to-string (string-to-number byte 16)))
9117 (cdr (split-string hex "%")) ""))
9119 (defun org-xor (a b)
9120 "Exclusive or."
9121 (if a (not b) b))
9123 (defun org-fixup-message-id-for-http (s)
9124 "Replace special characters in a message id, so it can be used in an http query."
9125 (when (string-match "%" s)
9126 (setq s (mapconcat (lambda (c)
9127 (if (eq c ?%)
9128 "%25"
9129 (char-to-string c)))
9130 s "")))
9131 (while (string-match "<" s)
9132 (setq s (replace-match "%3C" t t s)))
9133 (while (string-match ">" s)
9134 (setq s (replace-match "%3E" t t s)))
9135 (while (string-match "@" s)
9136 (setq s (replace-match "%40" t t s)))
9139 (defun org-link-prettify (link)
9140 "Return a human-readable representation of LINK.
9141 The car of LINK must be a raw link the cdr of LINK must be either
9142 a link description or nil."
9143 (let ((desc (or (cadr link) "<no description>")))
9144 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9145 "<" (car link) ">")))
9147 ;;;###autoload
9148 (defun org-insert-link-global ()
9149 "Insert a link like Org-mode does.
9150 This command can be called in any mode to insert a link in Org-mode syntax."
9151 (interactive)
9152 (org-load-modules-maybe)
9153 (org-run-like-in-org-mode 'org-insert-link))
9155 (defun org-insert-all-links (&optional keep)
9156 "Insert all links in `org-stored-links'."
9157 (interactive "P")
9158 (let ((links (copy-sequence org-stored-links)) l)
9159 (while (setq l (if keep (pop links) (pop org-stored-links)))
9160 (insert "- ")
9161 (org-insert-link nil (car l) (cadr l))
9162 (insert "\n"))))
9164 (defun org-link-fontify-links-to-this-file ()
9165 "Fontify links to the current file in `org-stored-links'."
9166 (let ((f (buffer-file-name)) a b)
9167 (setq a (mapcar (lambda(l)
9168 (let ((ll (car l)))
9169 (when (and (string-match "^file:\\(.+\\)::" ll)
9170 (equal f (expand-file-name (match-string 1 ll))))
9171 ll)))
9172 org-stored-links))
9173 (when (featurep 'org-id)
9174 (setq b (mapcar (lambda(l)
9175 (let ((ll (car l)))
9176 (when (and (string-match "^id:\\(.+\\)$" ll)
9177 (equal f (expand-file-name
9178 (or (org-id-find-id-file
9179 (match-string 1 ll)) ""))))
9180 ll)))
9181 org-stored-links)))
9182 (mapcar (lambda(l)
9183 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9184 (delq nil (append a b)))))
9186 (defvar org-link-links-in-this-file nil)
9187 (defun org-insert-link (&optional complete-file link-location default-description)
9188 "Insert a link. At the prompt, enter the link.
9190 Completion can be used to insert any of the link protocol prefixes like
9191 http or ftp in use.
9193 The history can be used to select a link previously stored with
9194 `org-store-link'. When the empty string is entered (i.e. if you just
9195 press RET at the prompt), the link defaults to the most recently
9196 stored link. As SPC triggers completion in the minibuffer, you need to
9197 use M-SPC or C-q SPC to force the insertion of a space character.
9199 You will also be prompted for a description, and if one is given, it will
9200 be displayed in the buffer instead of the link.
9202 If there is already a link at point, this command will allow you to edit link
9203 and description parts.
9205 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9206 be selected using completion. The path to the file will be relative to the
9207 current directory if the file is in the current directory or a subdirectory.
9208 Otherwise, the link will be the absolute path as completed in the minibuffer
9209 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9210 option `org-link-file-path-type'.
9212 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9213 the current directory or below.
9215 With three \\[universal-argument] prefixes, negate the meaning of
9216 `org-keep-stored-link-after-insertion'.
9218 If `org-make-link-description-function' is non-nil, this function will be
9219 called with the link target, and the result will be the default
9220 link description.
9222 If the LINK-LOCATION parameter is non-nil, this value will be
9223 used as the link location instead of reading one interactively.
9225 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9226 be used as the default description."
9227 (interactive "P")
9228 (let* ((wcf (current-window-configuration))
9229 (region (if (org-region-active-p)
9230 (buffer-substring (region-beginning) (region-end))))
9231 (remove (and region (list (region-beginning) (region-end))))
9232 (desc region)
9233 tmphist ; byte-compile incorrectly complains about this
9234 (link link-location)
9235 (abbrevs org-link-abbrev-alist-local)
9236 entry file all-prefixes auto-desc)
9237 (cond
9238 (link-location) ; specified by arg, just use it.
9239 ((org-in-regexp org-bracket-link-regexp 1)
9240 ;; We do have a link at point, and we are going to edit it.
9241 (setq remove (list (match-beginning 0) (match-end 0)))
9242 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9243 (setq link (read-string "Link: "
9244 (org-link-unescape
9245 (org-match-string-no-properties 1)))))
9246 ((or (org-in-regexp org-angle-link-re)
9247 (org-in-regexp org-plain-link-re))
9248 ;; Convert to bracket link
9249 (setq remove (list (match-beginning 0) (match-end 0))
9250 link (read-string "Link: "
9251 (org-remove-angle-brackets (match-string 0)))))
9252 ((member complete-file '((4) (16)))
9253 ;; Completing read for file names.
9254 (setq link (org-file-complete-link complete-file)))
9256 ;; Read link, with completion for stored links.
9257 (org-link-fontify-links-to-this-file)
9258 (org-switch-to-buffer-other-window "*Org Links*")
9259 (with-current-buffer "*Org Links*"
9260 (erase-buffer)
9261 (insert "Insert a link.
9262 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9263 (when org-stored-links
9264 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9265 (insert (mapconcat 'org-link-prettify
9266 (reverse org-stored-links) "\n")))
9267 (goto-char (point-min)))
9268 (let ((cw (selected-window)))
9269 (select-window (get-buffer-window "*Org Links*" 'visible))
9270 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9271 (unless (pos-visible-in-window-p (point-max))
9272 (org-fit-window-to-buffer))
9273 (and (window-live-p cw) (select-window cw)))
9274 ;; Fake a link history, containing the stored links.
9275 (setq tmphist (append (mapcar 'car org-stored-links)
9276 org-insert-link-history))
9277 (setq all-prefixes (append (mapcar 'car abbrevs)
9278 (mapcar 'car org-link-abbrev-alist)
9279 org-link-types))
9280 (unwind-protect
9281 (progn
9282 (setq link
9283 (let ((org-completion-use-ido nil)
9284 (org-completion-use-iswitchb nil))
9285 (org-completing-read
9286 "Link: "
9287 (append
9288 (mapcar (lambda (x) (list (concat x ":")))
9289 all-prefixes)
9290 (mapcar 'car org-stored-links)
9291 (mapcar 'cadr org-stored-links))
9292 nil nil nil
9293 'tmphist
9294 (caar org-stored-links))))
9295 (if (not (string-match "\\S-" link))
9296 (error "No link selected"))
9297 (mapc (lambda(l)
9298 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9299 org-stored-links)
9300 (if (or (member link all-prefixes)
9301 (and (equal ":" (substring link -1))
9302 (member (substring link 0 -1) all-prefixes)
9303 (setq link (substring link 0 -1))))
9304 (setq link (org-link-try-special-completion link))))
9305 (set-window-configuration wcf)
9306 (kill-buffer "*Org Links*"))
9307 (setq entry (assoc link org-stored-links))
9308 (or entry (push link org-insert-link-history))
9309 (setq desc (or desc (nth 1 entry)))))
9311 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9312 (not org-keep-stored-link-after-insertion))
9313 (setq org-stored-links (delq (assoc link org-stored-links)
9314 org-stored-links)))
9316 (if (string-match org-plain-link-re link)
9317 ;; URL-like link, normalize the use of angular brackets.
9318 (setq link (org-remove-angle-brackets link)))
9320 ;; Check if we are linking to the current file with a search option
9321 ;; If yes, simplify the link by using only the search option.
9322 (when (and buffer-file-name
9323 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9324 (let* ((path (match-string 1 link))
9325 (case-fold-search nil)
9326 (search (match-string 2 link)))
9327 (save-match-data
9328 (if (equal (file-truename buffer-file-name) (file-truename path))
9329 ;; We are linking to this same file, with a search option
9330 (setq link search)))))
9332 ;; Check if we can/should use a relative path. If yes, simplify the link
9333 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9334 (let* ((type (match-string 1 link))
9335 (path (match-string 2 link))
9336 (origpath path)
9337 (case-fold-search nil))
9338 (cond
9339 ((or (eq org-link-file-path-type 'absolute)
9340 (equal complete-file '(16)))
9341 (setq path (abbreviate-file-name (expand-file-name path))))
9342 ((eq org-link-file-path-type 'noabbrev)
9343 (setq path (expand-file-name path)))
9344 ((eq org-link-file-path-type 'relative)
9345 (setq path (file-relative-name path)))
9347 (save-match-data
9348 (if (string-match (concat "^" (regexp-quote
9349 (expand-file-name
9350 (file-name-as-directory
9351 default-directory))))
9352 (expand-file-name path))
9353 ;; We are linking a file with relative path name.
9354 (setq path (substring (expand-file-name path)
9355 (match-end 0)))
9356 (setq path (abbreviate-file-name (expand-file-name path)))))))
9357 (setq link (concat type path))
9358 (if (equal desc origpath)
9359 (setq desc path))))
9361 (if org-make-link-description-function
9362 (setq desc
9363 (or (condition-case nil
9364 (funcall org-make-link-description-function link desc)
9365 (error (progn (message "Can't get link description from `%s'"
9366 (symbol-name org-make-link-description-function))
9367 (sit-for 2) nil)))
9368 (read-string "Description: " default-description)))
9369 (if default-description (setq desc default-description)
9370 (setq desc (or (and auto-desc desc)
9371 (read-string "Description: " desc)))))
9373 (unless (string-match "\\S-" desc) (setq desc nil))
9374 (if remove (apply 'delete-region remove))
9375 (insert (org-make-link-string link desc))))
9377 (defun org-link-try-special-completion (type)
9378 "If there is completion support for link type TYPE, offer it."
9379 (let ((fun (intern (concat "org-" type "-complete-link"))))
9380 (if (functionp fun)
9381 (funcall fun)
9382 (read-string "Link (no completion support): " (concat type ":")))))
9384 (defun org-file-complete-link (&optional arg)
9385 "Create a file link using completion."
9386 (let (file link)
9387 (setq file (read-file-name "File: "))
9388 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9389 (pwd1 (file-name-as-directory (abbreviate-file-name
9390 (expand-file-name ".")))))
9391 (cond
9392 ((equal arg '(16))
9393 (setq link (concat
9394 "file:"
9395 (abbreviate-file-name (expand-file-name file)))))
9396 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9397 (setq link (concat "file:" (match-string 1 file))))
9398 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9399 (expand-file-name file))
9400 (setq link (concat
9401 "file:" (match-string 1 (expand-file-name file)))))
9402 (t (setq link (concat "file:" file)))))
9403 link))
9405 (defun org-completing-read (&rest args)
9406 "Completing-read with SPACE being a normal character."
9407 (let ((enable-recursive-minibuffers t)
9408 (minibuffer-local-completion-map
9409 (copy-keymap minibuffer-local-completion-map)))
9410 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9411 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9412 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9413 (apply 'org-icompleting-read args)))
9415 (defun org-completing-read-no-i (&rest args)
9416 (let (org-completion-use-ido org-completion-use-iswitchb)
9417 (apply 'org-completing-read args)))
9419 (defun org-iswitchb-completing-read (prompt choices &rest args)
9420 "Use iswitch as a completing-read replacement to choose from choices.
9421 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9422 from."
9423 (let* ((iswitchb-use-virtual-buffers nil)
9424 (iswitchb-make-buflist-hook
9425 (lambda ()
9426 (setq iswitchb-temp-buflist choices))))
9427 (iswitchb-read-buffer prompt)))
9429 (defun org-icompleting-read (&rest args)
9430 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9431 (org-without-partial-completion
9432 (if (and org-completion-use-ido
9433 (fboundp 'ido-completing-read)
9434 (boundp 'ido-mode) ido-mode
9435 (listp (second args)))
9436 (let ((ido-enter-matching-directory nil))
9437 (apply 'ido-completing-read (concat (car args))
9438 (if (consp (car (nth 1 args)))
9439 (mapcar 'car (nth 1 args))
9440 (nth 1 args))
9441 (cddr args)))
9442 (if (and org-completion-use-iswitchb
9443 (boundp 'iswitchb-mode) iswitchb-mode
9444 (listp (second args)))
9445 (apply 'org-iswitchb-completing-read (concat (car args))
9446 (if (consp (car (nth 1 args)))
9447 (mapcar 'car (nth 1 args))
9448 (nth 1 args))
9449 (cddr args))
9450 (apply 'completing-read args)))))
9452 (defun org-extract-attributes (s)
9453 "Extract the attributes cookie from a string and set as text property."
9454 (let (a attr (start 0) key value)
9455 (save-match-data
9456 (when (string-match "{{\\([^}]+\\)}}$" s)
9457 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9458 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9459 (setq key (match-string 1 a) value (match-string 2 a)
9460 start (match-end 0)
9461 attr (plist-put attr (intern key) value))))
9462 (org-add-props s nil 'org-attr attr))
9465 (defun org-extract-attributes-from-string (tag)
9466 (let (key value attr)
9467 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9468 (setq key (match-string 1 tag) value (match-string 2 tag)
9469 tag (replace-match "" t t tag)
9470 attr (plist-put attr (intern key) value)))
9471 (cons tag attr)))
9473 (defun org-attributes-to-string (plist)
9474 "Format a property list into an HTML attribute list."
9475 (let ((s "") key value)
9476 (while plist
9477 (setq key (pop plist) value (pop plist))
9478 (and value
9479 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9482 ;;; Opening/following a link
9484 (defvar org-link-search-failed nil)
9486 (defvar org-open-link-functions nil
9487 "Hook for functions finding a plain text link.
9488 These functions must take a single argument, the link content.
9489 They will be called for links that look like [[link text][description]]
9490 when LINK TEXT does not have a protocol like \"http:\" and does not look
9491 like a filename (e.g. \"./blue.png\").
9493 These functions will be called *before* Org attempts to resolve the
9494 link by doing text searches in the current buffer - so if you want a
9495 link \"[[target]]\" to still find \"<<target>>\", your function should
9496 handle this as a special case.
9498 When the function does handle the link, it must return a non-nil value.
9499 If it decides that it is not responsible for this link, it must return
9500 nil to indicate that that Org-mode can continue with other options
9501 like exact and fuzzy text search.")
9503 (defun org-next-link ()
9504 "Move forward to the next link.
9505 If the link is in hidden text, expose it."
9506 (interactive)
9507 (when (and org-link-search-failed (eq this-command last-command))
9508 (goto-char (point-min))
9509 (message "Link search wrapped back to beginning of buffer"))
9510 (setq org-link-search-failed nil)
9511 (let* ((pos (point))
9512 (ct (org-context))
9513 (a (assoc :link ct)))
9514 (if a (goto-char (nth 2 a)))
9515 (if (re-search-forward org-any-link-re nil t)
9516 (progn
9517 (goto-char (match-beginning 0))
9518 (if (outline-invisible-p) (org-show-context)))
9519 (goto-char pos)
9520 (setq org-link-search-failed t)
9521 (error "No further link found"))))
9523 (defun org-previous-link ()
9524 "Move backward to the previous link.
9525 If the link is in hidden text, expose it."
9526 (interactive)
9527 (when (and org-link-search-failed (eq this-command last-command))
9528 (goto-char (point-max))
9529 (message "Link search wrapped back to end of buffer"))
9530 (setq org-link-search-failed nil)
9531 (let* ((pos (point))
9532 (ct (org-context))
9533 (a (assoc :link ct)))
9534 (if a (goto-char (nth 1 a)))
9535 (if (re-search-backward org-any-link-re nil t)
9536 (progn
9537 (goto-char (match-beginning 0))
9538 (if (outline-invisible-p) (org-show-context)))
9539 (goto-char pos)
9540 (setq org-link-search-failed t)
9541 (error "No further link found"))))
9543 (defun org-translate-link (s)
9544 "Translate a link string if a translation function has been defined."
9545 (if (and org-link-translation-function
9546 (fboundp org-link-translation-function)
9547 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9548 (progn
9549 (setq s (funcall org-link-translation-function
9550 (match-string 1 s) (match-string 2 s)))
9551 (concat (car s) ":" (cdr s)))
9554 (defun org-translate-link-from-planner (type path)
9555 "Translate a link from Emacs Planner syntax so that Org can follow it.
9556 This is still an experimental function, your mileage may vary."
9557 (cond
9558 ((member type '("http" "https" "news" "ftp"))
9559 ;; standard Internet links are the same.
9560 nil)
9561 ((and (equal type "irc") (string-match "^//" path))
9562 ;; Planner has two / at the beginning of an irc link, we have 1.
9563 ;; We should have zero, actually....
9564 (setq path (substring path 1)))
9565 ((and (equal type "lisp") (string-match "^/" path))
9566 ;; Planner has a slash, we do not.
9567 (setq type "elisp" path (substring path 1)))
9568 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9569 ;; A typical message link. Planner has the id after the final slash,
9570 ;; we separate it with a hash mark
9571 (setq path (concat (match-string 1 path) "#"
9572 (org-remove-angle-brackets (match-string 2 path)))))
9574 (cons type path))
9576 (defun org-find-file-at-mouse (ev)
9577 "Open file link or URL at mouse."
9578 (interactive "e")
9579 (mouse-set-point ev)
9580 (org-open-at-point 'in-emacs))
9582 (defun org-open-at-mouse (ev)
9583 "Open file link or URL at mouse.
9584 See the docstring of `org-open-file' for details."
9585 (interactive "e")
9586 (mouse-set-point ev)
9587 (if (eq major-mode 'org-agenda-mode)
9588 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9589 (org-open-at-point))
9591 (defvar org-window-config-before-follow-link nil
9592 "The window configuration before following a link.
9593 This is saved in case the need arises to restore it.")
9595 (defvar org-open-link-marker (make-marker)
9596 "Marker pointing to the location where `org-open-at-point; was called.")
9598 ;;;###autoload
9599 (defun org-open-at-point-global ()
9600 "Follow a link like Org-mode does.
9601 This command can be called in any mode to follow a link that has
9602 Org-mode syntax."
9603 (interactive)
9604 (org-run-like-in-org-mode 'org-open-at-point))
9606 ;;;###autoload
9607 (defun org-open-link-from-string (s &optional arg reference-buffer)
9608 "Open a link in the string S, as if it was in Org-mode."
9609 (interactive "sLink: \nP")
9610 (let ((reference-buffer (or reference-buffer (current-buffer))))
9611 (with-temp-buffer
9612 (let ((org-inhibit-startup (not reference-buffer)))
9613 (org-mode)
9614 (insert s)
9615 (goto-char (point-min))
9616 (when reference-buffer
9617 (setq org-link-abbrev-alist-local
9618 (with-current-buffer reference-buffer
9619 org-link-abbrev-alist-local)))
9620 (org-open-at-point arg reference-buffer)))))
9622 (defvar org-open-at-point-functions nil
9623 "Hook that is run when following a link at point.
9625 Functions in this hook must return t if they identify and follow
9626 a link at point. If they don't find anything interesting at point,
9627 they must return nil.")
9629 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9630 (defun org-open-at-point (&optional arg reference-buffer)
9631 "Open link at or after point.
9632 If there is no link at point, this function will search forward up to
9633 the end of the current line.
9634 Normally, files will be opened by an appropriate application. If the
9635 optional prefix argument ARG is non-nil, Emacs will visit the file.
9636 With a double prefix argument, try to open outside of Emacs, in the
9637 application the system uses for this file type."
9638 (interactive "P")
9639 ;; if in a code block, then open the block's results
9640 (unless (call-interactively #'org-babel-open-src-block-result)
9641 (org-load-modules-maybe)
9642 (move-marker org-open-link-marker (point))
9643 (setq org-window-config-before-follow-link (current-window-configuration))
9644 (org-remove-occur-highlights nil nil t)
9645 (cond
9646 ((and (org-at-heading-p)
9647 (not (org-at-timestamp-p t))
9648 (not (org-in-regexp
9649 (concat org-plain-link-re "\\|"
9650 org-bracket-link-regexp "\\|"
9651 org-angle-link-re "\\|"
9652 "[ \t]:[^ \t\n]+:[ \t]*$")))
9653 (not (get-text-property (point) 'org-linked-text)))
9654 (or (org-offer-links-in-entry arg)
9655 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9656 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9657 ((and (org-at-timestamp-p t)
9658 (not (org-in-regexp org-bracket-link-regexp)))
9659 (org-follow-timestamp-link))
9660 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9661 (not (org-in-regexp org-any-link-re)))
9662 (org-footnote-action))
9664 (let (type path link line search (pos (point)))
9665 (catch 'match
9666 (save-excursion
9667 (skip-chars-forward "^]\n\r")
9668 (when (org-in-regexp org-bracket-link-regexp 1)
9669 (setq link (org-extract-attributes
9670 (org-link-unescape (org-match-string-no-properties 1))))
9671 (while (string-match " *\n *" link)
9672 (setq link (replace-match " " t t link)))
9673 (setq link (org-link-expand-abbrev link))
9674 (cond
9675 ((or (file-name-absolute-p link)
9676 (string-match "^\\.\\.?/" link))
9677 (setq type "file" path link))
9678 ((string-match org-link-re-with-space3 link)
9679 (setq type (match-string 1 link) path (match-string 2 link)))
9680 ((string-match "^help:+\\(.+\\)" link)
9681 (setq type "help" path (match-string 1 link)))
9682 (t (setq type "thisfile" path link)))
9683 (throw 'match t)))
9685 (when (get-text-property (point) 'org-linked-text)
9686 (setq type "thisfile"
9687 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9688 (1+ (point)) (point))
9689 path (buffer-substring
9690 (or (previous-single-property-change pos 'org-linked-text)
9691 (point-min))
9692 (or (next-single-property-change pos 'org-linked-text)
9693 (point-max))))
9694 (throw 'match t))
9696 (save-excursion
9697 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9698 (when (or (org-in-regexp org-angle-link-re)
9699 (and plinkpos (goto-char (car plinkpos))
9700 (save-match-data (not (looking-back "\\[\\[")))))
9701 (setq type (match-string 1)
9702 path (org-link-unescape (match-string 2)))
9703 (throw 'match t))))
9704 (save-excursion
9705 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9706 (setq type "tags"
9707 path (match-string 1))
9708 (while (string-match ":" path)
9709 (setq path (replace-match "+" t t path)))
9710 (throw 'match t)))
9711 (when (org-in-regexp "<\\([^><\n]+\\)>")
9712 (setq type "tree-match"
9713 path (match-string 1))
9714 (throw 'match t)))
9715 (unless path
9716 (user-error "No link found"))
9718 ;; switch back to reference buffer
9719 ;; needed when if called in a temporary buffer through
9720 ;; org-open-link-from-string
9721 (with-current-buffer (or reference-buffer (current-buffer))
9723 ;; Remove any trailing spaces in path
9724 (if (string-match " +\\'" path)
9725 (setq path (replace-match "" t t path)))
9726 (if (and org-link-translation-function
9727 (fboundp org-link-translation-function))
9728 ;; Check if we need to translate the link
9729 (let ((tmp (funcall org-link-translation-function type path)))
9730 (setq type (car tmp) path (cdr tmp))))
9732 (cond
9734 ((assoc type org-link-protocols)
9735 (funcall (nth 1 (assoc type org-link-protocols)) path))
9737 ((equal type "help")
9738 (let ((f-or-v (intern path)))
9739 (cond ((fboundp f-or-v)
9740 (describe-function f-or-v))
9741 ((boundp f-or-v)
9742 (describe-variable f-or-v))
9743 (t (error "Not a known function or variable")))))
9745 ((equal type "mailto")
9746 (let ((cmd (car org-link-mailto-program))
9747 (args (cdr org-link-mailto-program)) args1
9748 (address path) (subject "") a)
9749 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9750 (setq address (match-string 1 path)
9751 subject (org-link-escape (match-string 2 path))))
9752 (while args
9753 (cond
9754 ((not (stringp (car args))) (push (pop args) args1))
9755 (t (setq a (pop args))
9756 (if (string-match "%a" a)
9757 (setq a (replace-match address t t a)))
9758 (if (string-match "%s" a)
9759 (setq a (replace-match subject t t a)))
9760 (push a args1))))
9761 (apply cmd (nreverse args1))))
9763 ((member type '("http" "https" "ftp" "news"))
9764 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9765 (org-link-escape
9766 path org-link-escape-chars-browser)
9767 path))))
9769 ((string= type "doi")
9770 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9771 (org-link-escape
9772 path org-link-escape-chars-browser)
9773 path))))
9775 ((member type '("message"))
9776 (browse-url (concat type ":" path)))
9778 ((string= type "tags")
9779 (org-tags-view arg path))
9781 ((string= type "tree-match")
9782 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9784 ((string= type "file")
9785 (if (string-match "::\\([0-9]+\\)\\'" path)
9786 (setq line (string-to-number (match-string 1 path))
9787 path (substring path 0 (match-beginning 0)))
9788 (if (string-match "::\\(.+\\)\\'" path)
9789 (setq search (match-string 1 path)
9790 path (substring path 0 (match-beginning 0)))))
9791 (if (string-match "[*?{]" (file-name-nondirectory path))
9792 (dired path)
9793 (org-open-file path arg line search)))
9795 ((string= type "shell")
9796 (let ((buf (generate-new-buffer "*Org Shell Output"))
9797 (cmd path))
9798 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9799 (string-match org-confirm-shell-link-not-regexp cmd))
9800 (not org-confirm-shell-link-function)
9801 (funcall org-confirm-shell-link-function
9802 (format "Execute \"%s\" in shell? "
9803 (org-add-props cmd nil
9804 'face 'org-warning))))
9805 (progn
9806 (message "Executing %s" cmd)
9807 (shell-command cmd buf)
9808 (if (featurep 'midnight)
9809 (setq clean-buffer-list-kill-buffer-names
9810 (cons buf clean-buffer-list-kill-buffer-names))))
9811 (error "Abort"))))
9813 ((string= type "elisp")
9814 (let ((cmd path))
9815 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9816 (string-match org-confirm-elisp-link-not-regexp cmd))
9817 (not org-confirm-elisp-link-function)
9818 (funcall org-confirm-elisp-link-function
9819 (format "Execute \"%s\" as elisp? "
9820 (org-add-props cmd nil
9821 'face 'org-warning))))
9822 (message "%s => %s" cmd
9823 (if (equal (string-to-char cmd) ?\()
9824 (eval (read cmd))
9825 (call-interactively (read cmd))))
9826 (error "Abort"))))
9828 ((and (string= type "thisfile")
9829 (run-hook-with-args-until-success
9830 'org-open-link-functions path)))
9832 ((string= type "thisfile")
9833 (if arg
9834 (switch-to-buffer-other-window
9835 (org-get-buffer-for-internal-link (current-buffer)))
9836 (org-mark-ring-push))
9837 (let ((cmd `(org-link-search
9838 ,path
9839 ,(cond ((equal arg '(4)) ''occur)
9840 ((equal arg '(16)) ''org-occur))
9841 ,pos)))
9842 (condition-case nil (let ((org-link-search-inhibit-query t))
9843 (eval cmd))
9844 (error (progn (widen) (eval cmd))))))
9846 (t (browse-url-at-point)))))))
9847 (move-marker org-open-link-marker nil)
9848 (run-hook-with-args 'org-follow-link-hook)))
9850 (defun org-offer-links-in-entry (&optional nth zero)
9851 "Offer links in the current entry and follow the selected link.
9852 If there is only one link, follow it immediately as well.
9853 If NTH is an integer, immediately pick the NTH link found.
9854 If ZERO is a string, check also this string for a link, and if
9855 there is one, offer it as link number zero."
9856 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9857 "\\(" org-angle-link-re "\\)\\|"
9858 "\\(" org-plain-link-re "\\)"))
9859 (cnt ?0)
9860 (in-emacs (if (integerp nth) nil nth))
9861 have-zero end links link c)
9862 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9863 (push (match-string 0 zero) links)
9864 (setq cnt (1- cnt) have-zero t))
9865 (save-excursion
9866 (org-back-to-heading t)
9867 (setq end (save-excursion (outline-next-heading) (point)))
9868 (while (re-search-forward re end t)
9869 (push (match-string 0) links))
9870 (setq links (org-uniquify (reverse links))))
9872 (cond
9873 ((null links)
9874 (message "No links"))
9875 ((equal (length links) 1)
9876 (setq link (list (car links))))
9877 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9878 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9879 (t ; we have to select a link
9880 (save-excursion
9881 (save-window-excursion
9882 (delete-other-windows)
9883 (with-output-to-temp-buffer "*Select Link*"
9884 (mapc (lambda (l)
9885 (if (not (string-match org-bracket-link-regexp l))
9886 (princ (format "[%c] %s\n" (incf cnt)
9887 (org-remove-angle-brackets l)))
9888 (if (match-end 3)
9889 (princ (format "[%c] %s (%s)\n" (incf cnt)
9890 (match-string 3 l) (match-string 1 l)))
9891 (princ (format "[%c] %s\n" (incf cnt)
9892 (match-string 1 l))))))
9893 links))
9894 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9895 (message "Select link to open, RET to open all:")
9896 (setq c (read-char-exclusive))
9897 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9898 (when (equal c ?q) (error "Abort"))
9899 (if (equal c ?\C-m)
9900 (setq link links)
9901 (setq nth (- c ?0))
9902 (if have-zero (setq nth (1+ nth)))
9903 (unless (and (integerp nth) (>= (length links) nth))
9904 (error "Invalid link selection"))
9905 (setq link (list (nth (1- nth) links))))))
9906 (if link
9907 (let ((buf (current-buffer)))
9908 (dolist (l link)
9909 (org-open-link-from-string l in-emacs buf))
9911 nil)))
9913 ;; Add special file links that specify the way of opening
9915 (org-add-link-type "file+sys" 'org-open-file-with-system)
9916 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9917 (defun org-open-file-with-system (path)
9918 "Open file at PATH using the system way of opening it."
9919 (org-open-file path 'system))
9920 (defun org-open-file-with-emacs (path)
9921 "Open file at PATH in Emacs."
9922 (org-open-file path 'emacs))
9923 (defun org-remove-file-link-modifiers ()
9924 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9925 (goto-char (point-min))
9926 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9927 (org-if-unprotected
9928 (replace-match "file:" t t))))
9929 (eval-after-load "org-exp"
9930 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9931 'org-remove-file-link-modifiers))
9933 ;;;; Time estimates
9935 (defun org-get-effort (&optional pom)
9936 "Get the effort estimate for the current entry."
9937 (org-entry-get pom org-effort-property))
9939 ;;; File search
9941 (defvar org-create-file-search-functions nil
9942 "List of functions to construct the right search string for a file link.
9943 These functions are called in turn with point at the location to
9944 which the link should point.
9946 A function in the hook should first test if it would like to
9947 handle this file type, for example by checking the `major-mode'
9948 or the file extension. If it decides not to handle this file, it
9949 should just return nil to give other functions a chance. If it
9950 does handle the file, it must return the search string to be used
9951 when following the link. The search string will be part of the
9952 file link, given after a double colon, and `org-open-at-point'
9953 will automatically search for it. If special measures must be
9954 taken to make the search successful, another function should be
9955 added to the companion hook `org-execute-file-search-functions',
9956 which see.
9958 A function in this hook may also use `setq' to set the variable
9959 `description' to provide a suggestion for the descriptive text to
9960 be used for this link when it gets inserted into an Org-mode
9961 buffer with \\[org-insert-link].")
9963 (defvar org-execute-file-search-functions nil
9964 "List of functions to execute a file search triggered by a link.
9966 Functions added to this hook must accept a single argument, the
9967 search string that was part of the file link, the part after the
9968 double colon. The function must first check if it would like to
9969 handle this search, for example by checking the `major-mode' or
9970 the file extension. If it decides not to handle this search, it
9971 should just return nil to give other functions a chance. If it
9972 does handle the search, it must return a non-nil value to keep
9973 other functions from trying.
9975 Each function can access the current prefix argument through the
9976 variable `current-prefix-argument'. Note that a single prefix is
9977 used to force opening a link in Emacs, so it may be good to only
9978 use a numeric or double prefix to guide the search function.
9980 In case this is needed, a function in this hook can also restore
9981 the window configuration before `org-open-at-point' was called using:
9983 (set-window-configuration org-window-config-before-follow-link)")
9985 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9986 (defun org-link-search (s &optional type avoid-pos stealth)
9987 "Search for a link search option.
9988 If S is surrounded by forward slashes, it is interpreted as a
9989 regular expression. In org-mode files, this will create an `org-occur'
9990 sparse tree. In ordinary files, `occur' will be used to list matches.
9991 If the current buffer is in `dired-mode', grep will be used to search
9992 in all files. If AVOID-POS is given, ignore matches near that position.
9994 When optional argument STEALTH is non-nil, do not modify
9995 visibility around point, thus ignoring
9996 `org-show-hierarchy-above', `org-show-following-heading' and
9997 `org-show-siblings' variables."
9998 (let ((case-fold-search t)
9999 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10000 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10001 (append '(("") (" ") ("\t") ("\n"))
10002 org-emphasis-alist)
10003 "\\|") "\\)"))
10004 (pos (point))
10005 (pre nil) (post nil)
10006 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10007 (cond
10008 ;; First check if there are any special search functions
10009 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10010 ;; Now try the builtin stuff
10011 ((and (equal (string-to-char s0) ?#)
10012 (> (length s0) 1)
10013 (save-excursion
10014 (goto-char (point-min))
10015 (and
10016 (re-search-forward
10017 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10018 (setq type 'dedicated
10019 pos (match-beginning 0))))
10020 ;; There is an exact target for this
10021 (goto-char pos)
10022 (org-back-to-heading t)))
10023 ((save-excursion
10024 (goto-char (point-min))
10025 (and
10026 (re-search-forward
10027 (concat "<<" (regexp-quote s0) ">>") nil t)
10028 (setq type 'dedicated
10029 pos (match-beginning 0))))
10030 ;; There is an exact target for this
10031 (goto-char pos))
10032 ((save-excursion
10033 (goto-char (point-min))
10034 (and
10035 (re-search-forward
10036 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10037 (setq type 'dedicated pos (match-beginning 0))))
10038 ;; Found an invisible target.
10039 (goto-char pos))
10040 ((save-excursion
10041 (goto-char (point-min))
10042 (and
10043 (re-search-forward
10044 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10045 (setq type 'dedicated pos (match-beginning 0))))
10046 ;; Found an element with a matching #+name affiliated keyword.
10047 (goto-char pos))
10048 ((and (string-match "^(\\(.*\\))$" s0)
10049 (save-excursion
10050 (goto-char (point-min))
10051 (and
10052 (re-search-forward
10053 (concat "[^[]" (regexp-quote
10054 (format org-coderef-label-format
10055 (match-string 1 s0))))
10056 nil t)
10057 (setq type 'dedicated
10058 pos (1+ (match-beginning 0))))))
10059 ;; There is a coderef target for this
10060 (goto-char pos))
10061 ((string-match "^/\\(.*\\)/$" s)
10062 ;; A regular expression
10063 (cond
10064 ((derived-mode-p 'org-mode)
10065 (org-occur (match-string 1 s)))
10066 ;;((eq major-mode 'dired-mode)
10067 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10068 (t (org-do-occur (match-string 1 s)))))
10069 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10070 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10071 (goto-char (point-min))
10072 (cond
10073 ((let (case-fold-search)
10074 (re-search-forward (format org-complex-heading-regexp-format
10075 (regexp-quote s))
10076 nil t))
10077 ;; OK, found a match
10078 (setq type 'dedicated)
10079 (goto-char (match-beginning 0)))
10080 ((and (not org-link-search-inhibit-query)
10081 (eq org-link-search-must-match-exact-headline 'query-to-create)
10082 (y-or-n-p "No match - create this as a new heading? "))
10083 (goto-char (point-max))
10084 (or (bolp) (newline))
10085 (insert "* " s "\n")
10086 (beginning-of-line 0))
10088 (goto-char pos)
10089 (error "No match"))))
10091 ;; A normal search string
10092 (when (equal (string-to-char s) ?*)
10093 ;; Anchor on headlines, post may include tags.
10094 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10095 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10096 s (substring s 1)))
10097 (remove-text-properties
10098 0 (length s)
10099 '(face nil mouse-face nil keymap nil fontified nil) s)
10100 ;; Make a series of regular expressions to find a match
10101 (setq words (org-split-string s "[ \n\r\t]+")
10103 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10104 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10105 "\\)" markers)
10106 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10107 re2a (concat "[ \t\r\n]" re2a_)
10108 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10109 re4 (concat "[^a-zA-Z_]" re4_)
10111 re1 (concat pre re2 post)
10112 re3 (concat pre (if pre re4_ re4) post)
10113 re5 (concat pre ".*" re4)
10114 re2 (concat pre re2)
10115 re2a (concat pre (if pre re2a_ re2a))
10116 re4 (concat pre (if pre re4_ re4))
10117 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10118 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10119 re5 "\\)"
10121 (cond
10122 ((eq type 'org-occur) (org-occur reall))
10123 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10124 (t (goto-char (point-min))
10125 (setq type 'fuzzy)
10126 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10127 (org-search-not-self 1 re1 nil t)
10128 (org-search-not-self 1 re2 nil t)
10129 (org-search-not-self 1 re2a nil t)
10130 (org-search-not-self 1 re3 nil t)
10131 (org-search-not-self 1 re4 nil t)
10132 (org-search-not-self 1 re5 nil t)
10134 (goto-char (match-beginning 1))
10135 (goto-char pos)
10136 (error "No match"))))))
10137 (and (derived-mode-p 'org-mode)
10138 (not stealth)
10139 (org-show-context 'link-search))
10140 type))
10142 (defun org-search-not-self (group &rest args)
10143 "Execute `re-search-forward', but only accept matches that do not
10144 enclose the position of `org-open-link-marker'."
10145 (let ((m org-open-link-marker))
10146 (catch 'exit
10147 (while (apply 're-search-forward args)
10148 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10149 (goto-char (match-end group))
10150 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10151 (> (match-beginning 0) (marker-position m))
10152 (< (match-end 0) (marker-position m)))
10153 (save-match-data
10154 (or (not (org-in-regexp
10155 org-bracket-link-analytic-regexp 1))
10156 (not (match-end 4)) ; no description
10157 (and (<= (match-beginning 4) (point))
10158 (>= (match-end 4) (point))))))
10159 (throw 'exit (point))))))))
10161 (defun org-get-buffer-for-internal-link (buffer)
10162 "Return a buffer to be used for displaying the link target of internal links."
10163 (cond
10164 ((not org-display-internal-link-with-indirect-buffer)
10165 buffer)
10166 ((string-match "(Clone)$" (buffer-name buffer))
10167 (message "Buffer is already a clone, not making another one")
10168 ;; we also do not modify visibility in this case
10169 buffer)
10170 (t ; make a new indirect buffer for displaying the link
10171 (let* ((bn (buffer-name buffer))
10172 (ibn (concat bn "(Clone)"))
10173 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10174 (with-current-buffer ib (org-overview))
10175 ib))))
10177 (defun org-do-occur (regexp &optional cleanup)
10178 "Call the Emacs command `occur'.
10179 If CLEANUP is non-nil, remove the printout of the regular expression
10180 in the *Occur* buffer. This is useful if the regex is long and not useful
10181 to read."
10182 (occur regexp)
10183 (when cleanup
10184 (let ((cwin (selected-window)) win beg end)
10185 (when (setq win (get-buffer-window "*Occur*"))
10186 (select-window win))
10187 (goto-char (point-min))
10188 (when (re-search-forward "match[a-z]+" nil t)
10189 (setq beg (match-end 0))
10190 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10191 (setq end (1- (match-beginning 0)))))
10192 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10193 (goto-char (point-min))
10194 (select-window cwin))))
10196 ;;; The mark ring for links jumps
10198 (defvar org-mark-ring nil
10199 "Mark ring for positions before jumps in Org-mode.")
10200 (defvar org-mark-ring-last-goto nil
10201 "Last position in the mark ring used to go back.")
10202 ;; Fill and close the ring
10203 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10204 (loop for i from 1 to org-mark-ring-length do
10205 (push (make-marker) org-mark-ring))
10206 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10207 org-mark-ring)
10209 (defun org-mark-ring-push (&optional pos buffer)
10210 "Put the current position or POS into the mark ring and rotate it."
10211 (interactive)
10212 (setq pos (or pos (point)))
10213 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10214 (move-marker (car org-mark-ring)
10215 (or pos (point))
10216 (or buffer (current-buffer)))
10217 (message "%s"
10218 (substitute-command-keys
10219 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10221 (defun org-mark-ring-goto (&optional n)
10222 "Jump to the previous position in the mark ring.
10223 With prefix arg N, jump back that many stored positions. When
10224 called several times in succession, walk through the entire ring.
10225 Org-mode commands jumping to a different position in the current file,
10226 or to another Org-mode file, automatically push the old position
10227 onto the ring."
10228 (interactive "p")
10229 (let (p m)
10230 (if (eq last-command this-command)
10231 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10232 (setq p org-mark-ring))
10233 (setq org-mark-ring-last-goto p)
10234 (setq m (car p))
10235 (org-pop-to-buffer-same-window (marker-buffer m))
10236 (goto-char m)
10237 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10239 (defun org-remove-angle-brackets (s)
10240 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10241 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10243 (defun org-add-angle-brackets (s)
10244 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10245 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10247 (defun org-remove-double-quotes (s)
10248 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10249 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10252 ;;; Following specific links
10254 (defun org-follow-timestamp-link ()
10255 "Open an agenda view for the time-stamp date/range at point."
10256 (cond
10257 ((org-at-date-range-p t)
10258 (let ((org-agenda-start-on-weekday)
10259 (t1 (match-string 1))
10260 (t2 (match-string 2)) tt1 tt2)
10261 (setq tt1 (time-to-days (org-time-string-to-time t1))
10262 tt2 (time-to-days (org-time-string-to-time t2)))
10263 (let ((org-agenda-buffer-tmp-name
10264 (format "*Org Agenda(a:%s)"
10265 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10266 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10267 ((org-at-timestamp-p t)
10268 (let ((org-agenda-buffer-tmp-name
10269 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10270 (org-agenda-list nil (time-to-days (org-time-string-to-time
10271 (substring (match-string 1) 0 10)))
10272 1)))
10273 (t (error "This should not happen"))))
10276 ;;; Following file links
10277 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10278 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10279 (declare-function mailcap-mime-info
10280 "mailcap" (string &optional request no-decode))
10281 (defvar org-wait nil)
10282 (defun org-open-file (path &optional in-emacs line search)
10283 "Open the file at PATH.
10284 First, this expands any special file name abbreviations. Then the
10285 configuration variable `org-file-apps' is checked if it contains an
10286 entry for this file type, and if yes, the corresponding command is launched.
10288 If no application is found, Emacs simply visits the file.
10290 With optional prefix argument IN-EMACS, Emacs will visit the file.
10291 With a double \\[universal-argument] \\[universal-argument] \
10292 prefix arg, Org tries to avoid opening in Emacs
10293 and to use an external application to visit the file.
10295 Optional LINE specifies a line to go to, optional SEARCH a string
10296 to search for. If LINE or SEARCH is given, the file will be
10297 opened in Emacs, unless an entry from org-file-apps that makes
10298 use of groups in a regexp matches.
10300 If you want to change the way frames are used when following a
10301 link, please customize `org-link-frame-setup'.
10303 If the file does not exist, an error is thrown."
10304 (let* ((file (if (equal path "")
10305 buffer-file-name
10306 (substitute-in-file-name (expand-file-name path))))
10307 (file-apps (append org-file-apps (org-default-apps)))
10308 (apps (org-remove-if
10309 'org-file-apps-entry-match-against-dlink-p file-apps))
10310 (apps-dlink (org-remove-if-not
10311 'org-file-apps-entry-match-against-dlink-p file-apps))
10312 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10313 (dirp (if remp nil (file-directory-p file)))
10314 (file (if (and dirp org-open-directory-means-index-dot-org)
10315 (concat (file-name-as-directory file) "index.org")
10316 file))
10317 (a-m-a-p (assq 'auto-mode apps))
10318 (dfile (downcase file))
10319 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10320 (link (cond ((and (eq line nil)
10321 (eq search nil))
10322 file)
10323 (line
10324 (concat file "::" (number-to-string line)))
10325 (search
10326 (concat file "::" search))))
10327 (dlink (downcase link))
10328 (old-buffer (current-buffer))
10329 (old-pos (point))
10330 (old-mode major-mode)
10331 ext cmd link-match-data)
10332 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10333 (setq ext (match-string 1 dfile))
10334 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10335 (setq ext (match-string 1 dfile))))
10336 (cond
10337 ((member in-emacs '((16) system))
10338 (setq cmd (cdr (assoc 'system apps))))
10339 (in-emacs (setq cmd 'emacs))
10341 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10342 (and dirp (cdr (assoc 'directory apps)))
10343 ; first, try matching against apps-dlink
10344 ; if we get a match here, store the match data for later
10345 (let ((match (assoc-default dlink apps-dlink
10346 'string-match)))
10347 (if match
10348 (progn (setq link-match-data (match-data))
10349 match)
10350 (progn (setq in-emacs (or in-emacs line search))
10351 nil))) ; if we have no match in apps-dlink,
10352 ; always open the file in emacs if line or search
10353 ; is given (for backwards compatibility)
10354 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10355 'string-match)
10356 (cdr (assoc ext apps))
10357 (cdr (assoc t apps))))))
10358 (when (eq cmd 'system)
10359 (setq cmd (cdr (assoc 'system apps))))
10360 (when (eq cmd 'default)
10361 (setq cmd (cdr (assoc t apps))))
10362 (when (eq cmd 'mailcap)
10363 (require 'mailcap)
10364 (mailcap-parse-mailcaps)
10365 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10366 (command (mailcap-mime-info mime-type)))
10367 (if (stringp command)
10368 (setq cmd command)
10369 (setq cmd 'emacs))))
10370 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10371 (not (file-exists-p file))
10372 (not org-open-non-existing-files))
10373 (error "No such file: %s" file))
10374 (cond
10375 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10376 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10377 (while (string-match "['\"]%s['\"]" cmd)
10378 (setq cmd (replace-match "%s" t t cmd)))
10379 (while (string-match "%s" cmd)
10380 (setq cmd (replace-match
10381 (save-match-data
10382 (shell-quote-argument
10383 (convert-standard-filename file)))
10384 t t cmd)))
10386 ;; Replace "%1", "%2" etc. in command with group matches from regex
10387 (save-match-data
10388 (let ((match-index 1)
10389 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10390 (set-match-data link-match-data)
10391 (while (<= match-index number-of-groups)
10392 (let ((regex (concat "%" (number-to-string match-index)))
10393 (replace-with (match-string match-index dlink)))
10394 (while (string-match regex cmd)
10395 (setq cmd (replace-match replace-with t t cmd))))
10396 (setq match-index (+ match-index 1)))))
10398 (save-window-excursion
10399 (start-process-shell-command cmd nil cmd)
10400 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10402 ((or (stringp cmd)
10403 (eq cmd 'emacs))
10404 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10405 (widen)
10406 (if line (org-goto-line line)
10407 (if search (org-link-search search))))
10408 ((consp cmd)
10409 (let ((file (convert-standard-filename file)))
10410 (save-match-data
10411 (set-match-data link-match-data)
10412 (eval cmd))))
10413 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10414 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10415 (or (not (equal old-buffer (current-buffer)))
10416 (not (equal old-pos (point))))
10417 (org-mark-ring-push old-pos old-buffer))))
10419 (defun org-file-apps-entry-match-against-dlink-p (entry)
10420 "This function returns non-nil if `entry' uses a regular
10421 expression which should be matched against the whole link by
10422 org-open-file.
10424 It assumes that is the case when the entry uses a regular
10425 expression which has at least one grouping construct and the
10426 action is either a lisp form or a command string containing
10427 '%1', i.e. using at least one subexpression match as a
10428 parameter."
10429 (let ((selector (car entry))
10430 (action (cdr entry)))
10431 (if (stringp selector)
10432 (and (> (regexp-opt-depth selector) 0)
10433 (or (and (stringp action)
10434 (string-match "%[0-9]" action))
10435 (consp action)))
10436 nil)))
10438 (defun org-default-apps ()
10439 "Return the default applications for this operating system."
10440 (cond
10441 ((eq system-type 'darwin)
10442 org-file-apps-defaults-macosx)
10443 ((eq system-type 'windows-nt)
10444 org-file-apps-defaults-windowsnt)
10445 (t org-file-apps-defaults-gnu)))
10447 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10448 "Convert extensions to regular expressions in the cars of LIST.
10449 Also, weed out any non-string entries, because the return value is used
10450 only for regexp matching.
10451 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10452 point to the symbol `emacs', indicating that the file should
10453 be opened in Emacs."
10454 (append
10455 (delq nil
10456 (mapcar (lambda (x)
10457 (if (not (stringp (car x)))
10459 (if (string-match "\\W" (car x))
10461 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10462 list))
10463 (if add-auto-mode
10464 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10466 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10467 (defun org-file-remote-p (file)
10468 "Test whether FILE specifies a location on a remote system.
10469 Return non-nil if the location is indeed remote.
10471 For example, the filename \"/user@host:/foo\" specifies a location
10472 on the system \"/user@host:\"."
10473 (cond ((fboundp 'file-remote-p)
10474 (file-remote-p file))
10475 ((fboundp 'tramp-handle-file-remote-p)
10476 (tramp-handle-file-remote-p file))
10477 ((and (boundp 'ange-ftp-name-format)
10478 (string-match (car ange-ftp-name-format) file))
10479 t)))
10482 ;;;; Refiling
10484 (defun org-get-org-file ()
10485 "Read a filename, with default directory `org-directory'."
10486 (let ((default (or org-default-notes-file remember-data-file)))
10487 (read-file-name (format "File name [%s]: " default)
10488 (file-name-as-directory org-directory)
10489 default)))
10491 (defun org-notes-order-reversed-p ()
10492 "Check if the current file should receive notes in reversed order."
10493 (cond
10494 ((not org-reverse-note-order) nil)
10495 ((eq t org-reverse-note-order) t)
10496 ((not (listp org-reverse-note-order)) nil)
10497 (t (catch 'exit
10498 (let ((all org-reverse-note-order)
10499 entry)
10500 (while (setq entry (pop all))
10501 (if (string-match (car entry) buffer-file-name)
10502 (throw 'exit (cdr entry))))
10503 nil)))))
10505 (defvar org-refile-target-table nil
10506 "The list of refile targets, created by `org-refile'.")
10508 (defvar org-agenda-new-buffers nil
10509 "Buffers created to visit agenda files.")
10511 (defvar org-refile-cache nil
10512 "Cache for refile targets.")
10514 (defvar org-refile-markers nil
10515 "All the markers used for caching refile locations.")
10517 (defun org-refile-marker (pos)
10518 "Get a new refile marker, but only if caching is in use."
10519 (if (not org-refile-use-cache)
10521 (let ((m (make-marker)))
10522 (move-marker m pos)
10523 (push m org-refile-markers)
10524 m)))
10526 (defun org-refile-cache-clear ()
10527 "Clear the refile cache and disable all the markers."
10528 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10529 (setq org-refile-markers nil)
10530 (setq org-refile-cache nil)
10531 (message "Refile cache has been cleared"))
10533 (defun org-refile-cache-check-set (set)
10534 "Check if all the markers in the cache still have live buffers."
10535 (let (marker)
10536 (catch 'exit
10537 (while (and set (setq marker (nth 3 (pop set))))
10538 ;; if org-refile-use-outline-path is 'file, marker may be nil
10539 (when (and marker (null (marker-buffer marker)))
10540 (message "not found") (sit-for 3)
10541 (throw 'exit nil)))
10542 t)))
10544 (defun org-refile-cache-put (set &rest identifiers)
10545 "Push the refile targets SET into the cache, under IDENTIFIERS."
10546 (let* ((key (sha1 (prin1-to-string identifiers)))
10547 (entry (assoc key org-refile-cache)))
10548 (if entry
10549 (setcdr entry set)
10550 (push (cons key set) org-refile-cache))))
10552 (defun org-refile-cache-get (&rest identifiers)
10553 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10554 (cond
10555 ((not org-refile-cache) nil)
10556 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10558 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10559 org-refile-cache))))
10560 (and set (org-refile-cache-check-set set) set)))))
10562 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10563 "Produce a table with refile targets."
10564 (let ((case-fold-search nil)
10565 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10566 (entries (or org-refile-targets '((nil . (:level . 1)))))
10567 targets tgs txt re files f desc descre fast-path-p level pos0)
10568 (message "Getting targets...")
10569 (with-current-buffer (or default-buffer (current-buffer))
10570 (while (setq entry (pop entries))
10571 (setq files (car entry) desc (cdr entry))
10572 (setq fast-path-p nil)
10573 (cond
10574 ((null files) (setq files (list (current-buffer))))
10575 ((eq files 'org-agenda-files)
10576 (setq files (org-agenda-files 'unrestricted)))
10577 ((and (symbolp files) (fboundp files))
10578 (setq files (funcall files)))
10579 ((and (symbolp files) (boundp files))
10580 (setq files (symbol-value files))))
10581 (if (stringp files) (setq files (list files)))
10582 (cond
10583 ((eq (car desc) :tag)
10584 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10585 ((eq (car desc) :todo)
10586 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10587 ((eq (car desc) :regexp)
10588 (setq descre (cdr desc)))
10589 ((eq (car desc) :level)
10590 (setq descre (concat "^\\*\\{" (number-to-string
10591 (if org-odd-levels-only
10592 (1- (* 2 (cdr desc)))
10593 (cdr desc)))
10594 "\\}[ \t]")))
10595 ((eq (car desc) :maxlevel)
10596 (setq fast-path-p t)
10597 (setq descre (concat "^\\*\\{1," (number-to-string
10598 (if org-odd-levels-only
10599 (1- (* 2 (cdr desc)))
10600 (cdr desc)))
10601 "\\}[ \t]")))
10602 (t (error "Bad refiling target description %s" desc)))
10603 (while (setq f (pop files))
10604 (with-current-buffer
10605 (if (bufferp f) f (org-get-agenda-file-buffer f))
10607 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10608 (progn
10609 (if (bufferp f) (setq f (buffer-file-name
10610 (buffer-base-buffer f))))
10611 (setq f (and f (expand-file-name f)))
10612 (if (eq org-refile-use-outline-path 'file)
10613 (push (list (file-name-nondirectory f) f nil nil) tgs))
10614 (save-excursion
10615 (save-restriction
10616 (widen)
10617 (goto-char (point-min))
10618 (while (re-search-forward descre nil t)
10619 (goto-char (setq pos0 (point-at-bol)))
10620 (catch 'next
10621 (when org-refile-target-verify-function
10622 (save-match-data
10623 (or (funcall org-refile-target-verify-function)
10624 (throw 'next t))))
10625 (when (and (looking-at org-complex-heading-regexp)
10626 (not (member (match-string 4) excluded-entries))
10627 (match-string 4))
10628 (setq level (org-reduced-level
10629 (- (match-end 1) (match-beginning 1)))
10630 txt (org-link-display-format (match-string 4))
10631 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10632 re (format org-complex-heading-regexp-format
10633 (regexp-quote (match-string 4))))
10634 (when org-refile-use-outline-path
10635 (setq txt (mapconcat
10636 'org-protect-slash
10637 (append
10638 (if (eq org-refile-use-outline-path
10639 'file)
10640 (list (file-name-nondirectory
10641 (buffer-file-name
10642 (buffer-base-buffer))))
10643 (if (eq org-refile-use-outline-path
10644 'full-file-path)
10645 (list (buffer-file-name
10646 (buffer-base-buffer)))))
10647 (org-get-outline-path fast-path-p
10648 level txt)
10649 (list txt))
10650 "/")))
10651 (push (list txt f re (org-refile-marker (point)))
10652 tgs)))
10653 (when (= (point) pos0)
10654 ;; verification function has not moved point
10655 (goto-char (point-at-eol))))))))
10656 (when org-refile-use-cache
10657 (org-refile-cache-put tgs (buffer-file-name) descre))
10658 (setq targets (append tgs targets))
10659 ))))
10660 (message "Getting targets...done")
10661 (nreverse targets)))
10663 (defun org-protect-slash (s)
10664 (while (string-match "/" s)
10665 (setq s (replace-match "\\" t t s)))
10668 (defvar org-olpa (make-vector 20 nil))
10670 (defun org-get-outline-path (&optional fastp level heading)
10671 "Return the outline path to the current entry, as a list.
10673 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10674 routine which makes outline path derivations for an entire file,
10675 avoiding backtracing. Refile target collection makes use of that."
10676 (if fastp
10677 (progn
10678 (if (> level 19)
10679 (error "Outline path failure, more than 19 levels"))
10680 (loop for i from level upto 19 do
10681 (aset org-olpa i nil))
10682 (prog1
10683 (delq nil (append org-olpa nil))
10684 (aset org-olpa level heading)))
10685 (let (rtn case-fold-search)
10686 (save-excursion
10687 (save-restriction
10688 (widen)
10689 (while (org-up-heading-safe)
10690 (when (looking-at org-complex-heading-regexp)
10691 (push (org-match-string-no-properties 4) rtn)))
10692 rtn)))))
10694 (defun org-format-outline-path (path &optional width prefix)
10695 "Format the outline path PATH for display.
10696 Width is the maximum number of characters that is available.
10697 Prefix is a prefix to be included in the returned string,
10698 such as the file name."
10699 (setq width (or width 79))
10700 (if prefix (setq width (- width (length prefix))))
10701 (if (not path)
10702 (or prefix "")
10703 (let* ((nsteps (length path))
10704 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10705 (maxwidth (if (<= total-width width)
10706 10000 ;; everything fits
10707 ;; we need to shorten the level headings
10708 (/ (- width nsteps) nsteps)))
10709 (org-odd-levels-only nil)
10710 (n 0)
10711 (total (1+ (length prefix))))
10712 (setq maxwidth (max maxwidth 10))
10713 (concat prefix
10714 (mapconcat
10715 (lambda (h)
10716 (setq n (1+ n))
10717 (if (and (= n nsteps) (< maxwidth 10000))
10718 (setq maxwidth (- total-width total)))
10719 (if (< (length h) maxwidth)
10720 (progn (setq total (+ total (length h) 1)) h)
10721 (setq h (substring h 0 (- maxwidth 2))
10722 total (+ total maxwidth 1))
10723 (if (string-match "[ \t]+\\'" h)
10724 (setq h (substring h 0 (match-beginning 0))))
10725 (setq h (concat h "..")))
10726 (org-add-props h nil 'face
10727 (nth (% (1- n) org-n-level-faces)
10728 org-level-faces))
10730 path "/")))))
10732 (defun org-display-outline-path (&optional file current)
10733 "Display the current outline path in the echo area."
10734 (interactive "P")
10735 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10736 (case-fold-search nil)
10737 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10738 (if current (setq path (append path
10739 (save-excursion
10740 (org-back-to-heading t)
10741 (if (looking-at org-complex-heading-regexp)
10742 (list (match-string 4)))))))
10743 (message "%s"
10744 (org-format-outline-path
10745 path
10746 (1- (frame-width))
10747 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10749 (defvar org-refile-history nil
10750 "History for refiling operations.")
10752 (defvar org-after-refile-insert-hook nil
10753 "Hook run after `org-refile' has inserted its stuff at the new location.
10754 Note that this is still *before* the stuff will be removed from
10755 the *old* location.")
10757 (defvar org-capture-last-stored-marker)
10758 (defun org-refile (&optional goto default-buffer rfloc)
10759 "Move the entry or entries at point to another heading.
10760 The list of target headings is compiled using the information in
10761 `org-refile-targets', which see.
10763 At the target location, the entry is filed as a subitem of the target
10764 heading. Depending on `org-reverse-note-order', the new subitem will
10765 either be the first or the last subitem.
10767 If there is an active region, all entries in that region will be moved.
10768 However, the region must fulfill the requirement that the first heading
10769 is the first one sets the top-level of the moved text - at most siblings
10770 below it are allowed.
10772 With prefix arg GOTO, the command will only visit the target location
10773 and not actually move anything.
10775 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10776 go to the location where the last refiling operation has put the subtree.
10777 With a prefix argument of `2', refile to the running clock.
10779 RFLOC can be a refile location obtained in a different way.
10781 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10783 If you are using target caching (see `org-refile-use-cache'),
10784 you have to clear the target cache in order to find new targets.
10785 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10786 prefix argument (`C-u C-u C-u C-c C-w')."
10788 (interactive "P")
10789 (if (member goto '(0 (64)))
10790 (org-refile-cache-clear)
10791 (let* ((cbuf (current-buffer))
10792 (regionp (org-region-active-p))
10793 (region-start (and regionp (region-beginning)))
10794 (region-end (and regionp (region-end)))
10795 (region-length (and regionp (- region-end region-start)))
10796 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10797 pos it nbuf file re level reversed)
10798 (setq last-command nil)
10799 (when regionp
10800 (goto-char region-start)
10801 (or (bolp) (goto-char (point-at-bol)))
10802 (setq region-start (point))
10803 (unless (or (org-kill-is-subtree-p
10804 (buffer-substring region-start region-end))
10805 (prog1 org-refile-active-region-within-subtree
10806 (org-toggle-heading)))
10807 (error "The region is not a (sequence of) subtree(s)")))
10808 (if (equal goto '(16))
10809 (org-refile-goto-last-stored)
10810 (when (or
10811 (and (equal goto 2)
10812 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10813 (prog1
10814 (setq it (list (or org-clock-heading "running clock")
10815 (buffer-file-name
10816 (marker-buffer org-clock-hd-marker))
10818 (marker-position org-clock-hd-marker)))
10819 (setq goto nil)))
10820 (setq it (or rfloc
10821 (let (heading-text)
10822 (save-excursion
10823 (unless goto
10824 (org-back-to-heading t)
10825 (setq heading-text
10826 (nth 4 (org-heading-components))))
10827 (org-refile-get-location
10828 (cond (goto "Goto")
10829 (regionp "Refile region to")
10830 (t (concat "Refile subtree \""
10831 heading-text "\" to")))
10832 default-buffer
10833 (and (not (equal '(4) goto))
10834 org-refile-allow-creating-parent-nodes)
10835 goto))))))
10836 (setq file (nth 1 it)
10837 re (nth 2 it)
10838 pos (nth 3 it))
10839 (if (and (not goto)
10841 (equal (buffer-file-name) file)
10842 (if regionp
10843 (and (>= pos region-start)
10844 (<= pos region-end))
10845 (and (>= pos (point))
10846 (< pos (save-excursion
10847 (org-end-of-subtree t t))))))
10848 (error "Cannot refile to position inside the tree or region"))
10850 (setq nbuf (or (find-buffer-visiting file)
10851 (find-file-noselect file)))
10852 (if goto
10853 (progn
10854 (org-pop-to-buffer-same-window nbuf)
10855 (goto-char pos)
10856 (org-show-context 'org-goto))
10857 (if regionp
10858 (progn
10859 (org-kill-new (buffer-substring region-start region-end))
10860 (org-save-markers-in-region region-start region-end))
10861 (org-copy-subtree 1 nil t))
10862 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10863 (find-file-noselect file)))
10864 (setq reversed (org-notes-order-reversed-p))
10865 (save-excursion
10866 (save-restriction
10867 (widen)
10868 (if pos
10869 (progn
10870 (goto-char pos)
10871 (looking-at org-outline-regexp)
10872 (setq level (org-get-valid-level (funcall outline-level) 1))
10873 (goto-char
10874 (if reversed
10875 (or (outline-next-heading) (point-max))
10876 (or (save-excursion (org-get-next-sibling))
10877 (org-end-of-subtree t t)
10878 (point-max)))))
10879 (setq level 1)
10880 (if (not reversed)
10881 (goto-char (point-max))
10882 (goto-char (point-min))
10883 (or (outline-next-heading) (goto-char (point-max)))))
10884 (if (not (bolp)) (newline))
10885 (org-paste-subtree level)
10886 (when org-log-refile
10887 (org-add-log-setup 'refile nil nil 'findpos
10888 org-log-refile)
10889 (unless (eq org-log-refile 'note)
10890 (save-excursion (org-add-log-note))))
10891 (and org-auto-align-tags
10892 (let ((org-loop-over-headlines-in-active-region nil))
10893 (org-set-tags nil t)))
10894 (with-demoted-errors
10895 (bookmark-set "org-refile-last-stored"))
10896 ;; If we are refiling for capture, make sure that the
10897 ;; last-capture pointers point here
10898 (when (org-bound-and-true-p org-refile-for-capture)
10899 (with-demoted-errors
10900 (bookmark-set "org-capture-last-stored-marker"))
10901 (move-marker org-capture-last-stored-marker (point)))
10902 (if (fboundp 'deactivate-mark) (deactivate-mark))
10903 (run-hooks 'org-after-refile-insert-hook))))
10904 (if regionp
10905 (delete-region (point) (+ (point) region-length))
10906 (org-cut-subtree))
10907 (when (featurep 'org-inlinetask)
10908 (org-inlinetask-remove-END-maybe))
10909 (setq org-markers-to-move nil)
10910 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10912 (defun org-refile-goto-last-stored ()
10913 "Go to the location where the last refile was stored."
10914 (interactive)
10915 (bookmark-jump "org-refile-last-stored")
10916 (message "This is the location of the last refile"))
10918 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10919 no-exclude)
10920 "Prompt the user for a refile location, using PROMPT.
10921 PROMPT should not be suffixed with a colon and a space, because
10922 this function appends the default value from
10923 `org-refile-history' automatically, if that is not empty.
10924 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10925 this is used for the GOTO interface."
10926 (let ((org-refile-targets org-refile-targets)
10927 (org-refile-use-outline-path org-refile-use-outline-path)
10928 excluded-entries)
10929 (when (and (derived-mode-p 'org-mode)
10930 (not org-refile-use-cache)
10931 (not no-exclude))
10932 (org-map-tree
10933 (lambda()
10934 (setq excluded-entries
10935 (append excluded-entries (list (org-get-heading t t)))))))
10936 (setq org-refile-target-table
10937 (org-refile-get-targets default-buffer excluded-entries)))
10938 (unless org-refile-target-table
10939 (error "No refile targets"))
10940 (let* ((prompt (concat prompt
10941 (and (car org-refile-history)
10942 (concat " (default " (car org-refile-history) ")"))
10943 ": "))
10944 (cbuf (current-buffer))
10945 (partial-completion-mode nil)
10946 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10947 (cfunc (if (and org-refile-use-outline-path
10948 org-outline-path-complete-in-steps)
10949 'org-olpath-completing-read
10950 'org-icompleting-read))
10951 (extra (if org-refile-use-outline-path "/" ""))
10952 (filename (and cfn (expand-file-name cfn)))
10953 (tbl (mapcar
10954 (lambda (x)
10955 (if (and (not (member org-refile-use-outline-path
10956 '(file full-file-path)))
10957 (not (equal filename (nth 1 x))))
10958 (cons (concat (car x) extra " ("
10959 (file-name-nondirectory (nth 1 x)) ")")
10960 (cdr x))
10961 (cons (concat (car x) extra) (cdr x))))
10962 org-refile-target-table))
10963 (completion-ignore-case t)
10964 pa answ parent-target child parent old-hist)
10965 (setq old-hist org-refile-history)
10966 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10967 nil 'org-refile-history (car org-refile-history)))
10968 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10969 (org-refile-check-position pa)
10970 (if pa
10971 (progn
10972 (when (or (not org-refile-history)
10973 (not (eq old-hist org-refile-history))
10974 (not (equal (car pa) (car org-refile-history))))
10975 (setq org-refile-history
10976 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10977 org-refile-history
10978 (cdr org-refile-history))))
10979 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10980 (pop org-refile-history)))
10982 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10983 (progn
10984 (setq parent (match-string 1 answ)
10985 child (match-string 2 answ))
10986 (setq parent-target (or (assoc parent tbl)
10987 (assoc (concat parent "/") tbl)))
10988 (when (and parent-target
10989 (or (eq new-nodes t)
10990 (and (eq new-nodes 'confirm)
10991 (y-or-n-p (format "Create new node \"%s\"? "
10992 child)))))
10993 (org-refile-new-child parent-target child)))
10994 (error "Invalid target location")))))
10996 (declare-function org-string-nw-p "org-macs" (s))
10997 (defun org-refile-check-position (refile-pointer)
10998 "Check if the refile pointer matches the headline to which it points."
10999 (let* ((file (nth 1 refile-pointer))
11000 (re (nth 2 refile-pointer))
11001 (pos (nth 3 refile-pointer))
11002 buffer)
11003 (if (and (not (markerp pos)) (not file))
11004 (error "Please save the buffer to a file before refiling")
11005 (when (org-string-nw-p re)
11006 (setq buffer (if (markerp pos)
11007 (marker-buffer pos)
11008 (or (find-buffer-visiting file)
11009 (find-file-noselect file))))
11010 (with-current-buffer buffer
11011 (save-excursion
11012 (save-restriction
11013 (widen)
11014 (goto-char pos)
11015 (beginning-of-line 1)
11016 (unless (org-looking-at-p re)
11017 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11019 (defun org-refile-new-child (parent-target child)
11020 "Use refile target PARENT-TARGET to add new CHILD below it."
11021 (unless parent-target
11022 (error "Cannot find parent for new node"))
11023 (let ((file (nth 1 parent-target))
11024 (pos (nth 3 parent-target))
11025 level)
11026 (with-current-buffer (or (find-buffer-visiting file)
11027 (find-file-noselect file))
11028 (save-excursion
11029 (save-restriction
11030 (widen)
11031 (if pos
11032 (goto-char pos)
11033 (goto-char (point-max))
11034 (if (not (bolp)) (newline)))
11035 (when (looking-at org-outline-regexp)
11036 (setq level (funcall outline-level))
11037 (org-end-of-subtree t t))
11038 (org-back-over-empty-lines)
11039 (insert "\n" (make-string
11040 (if pos (org-get-valid-level level 1) 1) ?*)
11041 " " child "\n")
11042 (beginning-of-line 0)
11043 (list (concat (car parent-target) "/" child) file "" (point)))))))
11045 (defun org-olpath-completing-read (prompt collection &rest args)
11046 "Read an outline path like a file name."
11047 (let ((thetable collection)
11048 (org-completion-use-ido nil) ; does not work with ido.
11049 (org-completion-use-iswitchb nil)) ; or iswitchb
11050 (apply
11051 'org-icompleting-read prompt
11052 (lambda (string predicate &optional flag)
11053 (let (rtn r f (l (length string)))
11054 (cond
11055 ((eq flag nil)
11056 ;; try completion
11057 (try-completion string thetable))
11058 ((eq flag t)
11059 ;; all-completions
11060 (setq rtn (all-completions string thetable predicate))
11061 (mapcar
11062 (lambda (x)
11063 (setq r (substring x l))
11064 (if (string-match " ([^)]*)$" x)
11065 (setq f (match-string 0 x))
11066 (setq f ""))
11067 (if (string-match "/" r)
11068 (concat string (substring r 0 (match-end 0)) f)
11070 rtn))
11071 ((eq flag 'lambda)
11072 ;; exact match?
11073 (assoc string thetable)))))
11074 args)))
11076 ;;;; Dynamic blocks
11078 (defun org-find-dblock (name)
11079 "Find the first dynamic block with name NAME in the buffer.
11080 If not found, stay at current position and return nil."
11081 (let ((case-fold-search t) pos)
11082 (save-excursion
11083 (goto-char (point-min))
11084 (setq pos (and (re-search-forward
11085 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11086 (match-beginning 0))))
11087 (if pos (goto-char pos))
11088 pos))
11090 (defconst org-dblock-start-re
11091 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11092 "Matches the start line of a dynamic block, with parameters.")
11094 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11095 "Matches the end of a dynamic block.")
11097 (defun org-create-dblock (plist)
11098 "Create a dynamic block section, with parameters taken from PLIST.
11099 PLIST must contain a :name entry which is used as name of the block."
11100 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11101 (end-of-line 1)
11102 (newline))
11103 (let ((col (current-column))
11104 (name (plist-get plist :name)))
11105 (insert "#+BEGIN: " name)
11106 (while plist
11107 (if (eq (car plist) :name)
11108 (setq plist (cddr plist))
11109 (insert " " (prin1-to-string (pop plist)))))
11110 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11111 (beginning-of-line -2)))
11113 (defun org-prepare-dblock ()
11114 "Prepare dynamic block for refresh.
11115 This empties the block, puts the cursor at the insert position and returns
11116 the property list including an extra property :name with the block name."
11117 (unless (looking-at org-dblock-start-re)
11118 (error "Not at a dynamic block"))
11119 (let* ((begdel (1+ (match-end 0)))
11120 (name (org-no-properties (match-string 1)))
11121 (params (append (list :name name)
11122 (read (concat "(" (match-string 3) ")")))))
11123 (save-excursion
11124 (beginning-of-line 1)
11125 (skip-chars-forward " \t")
11126 (setq params (plist-put params :indentation-column (current-column))))
11127 (unless (re-search-forward org-dblock-end-re nil t)
11128 (error "Dynamic block not terminated"))
11129 (setq params
11130 (append params
11131 (list :content (buffer-substring
11132 begdel (match-beginning 0)))))
11133 (delete-region begdel (match-beginning 0))
11134 (goto-char begdel)
11135 (open-line 1)
11136 params))
11138 (defun org-map-dblocks (&optional command)
11139 "Apply COMMAND to all dynamic blocks in the current buffer.
11140 If COMMAND is not given, use `org-update-dblock'."
11141 (let ((cmd (or command 'org-update-dblock)))
11142 (save-excursion
11143 (goto-char (point-min))
11144 (while (re-search-forward org-dblock-start-re nil t)
11145 (goto-char (match-beginning 0))
11146 (save-excursion
11147 (condition-case nil
11148 (funcall cmd)
11149 (error (message "Error during update of dynamic block"))))
11150 (unless (re-search-forward org-dblock-end-re nil t)
11151 (error "Dynamic block not terminated"))))))
11153 (defun org-dblock-update (&optional arg)
11154 "User command for updating dynamic blocks.
11155 Update the dynamic block at point. With prefix ARG, update all dynamic
11156 blocks in the buffer."
11157 (interactive "P")
11158 (if arg
11159 (org-update-all-dblocks)
11160 (or (looking-at org-dblock-start-re)
11161 (org-beginning-of-dblock))
11162 (org-update-dblock)))
11164 (defun org-update-dblock ()
11165 "Update the dynamic block at point.
11166 This means to empty the block, parse for parameters and then call
11167 the correct writing function."
11168 (interactive)
11169 (save-window-excursion
11170 (let* ((pos (point))
11171 (line (org-current-line))
11172 (params (org-prepare-dblock))
11173 (name (plist-get params :name))
11174 (indent (plist-get params :indentation-column))
11175 (cmd (intern (concat "org-dblock-write:" name))))
11176 (message "Updating dynamic block `%s' at line %d..." name line)
11177 (funcall cmd params)
11178 (message "Updating dynamic block `%s' at line %d...done" name line)
11179 (goto-char pos)
11180 (when (and indent (> indent 0))
11181 (setq indent (make-string indent ?\ ))
11182 (save-excursion
11183 (org-beginning-of-dblock)
11184 (forward-line 1)
11185 (while (not (looking-at org-dblock-end-re))
11186 (insert indent)
11187 (beginning-of-line 2))
11188 (when (looking-at org-dblock-end-re)
11189 (and (looking-at "[ \t]+")
11190 (replace-match ""))
11191 (insert indent)))))))
11193 (defun org-beginning-of-dblock ()
11194 "Find the beginning of the dynamic block at point.
11195 Error if there is no such block at point."
11196 (let ((pos (point))
11197 beg)
11198 (end-of-line 1)
11199 (if (and (re-search-backward org-dblock-start-re nil t)
11200 (setq beg (match-beginning 0))
11201 (re-search-forward org-dblock-end-re nil t)
11202 (> (match-end 0) pos))
11203 (goto-char beg)
11204 (goto-char pos)
11205 (error "Not in a dynamic block"))))
11207 (defun org-update-all-dblocks ()
11208 "Update all dynamic blocks in the buffer.
11209 This function can be used in a hook."
11210 (interactive)
11211 (when (derived-mode-p 'org-mode)
11212 (org-map-dblocks 'org-update-dblock)))
11215 ;;;; Completion
11217 (defconst org-additional-option-like-keywords
11218 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11219 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11220 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11221 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11222 "BEGIN:" "END:"
11223 "ORGTBL" "TBLFM:" "TBLNAME:"
11224 "BEGIN_EXAMPLE" "END_EXAMPLE"
11225 "BEGIN_VERBATIM" "END_VERBATIM"
11226 "BEGIN_QUOTE" "END_QUOTE"
11227 "BEGIN_VERSE" "END_VERSE"
11228 "BEGIN_CENTER" "END_CENTER"
11229 "BEGIN_SRC" "END_SRC"
11230 "BEGIN_RESULT" "END_RESULT"
11231 "BEGIN_lstlisting" "END_lstlisting"
11232 "NAME:" "RESULTS:"
11233 "HEADER:" "HEADERS:"
11234 "COLUMNS:" "PROPERTY:"
11235 "CAPTION:" "LABEL:"
11236 "SETUPFILE:"
11237 "INCLUDE:" "INDEX:"
11238 "BIND:"
11239 "MACRO:"))
11241 (defconst org-options-keywords
11242 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11243 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11244 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11245 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11246 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11247 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11248 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11250 (defconst org-additional-option-like-keywords-for-flyspell
11251 (delete-dups
11252 (split-string
11253 (mapconcat (lambda(k)
11254 (replace-regexp-in-string
11255 "_\\|:" " "
11256 (concat k " " (downcase k) " " (upcase k))))
11257 (append org-options-keywords org-additional-option-like-keywords)
11258 " ")
11259 " +" t)))
11261 (defcustom org-structure-template-alist
11263 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11264 "<src lang=\"?\">\n\n</src>")
11265 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11266 "<example>\n?\n</example>")
11267 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11268 "<quote>\n?\n</quote>")
11269 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11270 "<verse>\n?\n</verse>")
11271 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11272 "<center>\n?\n</center>")
11273 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11274 "<literal style=\"latex\">\n?\n</literal>")
11275 ("L" "#+LaTeX: "
11276 "<literal style=\"latex\">?</literal>")
11277 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11278 "<literal style=\"html\">\n?\n</literal>")
11279 ("H" "#+HTML: "
11280 "<literal style=\"html\">?</literal>")
11281 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11282 ("A" "#+ASCII: ")
11283 ("i" "#+INDEX: ?"
11284 "#+INDEX: ?")
11285 ("I" "#+INCLUDE: %file ?"
11286 "<include file=%file markup=\"?\">")
11288 "Structure completion elements.
11289 This is a list of abbreviation keys and values. The value gets inserted
11290 if you type `<' followed by the key and then press the completion key,
11291 usually `M-TAB'. %file will be replaced by a file name after prompting
11292 for the file using completion. The cursor will be placed at the position
11293 of the `?` in the template.
11294 There are two templates for each key, the first uses the original Org syntax,
11295 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11296 the default when the /org-mtags.el/ module has been loaded. See also the
11297 variable `org-mtags-prefer-muse-templates'."
11298 :group 'org-completion
11299 :type '(repeat
11300 (string :tag "Key")
11301 (string :tag "Template")
11302 (string :tag "Muse Template")))
11304 (defun org-try-structure-completion ()
11305 "Try to complete a structure template before point.
11306 This looks for strings like \"<e\" on an otherwise empty line and
11307 expands them."
11308 (let ((l (buffer-substring (point-at-bol) (point)))
11310 (when (and (looking-at "[ \t]*$")
11311 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11312 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11313 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11314 (match-beginning 1)) a)
11315 t)))
11317 (defun org-complete-expand-structure-template (start cell)
11318 "Expand a structure template."
11319 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11320 (rpl (nth (if musep 2 1) cell))
11321 (ind ""))
11322 (delete-region start (point))
11323 (when (string-match "\\`#\\+" rpl)
11324 (cond
11325 ((bolp))
11326 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11327 (setq ind (buffer-substring (point-at-bol) (point))))
11328 (t (newline))))
11329 (setq start (point))
11330 (if (string-match "%file" rpl)
11331 (setq rpl (replace-match
11332 (concat
11333 "\""
11334 (save-match-data
11335 (abbreviate-file-name (read-file-name "Include file: ")))
11336 "\"")
11337 t t rpl)))
11338 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11339 (concat "\n" ind)))
11340 (insert rpl)
11341 (if (re-search-backward "\\?" start t) (delete-char 1))))
11343 ;;;; TODO, DEADLINE, Comments
11345 (defun org-toggle-comment ()
11346 "Change the COMMENT state of an entry."
11347 (interactive)
11348 (save-excursion
11349 (org-back-to-heading)
11350 (let (case-fold-search)
11351 (cond
11352 ((looking-at (format org-heading-keyword-regexp-format
11353 org-comment-string))
11354 (goto-char (match-end 1))
11355 (looking-at (concat " +" org-comment-string))
11356 (replace-match "" t t)
11357 (when (eolp) (insert " ")))
11358 ((looking-at org-outline-regexp)
11359 (goto-char (match-end 0))
11360 (insert org-comment-string " "))))))
11362 (defvar org-last-todo-state-is-todo nil
11363 "This is non-nil when the last TODO state change led to a TODO state.
11364 If the last change removed the TODO tag or switched to DONE, then
11365 this is nil.")
11367 (defvar org-setting-tags nil) ; dynamically skipped
11369 (defvar org-todo-setup-filter-hook nil
11370 "Hook for functions that pre-filter todo specs.
11371 Each function takes a todo spec and returns either nil or the spec
11372 transformed into canonical form." )
11374 (defvar org-todo-get-default-hook nil
11375 "Hook for functions that get a default item for todo.
11376 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11377 nil or a string to be used for the todo mark." )
11379 (defvar org-agenda-headline-snapshot-before-repeat)
11381 (defun org-current-effective-time ()
11382 "Return current time adjusted for `org-extend-today-until' variable."
11383 (let* ((ct (org-current-time))
11384 (dct (decode-time ct))
11385 (ct1
11386 (if (and org-use-effective-time
11387 (< (nth 2 dct) org-extend-today-until))
11388 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11389 ct)))
11390 ct1))
11392 (defun org-todo-yesterday (&optional arg)
11393 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11394 (interactive "P")
11395 (if (eq major-mode 'org-agenda-mode)
11396 (apply 'org-agenda-todo-yesterday arg)
11397 (let* ((hour (third (decode-time
11398 (org-current-time))))
11399 (org-extend-today-until (1+ hour)))
11400 (org-todo arg))))
11402 (defun org-todo (&optional arg)
11403 "Change the TODO state of an item.
11404 The state of an item is given by a keyword at the start of the heading,
11405 like
11406 *** TODO Write paper
11407 *** DONE Call mom
11409 The different keywords are specified in the variable `org-todo-keywords'.
11410 By default the available states are \"TODO\" and \"DONE\".
11411 So for this example: when the item starts with TODO, it is changed to DONE.
11412 When it starts with DONE, the DONE is removed. And when neither TODO nor
11413 DONE are present, add TODO at the beginning of the heading.
11415 With \\[universal-argument] prefix arg, use completion to determine the new \
11416 state.
11417 With numeric prefix arg, switch to that state.
11418 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11419 keywords (nextset).
11420 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11421 With a numeric prefix arg of 0, inhibit note taking for the change.
11423 For calling through lisp, arg is also interpreted in the following way:
11424 'none -> empty state
11425 \"\"(empty string) -> switch to empty state
11426 'done -> switch to DONE
11427 'nextset -> switch to the next set of keywords
11428 'previousset -> switch to the previous set of keywords
11429 \"WAITING\" -> switch to the specified keyword, but only if it
11430 really is a member of `org-todo-keywords'."
11431 (interactive "P")
11432 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11433 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11434 'region-start-level 'region))
11435 org-loop-over-headlines-in-active-region)
11436 (org-map-entries
11437 `(org-todo ,arg)
11438 org-loop-over-headlines-in-active-region
11439 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11440 (if (equal arg '(16)) (setq arg 'nextset))
11441 (let ((org-blocker-hook org-blocker-hook)
11442 (case-fold-search nil))
11443 (when (equal arg '(64))
11444 (setq arg nil org-blocker-hook nil))
11445 (when (and org-blocker-hook
11446 (or org-inhibit-blocking
11447 (org-entry-get nil "NOBLOCKING")))
11448 (setq org-blocker-hook nil))
11449 (save-excursion
11450 (catch 'exit
11451 (org-back-to-heading t)
11452 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11453 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11454 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11455 (let* ((match-data (match-data))
11456 (startpos (point-at-bol))
11457 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11458 (org-log-done org-log-done)
11459 (org-log-repeat org-log-repeat)
11460 (org-todo-log-states org-todo-log-states)
11461 (org-inhibit-logging
11462 (if (equal arg 0)
11463 (progn (setq arg nil) 'note) org-inhibit-logging))
11464 (this (match-string 1))
11465 (hl-pos (match-beginning 0))
11466 (head (org-get-todo-sequence-head this))
11467 (ass (assoc head org-todo-kwd-alist))
11468 (interpret (nth 1 ass))
11469 (done-word (nth 3 ass))
11470 (final-done-word (nth 4 ass))
11471 (org-last-state (or this ""))
11472 (completion-ignore-case t)
11473 (member (member this org-todo-keywords-1))
11474 (tail (cdr member))
11475 (org-state (cond
11476 ((and org-todo-key-trigger
11477 (or (and (equal arg '(4))
11478 (eq org-use-fast-todo-selection 'prefix))
11479 (and (not arg) org-use-fast-todo-selection
11480 (not (eq org-use-fast-todo-selection
11481 'prefix)))))
11482 ;; Use fast selection
11483 (org-fast-todo-selection))
11484 ((and (equal arg '(4))
11485 (or (not org-use-fast-todo-selection)
11486 (not org-todo-key-trigger)))
11487 ;; Read a state with completion
11488 (org-icompleting-read
11489 "State: " (mapcar (lambda(x) (list x))
11490 org-todo-keywords-1)
11491 nil t))
11492 ((eq arg 'right)
11493 (if this
11494 (if tail (car tail) nil)
11495 (car org-todo-keywords-1)))
11496 ((eq arg 'left)
11497 (if (equal member org-todo-keywords-1)
11499 (if this
11500 (nth (- (length org-todo-keywords-1)
11501 (length tail) 2)
11502 org-todo-keywords-1)
11503 (org-last org-todo-keywords-1))))
11504 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11505 (setq arg nil))) ; hack to fall back to cycling
11506 (arg
11507 ;; user or caller requests a specific state
11508 (cond
11509 ((equal arg "") nil)
11510 ((eq arg 'none) nil)
11511 ((eq arg 'done) (or done-word (car org-done-keywords)))
11512 ((eq arg 'nextset)
11513 (or (car (cdr (member head org-todo-heads)))
11514 (car org-todo-heads)))
11515 ((eq arg 'previousset)
11516 (let ((org-todo-heads (reverse org-todo-heads)))
11517 (or (car (cdr (member head org-todo-heads)))
11518 (car org-todo-heads))))
11519 ((car (member arg org-todo-keywords-1)))
11520 ((stringp arg)
11521 (error "State `%s' not valid in this file" arg))
11522 ((nth (1- (prefix-numeric-value arg))
11523 org-todo-keywords-1))))
11524 ((null member) (or head (car org-todo-keywords-1)))
11525 ((equal this final-done-word) nil) ;; -> make empty
11526 ((null tail) nil) ;; -> first entry
11527 ((memq interpret '(type priority))
11528 (if (eq this-command last-command)
11529 (car tail)
11530 (if (> (length tail) 0)
11531 (or done-word (car org-done-keywords))
11532 nil)))
11534 (car tail))))
11535 (org-state (or
11536 (run-hook-with-args-until-success
11537 'org-todo-get-default-hook org-state org-last-state)
11538 org-state))
11539 (next (if org-state (concat " " org-state " ") " "))
11540 (change-plist (list :type 'todo-state-change :from this :to org-state
11541 :position startpos))
11542 dolog now-done-p)
11543 (when org-blocker-hook
11544 (setq org-last-todo-state-is-todo
11545 (not (member this org-done-keywords)))
11546 (unless (save-excursion
11547 (save-match-data
11548 (org-with-wide-buffer
11549 (run-hook-with-args-until-failure
11550 'org-blocker-hook change-plist))))
11551 (if (org-called-interactively-p 'interactive)
11552 (error "TODO state change from %s to %s blocked" this org-state)
11553 ;; fail silently
11554 (message "TODO state change from %s to %s blocked" this org-state)
11555 (throw 'exit nil))))
11556 (store-match-data match-data)
11557 (replace-match next t t)
11558 (unless (pos-visible-in-window-p hl-pos)
11559 (message "TODO state changed to %s" (org-trim next)))
11560 (unless head
11561 (setq head (org-get-todo-sequence-head org-state)
11562 ass (assoc head org-todo-kwd-alist)
11563 interpret (nth 1 ass)
11564 done-word (nth 3 ass)
11565 final-done-word (nth 4 ass)))
11566 (when (memq arg '(nextset previousset))
11567 (message "Keyword-Set %d/%d: %s"
11568 (- (length org-todo-sets) -1
11569 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11570 (length org-todo-sets)
11571 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11572 (setq org-last-todo-state-is-todo
11573 (not (member org-state org-done-keywords)))
11574 (setq now-done-p (and (member org-state org-done-keywords)
11575 (not (member this org-done-keywords))))
11576 (and logging (org-local-logging logging))
11577 (when (and (or org-todo-log-states org-log-done)
11578 (not (eq org-inhibit-logging t))
11579 (not (memq arg '(nextset previousset))))
11580 ;; we need to look at recording a time and note
11581 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11582 (nth 2 (assoc this org-todo-log-states))))
11583 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11584 (setq dolog 'time))
11585 (when (and org-state
11586 (member org-state org-not-done-keywords)
11587 (not (member this org-not-done-keywords)))
11588 ;; This is now a todo state and was not one before
11589 ;; If there was a CLOSED time stamp, get rid of it.
11590 (org-add-planning-info nil nil 'closed))
11591 (when (and now-done-p org-log-done)
11592 ;; It is now done, and it was not done before
11593 (org-add-planning-info 'closed (org-current-effective-time))
11594 (if (and (not dolog) (eq 'note org-log-done))
11595 (org-add-log-setup 'done org-state this 'findpos 'note)))
11596 (when (and org-state dolog)
11597 ;; This is a non-nil state, and we need to log it
11598 (org-add-log-setup 'state org-state this 'findpos dolog)))
11599 ;; Fixup tag positioning
11600 (org-todo-trigger-tag-changes org-state)
11601 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11602 (when org-provide-todo-statistics
11603 (org-update-parent-todo-statistics))
11604 (run-hooks 'org-after-todo-state-change-hook)
11605 (if (and arg (not (member org-state org-done-keywords)))
11606 (setq head (org-get-todo-sequence-head org-state)))
11607 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11608 ;; Do we need to trigger a repeat?
11609 (when now-done-p
11610 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11611 ;; This is for the agenda, take a snapshot of the headline.
11612 (save-match-data
11613 (setq org-agenda-headline-snapshot-before-repeat
11614 (org-get-heading))))
11615 (org-auto-repeat-maybe org-state))
11616 ;; Fixup cursor location if close to the keyword
11617 (if (and (outline-on-heading-p)
11618 (not (bolp))
11619 (save-excursion (beginning-of-line 1)
11620 (looking-at org-todo-line-regexp))
11621 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11622 (progn
11623 (goto-char (or (match-end 2) (match-end 1)))
11624 (and (looking-at " ") (just-one-space))))
11625 (when org-trigger-hook
11626 (save-excursion
11627 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11629 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11630 "Block turning an entry into a TODO, using the hierarchy.
11631 This checks whether the current task should be blocked from state
11632 changes. Such blocking occurs when:
11634 1. The task has children which are not all in a completed state.
11636 2. A task has a parent with the property :ORDERED:, and there
11637 are siblings prior to the current task with incomplete
11638 status.
11640 3. The parent of the task is blocked because it has siblings that should
11641 be done first, or is child of a block grandparent TODO entry."
11643 (if (not org-enforce-todo-dependencies)
11644 t ; if locally turned off don't block
11645 (catch 'dont-block
11646 ;; If this is not a todo state change, or if this entry is already DONE,
11647 ;; do not block
11648 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11649 (member (plist-get change-plist :from)
11650 (cons 'done org-done-keywords))
11651 (member (plist-get change-plist :to)
11652 (cons 'todo org-not-done-keywords))
11653 (not (plist-get change-plist :to)))
11654 (throw 'dont-block t))
11655 ;; If this task has children, and any are undone, it's blocked
11656 (save-excursion
11657 (org-back-to-heading t)
11658 (let ((this-level (funcall outline-level)))
11659 (outline-next-heading)
11660 (let ((child-level (funcall outline-level)))
11661 (while (and (not (eobp))
11662 (> child-level this-level))
11663 ;; this todo has children, check whether they are all
11664 ;; completed
11665 (if (and (not (org-entry-is-done-p))
11666 (org-entry-is-todo-p))
11667 (throw 'dont-block nil))
11668 (outline-next-heading)
11669 (setq child-level (funcall outline-level))))))
11670 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11671 ;; any previous siblings are undone, it's blocked
11672 (save-excursion
11673 (org-back-to-heading t)
11674 (let* ((pos (point))
11675 (parent-pos (and (org-up-heading-safe) (point))))
11676 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11677 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11678 (forward-line 1)
11679 (re-search-forward org-not-done-heading-regexp pos t))
11680 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11681 ;; Search further up the hierarchy, to see if an ancestor is blocked
11682 (while t
11683 (goto-char parent-pos)
11684 (if (not (looking-at org-not-done-heading-regexp))
11685 (throw 'dont-block t)) ; do not block, parent is not a TODO
11686 (setq pos (point))
11687 (setq parent-pos (and (org-up-heading-safe) (point)))
11688 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11689 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11690 (forward-line 1)
11691 (re-search-forward org-not-done-heading-regexp pos t))
11692 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11694 (defcustom org-track-ordered-property-with-tag nil
11695 "Should the ORDERED property also be shown as a tag?
11696 The ORDERED property decides if an entry should require subtasks to be
11697 completed in sequence. Since a property is not very visible, setting
11698 this option means that toggling the ORDERED property with the command
11699 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11700 not relevant for the behavior, but it makes things more visible.
11702 Note that toggling the tag with tags commands will not change the property
11703 and therefore not influence behavior!
11705 This can be t, meaning the tag ORDERED should be used, It can also be a
11706 string to select a different tag for this task."
11707 :group 'org-todo
11708 :type '(choice
11709 (const :tag "No tracking" nil)
11710 (const :tag "Track with ORDERED tag" t)
11711 (string :tag "Use other tag")))
11713 (defun org-toggle-ordered-property ()
11714 "Toggle the ORDERED property of the current entry.
11715 For better visibility, you can track the value of this property with a tag.
11716 See variable `org-track-ordered-property-with-tag'."
11717 (interactive)
11718 (let* ((t1 org-track-ordered-property-with-tag)
11719 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11720 (save-excursion
11721 (org-back-to-heading)
11722 (if (org-entry-get nil "ORDERED")
11723 (progn
11724 (org-delete-property "ORDERED")
11725 (and tag (org-toggle-tag tag 'off))
11726 (message "Subtasks can be completed in arbitrary order"))
11727 (org-entry-put nil "ORDERED" "t")
11728 (and tag (org-toggle-tag tag 'on))
11729 (message "Subtasks must be completed in sequence")))))
11731 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11732 (defun org-block-todo-from-checkboxes (change-plist)
11733 "Block turning an entry into a TODO, using checkboxes.
11734 This checks whether the current task should be blocked from state
11735 changes because there are unchecked boxes in this entry."
11736 (if (not org-enforce-todo-checkbox-dependencies)
11737 t ; if locally turned off don't block
11738 (catch 'dont-block
11739 ;; If this is not a todo state change, or if this entry is already DONE,
11740 ;; do not block
11741 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11742 (member (plist-get change-plist :from)
11743 (cons 'done org-done-keywords))
11744 (member (plist-get change-plist :to)
11745 (cons 'todo org-not-done-keywords))
11746 (not (plist-get change-plist :to)))
11747 (throw 'dont-block t))
11748 ;; If this task has checkboxes that are not checked, it's blocked
11749 (save-excursion
11750 (org-back-to-heading t)
11751 (let ((beg (point)) end)
11752 (outline-next-heading)
11753 (setq end (point))
11754 (goto-char beg)
11755 (if (org-list-search-forward
11756 (concat (org-item-beginning-re)
11757 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11758 "\\[[- ]\\]")
11759 end t)
11760 (progn
11761 (if (boundp 'org-blocked-by-checkboxes)
11762 (setq org-blocked-by-checkboxes t))
11763 (throw 'dont-block nil)))))
11764 t))) ; do not block
11766 (defun org-entry-blocked-p ()
11767 "Is the current entry blocked?"
11768 (if (org-entry-get nil "NOBLOCKING")
11769 nil ;; Never block this entry
11770 (not
11771 (run-hook-with-args-until-failure
11772 'org-blocker-hook
11773 (list :type 'todo-state-change
11774 :position (point)
11775 :from 'todo
11776 :to 'done)))))
11778 (defun org-update-statistics-cookies (all)
11779 "Update the statistics cookie, either from TODO or from checkboxes.
11780 This should be called with the cursor in a line with a statistics cookie."
11781 (interactive "P")
11782 (if all
11783 (progn
11784 (org-update-checkbox-count 'all)
11785 (org-map-entries 'org-update-parent-todo-statistics))
11786 (if (not (org-at-heading-p))
11787 (org-update-checkbox-count)
11788 (let ((pos (point-marker))
11789 end l1 l2)
11790 (ignore-errors (org-back-to-heading t))
11791 (if (not (org-at-heading-p))
11792 (org-update-checkbox-count)
11793 (setq l1 (org-outline-level))
11794 (setq end (save-excursion
11795 (outline-next-heading)
11796 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11797 (point)))
11798 (if (and (save-excursion
11799 (re-search-forward
11800 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11801 (not (save-excursion (re-search-forward
11802 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11803 (org-update-checkbox-count)
11804 (if (and l2 (> l2 l1))
11805 (progn
11806 (goto-char end)
11807 (org-update-parent-todo-statistics))
11808 (goto-char pos)
11809 (beginning-of-line 1)
11810 (while (re-search-forward
11811 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11812 (point-at-eol) t)
11813 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11814 (goto-char pos)
11815 (move-marker pos nil)))))
11817 (defvar org-entry-property-inherited-from) ;; defined below
11818 (defun org-update-parent-todo-statistics ()
11819 "Update any statistics cookie in the parent of the current headline.
11820 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11821 the entire subtree and this will travel up the hierarchy and update
11822 statistics everywhere."
11823 (let* ((prop (save-excursion (org-up-heading-safe)
11824 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11825 (recursive (or (not org-hierarchical-todo-statistics)
11826 (and prop (string-match "\\<recursive\\>" prop))))
11827 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11829 (first t)
11830 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11831 level ltoggle l1 new ndel
11832 (cnt-all 0) (cnt-done 0) is-percent kwd
11833 checkbox-beg ov ovs ove cookie-present)
11834 (catch 'exit
11835 (save-excursion
11836 (beginning-of-line 1)
11837 (setq ltoggle (funcall outline-level))
11838 ;; Three situations are to consider:
11840 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11841 ;; to the top-level ancestor on the headline;
11843 ;; 2. If parent has "recursive" property, repeat up to the
11844 ;; headline setting that property, taking inheritance into
11845 ;; account;
11847 ;; 3. Else, move up to direct parent and proceed only once.
11848 (while (and (setq level (org-up-heading-safe))
11849 (or recursive first)
11850 (>= (point) lim))
11851 (setq first nil cookie-present nil)
11852 (unless (and level
11853 (not (string-match
11854 "\\<checkbox\\>"
11855 (downcase (or (org-entry-get nil "COOKIE_DATA")
11856 "")))))
11857 (throw 'exit nil))
11858 (while (re-search-forward box-re (point-at-eol) t)
11859 (setq cnt-all 0 cnt-done 0 cookie-present t)
11860 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11861 (save-match-data
11862 (unless (outline-next-heading) (throw 'exit nil))
11863 (while (and (looking-at org-complex-heading-regexp)
11864 (> (setq l1 (length (match-string 1))) level))
11865 (setq kwd (and (or recursive (= l1 ltoggle))
11866 (match-string 2)))
11867 (if (or (eq org-provide-todo-statistics 'all-headlines)
11868 (and (listp org-provide-todo-statistics)
11869 (or (member kwd org-provide-todo-statistics)
11870 (member kwd org-done-keywords))))
11871 (setq cnt-all (1+ cnt-all))
11872 (if (eq org-provide-todo-statistics t)
11873 (and kwd (setq cnt-all (1+ cnt-all)))))
11874 (and (member kwd org-done-keywords)
11875 (setq cnt-done (1+ cnt-done)))
11876 (outline-next-heading)))
11877 (setq new
11878 (if is-percent
11879 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11880 (format "[%d/%d]" cnt-done cnt-all))
11881 ndel (- (match-end 0) checkbox-beg))
11882 ;; handle overlays when updating cookie from column view
11883 (when (setq ov (car (overlays-at checkbox-beg)))
11884 (setq ovs (overlay-start ov) ove (overlay-end ov))
11885 (delete-overlay ov))
11886 (goto-char checkbox-beg)
11887 (insert new)
11888 (delete-region (point) (+ (point) ndel))
11889 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11890 (when ov (move-overlay ov ovs ove)))
11891 (when cookie-present
11892 (run-hook-with-args 'org-after-todo-statistics-hook
11893 cnt-done (- cnt-all cnt-done))))))
11894 (run-hooks 'org-todo-statistics-hook)))
11896 (defvar org-after-todo-statistics-hook nil
11897 "Hook that is called after a TODO statistics cookie has been updated.
11898 Each function is called with two arguments: the number of not-done entries
11899 and the number of done entries.
11901 For example, the following function, when added to this hook, will switch
11902 an entry to DONE when all children are done, and back to TODO when new
11903 entries are set to a TODO status. Note that this hook is only called
11904 when there is a statistics cookie in the headline!
11906 (defun org-summary-todo (n-done n-not-done)
11907 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11908 (let (org-log-done org-log-states) ; turn off logging
11909 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11912 (defvar org-todo-statistics-hook nil
11913 "Hook that is run whenever Org thinks TODO statistics should be updated.
11914 This hook runs even if there is no statistics cookie present, in which case
11915 `org-after-todo-statistics-hook' would not run.")
11917 (defun org-todo-trigger-tag-changes (state)
11918 "Apply the changes defined in `org-todo-state-tags-triggers'."
11919 (let ((l org-todo-state-tags-triggers)
11920 changes)
11921 (when (or (not state) (equal state ""))
11922 (setq changes (append changes (cdr (assoc "" l)))))
11923 (when (and (stringp state) (> (length state) 0))
11924 (setq changes (append changes (cdr (assoc state l)))))
11925 (when (member state org-not-done-keywords)
11926 (setq changes (append changes (cdr (assoc 'todo l)))))
11927 (when (member state org-done-keywords)
11928 (setq changes (append changes (cdr (assoc 'done l)))))
11929 (dolist (c changes)
11930 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11932 (defun org-local-logging (value)
11933 "Get logging settings from a property VALUE."
11934 (let* (words w a)
11935 ;; directly set the variables, they are already local.
11936 (setq org-log-done nil
11937 org-log-repeat nil
11938 org-todo-log-states nil)
11939 (setq words (org-split-string value))
11940 (while (setq w (pop words))
11941 (cond
11942 ((setq a (assoc w org-startup-options))
11943 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11944 (set (nth 1 a) (nth 2 a))))
11945 ((setq a (org-extract-log-state-settings w))
11946 (and (member (car a) org-todo-keywords-1)
11947 (push a org-todo-log-states)))))))
11949 (defun org-get-todo-sequence-head (kwd)
11950 "Return the head of the TODO sequence to which KWD belongs.
11951 If KWD is not set, check if there is a text property remembering the
11952 right sequence."
11953 (let (p)
11954 (cond
11955 ((not kwd)
11956 (or (get-text-property (point-at-bol) 'org-todo-head)
11957 (progn
11958 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11959 nil (point-at-eol)))
11960 (get-text-property p 'org-todo-head))))
11961 ((not (member kwd org-todo-keywords-1))
11962 (car org-todo-keywords-1))
11963 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11965 (defun org-fast-todo-selection ()
11966 "Fast TODO keyword selection with single keys.
11967 Returns the new TODO keyword, or nil if no state change should occur."
11968 (let* ((fulltable org-todo-key-alist)
11969 (done-keywords org-done-keywords) ;; needed for the faces.
11970 (maxlen (apply 'max (mapcar
11971 (lambda (x)
11972 (if (stringp (car x)) (string-width (car x)) 0))
11973 fulltable)))
11974 (expert nil)
11975 (fwidth (+ maxlen 3 1 3))
11976 (ncol (/ (- (window-width) 4) fwidth))
11977 tg cnt e c tbl
11978 groups ingroup)
11979 (save-excursion
11980 (save-window-excursion
11981 (if expert
11982 (set-buffer (get-buffer-create " *Org todo*"))
11983 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11984 (erase-buffer)
11985 (org-set-local 'org-done-keywords done-keywords)
11986 (setq tbl fulltable cnt 0)
11987 (while (setq e (pop tbl))
11988 (cond
11989 ((equal e '(:startgroup))
11990 (push '() groups) (setq ingroup t)
11991 (when (not (= cnt 0))
11992 (setq cnt 0)
11993 (insert "\n"))
11994 (insert "{ "))
11995 ((equal e '(:endgroup))
11996 (setq ingroup nil cnt 0)
11997 (insert "}\n"))
11998 ((equal e '(:newline))
11999 (when (not (= cnt 0))
12000 (setq cnt 0)
12001 (insert "\n")
12002 (setq e (car tbl))
12003 (while (equal (car tbl) '(:newline))
12004 (insert "\n")
12005 (setq tbl (cdr tbl)))))
12007 (setq tg (car e) c (cdr e))
12008 (if ingroup (push tg (car groups)))
12009 (setq tg (org-add-props tg nil 'face
12010 (org-get-todo-face tg)))
12011 (if (and (= cnt 0) (not ingroup)) (insert " "))
12012 (insert "[" c "] " tg (make-string
12013 (- fwidth 4 (length tg)) ?\ ))
12014 (when (= (setq cnt (1+ cnt)) ncol)
12015 (insert "\n")
12016 (if ingroup (insert " "))
12017 (setq cnt 0)))))
12018 (insert "\n")
12019 (goto-char (point-min))
12020 (if (not expert) (org-fit-window-to-buffer))
12021 (message "[a-z..]:Set [SPC]:clear")
12022 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12023 (cond
12024 ((or (= c ?\C-g)
12025 (and (= c ?q) (not (rassoc c fulltable))))
12026 (setq quit-flag t))
12027 ((= c ?\ ) nil)
12028 ((setq e (rassoc c fulltable) tg (car e))
12030 (t (setq quit-flag t)))))))
12032 (defun org-entry-is-todo-p ()
12033 (member (org-get-todo-state) org-not-done-keywords))
12035 (defun org-entry-is-done-p ()
12036 (member (org-get-todo-state) org-done-keywords))
12038 (defun org-get-todo-state ()
12039 (save-excursion
12040 (org-back-to-heading t)
12041 (and (looking-at org-todo-line-regexp)
12042 (match-end 2)
12043 (match-string 2))))
12045 (defun org-at-date-range-p (&optional inactive-ok)
12046 "Is the cursor inside a date range?"
12047 (interactive)
12048 (save-excursion
12049 (catch 'exit
12050 (let ((pos (point)))
12051 (skip-chars-backward "^[<\r\n")
12052 (skip-chars-backward "<[")
12053 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12054 (>= (match-end 0) pos)
12055 (throw 'exit t))
12056 (skip-chars-backward "^<[\r\n")
12057 (skip-chars-backward "<[")
12058 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12059 (>= (match-end 0) pos)
12060 (throw 'exit t)))
12061 nil)))
12063 (defun org-get-repeat (&optional tagline)
12064 "Check if there is a deadline/schedule with repeater in this entry."
12065 (save-match-data
12066 (save-excursion
12067 (org-back-to-heading t)
12068 (and (re-search-forward (if tagline
12069 (concat tagline "\\s-*" org-repeat-re)
12070 org-repeat-re)
12071 (org-entry-end-position) t)
12072 (match-string-no-properties 1)))))
12074 (defvar org-last-changed-timestamp)
12075 (defvar org-last-inserted-timestamp)
12076 (defvar org-log-post-message)
12077 (defvar org-log-note-purpose)
12078 (defvar org-log-note-how)
12079 (defvar org-log-note-extra)
12080 (defun org-auto-repeat-maybe (done-word)
12081 "Check if the current headline contains a repeated deadline/schedule.
12082 If yes, set TODO state back to what it was and change the base date
12083 of repeating deadline/scheduled time stamps to new date.
12084 This function is run automatically after each state change to a DONE state."
12085 ;; last-state is dynamically scoped into this function
12086 (let* ((repeat (org-get-repeat))
12087 (aa (assoc org-last-state org-todo-kwd-alist))
12088 (interpret (nth 1 aa))
12089 (head (nth 2 aa))
12090 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12091 (msg "Entry repeats: ")
12092 (org-log-done nil)
12093 (org-todo-log-states nil)
12094 re type n what ts time to-state)
12095 (when repeat
12096 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12097 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12098 org-todo-repeat-to-state))
12099 (unless (and to-state (member to-state org-todo-keywords-1))
12100 (setq to-state (if (eq interpret 'type) org-last-state head)))
12101 (org-todo to-state)
12102 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12103 (org-entry-put nil "LAST_REPEAT" (format-time-string
12104 (org-time-stamp-format t t))))
12105 (when org-log-repeat
12106 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12107 (memq 'org-add-log-note post-command-hook))
12108 ;; OK, we are already setup for some record
12109 (if (eq org-log-repeat 'note)
12110 ;; make sure we take a note, not only a time stamp
12111 (setq org-log-note-how 'note))
12112 ;; Set up for taking a record
12113 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12114 org-last-state
12115 'findpos org-log-repeat)))
12116 (org-back-to-heading t)
12117 (org-add-planning-info nil nil 'closed)
12118 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12119 org-deadline-time-regexp "\\)\\|\\("
12120 org-ts-regexp "\\)"))
12121 (while (re-search-forward
12122 re (save-excursion (outline-next-heading) (point)) t)
12123 (setq type (if (match-end 1) org-scheduled-string
12124 (if (match-end 3) org-deadline-string "Plain:"))
12125 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12126 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12127 (setq n (string-to-number (match-string 2 ts))
12128 what (match-string 3 ts))
12129 (if (equal what "w") (setq n (* n 7) what "d"))
12130 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12131 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12132 ;; Preparation, see if we need to modify the start date for the change
12133 (when (match-end 1)
12134 (setq time (save-match-data (org-time-string-to-time ts)))
12135 (cond
12136 ((equal (match-string 1 ts) ".")
12137 ;; Shift starting date to today
12138 (org-timestamp-change
12139 (- (org-today) (time-to-days time))
12140 'day))
12141 ((equal (match-string 1 ts) "+")
12142 (let ((nshiftmax 10) (nshift 0))
12143 (while (or (= nshift 0)
12144 (<= (time-to-days time)
12145 (time-to-days (current-time))))
12146 (when (= (incf nshift) nshiftmax)
12147 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12148 (error "Abort")))
12149 (org-timestamp-change n (cdr (assoc what whata)))
12150 (org-at-timestamp-p t)
12151 (setq ts (match-string 1))
12152 (setq time (save-match-data (org-time-string-to-time ts)))))
12153 (org-timestamp-change (- n) (cdr (assoc what whata)))
12154 ;; rematch, so that we have everything in place for the real shift
12155 (org-at-timestamp-p t)
12156 (setq ts (match-string 1))
12157 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12158 (org-timestamp-change n (cdr (assoc what whata)))
12159 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12160 (setq org-log-post-message msg)
12161 (message "%s" msg))))
12163 (defun org-show-todo-tree (arg)
12164 "Make a compact tree which shows all headlines marked with TODO.
12165 The tree will show the lines where the regexp matches, and all higher
12166 headlines above the match.
12167 With a \\[universal-argument] prefix, prompt for a regexp to match.
12168 With a numeric prefix N, construct a sparse tree for the Nth element
12169 of `org-todo-keywords-1'."
12170 (interactive "P")
12171 (let ((case-fold-search nil)
12172 (kwd-re
12173 (cond ((null arg) org-not-done-regexp)
12174 ((equal arg '(4))
12175 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12176 (mapcar 'list org-todo-keywords-1))))
12177 (concat "\\("
12178 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12179 "\\)\\>")))
12180 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12181 (regexp-quote (nth (1- (prefix-numeric-value arg))
12182 org-todo-keywords-1)))
12183 (t (error "Invalid prefix argument: %s" arg)))))
12184 (message "%d TODO entries found"
12185 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12187 (defun org-deadline (&optional remove time)
12188 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12189 With argument REMOVE, remove any deadline from the item.
12190 With argument TIME, set the deadline at the corresponding date. TIME
12191 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12192 (interactive "P")
12193 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12194 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12195 'region-start-level 'region))
12196 org-loop-over-headlines-in-active-region)
12197 (org-map-entries
12198 `(org-deadline ',remove ,time)
12199 org-loop-over-headlines-in-active-region
12200 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12201 (let* ((old-date (org-entry-get nil "DEADLINE"))
12202 (repeater (and old-date
12203 (string-match
12204 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12205 old-date)
12206 (match-string 1 old-date))))
12207 (if remove
12208 (progn
12209 (when (and old-date org-log-redeadline)
12210 (org-add-log-setup 'deldeadline nil old-date 'findpos
12211 org-log-redeadline))
12212 (org-remove-timestamp-with-keyword org-deadline-string)
12213 (message "Item no longer has a deadline."))
12214 (org-add-planning-info 'deadline time 'closed)
12215 (when (and old-date org-log-redeadline
12216 (not (equal old-date
12217 (substring org-last-inserted-timestamp 1 -1))))
12218 (org-add-log-setup 'redeadline nil old-date 'findpos
12219 org-log-redeadline))
12220 (when repeater
12221 (save-excursion
12222 (org-back-to-heading t)
12223 (when (re-search-forward (concat org-deadline-string " "
12224 org-last-inserted-timestamp)
12225 (save-excursion
12226 (outline-next-heading) (point)) t)
12227 (goto-char (1- (match-end 0)))
12228 (insert " " repeater)
12229 (setq org-last-inserted-timestamp
12230 (concat (substring org-last-inserted-timestamp 0 -1)
12231 " " repeater
12232 (substring org-last-inserted-timestamp -1))))))
12233 (message "Deadline on %s" org-last-inserted-timestamp)))))
12235 (defun org-schedule (&optional remove time)
12236 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12237 With argument REMOVE, remove any scheduling date from the item.
12238 With argument TIME, scheduled at the corresponding date. TIME can
12239 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12240 (interactive "P")
12241 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12242 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12243 'region-start-level 'region))
12244 org-loop-over-headlines-in-active-region)
12245 (org-map-entries
12246 `(org-schedule ',remove ,time)
12247 org-loop-over-headlines-in-active-region
12248 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12249 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12250 (repeater (and old-date
12251 (string-match
12252 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12253 old-date)
12254 (match-string 1 old-date))))
12255 (if remove
12256 (progn
12257 (when (and old-date org-log-reschedule)
12258 (org-add-log-setup 'delschedule nil old-date 'findpos
12259 org-log-reschedule))
12260 (org-remove-timestamp-with-keyword org-scheduled-string)
12261 (message "Item is no longer scheduled."))
12262 (org-add-planning-info 'scheduled time 'closed)
12263 (when (and old-date org-log-reschedule
12264 (not (equal old-date
12265 (substring org-last-inserted-timestamp 1 -1))))
12266 (org-add-log-setup 'reschedule nil old-date 'findpos
12267 org-log-reschedule))
12268 (when repeater
12269 (save-excursion
12270 (org-back-to-heading t)
12271 (when (re-search-forward (concat org-scheduled-string " "
12272 org-last-inserted-timestamp)
12273 (save-excursion
12274 (outline-next-heading) (point)) t)
12275 (goto-char (1- (match-end 0)))
12276 (insert " " repeater)
12277 (setq org-last-inserted-timestamp
12278 (concat (substring org-last-inserted-timestamp 0 -1)
12279 " " repeater
12280 (substring org-last-inserted-timestamp -1))))))
12281 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12283 (defun org-get-scheduled-time (pom &optional inherit)
12284 "Get the scheduled time as a time tuple, of a format suitable
12285 for calling org-schedule with, or if there is no scheduling,
12286 returns nil."
12287 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12288 (when time
12289 (apply 'encode-time (org-parse-time-string time)))))
12291 (defun org-get-deadline-time (pom &optional inherit)
12292 "Get the deadline as a time tuple, of a format suitable for
12293 calling org-deadline with, or if there is no scheduling, returns
12294 nil."
12295 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12296 (when time
12297 (apply 'encode-time (org-parse-time-string time)))))
12299 (defun org-remove-timestamp-with-keyword (keyword)
12300 "Remove all time stamps with KEYWORD in the current entry."
12301 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12302 beg)
12303 (save-excursion
12304 (org-back-to-heading t)
12305 (setq beg (point))
12306 (outline-next-heading)
12307 (while (re-search-backward re beg t)
12308 (replace-match "")
12309 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12310 (equal (char-before) ?\ ))
12311 (backward-delete-char 1)
12312 (if (string-match "^[ \t]*$" (buffer-substring
12313 (point-at-bol) (point-at-eol)))
12314 (delete-region (point-at-bol)
12315 (min (point-max) (1+ (point-at-eol))))))))))
12317 (defun org-add-planning-info (what &optional time &rest remove)
12318 "Insert new timestamp with keyword in the line directly after the headline.
12319 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12320 If non is given, the user is prompted for a date.
12321 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12322 be removed."
12323 (interactive)
12324 (let (org-time-was-given org-end-time-was-given ts
12325 end default-time default-input)
12327 (catch 'exit
12328 (when (and (memq what '(scheduled deadline))
12329 (or (not time)
12330 (and (stringp time)
12331 (string-match "^[-+]+[0-9]" time))))
12332 ;; Try to get a default date/time from existing timestamp
12333 (save-excursion
12334 (org-back-to-heading t)
12335 (setq end (save-excursion (outline-next-heading) (point)))
12336 (when (re-search-forward (if (eq what 'scheduled)
12337 org-scheduled-time-regexp
12338 org-deadline-time-regexp)
12339 end t)
12340 (setq ts (match-string 1)
12341 default-time
12342 (apply 'encode-time (org-parse-time-string ts))
12343 default-input (and ts (org-get-compact-tod ts))))))
12344 (when what
12345 (setq time
12346 (if (stringp time)
12347 ;; This is a string (relative or absolute), set proper date
12348 (apply 'encode-time
12349 (org-read-date-analyze
12350 time default-time (decode-time default-time)))
12351 ;; If necessary, get the time from the user
12352 (or time (org-read-date nil 'to-time nil nil
12353 default-time default-input)))))
12355 (when (and org-insert-labeled-timestamps-at-point
12356 (member what '(scheduled deadline)))
12357 (insert
12358 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12359 (org-insert-time-stamp time org-time-was-given
12360 nil nil nil (list org-end-time-was-given))
12361 (setq what nil))
12362 (save-excursion
12363 (save-restriction
12364 (let (col list elt ts buffer-invisibility-spec)
12365 (org-back-to-heading t)
12366 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12367 (goto-char (match-end 1))
12368 (setq col (current-column))
12369 (goto-char (match-end 0))
12370 (if (eobp) (insert "\n") (forward-char 1))
12371 (when (and (not what)
12372 (not (looking-at
12373 (concat "[ \t]*"
12374 org-keyword-time-not-clock-regexp))))
12375 ;; Nothing to add, nothing to remove...... :-)
12376 (throw 'exit nil))
12377 (if (and (not (looking-at org-outline-regexp))
12378 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12379 "[^\r\n]*"))
12380 (not (equal (match-string 1) org-clock-string)))
12381 (narrow-to-region (match-beginning 0) (match-end 0))
12382 (insert-before-markers "\n")
12383 (backward-char 1)
12384 (narrow-to-region (point) (point))
12385 (and org-adapt-indentation (org-indent-to-column col)))
12386 ;; Check if we have to remove something.
12387 (setq list (cons what remove))
12388 (while list
12389 (setq elt (pop list))
12390 (when (or (and (eq elt 'scheduled)
12391 (re-search-forward org-scheduled-time-regexp nil t))
12392 (and (eq elt 'deadline)
12393 (re-search-forward org-deadline-time-regexp nil t))
12394 (and (eq elt 'closed)
12395 (re-search-forward org-closed-time-regexp nil t)))
12396 (replace-match "")
12397 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12398 (and (looking-at "[ \t]+") (replace-match ""))
12399 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12400 (when what
12401 (insert
12402 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12403 (cond ((eq what 'scheduled) org-scheduled-string)
12404 ((eq what 'deadline) org-deadline-string)
12405 ((eq what 'closed) org-closed-string))
12406 " ")
12407 (setq ts (org-insert-time-stamp
12408 time
12409 (or org-time-was-given
12410 (and (eq what 'closed) org-log-done-with-time))
12411 (eq what 'closed)
12412 nil nil (list org-end-time-was-given)))
12413 (insert
12414 (if (not (or (bolp) (eq (char-before) ?\ )
12415 (memq (char-after) '(32 10))
12416 (eobp))) " " ""))
12417 (end-of-line 1))
12418 (goto-char (point-min))
12419 (widen)
12420 (if (and (looking-at "[ \t]*\n")
12421 (equal (char-before) ?\n))
12422 (delete-region (1- (point)) (point-at-eol)))
12423 ts))))))
12425 (defvar org-log-note-marker (make-marker))
12426 (defvar org-log-note-purpose nil)
12427 (defvar org-log-note-state nil)
12428 (defvar org-log-note-previous-state nil)
12429 (defvar org-log-note-how nil)
12430 (defvar org-log-note-extra nil)
12431 (defvar org-log-note-window-configuration nil)
12432 (defvar org-log-note-return-to (make-marker))
12433 (defvar org-log-note-effective-time nil
12434 "Remembered current time so that dynamically scoped
12435 `org-extend-today-until' affects tha timestamps in state change
12436 log")
12438 (defvar org-log-post-message nil
12439 "Message to be displayed after a log note has been stored.
12440 The auto-repeater uses this.")
12442 (defun org-add-note ()
12443 "Add a note to the current entry.
12444 This is done in the same way as adding a state change note."
12445 (interactive)
12446 (org-add-log-setup 'note nil nil 'findpos nil))
12448 (defvar org-property-end-re)
12449 (defun org-add-log-setup (&optional purpose state prev-state
12450 findpos how extra)
12451 "Set up the post command hook to take a note.
12452 If this is about to TODO state change, the new state is expected in STATE.
12453 When FINDPOS is non-nil, find the correct position for the note in
12454 the current entry. If not, assume that it can be inserted at point.
12455 HOW is an indicator what kind of note should be created.
12456 EXTRA is additional text that will be inserted into the notes buffer."
12457 (let* ((org-log-into-drawer (org-log-into-drawer))
12458 (drawer (cond ((stringp org-log-into-drawer)
12459 org-log-into-drawer)
12460 (org-log-into-drawer "LOGBOOK"))))
12461 (save-restriction
12462 (save-excursion
12463 (when findpos
12464 (org-back-to-heading t)
12465 (narrow-to-region (point) (save-excursion
12466 (outline-next-heading) (point)))
12467 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12468 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12469 "[^\r\n]*\\)?"))
12470 (goto-char (match-end 0))
12471 (cond
12472 (drawer
12473 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12474 nil t)
12475 (progn
12476 (goto-char (match-end 0))
12477 (or org-log-states-order-reversed
12478 (and (re-search-forward org-property-end-re nil t)
12479 (goto-char (1- (match-beginning 0))))))
12480 (insert "\n:" drawer ":\n:END:")
12481 (beginning-of-line 0)
12482 (org-indent-line)
12483 (beginning-of-line 2)
12484 (org-indent-line)
12485 (end-of-line 0)))
12486 ((and org-log-state-notes-insert-after-drawers
12487 (save-excursion
12488 (forward-line) (looking-at org-drawer-regexp)))
12489 (forward-line)
12490 (while (looking-at org-drawer-regexp)
12491 (goto-char (match-end 0))
12492 (re-search-forward org-property-end-re (point-max) t)
12493 (forward-line))
12494 (forward-line -1)))
12495 (unless org-log-states-order-reversed
12496 (and (= (char-after) ?\n) (forward-char 1))
12497 (org-skip-over-state-notes)
12498 (skip-chars-backward " \t\n\r")))
12499 (move-marker org-log-note-marker (point))
12500 (setq org-log-note-purpose purpose
12501 org-log-note-state state
12502 org-log-note-previous-state prev-state
12503 org-log-note-how how
12504 org-log-note-extra extra
12505 org-log-note-effective-time (org-current-effective-time))
12506 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12508 (defun org-skip-over-state-notes ()
12509 "Skip past the list of State notes in an entry."
12510 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12511 (when (ignore-errors (goto-char (org-in-item-p)))
12512 (let* ((struct (org-list-struct))
12513 (prevs (org-list-prevs-alist struct)))
12514 (while (looking-at "[ \t]*- State")
12515 (goto-char (or (org-list-get-next-item (point) struct prevs)
12516 (org-list-get-item-end (point) struct)))))))
12518 (defun org-add-log-note (&optional purpose)
12519 "Pop up a window for taking a note, and add this note later at point."
12520 (remove-hook 'post-command-hook 'org-add-log-note)
12521 (setq org-log-note-window-configuration (current-window-configuration))
12522 (delete-other-windows)
12523 (move-marker org-log-note-return-to (point))
12524 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12525 (goto-char org-log-note-marker)
12526 (org-switch-to-buffer-other-window "*Org Note*")
12527 (erase-buffer)
12528 (if (memq org-log-note-how '(time state))
12529 (let (current-prefix-arg) (org-store-log-note))
12530 (let ((org-inhibit-startup t)) (org-mode))
12531 (insert (format "# Insert note for %s.
12532 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12533 (cond
12534 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12535 ((eq org-log-note-purpose 'done) "closed todo item")
12536 ((eq org-log-note-purpose 'state)
12537 (format "state change from \"%s\" to \"%s\""
12538 (or org-log-note-previous-state "")
12539 (or org-log-note-state "")))
12540 ((eq org-log-note-purpose 'reschedule)
12541 "rescheduling")
12542 ((eq org-log-note-purpose 'delschedule)
12543 "no longer scheduled")
12544 ((eq org-log-note-purpose 'redeadline)
12545 "changing deadline")
12546 ((eq org-log-note-purpose 'deldeadline)
12547 "removing deadline")
12548 ((eq org-log-note-purpose 'refile)
12549 "refiling")
12550 ((eq org-log-note-purpose 'note)
12551 "this entry")
12552 (t (error "This should not happen")))))
12553 (if org-log-note-extra (insert org-log-note-extra))
12554 (org-set-local 'org-finish-function 'org-store-log-note)
12555 (run-hooks 'org-log-buffer-setup-hook)))
12557 (defvar org-note-abort nil) ; dynamically scoped
12558 (defun org-store-log-note ()
12559 "Finish taking a log note, and insert it to where it belongs."
12560 (let ((txt (buffer-string))
12561 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12562 lines ind bul)
12563 (kill-buffer (current-buffer))
12564 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12565 (setq txt (replace-match "" t t txt)))
12566 (if (string-match "\\s-+\\'" txt)
12567 (setq txt (replace-match "" t t txt)))
12568 (setq lines (org-split-string txt "\n"))
12569 (when (and note (string-match "\\S-" note))
12570 (setq note
12571 (org-replace-escapes
12572 note
12573 (list (cons "%u" (user-login-name))
12574 (cons "%U" user-full-name)
12575 (cons "%t" (format-time-string
12576 (org-time-stamp-format 'long 'inactive)
12577 org-log-note-effective-time))
12578 (cons "%T" (format-time-string
12579 (org-time-stamp-format 'long nil)
12580 org-log-note-effective-time))
12581 (cons "%d" (format-time-string
12582 (org-time-stamp-format nil 'inactive)
12583 org-log-note-effective-time))
12584 (cons "%D" (format-time-string
12585 (org-time-stamp-format nil nil)
12586 org-log-note-effective-time))
12587 (cons "%s" (if org-log-note-state
12588 (concat "\"" org-log-note-state "\"")
12589 ""))
12590 (cons "%S" (if org-log-note-previous-state
12591 (concat "\"" org-log-note-previous-state "\"")
12592 "\"\"")))))
12593 (if lines (setq note (concat note " \\\\")))
12594 (push note lines))
12595 (when (or current-prefix-arg org-note-abort)
12596 (when org-log-into-drawer
12597 (org-remove-empty-drawer-at
12598 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12599 org-log-note-marker))
12600 (setq lines nil))
12601 (when lines
12602 (with-current-buffer (marker-buffer org-log-note-marker)
12603 (save-excursion
12604 (goto-char org-log-note-marker)
12605 (move-marker org-log-note-marker nil)
12606 (end-of-line 1)
12607 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12608 (setq ind (save-excursion
12609 (if (ignore-errors (goto-char (org-in-item-p)))
12610 (let ((struct (org-list-struct)))
12611 (org-list-get-ind
12612 (org-list-get-top-point struct) struct))
12613 (skip-chars-backward " \r\t\n")
12614 (cond
12615 ((and (org-at-heading-p)
12616 org-adapt-indentation)
12617 (1+ (org-current-level)))
12618 ((org-at-heading-p) 0)
12619 (t (org-get-indentation))))))
12620 (setq bul (org-list-bullet-string "-"))
12621 (org-indent-line-to ind)
12622 (insert bul (pop lines))
12623 (let ((ind-body (+ (length bul) ind)))
12624 (while lines
12625 (insert "\n")
12626 (org-indent-line-to ind-body)
12627 (insert (pop lines))))
12628 (message "Note stored")
12629 (org-back-to-heading t)
12630 (org-cycle-hide-drawers 'children)))))
12631 (set-window-configuration org-log-note-window-configuration)
12632 (with-current-buffer (marker-buffer org-log-note-return-to)
12633 (goto-char org-log-note-return-to))
12634 (move-marker org-log-note-return-to nil)
12635 (and org-log-post-message (message "%s" org-log-post-message)))
12637 (defun org-remove-empty-drawer-at (drawer pos)
12638 "Remove an empty drawer DRAWER at position POS.
12639 POS may also be a marker."
12640 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12641 (save-excursion
12642 (save-restriction
12643 (widen)
12644 (goto-char pos)
12645 (if (org-in-regexp
12646 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12647 (replace-match ""))))))
12649 (defvar org-ts-type nil)
12650 (defun org-sparse-tree (&optional arg type)
12651 "Create a sparse tree, prompt for the details.
12652 This command can create sparse trees. You first need to select the type
12653 of match used to create the tree:
12655 t Show all TODO entries.
12656 T Show entries with a specific TODO keyword.
12657 m Show entries selected by a tags/property match.
12658 p Enter a property name and its value (both with completion on existing
12659 names/values) and show entries with that property.
12660 r Show entries matching a regular expression (`/' can be used as well).
12661 b Show deadlines and scheduled items before a date.
12662 a Show deadlines and scheduled items after a date.
12663 d Show deadlines due within `org-deadline-warning-days'.
12664 D Show deadlines and scheduled items between a date range."
12665 (interactive "P")
12666 (let (ans kwd value ts-type)
12667 (setq type (or type org-sparse-tree-default-date-type))
12668 (setq org-ts-type type)
12669 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12670 (cond ((eq type 'all) "all timestamps")
12671 ((eq type 'scheduled) "only scheduled")
12672 ((eq type 'deadline) "only deadline")
12673 ((eq type 'active) "only active timestamps")
12674 ((eq type 'inactive) "only inactive timestamps")
12675 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12676 (t "scheduled/deadline")))
12677 (setq ans (read-char-exclusive))
12678 (cond
12679 ((equal ans ?c)
12680 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12681 ((equal ans ?d)
12682 (call-interactively 'org-check-deadlines))
12683 ((equal ans ?b)
12684 (call-interactively 'org-check-before-date))
12685 ((equal ans ?a)
12686 (call-interactively 'org-check-after-date))
12687 ((equal ans ?D)
12688 (call-interactively 'org-check-dates-range))
12689 ((equal ans ?t)
12690 (call-interactively 'org-show-todo-tree))
12691 ((equal ans ?T)
12692 (org-show-todo-tree '(4)))
12693 ((member ans '(?T ?m))
12694 (call-interactively 'org-match-sparse-tree))
12695 ((member ans '(?p ?P))
12696 (setq kwd (org-icompleting-read "Property: "
12697 (mapcar 'list (org-buffer-property-keys))))
12698 (setq value (org-icompleting-read "Value: "
12699 (mapcar 'list (org-property-values kwd))))
12700 (unless (string-match "\\`{.*}\\'" value)
12701 (setq value (concat "\"" value "\"")))
12702 (org-match-sparse-tree arg (concat kwd "=" value)))
12703 ((member ans '(?r ?R ?/))
12704 (call-interactively 'org-occur))
12705 (t (error "No such sparse tree command \"%c\"" ans)))))
12707 (defvar org-occur-highlights nil
12708 "List of overlays used for occur matches.")
12709 (make-variable-buffer-local 'org-occur-highlights)
12710 (defvar org-occur-parameters nil
12711 "Parameters of the active org-occur calls.
12712 This is a list, each call to org-occur pushes as cons cell,
12713 containing the regular expression and the callback, onto the list.
12714 The list can contain several entries if `org-occur' has been called
12715 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12716 will only contain one set of parameters. When the highlights are
12717 removed (for example with `C-c C-c', or with the next edit (depending
12718 on `org-remove-highlights-with-change'), this variable is emptied
12719 as well.")
12720 (make-variable-buffer-local 'org-occur-parameters)
12722 (defun org-occur (regexp &optional keep-previous callback)
12723 "Make a compact tree which shows all matches of REGEXP.
12724 The tree will show the lines where the regexp matches, and all higher
12725 headlines above the match. It will also show the heading after the match,
12726 to make sure editing the matching entry is easy.
12727 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12728 call to `org-occur' will be kept, to allow stacking of calls to this
12729 command.
12730 If CALLBACK is non-nil, it is a function which is called to confirm
12731 that the match should indeed be shown."
12732 (interactive "sRegexp: \nP")
12733 (when (equal regexp "")
12734 (error "Regexp cannot be empty"))
12735 (unless keep-previous
12736 (org-remove-occur-highlights nil nil t))
12737 (push (cons regexp callback) org-occur-parameters)
12738 (let ((cnt 0))
12739 (save-excursion
12740 (goto-char (point-min))
12741 (if (or (not keep-previous) ; do not want to keep
12742 (not org-occur-highlights)) ; no previous matches
12743 ;; hide everything
12744 (org-overview))
12745 (while (re-search-forward regexp nil t)
12746 (when (or (not callback)
12747 (save-match-data (funcall callback)))
12748 (setq cnt (1+ cnt))
12749 (when org-highlight-sparse-tree-matches
12750 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12751 (org-show-context 'occur-tree))))
12752 (when org-remove-highlights-with-change
12753 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12754 nil 'local))
12755 (unless org-sparse-tree-open-archived-trees
12756 (org-hide-archived-subtrees (point-min) (point-max)))
12757 (run-hooks 'org-occur-hook)
12758 (if (org-called-interactively-p 'interactive)
12759 (message "%d match(es) for regexp %s" cnt regexp))
12760 cnt))
12762 (defun org-occur-next-match (&optional n reset)
12763 "Function for `next-error-function' to find sparse tree matches.
12764 N is the number of matches to move, when negative move backwards.
12765 RESET is entirely ignored - this function always goes back to the
12766 starting point when no match is found."
12767 (let* ((limit (if (< n 0) (point-min) (point-max)))
12768 (search-func (if (< n 0)
12769 'previous-single-char-property-change
12770 'next-single-char-property-change))
12771 (n (abs n))
12772 (pos (point))
12774 (catch 'exit
12775 (while (setq p1 (funcall search-func (point) 'org-type))
12776 (when (equal p1 limit)
12777 (goto-char pos)
12778 (error "No more matches"))
12779 (when (equal (get-char-property p1 'org-type) 'org-occur)
12780 (setq n (1- n))
12781 (when (= n 0)
12782 (goto-char p1)
12783 (throw 'exit (point))))
12784 (goto-char p1))
12785 (goto-char p1)
12786 (error "No more matches"))))
12788 (defun org-show-context (&optional key)
12789 "Make sure point and context are visible.
12790 How much context is shown depends upon the variables
12791 `org-show-hierarchy-above', `org-show-following-heading',
12792 `org-show-entry-below' and `org-show-siblings'."
12793 (let ((heading-p (org-at-heading-p t))
12794 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12795 (following-p (org-get-alist-option org-show-following-heading key))
12796 (entry-p (org-get-alist-option org-show-entry-below key))
12797 (siblings-p (org-get-alist-option org-show-siblings key)))
12798 (catch 'exit
12799 ;; Show heading or entry text
12800 (if (and heading-p (not entry-p))
12801 (org-flag-heading nil) ; only show the heading
12802 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12803 (org-show-hidden-entry))) ; show entire entry
12804 (when following-p
12805 ;; Show next sibling, or heading below text
12806 (save-excursion
12807 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12808 (org-flag-heading nil))))
12809 (when siblings-p (org-show-siblings))
12810 (when hierarchy-p
12811 ;; show all higher headings, possibly with siblings
12812 (save-excursion
12813 (while (and (condition-case nil
12814 (progn (org-up-heading-all 1) t)
12815 (error nil))
12816 (not (bobp)))
12817 (org-flag-heading nil)
12818 (when siblings-p (org-show-siblings))))))))
12820 (defvar org-reveal-start-hook nil
12821 "Hook run before revealing a location.")
12823 (defun org-reveal (&optional siblings)
12824 "Show current entry, hierarchy above it, and the following headline.
12825 This can be used to show a consistent set of context around locations
12826 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12827 not t for the search context.
12829 With optional argument SIBLINGS, on each level of the hierarchy all
12830 siblings are shown. This repairs the tree structure to what it would
12831 look like when opened with hierarchical calls to `org-cycle'.
12832 With double optional argument \\[universal-argument] \\[universal-argument], \
12833 go to the parent and show the
12834 entire tree."
12835 (interactive "P")
12836 (run-hooks 'org-reveal-start-hook)
12837 (let ((org-show-hierarchy-above t)
12838 (org-show-following-heading t)
12839 (org-show-siblings (if siblings t org-show-siblings)))
12840 (org-show-context nil))
12841 (when (equal siblings '(16))
12842 (save-excursion
12843 (when (org-up-heading-safe)
12844 (org-show-subtree)
12845 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12847 (defun org-highlight-new-match (beg end)
12848 "Highlight from BEG to END and mark the highlight is an occur headline."
12849 (let ((ov (make-overlay beg end)))
12850 (overlay-put ov 'face 'secondary-selection)
12851 (overlay-put ov 'org-type 'org-occur)
12852 (push ov org-occur-highlights)))
12854 (defun org-remove-occur-highlights (&optional beg end noremove)
12855 "Remove the occur highlights from the buffer.
12856 BEG and END are ignored. If NOREMOVE is nil, remove this function
12857 from the `before-change-functions' in the current buffer."
12858 (interactive)
12859 (unless org-inhibit-highlight-removal
12860 (mapc 'delete-overlay org-occur-highlights)
12861 (setq org-occur-highlights nil)
12862 (setq org-occur-parameters nil)
12863 (unless noremove
12864 (remove-hook 'before-change-functions
12865 'org-remove-occur-highlights 'local))))
12867 ;;;; Priorities
12869 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12870 "Regular expression matching the priority indicator.")
12872 (defvar org-remove-priority-next-time nil)
12874 (defun org-priority-up ()
12875 "Increase the priority of the current item."
12876 (interactive)
12877 (org-priority 'up))
12879 (defun org-priority-down ()
12880 "Decrease the priority of the current item."
12881 (interactive)
12882 (org-priority 'down))
12884 (defun org-priority (&optional action show)
12885 "Change the priority of an item.
12886 ACTION can be `set', `up', `down', or a character."
12887 (interactive "P")
12888 (if (equal action '(4))
12889 (org-show-priority)
12890 (unless org-enable-priority-commands
12891 (error "Priority commands are disabled"))
12892 (setq action (or action 'set))
12893 (let (current new news have remove)
12894 (save-excursion
12895 (org-back-to-heading t)
12896 (if (looking-at org-priority-regexp)
12897 (setq current (string-to-char (match-string 2))
12898 have t))
12899 (cond
12900 ((eq action 'remove)
12901 (setq remove t new ?\ ))
12902 ((or (eq action 'set)
12903 (if (featurep 'xemacs) (characterp action) (integerp action)))
12904 (if (not (eq action 'set))
12905 (setq new action)
12906 (message "Priority %c-%c, SPC to remove: "
12907 org-highest-priority org-lowest-priority)
12908 (save-match-data
12909 (setq new (read-char-exclusive))))
12910 (if (and (= (upcase org-highest-priority) org-highest-priority)
12911 (= (upcase org-lowest-priority) org-lowest-priority))
12912 (setq new (upcase new)))
12913 (cond ((equal new ?\ ) (setq remove t))
12914 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12915 (error "Priority must be between `%c' and `%c'"
12916 org-highest-priority org-lowest-priority))))
12917 ((eq action 'up)
12918 (setq new (if have
12919 (1- current) ; normal cycling
12920 ;; last priority was empty
12921 (if (eq last-command this-command)
12922 org-lowest-priority ; wrap around empty to lowest
12923 ;; default
12924 (if org-priority-start-cycle-with-default
12925 org-default-priority
12926 (1- org-default-priority))))))
12927 ((eq action 'down)
12928 (setq new (if have
12929 (1+ current) ; normal cycling
12930 ;; last priority was empty
12931 (if (eq last-command this-command)
12932 org-highest-priority ; wrap around empty to highest
12933 ;; default
12934 (if org-priority-start-cycle-with-default
12935 org-default-priority
12936 (1+ org-default-priority))))))
12937 (t (error "Invalid action")))
12938 (if (or (< (upcase new) org-highest-priority)
12939 (> (upcase new) org-lowest-priority))
12940 (if (and (memq action '(up down))
12941 (not have) (not (eq last-command this-command)))
12942 ;; `new' is from default priority
12943 (error
12944 "The default can not be set, see `org-default-priority' why")
12945 ;; normal cycling: `new' is beyond highest/lowest priority
12946 ;; and is wrapped around to the empty priority
12947 (setq remove t)))
12948 (setq news (format "%c" new))
12949 (if have
12950 (if remove
12951 (replace-match "" t t nil 1)
12952 (replace-match news t t nil 2))
12953 (if remove
12954 (error "No priority cookie found in line")
12955 (let ((case-fold-search nil))
12956 (looking-at org-todo-line-regexp))
12957 (if (match-end 2)
12958 (progn
12959 (goto-char (match-end 2))
12960 (insert " [#" news "]"))
12961 (goto-char (match-beginning 3))
12962 (insert "[#" news "] "))))
12963 (org-preserve-lc (org-set-tags nil 'align)))
12964 (if remove
12965 (message "Priority removed")
12966 (message "Priority of current item set to %s" news)))))
12968 (defun org-show-priority ()
12969 "Show the priority of the current item.
12970 This priority is composed of the main priority given with the [#A] cookies,
12971 and by additional input from the age of a schedules or deadline entry."
12972 (interactive)
12973 (let ((pri (if (eq major-mode 'org-agenda-mode)
12974 (org-get-at-bol 'priority)
12975 (save-excursion
12976 (save-match-data
12977 (beginning-of-line)
12978 (and (looking-at org-heading-regexp)
12979 (org-get-priority (match-string 0))))))))
12980 (message "Priority is %d" (if pri pri -1000))))
12982 (defun org-get-priority (s)
12983 "Find priority cookie and return priority."
12984 (if (functionp org-get-priority-function)
12985 (funcall org-get-priority-function)
12986 (save-match-data
12987 (if (not (string-match org-priority-regexp s))
12988 (* 1000 (- org-lowest-priority org-default-priority))
12989 (* 1000 (- org-lowest-priority
12990 (string-to-char (match-string 2 s))))))))
12992 ;;;; Tags
12994 (defvar org-agenda-archives-mode)
12995 (defvar org-map-continue-from nil
12996 "Position from where mapping should continue.
12997 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12999 (defvar org-scanner-tags nil
13000 "The current tag list while the tags scanner is running.")
13001 (defvar org-trust-scanner-tags nil
13002 "Should `org-get-tags-at' use the tags for the scanner.
13003 This is for internal dynamical scoping only.
13004 When this is non-nil, the function `org-get-tags-at' will return the value
13005 of `org-scanner-tags' instead of building the list by itself. This
13006 can lead to large speed-ups when the tags scanner is used in a file with
13007 many entries, and when the list of tags is retrieved, for example to
13008 obtain a list of properties. Building the tags list for each entry in such
13009 a file becomes an N^2 operation - but with this variable set, it scales
13010 as N.")
13012 (defun org-scan-tags (action matcher todo-only &optional start-level)
13013 "Scan headline tags with inheritance and produce output ACTION.
13015 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13016 or `agenda' to produce an entry list for an agenda view. It can also be
13017 a Lisp form or a function that should be called at each matched headline, in
13018 this case the return value is a list of all return values from these calls.
13020 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13021 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13022 only lines with a not-done TODO keyword are included in the output.
13023 This should be the same variable that was scoped into
13024 and set by `org-make-tags-matcher' when it constructed MATCHER.
13026 START-LEVEL can be a string with asterisks, reducing the scope to
13027 headlines matching this string."
13028 (require 'org-agenda)
13029 (let* ((re (concat "^"
13030 (if start-level
13031 ;; Get the correct level to match
13032 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13033 org-outline-regexp)
13034 " *\\(\\<\\("
13035 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13036 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13037 (props (list 'face 'default
13038 'done-face 'org-agenda-done
13039 'undone-face 'default
13040 'mouse-face 'highlight
13041 'org-not-done-regexp org-not-done-regexp
13042 'org-todo-regexp org-todo-regexp
13043 'org-complex-heading-regexp org-complex-heading-regexp
13044 'help-echo
13045 (format "mouse-2 or RET jump to org file %s"
13046 (abbreviate-file-name
13047 (or (buffer-file-name (buffer-base-buffer))
13048 (buffer-name (buffer-base-buffer)))))))
13049 (case-fold-search nil)
13050 (org-map-continue-from nil)
13051 lspos tags tags-list
13052 (tags-alist (list (cons 0 org-file-tags)))
13053 (llast 0) rtn rtn1 level category i txt
13054 todo marker entry priority)
13055 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13056 (setq action (list 'lambda nil action)))
13057 (save-excursion
13058 (goto-char (point-min))
13059 (when (eq action 'sparse-tree)
13060 (org-overview)
13061 (org-remove-occur-highlights))
13062 (while (re-search-forward re nil t)
13063 (setq org-map-continue-from nil)
13064 (catch :skip
13065 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13066 tags (if (match-end 4) (org-match-string-no-properties 4)))
13067 (goto-char (setq lspos (match-beginning 0)))
13068 (setq level (org-reduced-level (funcall outline-level))
13069 category (org-get-category))
13070 (setq i llast llast level)
13071 ;; remove tag lists from same and sublevels
13072 (while (>= i level)
13073 (when (setq entry (assoc i tags-alist))
13074 (setq tags-alist (delete entry tags-alist)))
13075 (setq i (1- i)))
13076 ;; add the next tags
13077 (when tags
13078 (setq tags (org-split-string tags ":")
13079 tags-alist
13080 (cons (cons level tags) tags-alist)))
13081 ;; compile tags for current headline
13082 (setq tags-list
13083 (if org-use-tag-inheritance
13084 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13085 tags)
13086 org-scanner-tags tags-list)
13087 (when org-use-tag-inheritance
13088 (setcdr (car tags-alist)
13089 (mapcar (lambda (x)
13090 (setq x (copy-sequence x))
13091 (org-add-prop-inherited x))
13092 (cdar tags-alist))))
13093 (when (and tags org-use-tag-inheritance
13094 (or (not (eq t org-use-tag-inheritance))
13095 org-tags-exclude-from-inheritance))
13096 ;; selective inheritance, remove uninherited ones
13097 (setcdr (car tags-alist)
13098 (org-remove-uninherited-tags (cdar tags-alist))))
13099 (when (and
13101 ;; eval matcher only when the todo condition is OK
13102 (and (or (not todo-only) (member todo org-not-done-keywords))
13103 (let ((case-fold-search t) (org-trust-scanner-tags t))
13104 (eval matcher)))
13106 ;; Call the skipper, but return t if it does not skip,
13107 ;; so that the `and' form continues evaluating
13108 (progn
13109 (unless (eq action 'sparse-tree) (org-agenda-skip))
13112 ;; Check if timestamps are deselecting this entry
13113 (or (not todo-only)
13114 (and (member todo org-not-done-keywords)
13115 (or (not org-agenda-tags-todo-honor-ignore-options)
13116 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13118 ;; Extra check for the archive tag
13119 ;; FIXME: Does the skipper already do this????
13121 (not (member org-archive-tag tags-list))
13122 ;; we have an archive tag, should we use this anyway?
13123 (or (not org-agenda-skip-archived-trees)
13124 (and (eq action 'agenda) org-agenda-archives-mode))))
13126 ;; select this headline
13128 (cond
13129 ((eq action 'sparse-tree)
13130 (and org-highlight-sparse-tree-matches
13131 (org-get-heading) (match-end 0)
13132 (org-highlight-new-match
13133 (match-beginning 1) (match-end 1)))
13134 (org-show-context 'tags-tree))
13135 ((eq action 'agenda)
13136 (setq txt (org-agenda-format-item
13138 (concat
13139 (if (eq org-tags-match-list-sublevels 'indented)
13140 (make-string (1- level) ?.) "")
13141 (org-get-heading))
13142 category
13143 tags-list)
13144 priority (org-get-priority txt))
13145 (goto-char lspos)
13146 (setq marker (org-agenda-new-marker))
13147 (org-add-props txt props
13148 'org-marker marker 'org-hd-marker marker 'org-category category
13149 'todo-state todo
13150 'priority priority 'type "tagsmatch")
13151 (push txt rtn))
13152 ((functionp action)
13153 (setq org-map-continue-from nil)
13154 (save-excursion
13155 (setq rtn1 (funcall action))
13156 (push rtn1 rtn)))
13157 (t (error "Invalid action")))
13159 ;; if we are to skip sublevels, jump to end of subtree
13160 (unless org-tags-match-list-sublevels
13161 (org-end-of-subtree t)
13162 (backward-char 1))))
13163 ;; Get the correct position from where to continue
13164 (if org-map-continue-from
13165 (goto-char org-map-continue-from)
13166 (and (= (point) lspos) (end-of-line 1)))))
13167 (when (and (eq action 'sparse-tree)
13168 (not org-sparse-tree-open-archived-trees))
13169 (org-hide-archived-subtrees (point-min) (point-max)))
13170 (nreverse rtn)))
13172 (defun org-remove-uninherited-tags (tags)
13173 "Remove all tags that are not inherited from the list TAGS."
13174 (cond
13175 ((eq org-use-tag-inheritance t)
13176 (if org-tags-exclude-from-inheritance
13177 (org-delete-all org-tags-exclude-from-inheritance tags)
13178 tags))
13179 ((not org-use-tag-inheritance) nil)
13180 ((stringp org-use-tag-inheritance)
13181 (delq nil (mapcar
13182 (lambda (x)
13183 (if (and (string-match org-use-tag-inheritance x)
13184 (not (member x org-tags-exclude-from-inheritance)))
13185 x nil))
13186 tags)))
13187 ((listp org-use-tag-inheritance)
13188 (delq nil (mapcar
13189 (lambda (x)
13190 (if (member x org-use-tag-inheritance) x nil))
13191 tags)))))
13193 (defun org-match-sparse-tree (&optional todo-only match)
13194 "Create a sparse tree according to tags string MATCH.
13195 MATCH can contain positive and negative selection of tags, like
13196 \"+WORK+URGENT-WITHBOSS\".
13197 If optional argument TODO-ONLY is non-nil, only select lines that are
13198 also TODO lines."
13199 (interactive "P")
13200 (org-agenda-prepare-buffers (list (current-buffer)))
13201 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13203 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13205 (defvar org-cached-props nil)
13206 (defun org-cached-entry-get (pom property)
13207 (if (or (eq t org-use-property-inheritance)
13208 (and (stringp org-use-property-inheritance)
13209 (string-match org-use-property-inheritance property))
13210 (and (listp org-use-property-inheritance)
13211 (member property org-use-property-inheritance)))
13212 ;; Caching is not possible, check it directly
13213 (org-entry-get pom property 'inherit)
13214 ;; Get all properties, so that we can do complicated checks easily
13215 (cdr (assoc property (or org-cached-props
13216 (setq org-cached-props
13217 (org-entry-properties pom)))))))
13219 (defun org-global-tags-completion-table (&optional files)
13220 "Return the list of all tags in all agenda buffer/files.
13221 Optional FILES argument is a list of files which can be used
13222 instead of the agenda files."
13223 (save-excursion
13224 (org-uniquify
13225 (delq nil
13226 (apply 'append
13227 (mapcar
13228 (lambda (file)
13229 (set-buffer (find-file-noselect file))
13230 (append (org-get-buffer-tags)
13231 (mapcar (lambda (x) (if (stringp (car-safe x))
13232 (list (car-safe x)) nil))
13233 org-tag-alist)))
13234 (if (and files (car files))
13235 files
13236 (org-agenda-files))))))))
13238 (defun org-make-tags-matcher (match)
13239 "Create the TAGS/TODO matcher form for the selection string MATCH.
13241 The variable `todo-only' is scoped dynamically into this function.
13242 It will be set to t if the matcher restricts matching to TODO entries,
13243 otherwise will not be touched.
13245 Returns a cons of the selection string MATCH and the constructed
13246 lisp form implementing the matcher. The matcher is to be evaluated
13247 at an Org entry, with point on the headline, and returns t if the
13248 entry matches the selection string MATCH. The returned lisp form
13249 references two variables with information about the entry, which
13250 must be bound around the form's evaluation: todo, the TODO keyword
13251 at the entry (or nil of none); and tags-list, the list of all tags
13252 at the entry including inherited ones. Additionally, the category
13253 of the entry (if any) must be specified as the text property
13254 'org-category on the headline.
13256 See also `org-scan-tags'.
13258 (declare (special todo-only))
13259 (unless (boundp 'todo-only)
13260 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13261 (unless match
13262 ;; Get a new match request, with completion
13263 (let ((org-last-tags-completion-table
13264 (org-global-tags-completion-table)))
13265 (setq match (org-completing-read-no-i
13266 "Match: " 'org-tags-completion-function nil nil nil
13267 'org-tags-history))))
13269 ;; Parse the string and create a lisp form
13270 (let ((match0 match)
13271 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13272 minus tag mm
13273 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13274 orterms term orlist re-p str-p level-p level-op time-p
13275 prop-p pn pv po gv rest)
13276 (if (string-match "/+" match)
13277 ;; match contains also a todo-matching request
13278 (progn
13279 (setq tagsmatch (substring match 0 (match-beginning 0))
13280 todomatch (substring match (match-end 0)))
13281 (if (string-match "^!" todomatch)
13282 (setq todo-only t todomatch (substring todomatch 1)))
13283 (if (string-match "^\\s-*$" todomatch)
13284 (setq todomatch nil)))
13285 ;; only matching tags
13286 (setq tagsmatch match todomatch nil))
13288 ;; Make the tags matcher
13289 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13290 (setq tagsmatcher t)
13291 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13292 (while (setq term (pop orterms))
13293 (while (and (equal (substring term -1) "\\") orterms)
13294 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13295 (while (string-match re term)
13296 (setq rest (substring term (match-end 0))
13297 minus (and (match-end 1)
13298 (equal (match-string 1 term) "-"))
13299 tag (save-match-data (replace-regexp-in-string
13300 "\\\\-" "-"
13301 (match-string 2 term)))
13302 re-p (equal (string-to-char tag) ?{)
13303 level-p (match-end 4)
13304 prop-p (match-end 5)
13305 mm (cond
13306 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13307 (level-p
13308 (setq level-op (org-op-to-function (match-string 3 term)))
13309 `(,level-op level ,(string-to-number
13310 (match-string 4 term))))
13311 (prop-p
13312 (setq pn (match-string 5 term)
13313 po (match-string 6 term)
13314 pv (match-string 7 term)
13315 re-p (equal (string-to-char pv) ?{)
13316 str-p (equal (string-to-char pv) ?\")
13317 time-p (save-match-data
13318 (string-match "^\"[[<].*[]>]\"$" pv))
13319 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13320 (if time-p (setq pv (org-matcher-time pv)))
13321 (setq po (org-op-to-function po (if time-p 'time str-p)))
13322 (cond
13323 ((equal pn "CATEGORY")
13324 (setq gv '(get-text-property (point) 'org-category)))
13325 ((equal pn "TODO")
13326 (setq gv 'todo))
13328 (setq gv `(org-cached-entry-get nil ,pn))))
13329 (if re-p
13330 (if (eq po 'org<>)
13331 `(not (string-match ,pv (or ,gv "")))
13332 `(string-match ,pv (or ,gv "")))
13333 (if str-p
13334 `(,po (or ,gv "") ,pv)
13335 `(,po (string-to-number (or ,gv ""))
13336 ,(string-to-number pv) ))))
13337 (t `(member ,tag tags-list)))
13338 mm (if minus (list 'not mm) mm)
13339 term rest)
13340 (push mm tagsmatcher))
13341 (push (if (> (length tagsmatcher) 1)
13342 (cons 'and tagsmatcher)
13343 (car tagsmatcher))
13344 orlist)
13345 (setq tagsmatcher nil))
13346 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13347 (setq tagsmatcher
13348 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13349 ;; Make the todo matcher
13350 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13351 (setq todomatcher t)
13352 (setq orterms (org-split-string todomatch "|") orlist nil)
13353 (while (setq term (pop orterms))
13354 (while (string-match re term)
13355 (setq minus (and (match-end 1)
13356 (equal (match-string 1 term) "-"))
13357 kwd (match-string 2 term)
13358 re-p (equal (string-to-char kwd) ?{)
13359 term (substring term (match-end 0))
13360 mm (if re-p
13361 `(string-match ,(substring kwd 1 -1) todo)
13362 (list 'equal 'todo kwd))
13363 mm (if minus (list 'not mm) mm))
13364 (push mm todomatcher))
13365 (push (if (> (length todomatcher) 1)
13366 (cons 'and todomatcher)
13367 (car todomatcher))
13368 orlist)
13369 (setq todomatcher nil))
13370 (setq todomatcher (if (> (length orlist) 1)
13371 (cons 'or orlist) (car orlist))))
13373 ;; Return the string and lisp forms of the matcher
13374 (setq matcher (if todomatcher
13375 (list 'and tagsmatcher todomatcher)
13376 tagsmatcher))
13377 (when todo-only
13378 (setq matcher (list 'and '(member todo org-not-done-keywords)
13379 matcher)))
13380 (cons match0 matcher)))
13382 (defun org-op-to-function (op &optional stringp)
13383 "Turn an operator into the appropriate function."
13384 (setq op
13385 (cond
13386 ((equal op "<" ) '(< string< org-time<))
13387 ((equal op ">" ) '(> org-string> org-time>))
13388 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13389 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13390 ((member op '("=" "==")) '(= string= org-time=))
13391 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13392 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13394 (defun org<> (a b) (not (= a b)))
13395 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13396 (defun org-string>= (a b) (not (string< a b)))
13397 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13398 (defun org-string<> (a b) (not (string= a b)))
13399 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13400 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13401 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13402 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13403 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13404 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13405 (defun org-2ft (s)
13406 "Convert S to a floating point time.
13407 If S is already a number, just return it. If it is a string, parse
13408 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13409 (cond
13410 ((numberp s) s)
13411 ((stringp s)
13412 (condition-case nil
13413 (float-time (apply 'encode-time (org-parse-time-string s)))
13414 (error 0.)))
13415 (t 0.)))
13417 (defun org-time-today ()
13418 "Time in seconds today at 0:00.
13419 Returns the float number of seconds since the beginning of the
13420 epoch to the beginning of today (00:00)."
13421 (float-time (apply 'encode-time
13422 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13424 (defun org-matcher-time (s)
13425 "Interpret a time comparison value."
13426 (save-match-data
13427 (cond
13428 ((string= s "<now>") (float-time))
13429 ((string= s "<today>") (org-time-today))
13430 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13431 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13432 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13433 (+ (org-time-today)
13434 (* (string-to-number (match-string 1 s))
13435 (cdr (assoc (match-string 2 s)
13436 '(("d" . 86400.0) ("w" . 604800.0)
13437 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13438 (t (org-2ft s)))))
13440 (defun org-match-any-p (re list)
13441 "Does re match any element of list?"
13442 (setq list (mapcar (lambda (x) (string-match re x)) list))
13443 (delq nil list))
13445 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13446 (defvar org-tags-overlay (make-overlay 1 1))
13447 (org-detach-overlay org-tags-overlay)
13449 (defun org-get-local-tags-at (&optional pos)
13450 "Get a list of tags defined in the current headline."
13451 (org-get-tags-at pos 'local))
13453 (defun org-get-local-tags ()
13454 "Get a list of tags defined in the current headline."
13455 (org-get-tags-at nil 'local))
13457 (defun org-get-tags-at (&optional pos local)
13458 "Get a list of all headline tags applicable at POS.
13459 POS defaults to point. If tags are inherited, the list contains
13460 the targets in the same sequence as the headlines appear, i.e.
13461 the tags of the current headline come last.
13462 When LOCAL is non-nil, only return tags from the current headline,
13463 ignore inherited ones."
13464 (interactive)
13465 (if (and org-trust-scanner-tags
13466 (or (not pos) (equal pos (point)))
13467 (not local))
13468 org-scanner-tags
13469 (let (tags ltags lastpos parent)
13470 (save-excursion
13471 (save-restriction
13472 (widen)
13473 (goto-char (or pos (point)))
13474 (save-match-data
13475 (catch 'done
13476 (condition-case nil
13477 (progn
13478 (org-back-to-heading t)
13479 (while (not (equal lastpos (point)))
13480 (setq lastpos (point))
13481 (when (looking-at
13482 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13483 (setq ltags (org-split-string
13484 (org-match-string-no-properties 1) ":"))
13485 (when parent
13486 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13487 (setq tags (append
13488 (if parent
13489 (org-remove-uninherited-tags ltags)
13490 ltags)
13491 tags)))
13492 (or org-use-tag-inheritance (throw 'done t))
13493 (if local (throw 'done t))
13494 (or (org-up-heading-safe) (error nil))
13495 (setq parent t)))
13496 (error nil)))))
13497 (if local
13498 tags
13499 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13501 (defun org-add-prop-inherited (s)
13502 (add-text-properties 0 (length s) '(inherited t) s)
13505 (defun org-toggle-tag (tag &optional onoff)
13506 "Toggle the tag TAG for the current line.
13507 If ONOFF is `on' or `off', don't toggle but set to this state."
13508 (let (res current)
13509 (save-excursion
13510 (org-back-to-heading t)
13511 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13512 (point-at-eol) t)
13513 (progn
13514 (setq current (match-string 1))
13515 (replace-match ""))
13516 (setq current ""))
13517 (setq current (nreverse (org-split-string current ":")))
13518 (cond
13519 ((eq onoff 'on)
13520 (setq res t)
13521 (or (member tag current) (push tag current)))
13522 ((eq onoff 'off)
13523 (or (not (member tag current)) (setq current (delete tag current))))
13524 (t (if (member tag current)
13525 (setq current (delete tag current))
13526 (setq res t)
13527 (push tag current))))
13528 (end-of-line 1)
13529 (if current
13530 (progn
13531 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13532 (org-set-tags nil t))
13533 (delete-horizontal-space))
13534 (run-hooks 'org-after-tags-change-hook))
13535 res))
13537 (defun org-align-tags-here (to-col)
13538 ;; Assumes that this is a headline
13539 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13540 (beginning-of-line 1)
13541 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13542 (< pos (match-beginning 2)))
13543 (progn
13544 (setq tags-l (- (match-end 2) (match-beginning 2)))
13545 (goto-char (match-beginning 1))
13546 (insert " ")
13547 (delete-region (point) (1+ (match-beginning 2)))
13548 (setq ncol (max (current-column)
13549 (1+ col)
13550 (if (> to-col 0)
13551 to-col
13552 (- (abs to-col) tags-l))))
13553 (setq p (point))
13554 (insert (make-string (- ncol (current-column)) ?\ ))
13555 (setq ncol (current-column))
13556 (when indent-tabs-mode (tabify p (point-at-eol)))
13557 (org-move-to-column (min ncol col) t))
13558 (goto-char pos))))
13560 (defun org-set-tags-command (&optional arg just-align)
13561 "Call the set-tags command for the current entry."
13562 (interactive "P")
13563 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13564 (org-set-tags arg just-align)
13565 (save-excursion
13566 (org-back-to-heading t)
13567 (org-set-tags arg just-align))))
13569 (defun org-set-tags-to (data)
13570 "Set the tags of the current entry to DATA, replacing the current tags.
13571 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13572 If DATA is nil or the empty string, any tags will be removed."
13573 (interactive "sTags: ")
13574 (setq data
13575 (cond
13576 ((eq data nil) "")
13577 ((equal data "") "")
13578 ((stringp data)
13579 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13580 ":"))
13581 ((listp data)
13582 (concat ":" (mapconcat 'identity data ":") ":"))))
13583 (when data
13584 (save-excursion
13585 (org-back-to-heading t)
13586 (when (looking-at org-complex-heading-regexp)
13587 (if (match-end 5)
13588 (progn
13589 (goto-char (match-beginning 5))
13590 (insert data)
13591 (delete-region (point) (point-at-eol))
13592 (org-set-tags nil 'align))
13593 (goto-char (point-at-eol))
13594 (insert " " data)
13595 (org-set-tags nil 'align)))
13596 (beginning-of-line 1)
13597 (if (looking-at ".*?\\([ \t]+\\)$")
13598 (delete-region (match-beginning 1) (match-end 1))))))
13600 (defun org-align-all-tags ()
13601 "Align the tags i all headings."
13602 (interactive)
13603 (save-excursion
13604 (or (ignore-errors (org-back-to-heading t))
13605 (outline-next-heading))
13606 (if (org-at-heading-p)
13607 (org-set-tags t)
13608 (message "No headings"))))
13610 (defvar org-indent-indentation-per-level)
13611 (defun org-set-tags (&optional arg just-align)
13612 "Set the tags for the current headline.
13613 With prefix ARG, realign all tags in headings in the current buffer."
13614 (interactive "P")
13615 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13616 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13617 'region-start-level 'region))
13618 org-loop-over-headlines-in-active-region)
13619 (org-map-entries
13620 ;; We don't use ARG and JUST-ALIGN here these args are not
13621 ;; useful when looping over headlines
13622 `(org-set-tags)
13623 org-loop-over-headlines-in-active-region
13624 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13625 (let* ((re org-outline-regexp-bol)
13626 (current (unless arg (org-get-tags-string)))
13627 (col (current-column))
13628 (org-setting-tags t)
13629 table current-tags inherited-tags ; computed below when needed
13630 tags p0 c0 c1 rpl di tc level)
13631 (if arg
13632 (save-excursion
13633 (goto-char (point-min))
13634 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13635 (while (re-search-forward re nil t)
13636 (org-set-tags nil t)
13637 (end-of-line 1)))
13638 (message "All tags realigned to column %d" org-tags-column))
13639 (if just-align
13640 (setq tags current)
13641 ;; Get a new set of tags from the user
13642 (save-excursion
13643 (setq table (append org-tag-persistent-alist
13644 (or org-tag-alist (org-get-buffer-tags))
13645 (and
13646 org-complete-tags-always-offer-all-agenda-tags
13647 (org-global-tags-completion-table
13648 (org-agenda-files))))
13649 org-last-tags-completion-table table
13650 current-tags (org-split-string current ":")
13651 inherited-tags (nreverse
13652 (nthcdr (length current-tags)
13653 (nreverse (org-get-tags-at))))
13654 tags
13655 (if (or (eq t org-use-fast-tag-selection)
13656 (and org-use-fast-tag-selection
13657 (delq nil (mapcar 'cdr table))))
13658 (org-fast-tag-selection
13659 current-tags inherited-tags table
13660 (if org-fast-tag-selection-include-todo
13661 org-todo-key-alist))
13662 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13663 (org-trim
13664 (org-icompleting-read "Tags: "
13665 'org-tags-completion-function
13666 nil nil current 'org-tags-history))))))
13667 (while (string-match "[-+&]+" tags)
13668 ;; No boolean logic, just a list
13669 (setq tags (replace-match ":" t t tags))))
13671 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13673 (if org-tags-sort-function
13674 (setq tags (mapconcat 'identity
13675 (sort (org-split-string
13676 tags (org-re "[^[:alnum:]_@#%]+"))
13677 org-tags-sort-function) ":")))
13679 (if (string-match "\\`[\t ]*\\'" tags)
13680 (setq tags "")
13681 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13682 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13684 ;; Insert new tags at the correct column
13685 (beginning-of-line 1)
13686 (setq level (or (and (looking-at org-outline-regexp)
13687 (- (match-end 0) (point) 1))
13689 (cond
13690 ((and (equal current "") (equal tags "")))
13691 ((re-search-forward
13692 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13693 (point-at-eol) t)
13694 (if (equal tags "")
13695 (setq rpl "")
13696 (goto-char (match-beginning 0))
13697 (setq c0 (current-column)
13698 ;; compute offset for the case of org-indent-mode active
13699 di (if org-indent-mode
13700 (* (1- org-indent-indentation-per-level) (1- level))
13702 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13703 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13704 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13705 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13706 (replace-match rpl t t)
13707 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13708 tags)
13709 (t (error "Tags alignment failed")))
13710 (org-move-to-column col)
13711 (unless just-align
13712 (run-hooks 'org-after-tags-change-hook))))))
13714 (defun org-change-tag-in-region (beg end tag off)
13715 "Add or remove TAG for each entry in the region.
13716 This works in the agenda, and also in an org-mode buffer."
13717 (interactive
13718 (list (region-beginning) (region-end)
13719 (let ((org-last-tags-completion-table
13720 (if (derived-mode-p 'org-mode)
13721 (org-get-buffer-tags)
13722 (org-global-tags-completion-table))))
13723 (org-icompleting-read
13724 "Tag: " 'org-tags-completion-function nil nil nil
13725 'org-tags-history))
13726 (progn
13727 (message "[s]et or [r]emove? ")
13728 (equal (read-char-exclusive) ?r))))
13729 (if (fboundp 'deactivate-mark) (deactivate-mark))
13730 (let ((agendap (equal major-mode 'org-agenda-mode))
13731 l1 l2 m buf pos newhead (cnt 0))
13732 (goto-char end)
13733 (setq l2 (1- (org-current-line)))
13734 (goto-char beg)
13735 (setq l1 (org-current-line))
13736 (loop for l from l1 to l2 do
13737 (org-goto-line l)
13738 (setq m (get-text-property (point) 'org-hd-marker))
13739 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13740 (and agendap m))
13741 (setq buf (if agendap (marker-buffer m) (current-buffer))
13742 pos (if agendap m (point)))
13743 (with-current-buffer buf
13744 (save-excursion
13745 (save-restriction
13746 (goto-char pos)
13747 (setq cnt (1+ cnt))
13748 (org-toggle-tag tag (if off 'off 'on))
13749 (setq newhead (org-get-heading)))))
13750 (and agendap (org-agenda-change-all-lines newhead m))))
13751 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13753 (defun org-tags-completion-function (string predicate &optional flag)
13754 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13755 (confirm (lambda (x) (stringp (car x)))))
13756 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13757 (setq s1 (match-string 1 string)
13758 s2 (match-string 2 string))
13759 (setq s1 "" s2 string))
13760 (cond
13761 ((eq flag nil)
13762 ;; try completion
13763 (setq rtn (try-completion s2 ctable confirm))
13764 (if (stringp rtn)
13765 (setq rtn
13766 (concat s1 s2 (substring rtn (length s2))
13767 (if (and org-add-colon-after-tag-completion
13768 (assoc rtn ctable))
13769 ":" ""))))
13770 rtn)
13771 ((eq flag t)
13772 ;; all-completions
13773 (all-completions s2 ctable confirm)
13775 ((eq flag 'lambda)
13776 ;; exact match?
13777 (assoc s2 ctable)))
13780 (defun org-fast-tag-insert (kwd tags face &optional end)
13781 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13782 (insert (format "%-12s" (concat kwd ":"))
13783 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13784 (or end "")))
13786 (defun org-fast-tag-show-exit (flag)
13787 (save-excursion
13788 (org-goto-line 3)
13789 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13790 (replace-match ""))
13791 (when flag
13792 (end-of-line 1)
13793 (org-move-to-column (- (window-width) 19) t)
13794 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13796 (defun org-set-current-tags-overlay (current prefix)
13797 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13798 (if (featurep 'xemacs)
13799 (org-overlay-display org-tags-overlay (concat prefix s)
13800 'secondary-selection)
13801 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13802 (org-overlay-display org-tags-overlay (concat prefix s)))))
13804 (defvar org-last-tag-selection-key nil)
13805 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13806 "Fast tag selection with single keys.
13807 CURRENT is the current list of tags in the headline, INHERITED is the
13808 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13809 possibly with grouping information. TODO-TABLE is a similar table with
13810 TODO keywords, should these have keys assigned to them.
13811 If the keys are nil, a-z are automatically assigned.
13812 Returns the new tags string, or nil to not change the current settings."
13813 (let* ((fulltable (append table todo-table))
13814 (maxlen (apply 'max (mapcar
13815 (lambda (x)
13816 (if (stringp (car x)) (string-width (car x)) 0))
13817 fulltable)))
13818 (buf (current-buffer))
13819 (expert (eq org-fast-tag-selection-single-key 'expert))
13820 (buffer-tags nil)
13821 (fwidth (+ maxlen 3 1 3))
13822 (ncol (/ (- (window-width) 4) fwidth))
13823 (i-face 'org-done)
13824 (c-face 'org-todo)
13825 tg cnt e c char c1 c2 ntable tbl rtn
13826 ov-start ov-end ov-prefix
13827 (exit-after-next org-fast-tag-selection-single-key)
13828 (done-keywords org-done-keywords)
13829 groups ingroup)
13830 (save-excursion
13831 (beginning-of-line 1)
13832 (if (looking-at
13833 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13834 (setq ov-start (match-beginning 1)
13835 ov-end (match-end 1)
13836 ov-prefix "")
13837 (setq ov-start (1- (point-at-eol))
13838 ov-end (1+ ov-start))
13839 (skip-chars-forward "^\n\r")
13840 (setq ov-prefix
13841 (concat
13842 (buffer-substring (1- (point)) (point))
13843 (if (> (current-column) org-tags-column)
13845 (make-string (- org-tags-column (current-column)) ?\ ))))))
13846 (move-overlay org-tags-overlay ov-start ov-end)
13847 (save-window-excursion
13848 (if expert
13849 (set-buffer (get-buffer-create " *Org tags*"))
13850 (delete-other-windows)
13851 (split-window-vertically)
13852 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13853 (erase-buffer)
13854 (org-set-local 'org-done-keywords done-keywords)
13855 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13856 (org-fast-tag-insert "Current" current c-face "\n\n")
13857 (org-fast-tag-show-exit exit-after-next)
13858 (org-set-current-tags-overlay current ov-prefix)
13859 (setq tbl fulltable char ?a cnt 0)
13860 (while (setq e (pop tbl))
13861 (cond
13862 ((equal (car e) :startgroup)
13863 (push '() groups) (setq ingroup t)
13864 (when (not (= cnt 0))
13865 (setq cnt 0)
13866 (insert "\n"))
13867 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13868 ((equal (car e) :endgroup)
13869 (setq ingroup nil cnt 0)
13870 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13871 ((equal e '(:newline))
13872 (when (not (= cnt 0))
13873 (setq cnt 0)
13874 (insert "\n")
13875 (setq e (car tbl))
13876 (while (equal (car tbl) '(:newline))
13877 (insert "\n")
13878 (setq tbl (cdr tbl)))))
13880 (setq tg (copy-sequence (car e)) c2 nil)
13881 (if (cdr e)
13882 (setq c (cdr e))
13883 ;; automatically assign a character.
13884 (setq c1 (string-to-char
13885 (downcase (substring
13886 tg (if (= (string-to-char tg) ?@) 1 0)))))
13887 (if (or (rassoc c1 ntable) (rassoc c1 table))
13888 (while (or (rassoc char ntable) (rassoc char table))
13889 (setq char (1+ char)))
13890 (setq c2 c1))
13891 (setq c (or c2 char)))
13892 (if ingroup (push tg (car groups)))
13893 (setq tg (org-add-props tg nil 'face
13894 (cond
13895 ((not (assoc tg table))
13896 (org-get-todo-face tg))
13897 ((member tg current) c-face)
13898 ((member tg inherited) i-face))))
13899 (if (and (= cnt 0) (not ingroup)) (insert " "))
13900 (insert "[" c "] " tg (make-string
13901 (- fwidth 4 (length tg)) ?\ ))
13902 (push (cons tg c) ntable)
13903 (when (= (setq cnt (1+ cnt)) ncol)
13904 (insert "\n")
13905 (if ingroup (insert " "))
13906 (setq cnt 0)))))
13907 (setq ntable (nreverse ntable))
13908 (insert "\n")
13909 (goto-char (point-min))
13910 (if (not expert) (org-fit-window-to-buffer))
13911 (setq rtn
13912 (catch 'exit
13913 (while t
13914 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13915 (if (not groups) "no " "")
13916 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13917 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13918 (setq org-last-tag-selection-key c)
13919 (cond
13920 ((= c ?\r) (throw 'exit t))
13921 ((= c ?!)
13922 (setq groups (not groups))
13923 (goto-char (point-min))
13924 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13925 ((= c ?\C-c)
13926 (if (not expert)
13927 (org-fast-tag-show-exit
13928 (setq exit-after-next (not exit-after-next)))
13929 (setq expert nil)
13930 (delete-other-windows)
13931 (set-window-buffer (split-window-vertically) " *Org tags*")
13932 (org-switch-to-buffer-other-window " *Org tags*")
13933 (org-fit-window-to-buffer)))
13934 ((or (= c ?\C-g)
13935 (and (= c ?q) (not (rassoc c ntable))))
13936 (org-detach-overlay org-tags-overlay)
13937 (setq quit-flag t))
13938 ((= c ?\ )
13939 (setq current nil)
13940 (if exit-after-next (setq exit-after-next 'now)))
13941 ((= c ?\t)
13942 (condition-case nil
13943 (setq tg (org-icompleting-read
13944 "Tag: "
13945 (or buffer-tags
13946 (with-current-buffer buf
13947 (org-get-buffer-tags)))))
13948 (quit (setq tg "")))
13949 (when (string-match "\\S-" tg)
13950 (add-to-list 'buffer-tags (list tg))
13951 (if (member tg current)
13952 (setq current (delete tg current))
13953 (push tg current)))
13954 (if exit-after-next (setq exit-after-next 'now)))
13955 ((setq e (rassoc c todo-table) tg (car e))
13956 (with-current-buffer buf
13957 (save-excursion (org-todo tg)))
13958 (if exit-after-next (setq exit-after-next 'now)))
13959 ((setq e (rassoc c ntable) tg (car e))
13960 (if (member tg current)
13961 (setq current (delete tg current))
13962 (loop for g in groups do
13963 (if (member tg g)
13964 (mapc (lambda (x)
13965 (setq current (delete x current)))
13966 g)))
13967 (push tg current))
13968 (if exit-after-next (setq exit-after-next 'now))))
13970 ;; Create a sorted list
13971 (setq current
13972 (sort current
13973 (lambda (a b)
13974 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13975 (if (eq exit-after-next 'now) (throw 'exit t))
13976 (goto-char (point-min))
13977 (beginning-of-line 2)
13978 (delete-region (point) (point-at-eol))
13979 (org-fast-tag-insert "Current" current c-face)
13980 (org-set-current-tags-overlay current ov-prefix)
13981 (while (re-search-forward
13982 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13983 (setq tg (match-string 1))
13984 (add-text-properties
13985 (match-beginning 1) (match-end 1)
13986 (list 'face
13987 (cond
13988 ((member tg current) c-face)
13989 ((member tg inherited) i-face)
13990 (t (get-text-property (match-beginning 1) 'face))))))
13991 (goto-char (point-min)))))
13992 (org-detach-overlay org-tags-overlay)
13993 (if rtn
13994 (mapconcat 'identity current ":")
13995 nil))))
13997 (defun org-get-tags-string ()
13998 "Get the TAGS string in the current headline."
13999 (unless (org-at-heading-p t)
14000 (error "Not on a heading"))
14001 (save-excursion
14002 (beginning-of-line 1)
14003 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14004 (org-match-string-no-properties 1)
14005 "")))
14007 (defun org-get-tags ()
14008 "Get the list of tags specified in the current headline."
14009 (org-split-string (org-get-tags-string) ":"))
14011 (defun org-get-buffer-tags ()
14012 "Get a table of all tags used in the buffer, for completion."
14013 (let (tags)
14014 (save-excursion
14015 (goto-char (point-min))
14016 (while (re-search-forward
14017 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14018 (when (equal (char-after (point-at-bol 0)) ?*)
14019 (mapc (lambda (x) (add-to-list 'tags x))
14020 (org-split-string (org-match-string-no-properties 1) ":")))))
14021 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14022 (mapcar 'list tags)))
14024 ;;;; The mapping API
14026 (defun org-map-entries (func &optional match scope &rest skip)
14027 "Call FUNC at each headline selected by MATCH in SCOPE.
14029 FUNC is a function or a lisp form. The function will be called without
14030 arguments, with the cursor positioned at the beginning of the headline.
14031 The return values of all calls to the function will be collected and
14032 returned as a list.
14034 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14035 does not need to preserve point. After evaluation, the cursor will be
14036 moved to the end of the line (presumably of the headline of the
14037 processed entry) and search continues from there. Under some
14038 circumstances, this may not produce the wanted results. For example,
14039 if you have removed (e.g. archived) the current (sub)tree it could
14040 mean that the next entry will be skipped entirely. In such cases, you
14041 can specify the position from where search should continue by making
14042 FUNC set the variable `org-map-continue-from' to the desired buffer
14043 position.
14045 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14046 Only headlines that are matched by this query will be considered during
14047 the iteration. When MATCH is nil or t, all headlines will be
14048 visited by the iteration.
14050 SCOPE determines the scope of this command. It can be any of:
14052 nil The current buffer, respecting the restriction if any
14053 tree The subtree started with the entry at point
14054 region The entries within the active region, if any
14055 region-start-level
14056 The entries within the active region, but only those at
14057 the same level than the first one.
14058 file The current buffer, without restriction
14059 file-with-archives
14060 The current buffer, and any archives associated with it
14061 agenda All agenda files
14062 agenda-with-archives
14063 All agenda files with any archive files associated with them
14064 \(file1 file2 ...)
14065 If this is a list, all files in the list will be scanned
14067 The remaining args are treated as settings for the skipping facilities of
14068 the scanner. The following items can be given here:
14070 archive skip trees with the archive tag.
14071 comment skip trees with the COMMENT keyword
14072 function or Emacs Lisp form:
14073 will be used as value for `org-agenda-skip-function', so whenever
14074 the function returns t, FUNC will not be called for that
14075 entry and search will continue from the point where the
14076 function leaves it.
14078 If your function needs to retrieve the tags including inherited tags
14079 at the *current* entry, you can use the value of the variable
14080 `org-scanner-tags' which will be much faster than getting the value
14081 with `org-get-tags-at'. If your function gets properties with
14082 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14083 to t around the call to `org-entry-properties' to get the same speedup.
14084 Note that if your function moves around to retrieve tags and properties at
14085 a *different* entry, you cannot use these techniques."
14086 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14087 (not (org-region-active-p)))
14088 (let* ((org-agenda-archives-mode nil) ; just to make sure
14089 (org-agenda-skip-archived-trees (memq 'archive skip))
14090 (org-agenda-skip-comment-trees (memq 'comment skip))
14091 (org-agenda-skip-function
14092 (car (org-delete-all '(comment archive) skip)))
14093 (org-tags-match-list-sublevels t)
14094 (start-level (eq scope 'region-start-level))
14095 matcher file res
14096 org-todo-keywords-for-agenda
14097 org-done-keywords-for-agenda
14098 org-todo-keyword-alist-for-agenda
14099 org-drawers-for-agenda
14100 org-tag-alist-for-agenda
14101 todo-only)
14103 (cond
14104 ((eq match t) (setq matcher t))
14105 ((eq match nil) (setq matcher t))
14106 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14108 (save-excursion
14109 (save-restriction
14110 (cond ((eq scope 'tree)
14111 (org-back-to-heading t)
14112 (org-narrow-to-subtree)
14113 (setq scope nil))
14114 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14115 (org-region-active-p))
14116 ;; If needed, set start-level to a string like "2"
14117 (when start-level
14118 (save-excursion
14119 (goto-char (region-beginning))
14120 (unless (org-at-heading-p) (outline-next-heading))
14121 (setq start-level (org-current-level))))
14122 (narrow-to-region (region-beginning)
14123 (save-excursion
14124 (goto-char (region-end))
14125 (unless (and (bolp) (org-at-heading-p))
14126 (outline-next-heading))
14127 (point)))
14128 (setq scope nil)))
14130 (if (not scope)
14131 (progn
14132 (org-agenda-prepare-buffers
14133 (list (buffer-file-name (current-buffer))))
14134 (setq res (org-scan-tags func matcher todo-only start-level)))
14135 ;; Get the right scope
14136 (cond
14137 ((and scope (listp scope) (symbolp (car scope)))
14138 (setq scope (eval scope)))
14139 ((eq scope 'agenda)
14140 (setq scope (org-agenda-files t)))
14141 ((eq scope 'agenda-with-archives)
14142 (setq scope (org-agenda-files t))
14143 (setq scope (org-add-archive-files scope)))
14144 ((eq scope 'file)
14145 (setq scope (list (buffer-file-name))))
14146 ((eq scope 'file-with-archives)
14147 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14148 (org-agenda-prepare-buffers scope)
14149 (while (setq file (pop scope))
14150 (with-current-buffer (org-find-base-buffer-visiting file)
14151 (save-excursion
14152 (save-restriction
14153 (widen)
14154 (goto-char (point-min))
14155 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14156 res)))
14158 ;;;; Properties
14160 ;;; Setting and retrieving properties
14162 (defconst org-special-properties
14163 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14164 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14165 "The special properties valid in Org-mode.
14167 These are properties that are not defined in the property drawer,
14168 but in some other way.")
14170 (defconst org-default-properties
14171 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14172 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14173 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14174 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14175 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14176 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14177 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14178 "Some properties that are used by Org-mode for various purposes.
14179 Being in this list makes sure that they are offered for completion.")
14181 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14182 "Regular expression matching the first line of a property drawer.")
14184 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14185 "Regular expression matching the last line of a property drawer.")
14187 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14188 "Regular expression matching the first line of a property drawer.")
14190 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14191 "Regular expression matching the first line of a property drawer.")
14193 (defconst org-property-drawer-re
14194 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14195 org-property-end-re "\\)\n?")
14196 "Matches an entire property drawer.")
14198 (defconst org-clock-drawer-re
14199 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14200 org-property-end-re "\\)\n?")
14201 "Matches an entire clock drawer.")
14203 (defsubst org-re-property (property)
14204 "Return a regexp matching a PROPERTY line.
14205 Match group 1 will be set to the value."
14206 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14208 (defsubst org-re-property-keyword (property)
14209 "Return a regexp matching a PROPERTY line, possibly with no
14210 value for the property."
14211 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14213 (defun org-property-action ()
14214 "Do an action on properties."
14215 (interactive)
14216 (let (c)
14217 (org-at-property-p)
14218 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14219 (setq c (read-char-exclusive))
14220 (cond
14221 ((equal c ?s)
14222 (call-interactively 'org-set-property))
14223 ((equal c ?d)
14224 (call-interactively 'org-delete-property))
14225 ((equal c ?D)
14226 (call-interactively 'org-delete-property-globally))
14227 ((equal c ?c)
14228 (call-interactively 'org-compute-property-at-point))
14229 (t (error "No such property action %c" c)))))
14231 (defun org-inc-effort ()
14232 "Increment the value of the effort property in the current entry."
14233 (interactive)
14234 (org-set-effort nil t))
14236 (defun org-set-effort (&optional value increment)
14237 "Set the effort property of the current entry.
14238 With numerical prefix arg, use the nth allowed value, 0 stands for the
14239 10th allowed value.
14241 When INCREMENT is non-nil, set the property to the next allowed value."
14242 (interactive "P")
14243 (if (equal value 0) (setq value 10))
14244 (let* ((completion-ignore-case t)
14245 (prop org-effort-property)
14246 (cur (org-entry-get nil prop))
14247 (allowed (org-property-get-allowed-values nil prop 'table))
14248 (existing (mapcar 'list (org-property-values prop)))
14250 (val (cond
14251 ((stringp value) value)
14252 ((and allowed (integerp value))
14253 (or (car (nth (1- value) allowed))
14254 (car (org-last allowed))))
14255 ((and allowed increment)
14256 (or (caadr (member (list cur) allowed))
14257 (error "Allowed effort values are not set")))
14258 (allowed
14259 (message "Select 1-9,0, [RET%s]: %s"
14260 (if cur (concat "=" cur) "")
14261 (mapconcat 'car allowed " "))
14262 (setq rpl (read-char-exclusive))
14263 (if (equal rpl ?\r)
14265 (setq rpl (- rpl ?0))
14266 (if (equal rpl 0) (setq rpl 10))
14267 (if (and (> rpl 0) (<= rpl (length allowed)))
14268 (car (nth (1- rpl) allowed))
14269 (org-completing-read "Effort: " allowed nil))))
14271 (let (org-completion-use-ido org-completion-use-iswitchb)
14272 (org-completing-read
14273 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14274 (concat "[" cur "]") "")
14275 ": ")
14276 existing nil nil "" nil cur))))))
14277 (unless (equal (org-entry-get nil prop) val)
14278 (org-entry-put nil prop val))
14279 (message "%s is now %s" prop val)))
14281 (defun org-at-property-p ()
14282 "Is cursor inside a property drawer?"
14283 (save-excursion
14284 (beginning-of-line 1)
14285 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14286 (save-match-data ;; Used by calling procedures
14287 (let ((p (point))
14288 (range (unless (org-before-first-heading-p)
14289 (org-get-property-block))))
14290 (and range (<= (car range) p) (< p (cdr range))))))))
14292 (defun org-get-property-block (&optional beg end force)
14293 "Return the (beg . end) range of the body of the property drawer.
14294 BEG and END are the beginning and end of the current subtree, or of
14295 the part before the first headline. If they are not given, they will
14296 be found. If the drawer does not exist and FORCE is non-nil, create
14297 the drawer."
14298 (catch 'exit
14299 (save-excursion
14300 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14301 (progn (org-back-to-heading t) (point))))
14302 (end (or end (and (not (outline-next-heading)) (point-max))
14303 (point))))
14304 (goto-char beg)
14305 (if (re-search-forward org-property-start-re end t)
14306 (setq beg (1+ (match-end 0)))
14307 (if force
14308 (save-excursion
14309 (org-insert-property-drawer)
14310 (setq end (progn (outline-next-heading) (point))))
14311 (throw 'exit nil))
14312 (goto-char beg)
14313 (if (re-search-forward org-property-start-re end t)
14314 (setq beg (1+ (match-end 0)))))
14315 (if (re-search-forward org-property-end-re end t)
14316 (setq end (match-beginning 0))
14317 (or force (throw 'exit nil))
14318 (goto-char beg)
14319 (setq end beg)
14320 (org-indent-line)
14321 (insert ":END:\n"))
14322 (cons beg end)))))
14324 (defun org-entry-properties (&optional pom which specific)
14325 "Get all properties of the entry at point-or-marker POM.
14326 This includes the TODO keyword, the tags, time strings for deadline,
14327 scheduled, and clocking, and any additional properties defined in the
14328 entry. The return value is an alist, keys may occur multiple times
14329 if the property key was used several times.
14330 POM may also be nil, in which case the current entry is used.
14331 If WHICH is nil or `all', get all properties. If WHICH is
14332 `special' or `standard', only get that subclass. If WHICH
14333 is a string only get exactly this property. SPECIFIC can be a string, the
14334 specific property we are interested in. Specifying it can speed
14335 things up because then unnecessary parsing is avoided."
14336 (setq which (or which 'all))
14337 (org-with-point-at pom
14338 (let ((clockstr (substring org-clock-string 0 -1))
14339 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14340 (case-fold-search nil)
14341 beg end range props sum-props key key1 value string clocksum clocksumt)
14342 (save-excursion
14343 (when (condition-case nil
14344 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14345 (error nil))
14346 (setq beg (point))
14347 (setq sum-props (get-text-property (point) 'org-summaries))
14348 (setq clocksum (get-text-property (point) :org-clock-minutes)
14349 clocksumt (get-text-property (point) :org-clock-minutes-today))
14350 (outline-next-heading)
14351 (setq end (point))
14352 (when (memq which '(all special))
14353 ;; Get the special properties, like TODO and tags
14354 (goto-char beg)
14355 (when (and (or (not specific) (string= specific "TODO"))
14356 (looking-at org-todo-line-regexp) (match-end 2))
14357 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14358 (when (and (or (not specific) (string= specific "PRIORITY"))
14359 (looking-at org-priority-regexp))
14360 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14361 (when (or (not specific) (string= specific "FILE"))
14362 (push (cons "FILE" buffer-file-name) props))
14363 (when (and (or (not specific) (string= specific "TAGS"))
14364 (setq value (org-get-tags-string))
14365 (string-match "\\S-" value))
14366 (push (cons "TAGS" value) props))
14367 (when (and (or (not specific) (string= specific "ALLTAGS"))
14368 (setq value (org-get-tags-at)))
14369 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14370 ":"))
14371 props))
14372 (when (or (not specific) (string= specific "BLOCKED"))
14373 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14374 (when (or (not specific)
14375 (member specific
14376 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14377 "TIMESTAMP" "TIMESTAMP_IA")))
14378 (catch 'match
14379 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14380 (setq key (if (match-end 1)
14381 (substring (org-match-string-no-properties 1)
14382 0 -1))
14383 string (if (equal key clockstr)
14384 (org-trim
14385 (buffer-substring-no-properties
14386 (match-beginning 3) (goto-char
14387 (point-at-eol))))
14388 (substring (org-match-string-no-properties 3)
14389 1 -1)))
14390 ;; Get the correct property name from the key. This is
14391 ;; necessary if the user has configured time keywords.
14392 (setq key1 (concat key ":"))
14393 (cond
14394 ((not key)
14395 (setq key
14396 (if (= (char-after (match-beginning 3)) ?\[)
14397 "TIMESTAMP_IA" "TIMESTAMP")))
14398 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14399 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14400 ((equal key1 org-closed-string) (setq key "CLOSED"))
14401 ((equal key1 org-clock-string) (setq key "CLOCK")))
14402 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14403 (progn
14404 (push (cons key string) props)
14405 ;; no need to search further if match is found
14406 (throw 'match t))
14407 (when (or (equal key "CLOCK") (not (assoc key props)))
14408 (push (cons key string) props)))))))
14410 (when (memq which '(all standard))
14411 ;; Get the standard properties, like :PROP: ...
14412 (setq range (org-get-property-block beg end))
14413 (when range
14414 (goto-char (car range))
14415 (while (re-search-forward
14416 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14417 (cdr range) t)
14418 (setq key (org-match-string-no-properties 1)
14419 value (org-trim (or (org-match-string-no-properties 2) "")))
14420 (unless (member key excluded)
14421 (push (cons key (or value "")) props)))))
14422 (if clocksum
14423 (push (cons "CLOCKSUM"
14424 (org-columns-number-to-string (/ (float clocksum) 60.)
14425 'add_times))
14426 props))
14427 (if clocksumt
14428 (push (cons "CLOCKSUM_T"
14429 (org-columns-number-to-string (/ (float clocksumt) 60.)
14430 'add_times))
14431 props))
14432 (unless (assoc "CATEGORY" props)
14433 (push (cons "CATEGORY" (org-get-category)) props))
14434 (append sum-props (nreverse props)))))))
14436 (defun org-entry-get (pom property &optional inherit literal-nil)
14437 "Get value of PROPERTY for entry or content at point-or-marker POM.
14438 If INHERIT is non-nil and the entry does not have the property,
14439 then also check higher levels of the hierarchy.
14440 If INHERIT is the symbol `selective', use inheritance only if the setting
14441 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14442 If the property is present but empty, the return value is the empty string.
14443 If the property is not present at all, nil is returned.
14445 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14446 do not interpret it as the list atom nil. This is used for inheritance
14447 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14448 (org-with-point-at pom
14449 (if (and inherit (if (eq inherit 'selective)
14450 (org-property-inherit-p property)
14452 (org-entry-get-with-inheritance property literal-nil)
14453 (if (member property org-special-properties)
14454 ;; We need a special property. Use `org-entry-properties' to
14455 ;; retrieve it, but specify the wanted property
14456 (cdr (assoc property (org-entry-properties nil 'special property)))
14457 (let* ((range (org-get-property-block))
14458 (props (list (or (assoc property org-file-properties)
14459 (assoc property org-global-properties)
14460 (assoc property org-global-properties-fixed))))
14461 (ap (lambda (key)
14462 (when (re-search-forward
14463 (org-re-property key) (cdr range) t)
14464 (setq props
14465 (org-update-property-plist
14467 (if (match-end 1)
14468 (org-match-string-no-properties 1) "")
14469 props)))))
14470 val)
14471 (when (and range (goto-char (car range)))
14472 (funcall ap property)
14473 (goto-char (car range))
14474 (while (funcall ap (concat property "+")))
14475 (setq val (cdr (assoc property props)))
14476 (when val (if literal-nil val (org-not-nil val)))))))))
14478 (defun org-property-or-variable-value (var &optional inherit)
14479 "Check if there is a property fixing the value of VAR.
14480 If yes, return this value. If not, return the current value of the variable."
14481 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14482 (if (and prop (stringp prop) (string-match "\\S-" prop))
14483 (read prop)
14484 (symbol-value var))))
14486 (defun org-entry-delete (pom property)
14487 "Delete the property PROPERTY from entry at point-or-marker POM."
14488 (org-with-point-at pom
14489 (if (member property org-special-properties)
14490 nil ; cannot delete these properties.
14491 (let ((range (org-get-property-block)))
14492 (if (and range
14493 (goto-char (car range))
14494 (re-search-forward
14495 (org-re-property property)
14496 (cdr range) t))
14497 (progn
14498 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14500 nil)))))
14502 ;; Multi-values properties are properties that contain multiple values
14503 ;; These values are assumed to be single words, separated by whitespace.
14504 (defun org-entry-add-to-multivalued-property (pom property value)
14505 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14506 (let* ((old (org-entry-get pom property))
14507 (values (and old (org-split-string old "[ \t]"))))
14508 (setq value (org-entry-protect-space value))
14509 (unless (member value values)
14510 (setq values (cons value values))
14511 (org-entry-put pom property
14512 (mapconcat 'identity values " ")))))
14514 (defun org-entry-remove-from-multivalued-property (pom property value)
14515 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14516 (let* ((old (org-entry-get pom property))
14517 (values (and old (org-split-string old "[ \t]"))))
14518 (setq value (org-entry-protect-space value))
14519 (when (member value values)
14520 (setq values (delete value values))
14521 (org-entry-put pom property
14522 (mapconcat 'identity values " ")))))
14524 (defun org-entry-member-in-multivalued-property (pom property value)
14525 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14526 (let* ((old (org-entry-get pom property))
14527 (values (and old (org-split-string old "[ \t]"))))
14528 (setq value (org-entry-protect-space value))
14529 (member value values)))
14531 (defun org-entry-get-multivalued-property (pom property)
14532 "Return a list of values in a multivalued property."
14533 (let* ((value (org-entry-get pom property))
14534 (values (and value (org-split-string value "[ \t]"))))
14535 (mapcar 'org-entry-restore-space values)))
14537 (defun org-entry-put-multivalued-property (pom property &rest values)
14538 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14539 VALUES should be a list of strings. Spaces will be protected."
14540 (org-entry-put pom property
14541 (mapconcat 'org-entry-protect-space values " "))
14542 (let* ((value (org-entry-get pom property))
14543 (values (and value (org-split-string value "[ \t]"))))
14544 (mapcar 'org-entry-restore-space values)))
14546 (defun org-entry-protect-space (s)
14547 "Protect spaces and newline in string S."
14548 (while (string-match " " s)
14549 (setq s (replace-match "%20" t t s)))
14550 (while (string-match "\n" s)
14551 (setq s (replace-match "%0A" t t s)))
14554 (defun org-entry-restore-space (s)
14555 "Restore spaces and newline in string S."
14556 (while (string-match "%20" s)
14557 (setq s (replace-match " " t t s)))
14558 (while (string-match "%0A" s)
14559 (setq s (replace-match "\n" t t s)))
14562 (defvar org-entry-property-inherited-from (make-marker)
14563 "Marker pointing to the entry from where a property was inherited.
14564 Each call to `org-entry-get-with-inheritance' will set this marker to the
14565 location of the entry where the inheritance search matched. If there was
14566 no match, the marker will point nowhere.
14567 Note that also `org-entry-get' calls this function, if the INHERIT flag
14568 is set.")
14570 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14571 "Get PROPERTY of entry or content at point, search higher levels if needed.
14572 The search will stop at the first ancestor which has the property defined.
14573 If the value found is \"nil\", return nil to show that the property
14574 should be considered as undefined (this is the meaning of nil here).
14575 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14576 (move-marker org-entry-property-inherited-from nil)
14577 (let (tmp)
14578 (save-excursion
14579 (save-restriction
14580 (widen)
14581 (catch 'ex
14582 (while t
14583 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14584 (or (ignore-errors (org-back-to-heading t))
14585 (goto-char (point-min)))
14586 (move-marker org-entry-property-inherited-from (point))
14587 (throw 'ex tmp))
14588 (or (ignore-errors (org-up-heading-safe))
14589 (throw 'ex nil))))))
14590 (setq tmp (or tmp
14591 (cdr (assoc property org-file-properties))
14592 (cdr (assoc property org-global-properties))
14593 (cdr (assoc property org-global-properties-fixed))))
14594 (if literal-nil tmp (org-not-nil tmp))))
14596 (defvar org-property-changed-functions nil
14597 "Hook called when the value of a property has changed.
14598 Each hook function should accept two arguments, the name of the property
14599 and the new value.")
14601 (defun org-entry-put (pom property value)
14602 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14603 (org-with-point-at pom
14604 (org-back-to-heading t)
14605 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14606 range)
14607 (cond
14608 ((equal property "TODO")
14609 (when (and (stringp value) (string-match "\\S-" value)
14610 (not (member value org-todo-keywords-1)))
14611 (error "\"%s\" is not a valid TODO state" value))
14612 (if (or (not value)
14613 (not (string-match "\\S-" value)))
14614 (setq value 'none))
14615 (org-todo value)
14616 (org-set-tags nil 'align))
14617 ((equal property "PRIORITY")
14618 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14619 (string-to-char value) ?\ ))
14620 (org-set-tags nil 'align))
14621 ((equal property "SCHEDULED")
14622 (if (re-search-forward org-scheduled-time-regexp end t)
14623 (cond
14624 ((eq value 'earlier) (org-timestamp-change -1 'day))
14625 ((eq value 'later) (org-timestamp-change 1 'day))
14626 (t (call-interactively 'org-schedule)))
14627 (call-interactively 'org-schedule)))
14628 ((equal property "DEADLINE")
14629 (if (re-search-forward org-deadline-time-regexp end t)
14630 (cond
14631 ((eq value 'earlier) (org-timestamp-change -1 'day))
14632 ((eq value 'later) (org-timestamp-change 1 'day))
14633 (t (call-interactively 'org-deadline)))
14634 (call-interactively 'org-deadline)))
14635 ((member property org-special-properties)
14636 (error "The %s property can not yet be set with `org-entry-put'"
14637 property))
14638 (t ; a non-special property
14639 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14640 (setq range (org-get-property-block beg end 'force))
14641 (goto-char (car range))
14642 (if (re-search-forward
14643 (org-re-property-keyword property) (cdr range) t)
14644 (progn
14645 (delete-region (match-beginning 0) (match-end 0))
14646 (goto-char (match-beginning 0)))
14647 (goto-char (cdr range))
14648 (insert "\n")
14649 (backward-char 1)
14650 (org-indent-line))
14651 (insert ":" property ":")
14652 (and value (insert " " value))
14653 (org-indent-line)))))
14654 (run-hook-with-args 'org-property-changed-functions property value)))
14656 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14657 "Get all property keys in the current buffer.
14658 With INCLUDE-SPECIALS, also list the special properties that reflect things
14659 like tags and TODO state.
14660 With INCLUDE-DEFAULTS, also include properties that has special meaning
14661 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14662 and others.
14663 With INCLUDE-COLUMNS, also include property names given in COLUMN
14664 formats in the current buffer."
14665 (let (rtn range cfmt s p)
14666 (save-excursion
14667 (save-restriction
14668 (widen)
14669 (goto-char (point-min))
14670 (while (re-search-forward org-property-start-re nil t)
14671 (setq range (org-get-property-block))
14672 (goto-char (car range))
14673 (while (re-search-forward
14674 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14675 (cdr range) t)
14676 (add-to-list 'rtn (org-match-string-no-properties 1)))
14677 (outline-next-heading))))
14679 (when include-specials
14680 (setq rtn (append org-special-properties rtn)))
14682 (when include-defaults
14683 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14684 (add-to-list 'rtn org-effort-property))
14686 (when include-columns
14687 (save-excursion
14688 (save-restriction
14689 (widen)
14690 (goto-char (point-min))
14691 (while (re-search-forward
14692 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14693 nil t)
14694 (setq cfmt (match-string 2) s 0)
14695 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14696 cfmt s)
14697 (setq s (match-end 0)
14698 p (match-string 1 cfmt))
14699 (unless (or (equal p "ITEM")
14700 (member p org-special-properties))
14701 (add-to-list 'rtn (match-string 1 cfmt))))))))
14703 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14705 (defun org-property-values (key)
14706 "Return a list of all values of property KEY in the current buffer."
14707 (save-excursion
14708 (save-restriction
14709 (widen)
14710 (goto-char (point-min))
14711 (let ((re (org-re-property key))
14712 values)
14713 (while (re-search-forward re nil t)
14714 (add-to-list 'values (org-trim (match-string 1))))
14715 (delete "" values)))))
14717 (defun org-insert-property-drawer ()
14718 "Insert a property drawer into the current entry."
14719 (org-back-to-heading t)
14720 (looking-at org-outline-regexp)
14721 (let ((indent (if org-adapt-indentation
14722 (- (match-end 0) (match-beginning 0))
14724 (beg (point))
14725 (re (concat "^[ \t]*" org-keyword-time-regexp))
14726 end hiddenp)
14727 (outline-next-heading)
14728 (setq end (point))
14729 (goto-char beg)
14730 (while (re-search-forward re end t))
14731 (setq hiddenp (outline-invisible-p))
14732 (end-of-line 1)
14733 (and (equal (char-after) ?\n) (forward-char 1))
14734 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14735 (if (member (match-string 1) '("CLOCK:" ":END:"))
14736 ;; just skip this line
14737 (beginning-of-line 2)
14738 ;; Drawer start, find the end
14739 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14740 (beginning-of-line 1)))
14741 (org-skip-over-state-notes)
14742 (skip-chars-backward " \t\n\r")
14743 (if (eq (char-before) ?*) (forward-char 1))
14744 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14745 (beginning-of-line 0)
14746 (org-indent-to-column indent)
14747 (beginning-of-line 2)
14748 (org-indent-to-column indent)
14749 (beginning-of-line 0)
14750 (if hiddenp
14751 (save-excursion
14752 (org-back-to-heading t)
14753 (hide-entry))
14754 (org-flag-drawer t))))
14756 (defun org-insert-drawer (&optional arg drawer)
14757 "Insert a drawer at point.
14759 Optional argument DRAWER, when non-nil, is a string representing
14760 drawer's name. Otherwise, the user is prompted for a name.
14762 If a region is active, insert the drawer around that region
14763 instead.
14765 Point is left between drawer's boundaries."
14766 (interactive "P")
14767 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14768 "LOGBOOK"))
14769 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14770 ;; internally by Org. They are meant to be inserted
14771 ;; automatically.
14772 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14773 ;; Remove system drawers from list. Note: For some reason,
14774 ;; `org-completing-read' ignores the predicate while
14775 ;; `completing-read' handles it fine.
14776 (drawer (if arg "PROPERTIES"
14777 (or drawer
14778 (completing-read
14779 "Drawer: " org-drawers
14780 (lambda (d) (not (member d system-drawers))))))))
14781 (cond
14782 ;; With C-u, fall back on `org-insert-property-drawer'
14783 (arg (org-insert-property-drawer))
14784 ;; With an active region, insert a drawer at point.
14785 ((not (org-region-active-p))
14786 (progn
14787 (unless (bolp) (insert "\n"))
14788 (insert (format ":%s:\n\n:END:\n" drawer))
14789 (forward-line -2)))
14790 ;; Otherwise, insert the drawer at point
14792 (let ((rbeg (region-beginning))
14793 (rend (copy-marker (region-end))))
14794 (unwind-protect
14795 (progn
14796 (goto-char rbeg)
14797 (beginning-of-line)
14798 (when (save-excursion
14799 (re-search-forward org-outline-regexp-bol rend t))
14800 (error "Drawers cannot contain headlines"))
14801 ;; Position point at the beginning of the first
14802 ;; non-blank line in region. Insert drawer's opening
14803 ;; there, then indent it.
14804 (org-skip-whitespace)
14805 (beginning-of-line)
14806 (insert ":" drawer ":\n")
14807 (forward-line -1)
14808 (indent-for-tab-command)
14809 ;; Move point to the beginning of the first blank line
14810 ;; after the last non-blank line in region. Insert
14811 ;; drawer's closing, then indent it.
14812 (goto-char rend)
14813 (skip-chars-backward " \r\t\n")
14814 (insert "\n:END:")
14815 (deactivate-mark t)
14816 (indent-for-tab-command)
14817 (unless (eolp) (insert "\n")))
14818 ;; Clear marker, whatever the outcome of insertion is.
14819 (set-marker rend nil)))))))
14821 (defvar org-property-set-functions-alist nil
14822 "Property set function alist.
14823 Each entry should have the following format:
14825 (PROPERTY . READ-FUNCTION)
14827 The read function will be called with the same argument as
14828 `org-completing-read'.")
14830 (defun org-set-property-function (property)
14831 "Get the function that should be used to set PROPERTY.
14832 This is computed according to `org-property-set-functions-alist'."
14833 (or (cdr (assoc property org-property-set-functions-alist))
14834 'org-completing-read))
14836 (defun org-read-property-value (property)
14837 "Read PROPERTY value from user."
14838 (let* ((completion-ignore-case t)
14839 (allowed (org-property-get-allowed-values nil property 'table))
14840 (cur (org-entry-get nil property))
14841 (prompt (concat property " value"
14842 (if (and cur (string-match "\\S-" cur))
14843 (concat " [" cur "]") "") ": "))
14844 (set-function (org-set-property-function property))
14845 (val (if allowed
14846 (funcall set-function prompt allowed nil
14847 (not (get-text-property 0 'org-unrestricted
14848 (caar allowed))))
14849 (let (org-completion-use-ido org-completion-use-iswitchb)
14850 (funcall set-function prompt
14851 (mapcar 'list (org-property-values property))
14852 nil nil "" nil cur)))))
14853 (if (equal val "")
14855 val)))
14857 (defvar org-last-set-property nil)
14858 (defun org-read-property-name ()
14859 "Read a property name."
14860 (let* ((completion-ignore-case t)
14861 (keys (org-buffer-property-keys nil t t))
14862 (default-prop (or (save-excursion
14863 (save-match-data
14864 (beginning-of-line)
14865 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14866 (null (string= (match-string 1) "END"))
14867 (match-string 1))))
14868 org-last-set-property))
14869 (property (org-icompleting-read
14870 (concat "Property"
14871 (if default-prop (concat " [" default-prop "]") "")
14872 ": ")
14873 (mapcar 'list keys)
14874 nil nil nil nil
14875 default-prop
14877 (if (member property keys)
14878 property
14879 (or (cdr (assoc (downcase property)
14880 (mapcar (lambda (x) (cons (downcase x) x))
14881 keys)))
14882 property))))
14884 (defun org-set-property (property value)
14885 "In the current entry, set PROPERTY to VALUE.
14886 When called interactively, this will prompt for a property name, offering
14887 completion on existing and default properties. And then it will prompt
14888 for a value, offering completion either on allowed values (via an inherited
14889 xxx_ALL property) or on existing values in other instances of this property
14890 in the current file."
14891 (interactive (list nil nil))
14892 (let* ((property (or property (org-read-property-name)))
14893 (value (or value (org-read-property-value property)))
14894 (fn (cdr (assoc property org-properties-postprocess-alist))))
14895 (setq org-last-set-property property)
14896 ;; Possibly postprocess the inserted value:
14897 (when fn (setq value (funcall fn value)))
14898 (unless (equal (org-entry-get nil property) value)
14899 (org-entry-put nil property value))))
14901 (defun org-delete-property (property)
14902 "In the current entry, delete PROPERTY."
14903 (interactive
14904 (let* ((completion-ignore-case t)
14905 (prop (org-icompleting-read "Property: "
14906 (org-entry-properties nil 'standard))))
14907 (list prop)))
14908 (message "Property %s %s" property
14909 (if (org-entry-delete nil property)
14910 "deleted"
14911 "was not present in the entry")))
14913 (defun org-delete-property-globally (property)
14914 "Remove PROPERTY globally, from all entries."
14915 (interactive
14916 (let* ((completion-ignore-case t)
14917 (prop (org-icompleting-read
14918 "Globally remove property: "
14919 (mapcar 'list (org-buffer-property-keys)))))
14920 (list prop)))
14921 (save-excursion
14922 (save-restriction
14923 (widen)
14924 (goto-char (point-min))
14925 (let ((cnt 0))
14926 (while (re-search-forward
14927 (org-re-property property)
14928 nil t)
14929 (setq cnt (1+ cnt))
14930 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14931 (message "Property \"%s\" removed from %d entries" property cnt)))))
14933 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14935 (defun org-compute-property-at-point ()
14936 "Compute the property at point.
14937 This looks for an enclosing column format, extracts the operator and
14938 then applies it to the property in the column format's scope."
14939 (interactive)
14940 (unless (org-at-property-p)
14941 (error "Not at a property"))
14942 (let ((prop (org-match-string-no-properties 2)))
14943 (org-columns-get-format-and-top-level)
14944 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14945 (error "No operator defined for property %s" prop))
14946 (org-columns-compute prop)))
14948 (defvar org-property-allowed-value-functions nil
14949 "Hook for functions supplying allowed values for a specific property.
14950 The functions must take a single argument, the name of the property, and
14951 return a flat list of allowed values. If \":ETC\" is one of
14952 the values, this means that these values are intended as defaults for
14953 completion, but that other values should be allowed too.
14954 The functions must return nil if they are not responsible for this
14955 property.")
14957 (defun org-property-get-allowed-values (pom property &optional table)
14958 "Get allowed values for the property PROPERTY.
14959 When TABLE is non-nil, return an alist that can directly be used for
14960 completion."
14961 (let (vals)
14962 (cond
14963 ((equal property "TODO")
14964 (setq vals (org-with-point-at pom
14965 (append org-todo-keywords-1 '("")))))
14966 ((equal property "PRIORITY")
14967 (let ((n org-lowest-priority))
14968 (while (>= n org-highest-priority)
14969 (push (char-to-string n) vals)
14970 (setq n (1- n)))))
14971 ((member property org-special-properties))
14972 ((setq vals (run-hook-with-args-until-success
14973 'org-property-allowed-value-functions property)))
14975 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14976 (when (and vals (string-match "\\S-" vals))
14977 (setq vals (car (read-from-string (concat "(" vals ")"))))
14978 (setq vals (mapcar (lambda (x)
14979 (cond ((stringp x) x)
14980 ((numberp x) (number-to-string x))
14981 ((symbolp x) (symbol-name x))
14982 (t "???")))
14983 vals)))))
14984 (when (member ":ETC" vals)
14985 (setq vals (remove ":ETC" vals))
14986 (org-add-props (car vals) '(org-unrestricted t)))
14987 (if table (mapcar 'list vals) vals)))
14989 (defun org-property-previous-allowed-value (&optional previous)
14990 "Switch to the next allowed value for this property."
14991 (interactive)
14992 (org-property-next-allowed-value t))
14994 (defun org-property-next-allowed-value (&optional previous)
14995 "Switch to the next allowed value for this property."
14996 (interactive)
14997 (unless (org-at-property-p)
14998 (error "Not at a property"))
14999 (let* ((key (match-string 2))
15000 (value (match-string 3))
15001 (allowed (or (org-property-get-allowed-values (point) key)
15002 (and (member value '("[ ]" "[-]" "[X]"))
15003 '("[ ]" "[X]"))))
15004 nval)
15005 (unless allowed
15006 (error "Allowed values for this property have not been defined"))
15007 (if previous (setq allowed (reverse allowed)))
15008 (if (member value allowed)
15009 (setq nval (car (cdr (member value allowed)))))
15010 (setq nval (or nval (car allowed)))
15011 (if (equal nval value)
15012 (error "Only one allowed value for this property"))
15013 (org-at-property-p)
15014 (replace-match (concat " :" key ": " nval) t t)
15015 (org-indent-line)
15016 (beginning-of-line 1)
15017 (skip-chars-forward " \t")
15018 (run-hook-with-args 'org-property-changed-functions key nval)))
15020 (defun org-find-olp (path &optional this-buffer)
15021 "Return a marker pointing to the entry at outline path OLP.
15022 If anything goes wrong, throw an error.
15023 You can wrap this call to catch the error like this:
15025 (condition-case msg
15026 (org-mobile-locate-entry (match-string 4))
15027 (error (nth 1 msg)))
15029 The return value will then be either a string with the error message,
15030 or a marker if everything is OK.
15032 If THIS-BUFFER is set, the outline path does not contain a file,
15033 only headings."
15034 (let* ((file (if this-buffer buffer-file-name (pop path)))
15035 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15036 (level 1)
15037 (lmin 1)
15038 (lmax 1)
15039 limit re end found pos heading cnt flevel)
15040 (unless buffer (error "File not found :%s" file))
15041 (with-current-buffer buffer
15042 (save-excursion
15043 (save-restriction
15044 (widen)
15045 (setq limit (point-max))
15046 (goto-char (point-min))
15047 (while (setq heading (pop path))
15048 (setq re (format org-complex-heading-regexp-format
15049 (regexp-quote heading)))
15050 (setq cnt 0 pos (point))
15051 (while (re-search-forward re end t)
15052 (setq level (- (match-end 1) (match-beginning 1)))
15053 (if (and (>= level lmin) (<= level lmax))
15054 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15055 (when (= cnt 0) (error "Heading not found on level %d: %s"
15056 lmax heading))
15057 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15058 lmax heading))
15059 (goto-char found)
15060 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15061 (setq end (save-excursion (org-end-of-subtree t t))))
15062 (when (org-at-heading-p)
15063 (point-marker)))))))
15065 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15066 "Find node HEADING in BUFFER.
15067 Return a marker to the heading if it was found, or nil if not.
15068 If POS-ONLY is set, return just the position instead of a marker.
15070 The heading text must match exact, but it may have a TODO keyword,
15071 a priority cookie and tags in the standard locations."
15072 (with-current-buffer (or buffer (current-buffer))
15073 (save-excursion
15074 (save-restriction
15075 (widen)
15076 (goto-char (point-min))
15077 (let (case-fold-search)
15078 (if (re-search-forward
15079 (format org-complex-heading-regexp-format
15080 (regexp-quote heading)) nil t)
15081 (if pos-only
15082 (match-beginning 0)
15083 (move-marker (make-marker) (match-beginning 0)))))))))
15085 (defun org-find-exact-heading-in-directory (heading &optional dir)
15086 "Find Org node headline HEADING in all .org files in directory DIR.
15087 When the target headline is found, return a marker to this location."
15088 (let ((files (directory-files (or dir default-directory)
15089 nil "\\`[^.#].*\\.org\\'"))
15090 file visiting m buffer)
15091 (catch 'found
15092 (while (setq file (pop files))
15093 (message "trying %s" file)
15094 (setq visiting (org-find-base-buffer-visiting file))
15095 (setq buffer (or visiting (find-file-noselect file)))
15096 (setq m (org-find-exact-headline-in-buffer
15097 heading buffer))
15098 (when (and (not m) (not visiting)) (kill-buffer buffer))
15099 (and m (throw 'found m))))))
15101 (defun org-find-entry-with-id (ident)
15102 "Locate the entry that contains the ID property with exact value IDENT.
15103 IDENT can be a string, a symbol or a number, this function will search for
15104 the string representation of it.
15105 Return the position where this entry starts, or nil if there is no such entry."
15106 (interactive "sID: ")
15107 (let ((id (cond
15108 ((stringp ident) ident)
15109 ((symbol-name ident) (symbol-name ident))
15110 ((numberp ident) (number-to-string ident))
15111 (t (error "IDENT %s must be a string, symbol or number" ident))))
15112 (case-fold-search nil))
15113 (save-excursion
15114 (save-restriction
15115 (widen)
15116 (goto-char (point-min))
15117 (when (re-search-forward
15118 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15119 nil t)
15120 (org-back-to-heading t)
15121 (point))))))
15123 ;;;; Timestamps
15125 (defvar org-last-changed-timestamp nil)
15126 (defvar org-last-inserted-timestamp nil
15127 "The last time stamp inserted with `org-insert-time-stamp'.")
15128 (defvar org-time-was-given) ; dynamically scoped parameter
15129 (defvar org-end-time-was-given) ; dynamically scoped parameter
15130 (defvar org-ts-what) ; dynamically scoped parameter
15132 (defun org-time-stamp (arg &optional inactive)
15133 "Prompt for a date/time and insert a time stamp.
15134 If the user specifies a time like HH:MM or if this command is
15135 called with at least one prefix argument, the time stamp contains
15136 the date and the time. Otherwise, only the date is be included.
15138 All parts of a date not specified by the user is filled in from
15139 the current date/time. So if you just press return without
15140 typing anything, the time stamp will represent the current
15141 date/time.
15143 If there is already a timestamp at the cursor, it will be
15144 modified.
15146 With two universal prefix arguments, insert an active timestamp
15147 with the current time without prompting the user."
15148 (interactive "P")
15149 (let* ((ts nil)
15150 (default-time
15151 ;; Default time is either today, or, when entering a range,
15152 ;; the range start.
15153 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15154 (save-excursion
15155 (re-search-backward
15156 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15157 (- (point) 20) t)))
15158 (apply 'encode-time (org-parse-time-string (match-string 1)))
15159 (current-time)))
15160 (default-input (and ts (org-get-compact-tod ts)))
15161 (repeater (save-excursion
15162 (save-match-data
15163 (beginning-of-line)
15164 (when (re-search-forward
15165 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15166 (save-excursion (progn (end-of-line) (point))) t)
15167 (match-string 0)))))
15168 org-time-was-given org-end-time-was-given time)
15169 (cond
15170 ((and (org-at-timestamp-p t)
15171 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15172 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15173 (insert "--")
15174 (setq time (let ((this-command this-command))
15175 (org-read-date arg 'totime nil nil
15176 default-time default-input inactive)))
15177 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15178 ((org-at-timestamp-p t)
15179 (setq time (let ((this-command this-command))
15180 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15181 (when (org-at-timestamp-p t) ; just to get the match data
15182 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15183 (replace-match "")
15184 (setq org-last-changed-timestamp
15185 (org-insert-time-stamp
15186 time (or org-time-was-given arg)
15187 inactive nil nil (list org-end-time-was-given)))
15188 (when repeater (goto-char (1- (point))) (insert " " repeater)
15189 (setq org-last-changed-timestamp
15190 (concat (substring org-last-inserted-timestamp 0 -1)
15191 " " repeater ">"))))
15192 (message "Timestamp updated"))
15193 ((equal arg '(16))
15194 (org-insert-time-stamp (current-time) t))
15196 (setq time (let ((this-command this-command))
15197 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15198 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15199 nil nil (list org-end-time-was-given))))))
15201 ;; FIXME: can we use this for something else, like computing time differences?
15202 (defun org-get-compact-tod (s)
15203 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15204 (let* ((t1 (match-string 1 s))
15205 (h1 (string-to-number (match-string 2 s)))
15206 (m1 (string-to-number (match-string 3 s)))
15207 (t2 (and (match-end 4) (match-string 5 s)))
15208 (h2 (and t2 (string-to-number (match-string 6 s))))
15209 (m2 (and t2 (string-to-number (match-string 7 s))))
15210 dh dm)
15211 (if (not t2)
15213 (setq dh (- h2 h1) dm (- m2 m1))
15214 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15215 (concat t1 "+" (number-to-string dh)
15216 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15218 (defun org-time-stamp-inactive (&optional arg)
15219 "Insert an inactive time stamp.
15220 An inactive time stamp is enclosed in square brackets instead of angle
15221 brackets. It is inactive in the sense that it does not trigger agenda entries,
15222 does not link to the calendar and cannot be changed with the S-cursor keys.
15223 So these are more for recording a certain time/date."
15224 (interactive "P")
15225 (org-time-stamp arg 'inactive))
15227 (defvar org-date-ovl (make-overlay 1 1))
15228 (overlay-put org-date-ovl 'face 'org-date-selected)
15229 (org-detach-overlay org-date-ovl)
15231 (defvar org-ans1) ; dynamically scoped parameter
15232 (defvar org-ans2) ; dynamically scoped parameter
15234 (defvar org-plain-time-of-day-regexp) ; defined below
15236 (defvar org-overriding-default-time nil) ; dynamically scoped
15237 (defvar org-read-date-overlay nil)
15238 (defvar org-dcst nil) ; dynamically scoped
15239 (defvar org-read-date-history nil)
15240 (defvar org-read-date-final-answer nil)
15241 (defvar org-read-date-analyze-futurep nil)
15242 (defvar org-read-date-analyze-forced-year nil)
15243 (defvar org-read-date-inactive)
15245 (defun org-read-date (&optional org-with-time to-time from-string prompt
15246 default-time default-input inactive)
15247 "Read a date, possibly a time, and make things smooth for the user.
15248 The prompt will suggest to enter an ISO date, but you can also enter anything
15249 which will at least partially be understood by `parse-time-string'.
15250 Unrecognized parts of the date will default to the current day, month, year,
15251 hour and minute. If this command is called to replace a timestamp at point,
15252 or to enter the second timestamp of a range, the default time is taken
15253 from the existing stamp. Furthermore, the command prefers the future,
15254 so if you are giving a date where the year is not given, and the day-month
15255 combination is already past in the current year, it will assume you
15256 mean next year. For details, see the manual. A few examples:
15258 3-2-5 --> 2003-02-05
15259 feb 15 --> currentyear-02-15
15260 2/15 --> currentyear-02-15
15261 sep 12 9 --> 2009-09-12
15262 12:45 --> today 12:45
15263 22 sept 0:34 --> currentyear-09-22 0:34
15264 12 --> currentyear-currentmonth-12
15265 Fri --> nearest Friday (today or later)
15266 etc.
15268 Furthermore you can specify a relative date by giving, as the *first* thing
15269 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15270 change in days weeks, months, years.
15271 With a single plus or minus, the date is relative to today. With a double
15272 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15273 +4d --> four days from today
15274 +4 --> same as above
15275 +2w --> two weeks from today
15276 ++5 --> five days from default date
15278 The function understands only English month and weekday abbreviations.
15280 While prompting, a calendar is popped up - you can also select the
15281 date with the mouse (button 1). The calendar shows a period of three
15282 months. To scroll it to other months, use the keys `>' and `<'.
15283 If you don't like the calendar, turn it off with
15284 \(setq org-read-date-popup-calendar nil)
15286 With optional argument TO-TIME, the date will immediately be converted
15287 to an internal time.
15288 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15289 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15290 still enter a time, and this function will inform the calling routine
15291 about this change. The calling routine may then choose to change the
15292 format used to insert the time stamp into the buffer to include the time.
15293 With optional argument FROM-STRING, read from this string instead from
15294 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15295 the time/date that is used for everything that is not specified by the
15296 user."
15297 (require 'parse-time)
15298 (let* ((org-time-stamp-rounding-minutes
15299 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15300 (org-dcst org-display-custom-times)
15301 (ct (org-current-time))
15302 (org-def (or org-overriding-default-time default-time ct))
15303 (org-defdecode (decode-time org-def))
15304 (dummy (progn
15305 (when (< (nth 2 org-defdecode) org-extend-today-until)
15306 (setcar (nthcdr 2 org-defdecode) -1)
15307 (setcar (nthcdr 1 org-defdecode) 59)
15308 (setq org-def (apply 'encode-time org-defdecode)
15309 org-defdecode (decode-time org-def)))))
15310 (calendar-frame-setup nil)
15311 (calendar-setup nil)
15312 (calendar-move-hook nil)
15313 (calendar-view-diary-initially-flag nil)
15314 (calendar-view-holidays-initially-flag nil)
15315 (timestr (format-time-string
15316 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15317 (prompt (concat (if prompt (concat prompt " ") "")
15318 (format "Date+time [%s]: " timestr)))
15319 ans (org-ans0 "") org-ans1 org-ans2 final)
15321 (cond
15322 (from-string (setq ans from-string))
15323 (org-read-date-popup-calendar
15324 (save-excursion
15325 (save-window-excursion
15326 (calendar)
15327 (org-eval-in-calendar '(setq cursor-type nil) t)
15328 (unwind-protect
15329 (progn
15330 (calendar-forward-day (- (time-to-days org-def)
15331 (calendar-absolute-from-gregorian
15332 (calendar-current-date))))
15333 (org-eval-in-calendar nil t)
15334 (let* ((old-map (current-local-map))
15335 (map (copy-keymap calendar-mode-map))
15336 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15337 (org-defkey map (kbd "RET") 'org-calendar-select)
15338 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15339 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15340 (org-defkey minibuffer-local-map [(meta shift left)]
15341 (lambda () (interactive)
15342 (org-eval-in-calendar '(calendar-backward-month 1))))
15343 (org-defkey minibuffer-local-map [(meta shift right)]
15344 (lambda () (interactive)
15345 (org-eval-in-calendar '(calendar-forward-month 1))))
15346 (org-defkey minibuffer-local-map [(meta shift up)]
15347 (lambda () (interactive)
15348 (org-eval-in-calendar '(calendar-backward-year 1))))
15349 (org-defkey minibuffer-local-map [(meta shift down)]
15350 (lambda () (interactive)
15351 (org-eval-in-calendar '(calendar-forward-year 1))))
15352 (org-defkey minibuffer-local-map [?\e (shift left)]
15353 (lambda () (interactive)
15354 (org-eval-in-calendar '(calendar-backward-month 1))))
15355 (org-defkey minibuffer-local-map [?\e (shift right)]
15356 (lambda () (interactive)
15357 (org-eval-in-calendar '(calendar-forward-month 1))))
15358 (org-defkey minibuffer-local-map [?\e (shift up)]
15359 (lambda () (interactive)
15360 (org-eval-in-calendar '(calendar-backward-year 1))))
15361 (org-defkey minibuffer-local-map [?\e (shift down)]
15362 (lambda () (interactive)
15363 (org-eval-in-calendar '(calendar-forward-year 1))))
15364 (org-defkey minibuffer-local-map [(shift up)]
15365 (lambda () (interactive)
15366 (org-eval-in-calendar '(calendar-backward-week 1))))
15367 (org-defkey minibuffer-local-map [(shift down)]
15368 (lambda () (interactive)
15369 (org-eval-in-calendar '(calendar-forward-week 1))))
15370 (org-defkey minibuffer-local-map [(shift left)]
15371 (lambda () (interactive)
15372 (org-eval-in-calendar '(calendar-backward-day 1))))
15373 (org-defkey minibuffer-local-map [(shift right)]
15374 (lambda () (interactive)
15375 (org-eval-in-calendar '(calendar-forward-day 1))))
15376 (org-defkey minibuffer-local-map ">"
15377 (lambda () (interactive)
15378 (org-eval-in-calendar '(scroll-calendar-left 1))))
15379 (org-defkey minibuffer-local-map "<"
15380 (lambda () (interactive)
15381 (org-eval-in-calendar '(scroll-calendar-right 1))))
15382 (org-defkey minibuffer-local-map "\C-v"
15383 (lambda () (interactive)
15384 (org-eval-in-calendar
15385 '(calendar-scroll-left-three-months 1))))
15386 (org-defkey minibuffer-local-map "\M-v"
15387 (lambda () (interactive)
15388 (org-eval-in-calendar
15389 '(calendar-scroll-right-three-months 1))))
15390 (run-hooks 'org-read-date-minibuffer-setup-hook)
15391 (unwind-protect
15392 (progn
15393 (use-local-map map)
15394 (setq org-read-date-inactive inactive)
15395 (add-hook 'post-command-hook 'org-read-date-display)
15396 (setq org-ans0 (read-string prompt default-input
15397 'org-read-date-history nil))
15398 ;; org-ans0: from prompt
15399 ;; org-ans1: from mouse click
15400 ;; org-ans2: from calendar motion
15401 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15402 (remove-hook 'post-command-hook 'org-read-date-display)
15403 (use-local-map old-map)
15404 (when org-read-date-overlay
15405 (delete-overlay org-read-date-overlay)
15406 (setq org-read-date-overlay nil)))))
15407 (bury-buffer "*Calendar*")))))
15409 (t ; Naked prompt only
15410 (unwind-protect
15411 (setq ans (read-string prompt default-input
15412 'org-read-date-history timestr))
15413 (when org-read-date-overlay
15414 (delete-overlay org-read-date-overlay)
15415 (setq org-read-date-overlay nil)))))
15417 (setq final (org-read-date-analyze ans org-def org-defdecode))
15419 (when org-read-date-analyze-forced-year
15420 (message "Year was forced into %s"
15421 (if org-read-date-force-compatible-dates
15422 "compatible range (1970-2037)"
15423 "range representable on this machine"))
15424 (ding))
15426 ;; One round trip to get rid of 34th of August and stuff like that....
15427 (setq final (decode-time (apply 'encode-time final)))
15429 (setq org-read-date-final-answer ans)
15431 (if to-time
15432 (apply 'encode-time final)
15433 (if (and (boundp 'org-time-was-given) org-time-was-given)
15434 (format "%04d-%02d-%02d %02d:%02d"
15435 (nth 5 final) (nth 4 final) (nth 3 final)
15436 (nth 2 final) (nth 1 final))
15437 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15439 (defvar org-def)
15440 (defvar org-defdecode)
15441 (defvar org-with-time)
15442 (defun org-read-date-display ()
15443 "Display the current date prompt interpretation in the minibuffer."
15444 (when org-read-date-display-live
15445 (when org-read-date-overlay
15446 (delete-overlay org-read-date-overlay))
15447 (when (minibufferp (current-buffer))
15448 (save-excursion
15449 (end-of-line 1)
15450 (while (not (equal (buffer-substring
15451 (max (point-min) (- (point) 4)) (point))
15452 " "))
15453 (insert " ")))
15454 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15455 " " (or org-ans1 org-ans2)))
15456 (org-end-time-was-given nil)
15457 (f (org-read-date-analyze ans org-def org-defdecode))
15458 (fmts (if org-dcst
15459 org-time-stamp-custom-formats
15460 org-time-stamp-formats))
15461 (fmt (if (or org-with-time
15462 (and (boundp 'org-time-was-given) org-time-was-given))
15463 (cdr fmts)
15464 (car fmts)))
15465 (txt (format-time-string fmt (apply 'encode-time f)))
15466 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15467 (txt (concat "=> " txt)))
15468 (when (and org-end-time-was-given
15469 (string-match org-plain-time-of-day-regexp txt))
15470 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15471 org-end-time-was-given
15472 (substring txt (match-end 0)))))
15473 (when org-read-date-analyze-futurep
15474 (setq txt (concat txt " (=>F)")))
15475 (setq org-read-date-overlay
15476 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15477 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15479 (defun org-read-date-analyze (ans org-def org-defdecode)
15480 "Analyze the combined answer of the date prompt."
15481 ;; FIXME: cleanup and comment
15482 (let ((nowdecode (decode-time (current-time)))
15483 delta deltan deltaw deltadef year month day
15484 hour minute second wday pm h2 m2 tl wday1
15485 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15486 (setq org-read-date-analyze-futurep nil
15487 org-read-date-analyze-forced-year nil)
15488 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15489 (setq ans "+0"))
15491 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15492 (setq ans (replace-match "" t t ans)
15493 deltan (car delta)
15494 deltaw (nth 1 delta)
15495 deltadef (nth 2 delta)))
15497 ;; Check if there is an iso week date in there. If yes, store the
15498 ;; info and postpone interpreting it until the rest of the parsing
15499 ;; is done.
15500 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15501 (setq iso-year (if (match-end 1)
15502 (org-small-year-to-year
15503 (string-to-number (match-string 1 ans))))
15504 iso-weekday (if (match-end 3)
15505 (string-to-number (match-string 3 ans)))
15506 iso-week (string-to-number (match-string 2 ans)))
15507 (setq ans (replace-match "" t t ans)))
15509 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15510 (when (string-match
15511 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15512 (setq year (if (match-end 2)
15513 (string-to-number (match-string 2 ans))
15514 (progn (setq kill-year t)
15515 (string-to-number (format-time-string "%Y"))))
15516 month (string-to-number (match-string 3 ans))
15517 day (string-to-number (match-string 4 ans)))
15518 (if (< year 100) (setq year (+ 2000 year)))
15519 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15520 t nil ans)))
15522 ;; Help matching dotted european dates
15523 (when (string-match
15524 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15525 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15526 (setq kill-year t)
15527 (string-to-number (format-time-string "%Y")))
15528 day (string-to-number (match-string 1 ans))
15529 month (string-to-number (match-string 2 ans))
15530 ans (replace-match (format "%04d-%02d-%02d" year month day)
15531 t nil ans)))
15533 ;; Help matching american dates, like 5/30 or 5/30/7
15534 (when (string-match
15535 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15536 (setq year (if (match-end 4)
15537 (string-to-number (match-string 4 ans))
15538 (progn (setq kill-year t)
15539 (string-to-number (format-time-string "%Y"))))
15540 month (string-to-number (match-string 1 ans))
15541 day (string-to-number (match-string 2 ans)))
15542 (if (< year 100) (setq year (+ 2000 year)))
15543 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15544 t nil ans)))
15545 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15546 ;; If there is a time with am/pm, and *no* time without it, we convert
15547 ;; so that matching will be successful.
15548 (loop for i from 1 to 2 do ; twice, for end time as well
15549 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15550 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15551 (setq hour (string-to-number (match-string 1 ans))
15552 minute (if (match-end 3)
15553 (string-to-number (match-string 3 ans))
15555 pm (equal ?p
15556 (string-to-char (downcase (match-string 4 ans)))))
15557 (if (and (= hour 12) (not pm))
15558 (setq hour 0)
15559 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15560 (setq ans (replace-match (format "%02d:%02d" hour minute)
15561 t t ans))))
15563 ;; Check if a time range is given as a duration
15564 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15565 (setq hour (string-to-number (match-string 1 ans))
15566 h2 (+ hour (string-to-number (match-string 3 ans)))
15567 minute (string-to-number (match-string 2 ans))
15568 m2 (+ minute (if (match-end 5) (string-to-number
15569 (match-string 5 ans))0)))
15570 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15571 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15572 t t ans)))
15574 ;; Check if there is a time range
15575 (when (boundp 'org-end-time-was-given)
15576 (setq org-time-was-given nil)
15577 (when (and (string-match org-plain-time-of-day-regexp ans)
15578 (match-end 8))
15579 (setq org-end-time-was-given (match-string 8 ans))
15580 (setq ans (concat (substring ans 0 (match-beginning 7))
15581 (substring ans (match-end 7))))))
15583 (setq tl (parse-time-string ans)
15584 day (or (nth 3 tl) (nth 3 org-defdecode))
15585 month (or (nth 4 tl)
15586 (if (and org-read-date-prefer-future
15587 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15588 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15589 (nth 4 org-defdecode)))
15590 year (or (and (not kill-year) (nth 5 tl))
15591 (if (and org-read-date-prefer-future
15592 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15593 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15594 (nth 5 org-defdecode)))
15595 hour (or (nth 2 tl) (nth 2 org-defdecode))
15596 minute (or (nth 1 tl) (nth 1 org-defdecode))
15597 second (or (nth 0 tl) 0)
15598 wday (nth 6 tl))
15600 (when (and (eq org-read-date-prefer-future 'time)
15601 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15602 (equal day (nth 3 nowdecode))
15603 (equal month (nth 4 nowdecode))
15604 (equal year (nth 5 nowdecode))
15605 (nth 2 tl)
15606 (or (< (nth 2 tl) (nth 2 nowdecode))
15607 (and (= (nth 2 tl) (nth 2 nowdecode))
15608 (nth 1 tl)
15609 (< (nth 1 tl) (nth 1 nowdecode)))))
15610 (setq day (1+ day)
15611 futurep t))
15613 ;; Special date definitions below
15614 (cond
15615 (iso-week
15616 ;; There was an iso week
15617 (require 'cal-iso)
15618 (setq futurep nil)
15619 (setq year (or iso-year year)
15620 day (or iso-weekday wday 1)
15621 wday nil ; to make sure that the trigger below does not match
15622 iso-date (calendar-gregorian-from-absolute
15623 (calendar-absolute-from-iso
15624 (list iso-week day year))))
15625 ; FIXME: Should we also push ISO weeks into the future?
15626 ; (when (and org-read-date-prefer-future
15627 ; (not iso-year)
15628 ; (< (calendar-absolute-from-gregorian iso-date)
15629 ; (time-to-days (current-time))))
15630 ; (setq year (1+ year)
15631 ; iso-date (calendar-gregorian-from-absolute
15632 ; (calendar-absolute-from-iso
15633 ; (list iso-week day year)))))
15634 (setq month (car iso-date)
15635 year (nth 2 iso-date)
15636 day (nth 1 iso-date)))
15637 (deltan
15638 (setq futurep nil)
15639 (unless deltadef
15640 (let ((now (decode-time (current-time))))
15641 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15642 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15643 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15644 ((equal deltaw "m") (setq month (+ month deltan)))
15645 ((equal deltaw "y") (setq year (+ year deltan)))))
15646 ((and wday (not (nth 3 tl)))
15647 ;; Weekday was given, but no day, so pick that day in the week
15648 ;; on or after the derived date.
15649 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15650 (unless (equal wday wday1)
15651 (setq day (+ day (% (- wday wday1 -7) 7))))))
15652 (if (and (boundp 'org-time-was-given)
15653 (nth 2 tl))
15654 (setq org-time-was-given t))
15655 (if (< year 100) (setq year (+ 2000 year)))
15656 ;; Check of the date is representable
15657 (if org-read-date-force-compatible-dates
15658 (progn
15659 (if (< year 1970)
15660 (setq year 1970 org-read-date-analyze-forced-year t))
15661 (if (> year 2037)
15662 (setq year 2037 org-read-date-analyze-forced-year t)))
15663 (condition-case nil
15664 (ignore (encode-time second minute hour day month year))
15665 (error
15666 (setq year (nth 5 org-defdecode))
15667 (setq org-read-date-analyze-forced-year t))))
15668 (setq org-read-date-analyze-futurep futurep)
15669 (list second minute hour day month year)))
15671 (defvar parse-time-weekdays)
15672 (defun org-read-date-get-relative (s today default)
15673 "Check string S for special relative date string.
15674 TODAY and DEFAULT are internal times, for today and for a default.
15675 Return shift list (N what def-flag)
15676 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15677 N is the number of WHATs to shift.
15678 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15679 the DEFAULT date rather than TODAY."
15680 (require 'parse-time)
15681 (when (and
15682 (string-match
15683 (concat
15684 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15685 "\\([0-9]+\\)?"
15686 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15687 "\\([ \t]\\|$\\)") s)
15688 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15689 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15690 (string-to-char (substring (match-string 1 s) -1))
15691 ?+))
15692 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15693 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15694 (what (if (match-end 3) (match-string 3 s) "d"))
15695 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15696 (date (if rel default today))
15697 (wday (nth 6 (decode-time date)))
15698 delta)
15699 (if wday1
15700 (progn
15701 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15702 (if (= dir ?-) (setq delta (- delta 7)))
15703 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15704 (list delta "d" rel))
15705 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15707 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15708 "Turn a user-specified date into the internal representation.
15709 The internal representation needed by the calendar is (month day year).
15710 This is a wrapper to handle the brain-dead convention in calendar that
15711 user function argument order change dependent on argument order."
15712 (if (boundp 'calendar-date-style)
15713 (cond
15714 ((eq calendar-date-style 'american)
15715 (list arg1 arg2 arg3))
15716 ((eq calendar-date-style 'european)
15717 (list arg2 arg1 arg3))
15718 ((eq calendar-date-style 'iso)
15719 (list arg2 arg3 arg1)))
15720 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15721 (if (org-bound-and-true-p european-calendar-style)
15722 (list arg2 arg1 arg3)
15723 (list arg1 arg2 arg3)))))
15725 (defun org-eval-in-calendar (form &optional keepdate)
15726 "Eval FORM in the calendar window and return to current window.
15727 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15728 otherwise stick to the current value of `org-ans2'."
15729 (let ((sf (selected-frame))
15730 (sw (selected-window)))
15731 (select-window (get-buffer-window "*Calendar*" t))
15732 (eval form)
15733 (when (and (not keepdate) (calendar-cursor-to-date))
15734 (let* ((date (calendar-cursor-to-date))
15735 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15736 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15737 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15738 (select-window sw)
15739 (org-select-frame-set-input-focus sf)))
15741 (defun org-calendar-select ()
15742 "Return to `org-read-date' with the date currently selected.
15743 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15744 (interactive)
15745 (when (calendar-cursor-to-date)
15746 (let* ((date (calendar-cursor-to-date))
15747 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15748 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15749 (if (active-minibuffer-window) (exit-minibuffer))))
15751 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15752 "Insert a date stamp for the date given by the internal TIME.
15753 WITH-HM means use the stamp format that includes the time of the day.
15754 INACTIVE means use square brackets instead of angular ones, so that the
15755 stamp will not contribute to the agenda.
15756 PRE and POST are optional strings to be inserted before and after the
15757 stamp.
15758 The command returns the inserted time stamp."
15759 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15760 stamp)
15761 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15762 (insert-before-markers (or pre ""))
15763 (when (listp extra)
15764 (setq extra (car extra))
15765 (if (and (stringp extra)
15766 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15767 (setq extra (format "-%02d:%02d"
15768 (string-to-number (match-string 1 extra))
15769 (string-to-number (match-string 2 extra))))
15770 (setq extra nil)))
15771 (when extra
15772 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15773 (insert-before-markers (setq stamp (format-time-string fmt time)))
15774 (insert-before-markers (or post ""))
15775 (setq org-last-inserted-timestamp stamp)))
15777 (defun org-toggle-time-stamp-overlays ()
15778 "Toggle the use of custom time stamp formats."
15779 (interactive)
15780 (setq org-display-custom-times (not org-display-custom-times))
15781 (unless org-display-custom-times
15782 (let ((p (point-min)) (bmp (buffer-modified-p)))
15783 (while (setq p (next-single-property-change p 'display))
15784 (if (and (get-text-property p 'display)
15785 (eq (get-text-property p 'face) 'org-date))
15786 (remove-text-properties
15787 p (setq p (next-single-property-change p 'display))
15788 '(display t))))
15789 (set-buffer-modified-p bmp)))
15790 (if (featurep 'xemacs)
15791 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15792 (org-restart-font-lock)
15793 (setq org-table-may-need-update t)
15794 (if org-display-custom-times
15795 (message "Time stamps are overlaid with custom format")
15796 (message "Time stamp overlays removed")))
15798 (defun org-display-custom-time (beg end)
15799 "Overlay modified time stamp format over timestamp between BEG and END."
15800 (let* ((ts (buffer-substring beg end))
15801 t1 w1 with-hm tf time str w2 (off 0))
15802 (save-match-data
15803 (setq t1 (org-parse-time-string ts t))
15804 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15805 (setq off (- (match-end 0) (match-beginning 0)))))
15806 (setq end (- end off))
15807 (setq w1 (- end beg)
15808 with-hm (and (nth 1 t1) (nth 2 t1))
15809 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15810 time (org-fix-decoded-time t1)
15811 str (org-add-props
15812 (format-time-string
15813 (substring tf 1 -1) (apply 'encode-time time))
15814 nil 'mouse-face 'highlight)
15815 w2 (length str))
15816 (if (not (= w2 w1))
15817 (add-text-properties (1+ beg) (+ 2 beg)
15818 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15819 (if (featurep 'xemacs)
15820 (progn
15821 (put-text-property beg end 'invisible t)
15822 (put-text-property beg end 'end-glyph (make-glyph str)))
15823 (put-text-property beg end 'display str))))
15825 (defun org-translate-time (string)
15826 "Translate all timestamps in STRING to custom format.
15827 But do this only if the variable `org-display-custom-times' is set."
15828 (when org-display-custom-times
15829 (save-match-data
15830 (let* ((start 0)
15831 (re org-ts-regexp-both)
15832 t1 with-hm inactive tf time str beg end)
15833 (while (setq start (string-match re string start))
15834 (setq beg (match-beginning 0)
15835 end (match-end 0)
15836 t1 (save-match-data
15837 (org-parse-time-string (substring string beg end) t))
15838 with-hm (and (nth 1 t1) (nth 2 t1))
15839 inactive (equal (substring string beg (1+ beg)) "[")
15840 tf (funcall (if with-hm 'cdr 'car)
15841 org-time-stamp-custom-formats)
15842 time (org-fix-decoded-time t1)
15843 str (format-time-string
15844 (concat
15845 (if inactive "[" "<") (substring tf 1 -1)
15846 (if inactive "]" ">"))
15847 (apply 'encode-time time))
15848 string (replace-match str t t string)
15849 start (+ start (length str)))))))
15850 string)
15852 (defun org-fix-decoded-time (time)
15853 "Set 0 instead of nil for the first 6 elements of time.
15854 Don't touch the rest."
15855 (let ((n 0))
15856 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15858 (defun org-days-to-time (timestamp-string)
15859 "Difference between TIMESTAMP-STRING and now in days."
15860 (- (time-to-days (org-time-string-to-time timestamp-string))
15861 (time-to-days (current-time))))
15863 (defun org-deadline-close (timestamp-string &optional ndays)
15864 "Is the time in TIMESTAMP-STRING close to the current date?"
15865 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15866 (and (< (org-days-to-time timestamp-string) ndays)
15867 (not (org-entry-is-done-p))))
15869 (defun org-get-wdays (ts)
15870 "Get the deadline lead time appropriate for timestring TS."
15871 (cond
15872 ((<= org-deadline-warning-days 0)
15873 ;; 0 or negative, enforce this value no matter what
15874 (- org-deadline-warning-days))
15875 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15876 ;; lead time is specified.
15877 (floor (* (string-to-number (match-string 1 ts))
15878 (cdr (assoc (match-string 2 ts)
15879 '(("d" . 1) ("w" . 7)
15880 ("m" . 30.4) ("y" . 365.25)))))))
15881 ;; go for the default.
15882 (t org-deadline-warning-days)))
15884 (defun org-calendar-select-mouse (ev)
15885 "Return to `org-read-date' with the date currently selected.
15886 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15887 (interactive "e")
15888 (mouse-set-point ev)
15889 (when (calendar-cursor-to-date)
15890 (let* ((date (calendar-cursor-to-date))
15891 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15892 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15893 (if (active-minibuffer-window) (exit-minibuffer))))
15895 (defun org-check-deadlines (ndays)
15896 "Check if there are any deadlines due or past due.
15897 A deadline is considered due if it happens within `org-deadline-warning-days'
15898 days from today's date. If the deadline appears in an entry marked DONE,
15899 it is not shown. The prefix arg NDAYS can be used to test that many
15900 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15901 (interactive "P")
15902 (let* ((org-warn-days
15903 (cond
15904 ((equal ndays '(4)) 100000)
15905 (ndays (prefix-numeric-value ndays))
15906 (t (abs org-deadline-warning-days))))
15907 (case-fold-search nil)
15908 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15909 (callback
15910 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15912 (message "%d deadlines past-due or due within %d days"
15913 (org-occur regexp nil callback)
15914 org-warn-days)))
15916 (defsubst org-re-timestamp (type)
15917 "Return a regexp for timestamp TYPE.
15918 Allowed values for TYPE are:
15920 all: all timestamps
15921 active: only active timestamps (<...>)
15922 inactive: only inactive timestamps ([...])
15923 scheduled: only scheduled timestamps
15924 deadline: only deadline timestamps
15926 When TYPE is nil, fall back on returning a regexp that matches
15927 both scheduled and deadline timestamps."
15928 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15929 ((eq type 'active) org-ts-regexp)
15930 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15931 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15932 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15933 ((eq type 'scheduled-or-deadline)
15934 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15936 (defun org-check-before-date (date)
15937 "Check if there are deadlines or scheduled entries before DATE."
15938 (interactive (list (org-read-date)))
15939 (let ((case-fold-search nil)
15940 (regexp (org-re-timestamp org-ts-type))
15941 (callback
15942 (lambda () (time-less-p
15943 (org-time-string-to-time (match-string 1))
15944 (org-time-string-to-time date)))))
15945 (message "%d entries before %s"
15946 (org-occur regexp nil callback) date)))
15948 (defun org-check-after-date (date)
15949 "Check if there are deadlines or scheduled entries after DATE."
15950 (interactive (list (org-read-date)))
15951 (let ((case-fold-search nil)
15952 (regexp (org-re-timestamp org-ts-type))
15953 (callback
15954 (lambda () (not
15955 (time-less-p
15956 (org-time-string-to-time (match-string 1))
15957 (org-time-string-to-time date))))))
15958 (message "%d entries after %s"
15959 (org-occur regexp nil callback) date)))
15961 (defun org-check-dates-range (start-date end-date)
15962 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15963 (interactive (list (org-read-date nil nil nil "Range starts")
15964 (org-read-date nil nil nil "Range end")))
15965 (let ((case-fold-search nil)
15966 (regexp (org-re-timestamp org-ts-type))
15967 (callback
15968 (lambda ()
15969 (let ((match (match-string 1)))
15970 (and
15971 (not (time-less-p
15972 (org-time-string-to-time match)
15973 (org-time-string-to-time start-date)))
15974 (time-less-p
15975 (org-time-string-to-time match)
15976 (org-time-string-to-time end-date)))))))
15977 (message "%d entries between %s and %s"
15978 (org-occur regexp nil callback) start-date end-date)))
15980 (defun org-evaluate-time-range (&optional to-buffer)
15981 "Evaluate a time range by computing the difference between start and end.
15982 Normally the result is just printed in the echo area, but with prefix arg
15983 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15984 If the time range is actually in a table, the result is inserted into the
15985 next column.
15986 For time difference computation, a year is assumed to be exactly 365
15987 days in order to avoid rounding problems."
15988 (interactive "P")
15990 (org-clock-update-time-maybe)
15991 (save-excursion
15992 (unless (org-at-date-range-p t)
15993 (goto-char (point-at-bol))
15994 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15995 (if (not (org-at-date-range-p t))
15996 (error "Not at a time-stamp range, and none found in current line")))
15997 (let* ((ts1 (match-string 1))
15998 (ts2 (match-string 2))
15999 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16000 (match-end (match-end 0))
16001 (time1 (org-time-string-to-time ts1))
16002 (time2 (org-time-string-to-time ts2))
16003 (t1 (org-float-time time1))
16004 (t2 (org-float-time time2))
16005 (diff (abs (- t2 t1)))
16006 (negative (< (- t2 t1) 0))
16007 ;; (ys (floor (* 365 24 60 60)))
16008 (ds (* 24 60 60))
16009 (hs (* 60 60))
16010 (fy "%dy %dd %02d:%02d")
16011 (fy1 "%dy %dd")
16012 (fd "%dd %02d:%02d")
16013 (fd1 "%dd")
16014 (fh "%02d:%02d")
16015 y d h m align)
16016 (if havetime
16017 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16019 d (floor (/ diff ds)) diff (mod diff ds)
16020 h (floor (/ diff hs)) diff (mod diff hs)
16021 m (floor (/ diff 60)))
16022 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16024 d (floor (+ (/ diff ds) 0.5))
16025 h 0 m 0))
16026 (if (not to-buffer)
16027 (message "%s" (org-make-tdiff-string y d h m))
16028 (if (org-at-table-p)
16029 (progn
16030 (goto-char match-end)
16031 (setq align t)
16032 (and (looking-at " *|") (goto-char (match-end 0))))
16033 (goto-char match-end))
16034 (if (looking-at
16035 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16036 (replace-match ""))
16037 (if negative (insert " -"))
16038 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16039 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16040 (insert " " (format fh h m))))
16041 (if align (org-table-align))
16042 (message "Time difference inserted")))))
16044 (defun org-make-tdiff-string (y d h m)
16045 (let ((fmt "")
16046 (l nil))
16047 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16048 l (push y l)))
16049 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16050 l (push d l)))
16051 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16052 l (push h l)))
16053 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16054 l (push m l)))
16055 (apply 'format fmt (nreverse l))))
16057 (defun org-time-string-to-time (s &optional buffer pos)
16058 "Convert a timestamp string into internal time."
16059 (condition-case errdata
16060 (apply 'encode-time (org-parse-time-string s))
16061 (error (error "Bad timestamp `%s'%s\nError was: %s"
16062 s (if (not (and buffer pos))
16064 (format " at %d in buffer `%s'" pos buffer))
16065 (cdr errdata)))))
16067 (defun org-time-string-to-seconds (s)
16068 "Convert a timestamp string to a number of seconds."
16069 (org-float-time (org-time-string-to-time s)))
16071 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16072 "Convert a time stamp to an absolute day number.
16073 If there is a specifier for a cyclic time stamp, get the closest date to
16074 DAYNR.
16075 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16076 The variable date is bound by the calendar when this is called."
16077 (cond
16078 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16079 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16080 daynr
16081 (+ daynr 1000)))
16082 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16083 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16084 (time-to-days (current-time))) (match-string 0 s)
16085 prefer show-all))
16086 (t (time-to-days
16087 (condition-case errdata
16088 (apply 'encode-time (org-parse-time-string s))
16089 (error (error "Bad timestamp `%s'%s\nError was: %s"
16090 s (if (not (and buffer pos))
16092 (format " at %d in buffer `%s'" pos buffer))
16093 (cdr errdata))))))))
16095 (defun org-days-to-iso-week (days)
16096 "Return the iso week number."
16097 (require 'cal-iso)
16098 (car (calendar-iso-from-absolute days)))
16100 (defun org-small-year-to-year (year)
16101 "Convert 2-digit years into 4-digit years.
16102 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16103 The year 2000 cannot be abbreviated. Any year larger than 99
16104 is returned unchanged."
16105 (if (< year 38)
16106 (setq year (+ 2000 year))
16107 (if (< year 100)
16108 (setq year (+ 1900 year))))
16109 year)
16111 (defun org-time-from-absolute (d)
16112 "Return the time corresponding to date D.
16113 D may be an absolute day number, or a calendar-type list (month day year)."
16114 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16115 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16117 (defun org-calendar-holiday ()
16118 "List of holidays, for Diary display in Org-mode."
16119 (require 'holidays)
16120 (let ((hl (funcall
16121 (if (fboundp 'calendar-check-holidays)
16122 'calendar-check-holidays 'check-calendar-holidays) date)))
16123 (if hl (mapconcat 'identity hl "; "))))
16125 (defun org-diary-sexp-entry (sexp entry date)
16126 "Process a SEXP diary ENTRY for DATE."
16127 (require 'diary-lib)
16128 (let ((result (if calendar-debug-sexp
16129 (let ((stack-trace-on-error t))
16130 (eval (car (read-from-string sexp))))
16131 (condition-case nil
16132 (eval (car (read-from-string sexp)))
16133 (error
16134 (beep)
16135 (message "Bad sexp at line %d in %s: %s"
16136 (org-current-line)
16137 (buffer-file-name) sexp)
16138 (sleep-for 2))))))
16139 (cond ((stringp result) (split-string result "; "))
16140 ((and (consp result)
16141 (not (consp (cdr result)))
16142 (stringp (cdr result))) (cdr result))
16143 ((and (consp result)
16144 (stringp (car result))) result)
16145 (result entry))))
16147 (defun org-diary-to-ical-string (frombuf)
16148 "Get iCalendar entries from diary entries in buffer FROMBUF.
16149 This uses the icalendar.el library."
16150 (let* ((tmpdir (if (featurep 'xemacs)
16151 (temp-directory)
16152 temporary-file-directory))
16153 (tmpfile (make-temp-name
16154 (expand-file-name "orgics" tmpdir)))
16155 buf rtn b e)
16156 (with-current-buffer frombuf
16157 (icalendar-export-region (point-min) (point-max) tmpfile)
16158 (setq buf (find-buffer-visiting tmpfile))
16159 (set-buffer buf)
16160 (goto-char (point-min))
16161 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16162 (setq b (match-beginning 0)))
16163 (goto-char (point-max))
16164 (if (re-search-backward "^END:VEVENT" nil t)
16165 (setq e (match-end 0)))
16166 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16167 (kill-buffer buf)
16168 (delete-file tmpfile)
16169 rtn))
16171 (defun org-closest-date (start current change prefer show-all)
16172 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16173 When PREFER is `past', return a date that is either CURRENT or past.
16174 When PREFER is `future', return a date that is either CURRENT or future.
16175 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16176 ;; Make the proper lists from the dates
16177 (catch 'exit
16178 (let ((a1 '(("h" . hour)
16179 ("d" . day)
16180 ("w" . week)
16181 ("m" . month)
16182 ("y" . year)))
16183 (shour (nth 2 (org-parse-time-string start)))
16184 dn dw sday cday n1 n2 n0
16185 d m y y1 y2 date1 date2 nmonths nm ny m2)
16187 (setq start (org-date-to-gregorian start)
16188 current (org-date-to-gregorian
16189 (if show-all
16190 current
16191 (time-to-days (current-time))))
16192 sday (calendar-absolute-from-gregorian start)
16193 cday (calendar-absolute-from-gregorian current))
16195 (if (<= cday sday) (throw 'exit sday))
16197 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16198 (setq dn (string-to-number (match-string 1 change))
16199 dw (cdr (assoc (match-string 2 change) a1)))
16200 (error "Invalid change specifier: %s" change))
16201 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16202 (cond
16203 ((eq dw 'hour)
16204 (let ((missing-hours
16205 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16206 dn)))
16207 (setq n1 (if (zerop missing-hours) cday
16208 (- cday (1+ (floor (/ missing-hours 24)))))
16209 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16210 ((eq dw 'day)
16211 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16212 n2 (+ n1 dn)))
16213 ((eq dw 'year)
16214 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16215 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16216 (setq date1 (list m d y1)
16217 n1 (calendar-absolute-from-gregorian date1)
16218 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16219 n2 (calendar-absolute-from-gregorian date2)))
16220 ((eq dw 'month)
16221 ;; approx number of month between the two dates
16222 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16223 ;; How often does dn fit in there?
16224 (setq d (nth 1 start) m (car start) y (nth 2 start)
16225 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16226 m (+ m nm)
16227 ny (floor (/ m 12))
16228 y (+ y ny)
16229 m (- m (* ny 12)))
16230 (while (> m 12) (setq m (- m 12) y (1+ y)))
16231 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16232 (setq m2 (+ m dn) y2 y)
16233 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16234 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16235 (while (<= n2 cday)
16236 (setq n1 n2 m m2 y y2)
16237 (setq m2 (+ m dn) y2 y)
16238 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16239 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16240 ;; Make sure n1 is the earlier date
16241 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16242 (if show-all
16243 (cond
16244 ((eq prefer 'past) (if (= cday n2) n2 n1))
16245 ((eq prefer 'future) (if (= cday n1) n1 n2))
16246 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16247 (cond
16248 ((eq prefer 'past) (if (= cday n2) n2 n1))
16249 ((eq prefer 'future) (if (= cday n1) n1 n2))
16250 (t (if (= cday n1) n1 n2)))))))
16252 (defun org-date-to-gregorian (date)
16253 "Turn any specification of DATE into a Gregorian date for the calendar."
16254 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16255 ((and (listp date) (= (length date) 3)) date)
16256 ((stringp date)
16257 (setq date (org-parse-time-string date))
16258 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16259 ((listp date)
16260 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16262 (defun org-parse-time-string (s &optional nodefault)
16263 "Parse the standard Org-mode time string.
16264 This should be a lot faster than the normal `parse-time-string'.
16265 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16266 hour and minute fields will be nil if not given."
16267 (if (string-match org-ts-regexp0 s)
16268 (list 0
16269 (if (or (match-beginning 8) (not nodefault))
16270 (string-to-number (or (match-string 8 s) "0")))
16271 (if (or (match-beginning 7) (not nodefault))
16272 (string-to-number (or (match-string 7 s) "0")))
16273 (string-to-number (match-string 4 s))
16274 (string-to-number (match-string 3 s))
16275 (string-to-number (match-string 2 s))
16276 nil nil nil)
16277 (error "Not a standard Org-mode time string: %s" s)))
16279 (defun org-timestamp-up (&optional arg)
16280 "Increase the date item at the cursor by one.
16281 If the cursor is on the year, change the year. If it is on the month,
16282 the day or the time, change that.
16283 With prefix ARG, change by that many units."
16284 (interactive "p")
16285 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16287 (defun org-timestamp-down (&optional arg)
16288 "Decrease the date item at the cursor by one.
16289 If the cursor is on the year, change the year. If it is on the month,
16290 the day or the time, change that.
16291 With prefix ARG, change by that many units."
16292 (interactive "p")
16293 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16295 (defun org-timestamp-up-day (&optional arg)
16296 "Increase the date in the time stamp by one day.
16297 With prefix ARG, change that many days."
16298 (interactive "p")
16299 (if (and (not (org-at-timestamp-p t))
16300 (org-at-heading-p))
16301 (org-todo 'up)
16302 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16304 (defun org-timestamp-down-day (&optional arg)
16305 "Decrease the date in the time stamp by one day.
16306 With prefix ARG, change that many days."
16307 (interactive "p")
16308 (if (and (not (org-at-timestamp-p t))
16309 (org-at-heading-p))
16310 (org-todo 'down)
16311 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16313 (defun org-at-timestamp-p (&optional inactive-ok)
16314 "Determine if the cursor is in or at a timestamp."
16315 (interactive)
16316 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16317 (pos (point))
16318 (ans (or (looking-at tsr)
16319 (save-excursion
16320 (skip-chars-backward "^[<\n\r\t")
16321 (if (> (point) (point-min)) (backward-char 1))
16322 (and (looking-at tsr)
16323 (> (- (match-end 0) pos) -1))))))
16324 (and ans
16325 (boundp 'org-ts-what)
16326 (setq org-ts-what
16327 (cond
16328 ((= pos (match-beginning 0)) 'bracket)
16329 ;; Point is considered to be "on the bracket" whether
16330 ;; it's really on it or right after it.
16331 ((= pos (1- (match-end 0))) 'bracket)
16332 ((= pos (match-end 0)) 'after)
16333 ((org-pos-in-match-range pos 2) 'year)
16334 ((org-pos-in-match-range pos 3) 'month)
16335 ((org-pos-in-match-range pos 7) 'hour)
16336 ((org-pos-in-match-range pos 8) 'minute)
16337 ((or (org-pos-in-match-range pos 4)
16338 (org-pos-in-match-range pos 5)) 'day)
16339 ((and (> pos (or (match-end 8) (match-end 5)))
16340 (< pos (match-end 0)))
16341 (- pos (or (match-end 8) (match-end 5))))
16342 (t 'day))))
16343 ans))
16345 (defun org-toggle-timestamp-type ()
16346 "Toggle the type (<active> or [inactive]) of a time stamp."
16347 (interactive)
16348 (when (org-at-timestamp-p t)
16349 (let ((beg (match-beginning 0)) (end (match-end 0))
16350 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16351 (save-excursion
16352 (goto-char beg)
16353 (while (re-search-forward "[][<>]" end t)
16354 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16355 t t)))
16356 (message "Timestamp is now %sactive"
16357 (if (equal (char-after beg) ?<) "" "in")))))
16359 (defvar org-clock-history) ; defined in org-clock.el
16360 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16361 (defun org-timestamp-change (n &optional what updown)
16362 "Change the date in the time stamp at point.
16363 The date will be changed by N times WHAT. WHAT can be `day', `month',
16364 `year', `minute', `second'. If WHAT is not given, the cursor position
16365 in the timestamp determines what will be changed."
16366 (let ((origin (point)) origin-cat
16367 with-hm inactive
16368 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16369 org-ts-what
16370 extra rem
16371 ts time time0 fixnext clrgx)
16372 (if (not (org-at-timestamp-p t))
16373 (error "Not at a timestamp"))
16374 (if (and (not what) (eq org-ts-what 'bracket))
16375 (org-toggle-timestamp-type)
16376 ;; Point isn't on brackets. Remember the part of the time-stamp
16377 ;; the point was in. Indeed, size of time-stamps may change,
16378 ;; but point must be kept in the same category nonetheless.
16379 (setq origin-cat org-ts-what)
16380 (if (and (not what) (not (eq org-ts-what 'day))
16381 org-display-custom-times
16382 (get-text-property (point) 'display)
16383 (not (get-text-property (1- (point)) 'display)))
16384 (setq org-ts-what 'day))
16385 (setq org-ts-what (or what org-ts-what)
16386 inactive (= (char-after (match-beginning 0)) ?\[)
16387 ts (match-string 0))
16388 (replace-match "")
16389 (if (string-match
16390 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16392 (setq extra (match-string 1 ts)))
16393 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16394 (setq with-hm t))
16395 (setq time0 (org-parse-time-string ts))
16396 (when (and updown
16397 (eq org-ts-what 'minute)
16398 (not current-prefix-arg))
16399 ;; This looks like s-up and s-down. Change by one rounding step.
16400 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16401 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16402 (setcar (cdr time0) (+ (nth 1 time0)
16403 (if (> n 0) (- rem) (- dm rem))))))
16404 (setq time
16405 (encode-time (or (car time0) 0)
16406 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16407 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16408 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16409 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16410 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16411 (nthcdr 6 time0)))
16412 (when (and (member org-ts-what '(hour minute))
16413 extra
16414 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16415 (setq extra (org-modify-ts-extra
16416 extra
16417 (if (eq org-ts-what 'hour) 2 5)
16418 n dm)))
16419 (when (integerp org-ts-what)
16420 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16421 (if (eq what 'calendar)
16422 (let ((cal-date (org-get-date-from-calendar)))
16423 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16424 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16425 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16426 (setcar time0 (or (car time0) 0))
16427 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16428 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16429 (setq time (apply 'encode-time time0))))
16430 ;; Insert the new time-stamp, and ensure point stays in the same
16431 ;; category as before (i.e. not after the last position in that
16432 ;; category).
16433 (let ((pos (point)))
16434 ;; Stay before inserted string. `save-excursion' is of no use.
16435 (setq org-last-changed-timestamp
16436 (org-insert-time-stamp time with-hm inactive nil nil extra))
16437 (goto-char pos))
16438 (save-match-data
16439 (looking-at org-ts-regexp3)
16440 (goto-char (cond
16441 ;; `day' category ends before `hour' if any, or at
16442 ;; the end of the day name.
16443 ((eq origin-cat 'day)
16444 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16445 ((eq origin-cat 'hour) (min (match-end 7) origin))
16446 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16447 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16448 ;; `year' and `month' have both fixed size: point
16449 ;; couldn't have moved into another part.
16450 (t origin))))
16451 ;; Update clock if on a CLOCK line.
16452 (org-clock-update-time-maybe)
16453 ;; Maybe adjust the closest clock in `org-clock-history'
16454 (when org-clock-adjust-closest
16455 (if (not (and (org-at-clock-log-p)
16456 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16457 org-clock-history))))))
16458 (message "No clock to adjust")
16459 (cond ((save-excursion ; fix previous clock?
16460 (re-search-backward org-ts-regexp0 nil t)
16461 (org-looking-back (concat org-clock-string " \\[")))
16462 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16463 ((save-excursion ; fix next clock?
16464 (re-search-backward org-ts-regexp0 nil t)
16465 (looking-at (concat org-ts-regexp0 "\\] =>")))
16466 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16467 (save-window-excursion
16468 ;; Find closest clock to point, adjust the previous/next one in history
16469 (let* ((p (save-excursion (org-back-to-heading t)))
16470 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16471 (clfixnth
16472 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16473 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16474 (if (not clfixpos)
16475 (message "No clock to adjust")
16476 (save-excursion
16477 (org-goto-marker-or-bmk clfixpos)
16478 (org-show-subtree)
16479 (when (re-search-forward clrgx nil t)
16480 (goto-char (match-beginning 1))
16481 (let (org-clock-adjust-closest)
16482 (org-timestamp-change n org-ts-what updown))
16483 (message "Clock adjusted in %s for heading: %s"
16484 (file-name-nondirectory (buffer-file-name))
16485 (org-get-heading t t)))))))))
16486 ;; Try to recenter the calendar window, if any.
16487 (if (and org-calendar-follow-timestamp-change
16488 (get-buffer-window "*Calendar*" t)
16489 (memq org-ts-what '(day month year)))
16490 (org-recenter-calendar (time-to-days time))))))
16492 (defun org-modify-ts-extra (s pos n dm)
16493 "Change the different parts of the lead-time and repeat fields in timestamp."
16494 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16495 ng h m new rem)
16496 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16497 (cond
16498 ((or (org-pos-in-match-range pos 2)
16499 (org-pos-in-match-range pos 3))
16500 (setq m (string-to-number (match-string 3 s))
16501 h (string-to-number (match-string 2 s)))
16502 (if (org-pos-in-match-range pos 2)
16503 (setq h (+ h n))
16504 (setq n (* dm (org-no-warnings (signum n))))
16505 (when (not (= 0 (setq rem (% m dm))))
16506 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16507 (setq m (+ m n)))
16508 (if (< m 0) (setq m (+ m 60) h (1- h)))
16509 (if (> m 59) (setq m (- m 60) h (1+ h)))
16510 (setq h (min 24 (max 0 h)))
16511 (setq ng 1 new (format "-%02d:%02d" h m)))
16512 ((org-pos-in-match-range pos 6)
16513 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16514 ((org-pos-in-match-range pos 5)
16515 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16517 ((org-pos-in-match-range pos 9)
16518 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16519 ((org-pos-in-match-range pos 8)
16520 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16522 (when ng
16523 (setq s (concat
16524 (substring s 0 (match-beginning ng))
16526 (substring s (match-end ng))))))
16529 (defun org-recenter-calendar (date)
16530 "If the calendar is visible, recenter it to DATE."
16531 (let ((cwin (get-buffer-window "*Calendar*" t)))
16532 (when cwin
16533 (let ((calendar-move-hook nil))
16534 (with-selected-window cwin
16535 (calendar-goto-date (if (listp date) date
16536 (calendar-gregorian-from-absolute date))))))))
16538 (defun org-goto-calendar (&optional arg)
16539 "Go to the Emacs calendar at the current date.
16540 If there is a time stamp in the current line, go to that date.
16541 A prefix ARG can be used to force the current date."
16542 (interactive "P")
16543 (let ((tsr org-ts-regexp) diff
16544 (calendar-move-hook nil)
16545 (calendar-view-holidays-initially-flag nil)
16546 (calendar-view-diary-initially-flag nil))
16547 (if (or (org-at-timestamp-p)
16548 (save-excursion
16549 (beginning-of-line 1)
16550 (looking-at (concat ".*" tsr))))
16551 (let ((d1 (time-to-days (current-time)))
16552 (d2 (time-to-days
16553 (org-time-string-to-time (match-string 1)))))
16554 (setq diff (- d2 d1))))
16555 (calendar)
16556 (calendar-goto-today)
16557 (if (and diff (not arg)) (calendar-forward-day diff))))
16559 (defun org-get-date-from-calendar ()
16560 "Return a list (month day year) of date at point in calendar."
16561 (with-current-buffer "*Calendar*"
16562 (save-match-data
16563 (calendar-cursor-to-date))))
16565 (defun org-date-from-calendar ()
16566 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16567 If there is already a time stamp at the cursor position, update it."
16568 (interactive)
16569 (if (org-at-timestamp-p t)
16570 (org-timestamp-change 0 'calendar)
16571 (let ((cal-date (org-get-date-from-calendar)))
16572 (org-insert-time-stamp
16573 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16575 (defun org-minutes-to-hh:mm-string (m)
16576 "Compute H:MM from a number of minutes."
16577 (let ((h (/ m 60)))
16578 (setq m (- m (* 60 h)))
16579 (format org-time-clocksum-format h m)))
16581 (defun org-hh:mm-string-to-minutes (s)
16582 "Convert a string H:MM to a number of minutes.
16583 If the string is just a number, interpret it as minutes.
16584 In fact, the first hh:mm or number in the string will be taken,
16585 there can be extra stuff in the string.
16586 If no number is found, the return value is 0."
16587 (cond
16588 ((integerp s) s)
16589 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16590 (+ (* (string-to-number (match-string 1 s)) 60)
16591 (string-to-number (match-string 2 s))))
16592 ((string-match "\\([0-9]+\\)" s)
16593 (string-to-number (match-string 1 s)))
16594 (t 0)))
16596 (defcustom org-effort-durations
16597 `(("h" . 60)
16598 ("d" . ,(* 60 8))
16599 ("w" . ,(* 60 8 5))
16600 ("m" . ,(* 60 8 5 4))
16601 ("y" . ,(* 60 8 5 40)))
16602 "Conversion factor to minutes for an effort modifier.
16604 Each entry has the form (MODIFIER . MINUTES).
16606 In an effort string, a number followed by MODIFIER is multiplied
16607 by the specified number of MINUTES to obtain an effort in
16608 minutes.
16610 For example, if the value of this variable is ((\"hours\" . 60)), then an
16611 effort string \"2hours\" is equivalent to 120 minutes."
16612 :group 'org-agenda
16613 :version "24.1"
16614 :type '(alist :key-type (string :tag "Modifier")
16615 :value-type (number :tag "Minutes")))
16617 (defun org-duration-string-to-minutes (s &optional output-to-string)
16618 "Convert a duration string S to minutes.
16620 A bare number is interpreted as minutes, modifiers can be set by
16621 customizing `org-effort-durations' (which see).
16623 Entries containing a colon are interpreted as H:MM by
16624 `org-hh:mm-string-to-minutes'."
16625 (let ((result 0)
16626 (re (concat "\\([0-9.]+\\) *\\("
16627 (regexp-opt (mapcar 'car org-effort-durations))
16628 "\\)")))
16629 (while (string-match re s)
16630 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16631 (string-to-number (match-string 1 s))))
16632 (setq s (replace-match "" nil t s)))
16633 (setq result (floor result))
16634 (incf result (org-hh:mm-string-to-minutes s))
16635 (if output-to-string (number-to-string result) result)))
16637 ;;;; Files
16639 (defun org-save-all-org-buffers ()
16640 "Save all Org-mode buffers without user confirmation."
16641 (interactive)
16642 (message "Saving all Org-mode buffers...")
16643 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16644 (when (featurep 'org-id) (org-id-locations-save))
16645 (message "Saving all Org-mode buffers... done"))
16647 (defun org-revert-all-org-buffers ()
16648 "Revert all Org-mode buffers.
16649 Prompt for confirmation when there are unsaved changes.
16650 Be sure you know what you are doing before letting this function
16651 overwrite your changes.
16653 This function is useful in a setup where one tracks org files
16654 with a version control system, to revert on one machine after pulling
16655 changes from another. I believe the procedure must be like this:
16657 1. M-x org-save-all-org-buffers
16658 2. Pull changes from the other machine, resolve conflicts
16659 3. M-x org-revert-all-org-buffers"
16660 (interactive)
16661 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16662 (error "Abort"))
16663 (save-excursion
16664 (save-window-excursion
16665 (mapc
16666 (lambda (b)
16667 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16668 (with-current-buffer b buffer-file-name))
16669 (org-pop-to-buffer-same-window b)
16670 (revert-buffer t 'no-confirm)))
16671 (buffer-list))
16672 (when (and (featurep 'org-id) org-id-track-globally)
16673 (org-id-locations-load)))))
16675 ;;;; Agenda files
16677 ;;;###autoload
16678 (defun org-switchb (&optional arg)
16679 "Switch between Org buffers.
16680 With one prefix argument, restrict available buffers to files.
16681 With two prefix arguments, restrict available buffers to agenda files.
16683 Defaults to `iswitchb' for buffer name completion.
16684 Set `org-completion-use-ido' to make it use ido instead."
16685 (interactive "P")
16686 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16687 ((equal arg '(16)) (org-buffer-list 'agenda))
16688 (t (org-buffer-list))))
16689 (org-completion-use-iswitchb org-completion-use-iswitchb)
16690 (org-completion-use-ido org-completion-use-ido))
16691 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16692 (setq org-completion-use-iswitchb t))
16693 (org-pop-to-buffer-same-window
16694 (org-icompleting-read "Org buffer: "
16695 (mapcar 'list (mapcar 'buffer-name blist))
16696 nil t))))
16698 ;;; Define some older names previously used for this functionality
16699 ;;;###autoload
16700 (defalias 'org-ido-switchb 'org-switchb)
16701 ;;;###autoload
16702 (defalias 'org-iswitchb 'org-switchb)
16704 (defun org-buffer-list (&optional predicate exclude-tmp)
16705 "Return a list of Org buffers.
16706 PREDICATE can be `export', `files' or `agenda'.
16708 export restrict the list to Export buffers.
16709 files restrict the list to buffers visiting Org files.
16710 agenda restrict the list to buffers visiting agenda files.
16712 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16713 (let* ((bfn nil)
16714 (agenda-files (and (eq predicate 'agenda)
16715 (mapcar 'file-truename (org-agenda-files t))))
16716 (filter
16717 (cond
16718 ((eq predicate 'files)
16719 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16720 ((eq predicate 'export)
16721 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16722 ((eq predicate 'agenda)
16723 (lambda (b)
16724 (with-current-buffer b
16725 (and (derived-mode-p 'org-mode)
16726 (setq bfn (buffer-file-name b))
16727 (member (file-truename bfn) agenda-files)))))
16728 (t (lambda (b) (with-current-buffer b
16729 (or (derived-mode-p 'org-mode)
16730 (string-match "\*Org .*Export"
16731 (buffer-name b)))))))))
16732 (delq nil
16733 (mapcar
16734 (lambda(b)
16735 (if (and (funcall filter b)
16736 (or (not exclude-tmp)
16737 (not (string-match "tmp" (buffer-name b)))))
16739 nil))
16740 (buffer-list)))))
16742 (defun org-agenda-files (&optional unrestricted archives)
16743 "Get the list of agenda files.
16744 Optional UNRESTRICTED means return the full list even if a restriction
16745 is currently in place.
16746 When ARCHIVES is t, include all archive files that are really being
16747 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16748 `org-agenda-archives-mode' is t."
16749 (let ((files
16750 (cond
16751 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16752 ((stringp org-agenda-files) (org-read-agenda-file-list))
16753 ((listp org-agenda-files) org-agenda-files)
16754 (t (error "Invalid value of `org-agenda-files'")))))
16755 (setq files (apply 'append
16756 (mapcar (lambda (f)
16757 (if (file-directory-p f)
16758 (directory-files
16759 f t org-agenda-file-regexp)
16760 (list f)))
16761 files)))
16762 (when org-agenda-skip-unavailable-files
16763 (setq files (delq nil
16764 (mapcar (function
16765 (lambda (file)
16766 (and (file-readable-p file) file)))
16767 files))))
16768 (when (or (eq archives t)
16769 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16770 (setq files (org-add-archive-files files)))
16771 files))
16773 (defun org-agenda-file-p (&optional file)
16774 "Return non-nil, if FILE is an agenda file.
16775 If FILE is omitted, use the file associated with the current
16776 buffer."
16777 (member (or file (buffer-file-name))
16778 (org-agenda-files t)))
16780 (defun org-edit-agenda-file-list ()
16781 "Edit the list of agenda files.
16782 Depending on setup, this either uses customize to edit the variable
16783 `org-agenda-files', or it visits the file that is holding the list. In the
16784 latter case, the buffer is set up in a way that saving it automatically kills
16785 the buffer and restores the previous window configuration."
16786 (interactive)
16787 (if (stringp org-agenda-files)
16788 (let ((cw (current-window-configuration)))
16789 (find-file org-agenda-files)
16790 (org-set-local 'org-window-configuration cw)
16791 (org-add-hook 'after-save-hook
16792 (lambda ()
16793 (set-window-configuration
16794 (prog1 org-window-configuration
16795 (kill-buffer (current-buffer))))
16796 (org-install-agenda-files-menu)
16797 (message "New agenda file list installed"))
16798 nil 'local)
16799 (message "%s" (substitute-command-keys
16800 "Edit list and finish with \\[save-buffer]")))
16801 (customize-variable 'org-agenda-files)))
16803 (defun org-store-new-agenda-file-list (list)
16804 "Set new value for the agenda file list and save it correctly."
16805 (if (stringp org-agenda-files)
16806 (let ((fe (org-read-agenda-file-list t)) b u)
16807 (while (setq b (find-buffer-visiting org-agenda-files))
16808 (kill-buffer b))
16809 (with-temp-file org-agenda-files
16810 (insert
16811 (mapconcat
16812 (lambda (f) ;; Keep un-expanded entries.
16813 (if (setq u (assoc f fe))
16814 (cdr u)
16816 list "\n")
16817 "\n")))
16818 (let ((org-mode-hook nil) (org-inhibit-startup t)
16819 (org-insert-mode-line-in-empty-file nil))
16820 (setq org-agenda-files list)
16821 (customize-save-variable 'org-agenda-files org-agenda-files))))
16823 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16824 "Read the list of agenda files from a file.
16825 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16826 filenames, used by `org-store-new-agenda-file-list' to write back
16827 un-expanded file names."
16828 (when (file-directory-p org-agenda-files)
16829 (error "`org-agenda-files' cannot be a single directory"))
16830 (when (stringp org-agenda-files)
16831 (with-temp-buffer
16832 (insert-file-contents org-agenda-files)
16833 (mapcar
16834 (lambda (f)
16835 (let ((e (expand-file-name (substitute-in-file-name f)
16836 org-directory)))
16837 (if pair-with-expansion
16838 (cons e f)
16839 e)))
16840 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16842 ;;;###autoload
16843 (defun org-cycle-agenda-files ()
16844 "Cycle through the files in `org-agenda-files'.
16845 If the current buffer visits an agenda file, find the next one in the list.
16846 If the current buffer does not, find the first agenda file."
16847 (interactive)
16848 (let* ((fs (org-agenda-files t))
16849 (files (append fs (list (car fs))))
16850 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16851 file)
16852 (unless files (error "No agenda files"))
16853 (catch 'exit
16854 (while (setq file (pop files))
16855 (if (equal (file-truename file) tcf)
16856 (when (car files)
16857 (find-file (car files))
16858 (throw 'exit t))))
16859 (find-file (car fs)))
16860 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16862 (defun org-agenda-file-to-front (&optional to-end)
16863 "Move/add the current file to the top of the agenda file list.
16864 If the file is not present in the list, it is added to the front. If it is
16865 present, it is moved there. With optional argument TO-END, add/move to the
16866 end of the list."
16867 (interactive "P")
16868 (let ((org-agenda-skip-unavailable-files nil)
16869 (file-alist (mapcar (lambda (x)
16870 (cons (file-truename x) x))
16871 (org-agenda-files t)))
16872 (ctf (file-truename
16873 (or buffer-file-name
16874 (error "Please save the current buffer to a file"))))
16875 x had)
16876 (setq x (assoc ctf file-alist) had x)
16878 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16879 (if to-end
16880 (setq file-alist (append (delq x file-alist) (list x)))
16881 (setq file-alist (cons x (delq x file-alist))))
16882 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16883 (org-install-agenda-files-menu)
16884 (message "File %s to %s of agenda file list"
16885 (if had "moved" "added") (if to-end "end" "front"))))
16887 (defun org-remove-file (&optional file)
16888 "Remove current file from the list of files in variable `org-agenda-files'.
16889 These are the files which are being checked for agenda entries.
16890 Optional argument FILE means use this file instead of the current."
16891 (interactive)
16892 (let* ((org-agenda-skip-unavailable-files nil)
16893 (file (or file buffer-file-name
16894 (error "Current buffer does not visit a file")))
16895 (true-file (file-truename file))
16896 (afile (abbreviate-file-name file))
16897 (files (delq nil (mapcar
16898 (lambda (x)
16899 (if (equal true-file
16900 (file-truename x))
16901 nil x))
16902 (org-agenda-files t)))))
16903 (if (not (= (length files) (length (org-agenda-files t))))
16904 (progn
16905 (org-store-new-agenda-file-list files)
16906 (org-install-agenda-files-menu)
16907 (message "Removed file: %s" afile))
16908 (message "File was not in list: %s (not removed)" afile))))
16910 (defun org-file-menu-entry (file)
16911 (vector file (list 'find-file file) t))
16913 (defun org-check-agenda-file (file)
16914 "Make sure FILE exists. If not, ask user what to do."
16915 (when (not (file-exists-p file))
16916 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16917 (abbreviate-file-name file))
16918 (let ((r (downcase (read-char-exclusive))))
16919 (cond
16920 ((equal r ?r)
16921 (org-remove-file file)
16922 (throw 'nextfile t))
16923 (t (error "Abort"))))))
16925 (defun org-get-agenda-file-buffer (file)
16926 "Get a buffer visiting FILE. If the buffer needs to be created, add
16927 it to the list of buffers which might be released later."
16928 (let ((buf (org-find-base-buffer-visiting file)))
16929 (if buf
16930 buf ; just return it
16931 ;; Make a new buffer and remember it
16932 (setq buf (find-file-noselect file))
16933 (if buf (push buf org-agenda-new-buffers))
16934 buf)))
16936 (defun org-release-buffers (blist)
16937 "Release all buffers in list, asking the user for confirmation when needed.
16938 When a buffer is unmodified, it is just killed. When modified, it is saved
16939 \(if the user agrees) and then killed."
16940 (let (buf file)
16941 (while (setq buf (pop blist))
16942 (setq file (buffer-file-name buf))
16943 (when (and (buffer-modified-p buf)
16944 file
16945 (y-or-n-p (format "Save file %s? " file)))
16946 (with-current-buffer buf (save-buffer)))
16947 (kill-buffer buf))))
16949 (defun org-agenda-prepare-buffers (files)
16950 "Create buffers for all agenda files, protect archived trees and comments."
16951 (interactive)
16952 (let ((pa '(:org-archived t))
16953 (pc '(:org-comment t))
16954 (pall '(:org-archived t :org-comment t))
16955 (inhibit-read-only t)
16956 (rea (concat ":" org-archive-tag ":"))
16957 bmp file re)
16958 (save-excursion
16959 (save-restriction
16960 (while (setq file (pop files))
16961 (catch 'nextfile
16962 (if (bufferp file)
16963 (set-buffer file)
16964 (org-check-agenda-file file)
16965 (set-buffer (org-get-agenda-file-buffer file)))
16966 (widen)
16967 (setq bmp (buffer-modified-p))
16968 (org-refresh-category-properties)
16969 (setq org-todo-keywords-for-agenda
16970 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16971 (setq org-done-keywords-for-agenda
16972 (append org-done-keywords-for-agenda org-done-keywords))
16973 (setq org-todo-keyword-alist-for-agenda
16974 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16975 (setq org-drawers-for-agenda
16976 (append org-drawers-for-agenda org-drawers))
16977 (setq org-tag-alist-for-agenda
16978 (append org-tag-alist-for-agenda org-tag-alist))
16980 (save-excursion
16981 (remove-text-properties (point-min) (point-max) pall)
16982 (when org-agenda-skip-archived-trees
16983 (goto-char (point-min))
16984 (while (re-search-forward rea nil t)
16985 (if (org-at-heading-p t)
16986 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16987 (goto-char (point-min))
16988 (setq re (format org-heading-keyword-regexp-format
16989 org-comment-string))
16990 (while (re-search-forward re nil t)
16991 (add-text-properties
16992 (match-beginning 0) (org-end-of-subtree t) pc)))
16993 (set-buffer-modified-p bmp)))))
16994 (setq org-todo-keywords-for-agenda
16995 (org-uniquify org-todo-keywords-for-agenda))
16996 (setq org-todo-keyword-alist-for-agenda
16997 (org-uniquify org-todo-keyword-alist-for-agenda)
16998 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17000 ;;;; Embedded LaTeX
17002 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17003 "Keymap for the minor `org-cdlatex-mode'.")
17005 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17006 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17007 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17008 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17009 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17011 (defvar org-cdlatex-texmathp-advice-is-done nil
17012 "Flag remembering if we have applied the advice to texmathp already.")
17014 (define-minor-mode org-cdlatex-mode
17015 "Toggle the minor `org-cdlatex-mode'.
17016 This mode supports entering LaTeX environment and math in LaTeX fragments
17017 in Org-mode.
17018 \\{org-cdlatex-mode-map}"
17019 nil " OCDL" nil
17020 (when org-cdlatex-mode
17021 (require 'cdlatex)
17022 (run-hooks 'cdlatex-mode-hook)
17023 (cdlatex-compute-tables))
17024 (unless org-cdlatex-texmathp-advice-is-done
17025 (setq org-cdlatex-texmathp-advice-is-done t)
17026 (defadvice texmathp (around org-math-always-on activate)
17027 "Always return t in org-mode buffers.
17028 This is because we want to insert math symbols without dollars even outside
17029 the LaTeX math segments. If Orgmode thinks that point is actually inside
17030 an embedded LaTeX fragment, let texmathp do its job.
17031 \\[org-cdlatex-mode-map]"
17032 (interactive)
17033 (let (p)
17034 (cond
17035 ((not (derived-mode-p 'org-mode)) ad-do-it)
17036 ((eq this-command 'cdlatex-math-symbol)
17037 (setq ad-return-value t
17038 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17040 (let ((p (org-inside-LaTeX-fragment-p)))
17041 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17042 (setq ad-return-value t
17043 texmathp-why '("Org-mode embedded math" . 0))
17044 (if p ad-do-it)))))))))
17046 (defun turn-on-org-cdlatex ()
17047 "Unconditionally turn on `org-cdlatex-mode'."
17048 (org-cdlatex-mode 1))
17050 (defun org-inside-LaTeX-fragment-p ()
17051 "Test if point is inside a LaTeX fragment.
17052 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17053 sequence appearing also before point.
17054 Even though the matchers for math are configurable, this function assumes
17055 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17056 delimiters are skipped when they have been removed by customization.
17057 The return value is nil, or a cons cell with the delimiter and the
17058 position of this delimiter.
17060 This function does a reasonably good job, but can locally be fooled by
17061 for example currency specifications. For example it will assume being in
17062 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17063 fragments that are properly closed, but during editing, we have to live
17064 with the uncertainty caused by missing closing delimiters. This function
17065 looks only before point, not after."
17066 (catch 'exit
17067 (let ((pos (point))
17068 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17069 (lim (progn
17070 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17071 (point)))
17072 dd-on str (start 0) m re)
17073 (goto-char pos)
17074 (when dodollar
17075 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17076 re (nth 1 (assoc "$" org-latex-regexps)))
17077 (while (string-match re str start)
17078 (cond
17079 ((= (match-end 0) (length str))
17080 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17081 ((= (match-end 0) (- (length str) 5))
17082 (throw 'exit nil))
17083 (t (setq start (match-end 0))))))
17084 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17085 (goto-char pos)
17086 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17087 (and (match-beginning 2) (throw 'exit nil))
17088 ;; count $$
17089 (while (re-search-backward "\\$\\$" lim t)
17090 (setq dd-on (not dd-on)))
17091 (goto-char pos)
17092 (if dd-on (cons "$$" m))))))
17094 (defun org-inside-latex-macro-p ()
17095 "Is point inside a LaTeX macro or its arguments?"
17096 (save-match-data
17097 (org-in-regexp
17098 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17100 (defun org-try-cdlatex-tab ()
17101 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17102 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17103 - inside a LaTeX fragment, or
17104 - after the first word in a line, where an abbreviation expansion could
17105 insert a LaTeX environment."
17106 (when org-cdlatex-mode
17107 (cond
17108 ;; Before any word on the line: No expansion possible.
17109 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17110 ;; Just after first word on the line: Expand it. Make sure it
17111 ;; cannot happen on headlines, though.
17112 ((save-excursion
17113 (skip-chars-backward "a-zA-Z0-9*")
17114 (skip-chars-backward " \t")
17115 (and (bolp) (not (org-at-heading-p))))
17116 (cdlatex-tab) t)
17117 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17119 (defun org-cdlatex-underscore-caret (&optional arg)
17120 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17121 Revert to the normal definition outside of these fragments."
17122 (interactive "P")
17123 (if (org-inside-LaTeX-fragment-p)
17124 (call-interactively 'cdlatex-sub-superscript)
17125 (let (org-cdlatex-mode)
17126 (call-interactively (key-binding (vector last-input-event))))))
17128 (defun org-cdlatex-math-modify (&optional arg)
17129 "Execute `cdlatex-math-modify' in LaTeX fragments.
17130 Revert to the normal definition outside of these fragments."
17131 (interactive "P")
17132 (if (org-inside-LaTeX-fragment-p)
17133 (call-interactively 'cdlatex-math-modify)
17134 (let (org-cdlatex-mode)
17135 (call-interactively (key-binding (vector last-input-event))))))
17137 (defvar org-latex-fragment-image-overlays nil
17138 "List of overlays carrying the images of latex fragments.")
17139 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17141 (defun org-remove-latex-fragment-image-overlays ()
17142 "Remove all overlays with LaTeX fragment images in current buffer."
17143 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17144 (setq org-latex-fragment-image-overlays nil))
17146 (defun org-preview-latex-fragment (&optional subtree)
17147 "Preview the LaTeX fragment at point, or all locally or globally.
17148 If the cursor is in a LaTeX fragment, create the image and overlay
17149 it over the source code. If there is no fragment at point, display
17150 all fragments in the current text, from one headline to the next. With
17151 prefix SUBTREE, display all fragments in the current subtree. With a
17152 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17153 the cursor is before the first headline,
17154 display all fragments in the buffer.
17155 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17156 (interactive "P")
17157 (unless buffer-file-name
17158 (error "Can't preview LaTeX fragment in a non-file buffer"))
17159 (org-remove-latex-fragment-image-overlays)
17160 (save-excursion
17161 (save-restriction
17162 (let (beg end at msg)
17163 (cond
17164 ((or (equal subtree '(16))
17165 (not (save-excursion
17166 (re-search-backward org-outline-regexp-bol nil t))))
17167 (setq beg (point-min) end (point-max)
17168 msg "Creating images for buffer...%s"))
17169 ((equal subtree '(4))
17170 (org-back-to-heading)
17171 (setq beg (point) end (org-end-of-subtree t)
17172 msg "Creating images for subtree...%s"))
17174 (if (setq at (org-inside-LaTeX-fragment-p))
17175 (goto-char (max (point-min) (- (cdr at) 2)))
17176 (org-back-to-heading))
17177 (setq beg (point) end (progn (outline-next-heading) (point))
17178 msg (if at "Creating image...%s"
17179 "Creating images for entry...%s"))))
17180 (message msg "")
17181 (narrow-to-region beg end)
17182 (goto-char beg)
17183 (org-format-latex
17184 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17185 (file-name-nondirectory
17186 buffer-file-name)))
17187 default-directory 'overlays msg at 'forbuffer
17188 org-latex-create-formula-image-program)
17189 (message msg "done. Use `C-c C-c' to remove images.")))))
17191 (defvar org-latex-regexps
17192 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17193 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17194 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17195 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17196 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17197 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17198 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17199 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17200 "Regular expressions for matching embedded LaTeX.")
17202 (defvar org-export-have-math nil) ;; dynamic scoping
17203 (defun org-format-latex (prefix &optional dir overlays msg at
17204 forbuffer processing-type)
17205 "Replace LaTeX fragments with links to an image, and produce images.
17206 Some of the options can be changed using the variable
17207 `org-format-latex-options'."
17208 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17209 (let* ((prefixnodir (file-name-nondirectory prefix))
17210 (absprefix (expand-file-name prefix dir))
17211 (todir (file-name-directory absprefix))
17212 (opt org-format-latex-options)
17213 (matchers (plist-get opt :matchers))
17214 (re-list org-latex-regexps)
17215 (org-format-latex-header-extra
17216 (plist-get (org-infile-export-plist) :latex-header-extra))
17217 (cnt 0) txt hash link beg end re e checkdir
17218 executables-checked string
17219 m n block-type block linkfile movefile ov)
17220 ;; Check the different regular expressions
17221 (while (setq e (pop re-list))
17222 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17223 block (if block-type "\n\n" ""))
17224 (when (member m matchers)
17225 (goto-char (point-min))
17226 (while (re-search-forward re nil t)
17227 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17228 (not (get-text-property (match-beginning n)
17229 'org-protected))
17230 (or (not overlays)
17231 (not (eq (get-char-property (match-beginning n)
17232 'org-overlay-type)
17233 'org-latex-overlay))))
17234 (setq org-export-have-math t)
17235 (cond
17236 ((eq processing-type 'verbatim)
17237 ;; Leave the text verbatim, just protect it
17238 (add-text-properties (match-beginning n) (match-end n)
17239 '(org-protected t)))
17240 ((eq processing-type 'mathjax)
17241 ;; Prepare for MathJax processing
17242 (setq string (match-string n))
17243 (if (member m '("$" "$1"))
17244 (save-excursion
17245 (delete-region (match-beginning n) (match-end n))
17246 (goto-char (match-beginning n))
17247 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17248 "\\)")
17249 '(org-protected t))))
17250 (add-text-properties (match-beginning n) (match-end n)
17251 '(org-protected t))))
17252 ((or (eq processing-type 'dvipng)
17253 (eq processing-type 'imagemagick))
17254 ;; Process to an image
17255 (setq txt (match-string n)
17256 beg (match-beginning n) end (match-end n)
17257 cnt (1+ cnt))
17258 (let (print-length print-level) ; make sure full list is printed
17259 (setq hash (sha1 (prin1-to-string
17260 (list org-format-latex-header
17261 org-format-latex-header-extra
17262 org-export-latex-default-packages-alist
17263 org-export-latex-packages-alist
17264 org-format-latex-options
17265 forbuffer txt)))
17266 linkfile (format "%s_%s.png" prefix hash)
17267 movefile (format "%s_%s.png" absprefix hash)))
17268 (setq link (concat block "[[file:" linkfile "]]" block))
17269 (if msg (message msg cnt))
17270 (goto-char beg)
17271 (unless checkdir ; make sure the directory exists
17272 (setq checkdir t)
17273 (or (file-directory-p todir) (make-directory todir t)))
17274 (cond
17275 ((eq processing-type 'dvipng)
17276 (unless executables-checked
17277 (org-check-external-command
17278 "latex" "needed to convert LaTeX fragments to images")
17279 (org-check-external-command
17280 "dvipng" "needed to convert LaTeX fragments to images")
17281 (setq executables-checked t))
17282 (unless (file-exists-p movefile)
17283 (org-create-formula-image-with-dvipng
17284 txt movefile opt forbuffer)))
17285 ((eq processing-type 'imagemagick)
17286 (unless executables-checked
17287 (org-check-external-command
17288 "convert" "you need to install imagemagick")
17289 (setq executables-checked t))
17290 (unless (file-exists-p movefile)
17291 (org-create-formula-image-with-imagemagick
17292 txt movefile opt forbuffer))))
17293 (if overlays
17294 (progn
17295 (mapc (lambda (o)
17296 (if (eq (overlay-get o 'org-overlay-type)
17297 'org-latex-overlay)
17298 (delete-overlay o)))
17299 (overlays-in beg end))
17300 (setq ov (make-overlay beg end))
17301 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17302 (if (featurep 'xemacs)
17303 (progn
17304 (overlay-put ov 'invisible t)
17305 (overlay-put
17306 ov 'end-glyph
17307 (make-glyph (vector 'png :file movefile))))
17308 (overlay-put
17309 ov 'display
17310 (list 'image :type 'png :file movefile :ascent 'center)))
17311 (push ov org-latex-fragment-image-overlays)
17312 (goto-char end))
17313 (delete-region beg end)
17314 (insert (org-add-props link
17315 (list 'org-latex-src
17316 (replace-regexp-in-string
17317 "\"" "" txt)
17318 'org-latex-src-embed-type
17319 (if block-type 'paragraph 'character))))))
17320 ((eq processing-type 'mathml)
17321 ;; Process to MathML
17322 (unless executables-checked
17323 (unless (save-match-data (org-format-latex-mathml-available-p))
17324 (error "LaTeX to MathML converter not configured"))
17325 (setq executables-checked t))
17326 (setq txt (match-string n)
17327 beg (match-beginning n) end (match-end n)
17328 cnt (1+ cnt))
17329 (if msg (message msg cnt))
17330 (goto-char beg)
17331 (delete-region beg end)
17332 (insert (org-format-latex-as-mathml
17333 txt block-type prefix dir)))
17335 (error "Unknown conversion type %s for latex fragments"
17336 processing-type)))))))))
17338 (defun org-create-math-formula (latex-frag &optional mathml-file)
17339 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17340 Use `org-latex-to-mathml-convert-command'. If the conversion is
17341 sucessful, return the portion between \"<math...> </math>\"
17342 elements otherwise return nil. When MATHML-FILE is specified,
17343 write the results in to that file. When invoked as an
17344 interactive command, prompt for LATEX-FRAG, with initial value
17345 set to the current active region and echo the results for user
17346 inspection."
17347 (interactive (list (let ((frag (when (org-region-active-p)
17348 (buffer-substring-no-properties
17349 (region-beginning) (region-end)))))
17350 (read-string "LaTeX Fragment: " frag nil frag))))
17351 (unless latex-frag (error "Invalid latex-frag"))
17352 (let* ((tmp-in-file (file-relative-name
17353 (make-temp-name (expand-file-name "ltxmathml-in"))))
17354 (ignore (write-region latex-frag nil tmp-in-file))
17355 (tmp-out-file (file-relative-name
17356 (make-temp-name (expand-file-name "ltxmathml-out"))))
17357 (cmd (format-spec
17358 org-latex-to-mathml-convert-command
17359 `((?j . ,(shell-quote-argument
17360 (expand-file-name org-latex-to-mathml-jar-file)))
17361 (?I . ,(shell-quote-argument tmp-in-file))
17362 (?o . ,(shell-quote-argument tmp-out-file)))))
17363 mathml shell-command-output)
17364 (when (org-called-interactively-p 'any)
17365 (unless (org-format-latex-mathml-available-p)
17366 (error "LaTeX to MathML converter not configured")))
17367 (message "Running %s" cmd)
17368 (setq shell-command-output (shell-command-to-string cmd))
17369 (setq mathml
17370 (when (file-readable-p tmp-out-file)
17371 (with-current-buffer (find-file-noselect tmp-out-file t)
17372 (goto-char (point-min))
17373 (when (re-search-forward
17374 (concat
17375 (regexp-quote
17376 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17377 "\\(.\\|\n\\)*"
17378 (regexp-quote "</math>")) nil t)
17379 (prog1 (match-string 0) (kill-buffer))))))
17380 (cond
17381 (mathml
17382 (setq mathml
17383 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17384 (when mathml-file
17385 (write-region mathml nil mathml-file))
17386 (when (org-called-interactively-p 'any)
17387 (message mathml)))
17388 ((message "LaTeX to MathML conversion failed")
17389 (message shell-command-output)))
17390 (delete-file tmp-in-file)
17391 (when (file-exists-p tmp-out-file)
17392 (delete-file tmp-out-file))
17393 mathml))
17395 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17396 prefix &optional dir)
17397 "Use `org-create-math-formula' but check local cache first."
17398 (let* ((absprefix (expand-file-name prefix dir))
17399 (print-length nil) (print-level nil)
17400 (formula-id (concat
17401 "formula-"
17402 (sha1
17403 (prin1-to-string
17404 (list latex-frag
17405 org-latex-to-mathml-convert-command)))))
17406 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17407 (formula-cache-dir (file-name-directory formula-cache)))
17409 (unless (file-directory-p formula-cache-dir)
17410 (make-directory formula-cache-dir t))
17412 (unless (file-exists-p formula-cache)
17413 (org-create-math-formula latex-frag formula-cache))
17415 (if (file-exists-p formula-cache)
17416 ;; Successful conversion. Return the link to MathML file.
17417 (org-add-props
17418 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17419 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17420 'org-latex-src-embed-type (if latex-frag-type
17421 'paragraph 'character)))
17422 ;; Failed conversion. Return the LaTeX fragment verbatim
17423 (add-text-properties
17424 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17425 latex-frag)))
17427 ;; This function borrows from Ganesh Swami's latex2png.el
17428 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17429 "This calls dvipng."
17430 (require 'org-latex)
17431 (let* ((tmpdir (if (featurep 'xemacs)
17432 (temp-directory)
17433 temporary-file-directory))
17434 (texfilebase (make-temp-name
17435 (expand-file-name "orgtex" tmpdir)))
17436 (texfile (concat texfilebase ".tex"))
17437 (dvifile (concat texfilebase ".dvi"))
17438 (pngfile (concat texfilebase ".png"))
17439 (fnh (if (featurep 'xemacs)
17440 (font-height (face-font 'default))
17441 (face-attribute 'default :height nil)))
17442 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17443 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17444 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17445 "Black"))
17446 (bg (or (plist-get options (if buffer :background :html-background))
17447 "Transparent")))
17448 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17449 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17450 (with-temp-file texfile
17451 (insert (org-splice-latex-header
17452 org-format-latex-header
17453 org-export-latex-default-packages-alist
17454 org-export-latex-packages-alist t
17455 org-format-latex-header-extra))
17456 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17457 (require 'org-latex)
17458 (org-export-latex-fix-inputenc))
17459 (let ((dir default-directory))
17460 (condition-case nil
17461 (progn
17462 (cd tmpdir)
17463 (call-process "latex" nil nil nil texfile))
17464 (error nil))
17465 (cd dir))
17466 (if (not (file-exists-p dvifile))
17467 (progn (message "Failed to create dvi file from %s" texfile) nil)
17468 (condition-case nil
17469 (if (featurep 'xemacs)
17470 (call-process "dvipng" nil nil nil
17471 "-fg" fg "-bg" bg
17472 "-T" "tight"
17473 "-o" pngfile
17474 dvifile)
17475 (call-process "dvipng" nil nil nil
17476 "-fg" fg "-bg" bg
17477 "-D" dpi
17478 ;;"-x" scale "-y" scale
17479 "-T" "tight"
17480 "-o" pngfile
17481 dvifile))
17482 (error nil))
17483 (if (not (file-exists-p pngfile))
17484 (if org-format-latex-signal-error
17485 (error "Failed to create png file from %s" texfile)
17486 (message "Failed to create png file from %s" texfile)
17487 nil)
17488 ;; Use the requested file name and clean up
17489 (copy-file pngfile tofile 'replace)
17490 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17491 (if (file-exists-p (concat texfilebase e))
17492 (delete-file (concat texfilebase e))))
17493 pngfile))))
17495 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17496 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17497 "This calls convert, which is included into imagemagick."
17498 (require 'org-latex)
17499 (let* ((tmpdir (if (featurep 'xemacs)
17500 (temp-directory)
17501 temporary-file-directory))
17502 (texfilebase (make-temp-name
17503 (expand-file-name "orgtex" tmpdir)))
17504 (texfile (concat texfilebase ".tex"))
17505 (pdffile (concat texfilebase ".pdf"))
17506 (pngfile (concat texfilebase ".png"))
17507 (fnh (if (featurep 'xemacs)
17508 (font-height (face-font 'default))
17509 (face-attribute 'default :height nil)))
17510 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17511 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17512 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17513 "black"))
17514 (bg (or (plist-get options (if buffer :background :html-background))
17515 "white")))
17516 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17517 (setq fg (org-latex-color-format fg)))
17518 (if (eq bg 'default) (setq bg (org-latex-color :background))
17519 (setq bg (org-latex-color-format
17520 (if (string= bg "Transparent")(setq bg "white")))))
17521 (with-temp-file texfile
17522 (insert (org-splice-latex-header
17523 org-format-latex-header
17524 org-export-latex-default-packages-alist
17525 org-export-latex-packages-alist t
17526 org-format-latex-header-extra))
17527 (insert "\n\\begin{document}\n"
17528 "\\definecolor{fg}{rgb}{" fg "}\n"
17529 "\\definecolor{bg}{rgb}{" bg "}\n"
17530 "\n\\pagecolor{bg}\n"
17531 "\n{\\color{fg}\n"
17532 string
17533 "\n}\n"
17534 "\n\\end{document}\n" )
17535 (require 'org-latex)
17536 (org-export-latex-fix-inputenc))
17537 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17538 (condition-case nil
17539 (progn
17540 (cd tmpdir)
17541 (setq cmds org-latex-to-pdf-process)
17542 (while cmds
17543 (setq latex-frags-cmds (pop cmds))
17544 (if (listp latex-frags-cmds)
17545 (setq cmds nil)
17546 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17547 (while latex-frags-cmds
17548 (setq cmd (pop latex-frags-cmds))
17549 (while (string-match "%b" cmd)
17550 (setq cmd (replace-match
17551 (save-match-data
17552 (shell-quote-argument texfile))
17553 t t cmd)))
17554 (while (string-match "%f" cmd)
17555 (setq cmd (replace-match
17556 (save-match-data
17557 (shell-quote-argument (file-name-nondirectory texfile)))
17558 t t cmd)))
17559 (while (string-match "%o" cmd)
17560 (setq cmd (replace-match
17561 (save-match-data
17562 (shell-quote-argument (file-name-directory texfile)))
17563 t t cmd)))
17564 (setq cmd (split-string cmd))
17565 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17566 (error nil))
17567 (cd dir))
17568 (if (not (file-exists-p pdffile))
17569 (progn (message "Failed to create pdf file from %s" texfile) nil)
17570 (condition-case nil
17571 (if (featurep 'xemacs)
17572 (call-process "convert" nil nil nil
17573 "-density" "96"
17574 "-trim"
17575 "-antialias"
17576 pdffile
17577 "-quality" "100"
17578 ;; "-sharpen" "0x1.0"
17579 pngfile)
17580 (call-process "convert" nil nil nil
17581 "-density" dpi
17582 "-trim"
17583 "-antialias"
17584 pdffile
17585 "-quality" "100"
17586 ; "-sharpen" "0x1.0"
17587 pngfile))
17588 (error nil))
17589 (if (not (file-exists-p pngfile))
17590 (if org-format-latex-signal-error
17591 (error "Failed to create png file from %s" texfile)
17592 (message "Failed to create png file from %s" texfile)
17593 nil)
17594 ;; Use the requested file name and clean up
17595 (copy-file pngfile tofile 'replace)
17596 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17597 (if (file-exists-p (concat texfilebase e))
17598 (delete-file (concat texfilebase e))))
17599 pngfile))))
17601 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17602 "Fill a LaTeX header template TPL.
17603 In the template, the following place holders will be recognized:
17605 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17606 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17607 [PACKAGES] \\usepackage statements for PKG
17608 [NO-PACKAGES] do not include PKG
17609 [EXTRA] the string EXTRA
17610 [NO-EXTRA] do not include EXTRA
17612 For backward compatibility, if both the positive and the negative place
17613 holder is missing, the positive one (without the \"NO-\") will be
17614 assumed to be present at the end of the template.
17615 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17616 EXTRA is a string.
17617 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17618 (let (rpl (end ""))
17619 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17620 (setq rpl (if (or (match-end 1) (not def-pkg))
17621 "" (org-latex-packages-to-string def-pkg snippets-p t))
17622 tpl (replace-match rpl t t tpl))
17623 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17625 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17626 (setq rpl (if (or (match-end 1) (not pkg))
17627 "" (org-latex-packages-to-string pkg snippets-p t))
17628 tpl (replace-match rpl t t tpl))
17629 (if pkg (setq end
17630 (concat end "\n"
17631 (org-latex-packages-to-string pkg snippets-p)))))
17633 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17634 (setq rpl (if (or (match-end 1) (not extra))
17635 "" (concat extra "\n"))
17636 tpl (replace-match rpl t t tpl))
17637 (if (and extra (string-match "\\S-" extra))
17638 (setq end (concat end "\n" extra))))
17640 (if (string-match "\\S-" end)
17641 (concat tpl "\n" end)
17642 tpl)))
17644 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17645 "Turn an alist of packages into a string with the \\usepackage macros."
17646 (setq pkg (mapconcat (lambda(p)
17647 (cond
17648 ((stringp p) p)
17649 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17650 (format "%% Package %s omitted" (cadr p)))
17651 ((equal "" (car p))
17652 (format "\\usepackage{%s}" (cadr p)))
17654 (format "\\usepackage[%s]{%s}"
17655 (car p) (cadr p)))))
17657 "\n"))
17658 (if newline (concat pkg "\n") pkg))
17660 (defun org-dvipng-color (attr)
17661 "Return a RGB color specification for dvipng."
17662 (apply 'format "rgb %s %s %s"
17663 (mapcar 'org-normalize-color
17664 (if (featurep 'xemacs)
17665 (color-rgb-components
17666 (face-property 'default
17667 (cond ((eq attr :foreground) 'foreground)
17668 ((eq attr :background) 'background))))
17669 (color-values (face-attribute 'default attr nil))))))
17671 (defun org-latex-color (attr)
17672 "Return a RGB color for the LaTeX color package."
17673 (apply 'format "%s,%s,%s"
17674 (mapcar 'org-normalize-color
17675 (if (featurep 'xemacs)
17676 (color-rgb-components
17677 (face-property 'default
17678 (cond ((eq attr :foreground) 'foreground)
17679 ((eq attr :background) 'background))))
17680 (color-values (face-attribute 'default attr nil))))))
17682 (defun org-latex-color-format (color-name)
17683 "Convert COLOR-NAME to a RGB color value."
17684 (apply 'format "%s,%s,%s"
17685 (mapcar 'org-normalize-color
17686 (color-values color-name))))
17688 (defun org-normalize-color (value)
17689 "Return string to be used as color value for an RGB component."
17690 (format "%g" (/ value 65535.0)))
17692 ;; Image display
17695 (defvar org-inline-image-overlays nil)
17696 (make-variable-buffer-local 'org-inline-image-overlays)
17698 (defun org-toggle-inline-images (&optional include-linked)
17699 "Toggle the display of inline images.
17700 INCLUDE-LINKED is passed to `org-display-inline-images'."
17701 (interactive "P")
17702 (if org-inline-image-overlays
17703 (progn
17704 (org-remove-inline-images)
17705 (message "Inline image display turned off"))
17706 (org-display-inline-images include-linked)
17707 (if org-inline-image-overlays
17708 (message "%d images displayed inline"
17709 (length org-inline-image-overlays))
17710 (message "No images to display inline"))))
17712 (defun org-redisplay-inline-images ()
17713 "Refresh the display of inline images."
17714 (interactive)
17715 (if (not org-inline-image-overlays)
17716 (org-toggle-inline-images)
17717 (org-toggle-inline-images)
17718 (org-toggle-inline-images)))
17720 (defun org-display-inline-images (&optional include-linked refresh beg end)
17721 "Display inline images.
17722 Normally only links without a description part are inlined, because this
17723 is how it will work for export. When INCLUDE-LINKED is set, also links
17724 with a description part will be inlined. This can be nice for a quick
17725 look at those images, but it does not reflect what exported files will look
17726 like.
17727 When REFRESH is set, refresh existing images between BEG and END.
17728 This will create new image displays only if necessary.
17729 BEG and END default to the buffer boundaries."
17730 (interactive "P")
17731 (unless refresh
17732 (org-remove-inline-images)
17733 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17734 (save-excursion
17735 (save-restriction
17736 (widen)
17737 (setq beg (or beg (point-min)) end (or end (point-max)))
17738 (goto-char beg)
17739 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17740 (substring (org-image-file-name-regexp) 0 -2)
17741 "\\)\\]" (if include-linked "" "\\]")))
17742 old file ov img)
17743 (while (re-search-forward re end t)
17744 (setq old (get-char-property-and-overlay (match-beginning 1)
17745 'org-image-overlay))
17746 (setq file (expand-file-name
17747 (concat (or (match-string 3) "") (match-string 4))))
17748 (when (file-exists-p file)
17749 (if (and (car-safe old) refresh)
17750 (image-refresh (overlay-get (cdr old) 'display))
17751 (setq img (save-match-data (create-image file)))
17752 (when img
17753 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17754 (overlay-put ov 'display img)
17755 (overlay-put ov 'face 'default)
17756 (overlay-put ov 'org-image-overlay t)
17757 (overlay-put ov 'modification-hooks
17758 (list 'org-display-inline-remove-overlay))
17759 (push ov org-inline-image-overlays)))))))))
17761 (define-obsolete-function-alias
17762 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17764 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17765 "Remove inline-display overlay if a corresponding region is modified."
17766 (let ((inhibit-modification-hooks t))
17767 (when (and ov after)
17768 (delete ov org-inline-image-overlays)
17769 (delete-overlay ov))))
17771 (defun org-remove-inline-images ()
17772 "Remove inline display of images."
17773 (interactive)
17774 (mapc 'delete-overlay org-inline-image-overlays)
17775 (setq org-inline-image-overlays nil))
17777 ;;;; Key bindings
17779 ;; Outline functions from `outline-mode-prefix-map'
17780 ;; that can be remapped in Org:
17781 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17782 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17783 (define-key org-mode-map [remap outline-forward-same-level]
17784 'org-forward-heading-same-level)
17785 (define-key org-mode-map [remap outline-backward-same-level]
17786 'org-backward-heading-same-level)
17787 (define-key org-mode-map [remap show-branches]
17788 'org-kill-note-or-show-branches)
17789 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17790 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17791 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17793 ;; Outline functions from `outline-mode-prefix-map' that can not
17794 ;; be remapped in Org:
17796 ;; - the column "key binding" shows whether the Outline function is still
17797 ;; available in Org mode on the same key that it has been bound to in
17798 ;; Outline mode:
17799 ;; - "overridden": key used for a different functionality in Org mode
17800 ;; - else: key still bound to the same Outline function in Org mode
17802 ;; | Outline function | key binding | Org replacement |
17803 ;; |------------------------------------+-------------+-----------------------|
17804 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17805 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17806 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17807 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17808 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17809 ;; | `show-entry' | overridden | no replacement |
17810 ;; | `show-children' | `C-c C-i' | visibility cycling |
17811 ;; | `show-branches' | `C-c C-k' | still same function |
17812 ;; | `show-subtree' | overridden | visibility cycling |
17813 ;; | `show-all' | overridden | no replacement |
17814 ;; | `hide-subtree' | overridden | visibility cycling |
17815 ;; | `hide-body' | overridden | no replacement |
17816 ;; | `hide-entry' | overridden | visibility cycling |
17817 ;; | `hide-leaves' | overridden | no replacement |
17818 ;; | `hide-sublevels' | overridden | no replacement |
17819 ;; | `hide-other' | overridden | no replacement |
17821 ;; Make `C-c C-x' a prefix key
17822 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17824 ;; TAB key with modifiers
17825 (org-defkey org-mode-map "\C-i" 'org-cycle)
17826 (org-defkey org-mode-map [(tab)] 'org-cycle)
17827 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17828 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17829 ;; The following line is necessary under Suse GNU/Linux
17830 (unless (featurep 'xemacs)
17831 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17832 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17833 (define-key org-mode-map [backtab] 'org-shifttab)
17835 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17836 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17837 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17839 ;; Cursor keys with modifiers
17840 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17841 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17842 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17843 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17845 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17846 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17847 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17848 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17850 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17851 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17852 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17853 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17855 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17856 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17857 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17858 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17860 ;; Babel keys
17861 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17862 (mapc (lambda (pair)
17863 (define-key org-babel-map (car pair) (cdr pair)))
17864 org-babel-key-bindings)
17866 ;;; Extra keys for tty access.
17867 ;; We only set them when really needed because otherwise the
17868 ;; menus don't show the simple keys
17870 (when (or org-use-extra-keys
17871 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17872 (not window-system))
17873 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17874 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17875 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17876 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17877 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17878 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17879 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17880 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17881 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17882 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17883 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17884 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17885 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17886 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17887 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17888 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17889 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17890 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17891 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17892 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17893 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17894 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17895 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17896 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17897 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17898 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17899 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17900 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17902 ;; All the other keys
17904 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17905 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17906 (if (boundp 'narrow-map)
17907 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17908 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17909 (if (boundp 'narrow-map)
17910 (org-defkey narrow-map "b" 'org-narrow-to-block)
17911 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17912 (if (boundp 'narrow-map)
17913 (org-defkey narrow-map "e" 'org-narrow-to-element)
17914 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17915 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17916 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17917 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17918 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17919 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17920 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17921 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17922 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17923 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17924 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17925 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17926 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17927 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17928 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17929 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17930 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17931 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17932 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17933 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17934 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17935 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17936 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17937 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17938 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17939 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17940 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17941 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17942 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17943 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17944 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17945 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17946 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17947 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17948 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17949 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17950 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17951 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17952 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17953 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17954 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17955 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17956 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17957 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17958 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17959 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17960 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17961 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17962 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17963 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17964 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17965 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17966 (org-defkey org-mode-map "\C-c^" 'org-sort)
17967 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17968 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17969 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17970 (org-defkey org-mode-map "\C-m" 'org-return)
17971 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17972 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17973 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17974 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17975 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17976 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17977 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17978 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17979 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17980 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17981 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17982 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17983 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17984 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17985 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17986 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17987 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17988 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17989 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17990 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17991 (org-defkey org-mode-map "\M-h" 'org-mark-element)
17992 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17993 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17995 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17996 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17997 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17999 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18000 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18001 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18002 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18003 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18004 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18005 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18006 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18007 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18008 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18009 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18010 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18011 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18012 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18013 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18014 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18015 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18016 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18017 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18018 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18019 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18020 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18022 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18023 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18024 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18025 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18026 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18028 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18030 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18032 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18033 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18035 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18038 (when (featurep 'xemacs)
18039 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18042 (defconst org-speed-commands-default
18044 ("Outline Navigation")
18045 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18046 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18047 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18048 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18049 ("u" . (org-speed-move-safe 'outline-up-heading))
18050 ("j" . org-goto)
18051 ("g" . (org-refile t))
18052 ("Outline Visibility")
18053 ("c" . org-cycle)
18054 ("C" . org-shifttab)
18055 (" " . org-display-outline-path)
18056 (":" . org-columns)
18057 ("Outline Structure Editing")
18058 ("U" . org-shiftmetaup)
18059 ("D" . org-shiftmetadown)
18060 ("r" . org-metaright)
18061 ("l" . org-metaleft)
18062 ("R" . org-shiftmetaright)
18063 ("L" . org-shiftmetaleft)
18064 ("i" . (progn (forward-char 1) (call-interactively
18065 'org-insert-heading-respect-content)))
18066 ("^" . org-sort)
18067 ("w" . org-refile)
18068 ("a" . org-archive-subtree-default-with-confirmation)
18069 ("." . org-mark-subtree)
18070 ("#" . org-toggle-comment)
18071 ("Clock Commands")
18072 ("I" . org-clock-in)
18073 ("O" . org-clock-out)
18074 ("Meta Data Editing")
18075 ("t" . org-todo)
18076 ("," . (org-priority))
18077 ("0" . (org-priority ?\ ))
18078 ("1" . (org-priority ?A))
18079 ("2" . (org-priority ?B))
18080 ("3" . (org-priority ?C))
18081 (";" . org-set-tags-command)
18082 ("e" . org-set-effort)
18083 ("E" . org-inc-effort)
18084 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18085 (org-entry-put (point) "APPT_WARNTIME" m)))
18086 ("Agenda Views etc")
18087 ("v" . org-agenda)
18088 ("/" . org-sparse-tree)
18089 ("Misc")
18090 ("o" . org-open-at-point)
18091 ("?" . org-speed-command-help)
18092 ("<" . (org-agenda-set-restriction-lock 'subtree))
18093 (">" . (org-agenda-remove-restriction-lock))
18095 "The default speed commands.")
18097 (defun org-print-speed-command (e)
18098 (if (> (length (car e)) 1)
18099 (progn
18100 (princ "\n")
18101 (princ (car e))
18102 (princ "\n")
18103 (princ (make-string (length (car e)) ?-))
18104 (princ "\n"))
18105 (princ (car e))
18106 (princ " ")
18107 (if (symbolp (cdr e))
18108 (princ (symbol-name (cdr e)))
18109 (prin1 (cdr e)))
18110 (princ "\n")))
18112 (defun org-speed-command-help ()
18113 "Show the available speed commands."
18114 (interactive)
18115 (if (not org-use-speed-commands)
18116 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18117 (with-output-to-temp-buffer "*Help*"
18118 (princ "User-defined Speed commands\n===========================\n")
18119 (mapc 'org-print-speed-command org-speed-commands-user)
18120 (princ "\n")
18121 (princ "Built-in Speed commands\n=======================\n")
18122 (mapc 'org-print-speed-command org-speed-commands-default))
18123 (with-current-buffer "*Help*"
18124 (setq truncate-lines t))))
18126 (defun org-speed-move-safe (cmd)
18127 "Execute CMD, but make sure that the cursor always ends up in a headline.
18128 If not, return to the original position and throw an error."
18129 (interactive)
18130 (let ((pos (point)))
18131 (call-interactively cmd)
18132 (unless (and (bolp) (org-at-heading-p))
18133 (goto-char pos)
18134 (error "Boundary reached while executing %s" cmd))))
18136 (defvar org-self-insert-command-undo-counter 0)
18138 (defvar org-table-auto-blank-field) ; defined in org-table.el
18139 (defvar org-speed-command nil)
18141 (define-obsolete-function-alias
18142 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18144 (defun org-speed-command-activate (keys)
18145 "Hook for activating single-letter speed commands.
18146 `org-speed-commands-default' specifies a minimal command set.
18147 Use `org-speed-commands-user' for further customization."
18148 (when (or (and (bolp) (looking-at org-outline-regexp))
18149 (and (functionp org-use-speed-commands)
18150 (funcall org-use-speed-commands)))
18151 (cdr (assoc keys (append org-speed-commands-user
18152 org-speed-commands-default)))))
18154 (define-obsolete-function-alias
18155 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18157 (defun org-babel-speed-command-activate (keys)
18158 "Hook for activating single-letter code block commands."
18159 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18160 (cdr (assoc keys org-babel-key-bindings))))
18162 (defcustom org-speed-command-hook
18163 '(org-speed-command-default-hook org-babel-speed-command-hook)
18164 "Hook for activating speed commands at strategic locations.
18165 Hook functions are called in sequence until a valid handler is
18166 found.
18168 Each hook takes a single argument, a user-pressed command key
18169 which is also a `self-insert-command' from the global map.
18171 Within the hook, examine the cursor position and the command key
18172 and return nil or a valid handler as appropriate. Handler could
18173 be one of an interactive command, a function, or a form.
18175 Set `org-use-speed-commands' to non-nil value to enable this
18176 hook. The default setting is `org-speed-command-activate'."
18177 :group 'org-structure
18178 :version "24.1"
18179 :type 'hook)
18181 (defun org-self-insert-command (N)
18182 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18183 If the cursor is in a table looking at whitespace, the whitespace is
18184 overwritten, and the table is not marked as requiring realignment."
18185 (interactive "p")
18186 (org-check-before-invisible-edit 'insert)
18187 (cond
18188 ((and org-use-speed-commands
18189 (setq org-speed-command
18190 (run-hook-with-args-until-success
18191 'org-speed-command-hook (this-command-keys))))
18192 (cond
18193 ((commandp org-speed-command)
18194 (setq this-command org-speed-command)
18195 (call-interactively org-speed-command))
18196 ((functionp org-speed-command)
18197 (funcall org-speed-command))
18198 ((and org-speed-command (listp org-speed-command))
18199 (eval org-speed-command))
18200 (t (let (org-use-speed-commands)
18201 (call-interactively 'org-self-insert-command)))))
18202 ((and
18203 (org-table-p)
18204 (progn
18205 ;; check if we blank the field, and if that triggers align
18206 (and (featurep 'org-table) org-table-auto-blank-field
18207 (member last-command
18208 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18209 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18210 ;; got extra space, this field does not determine column width
18211 (let (org-table-may-need-update) (org-table-blank-field))
18212 ;; no extra space, this field may determine column width
18213 (org-table-blank-field)))
18215 (eq N 1)
18216 (looking-at "[^|\n]* |"))
18217 (let (org-table-may-need-update)
18218 (goto-char (1- (match-end 0)))
18219 (backward-delete-char 1)
18220 (goto-char (match-beginning 0))
18221 (self-insert-command N)))
18223 (setq org-table-may-need-update t)
18224 (self-insert-command N)
18225 (org-fix-tags-on-the-fly)
18226 (if org-self-insert-cluster-for-undo
18227 (if (not (eq last-command 'org-self-insert-command))
18228 (setq org-self-insert-command-undo-counter 1)
18229 (if (>= org-self-insert-command-undo-counter 20)
18230 (setq org-self-insert-command-undo-counter 1)
18231 (and (> org-self-insert-command-undo-counter 0)
18232 buffer-undo-list (listp buffer-undo-list)
18233 (not (cadr buffer-undo-list)) ; remove nil entry
18234 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18235 (setq org-self-insert-command-undo-counter
18236 (1+ org-self-insert-command-undo-counter))))))))
18238 (defun org-check-before-invisible-edit (kind)
18239 "Check is editing if kind KIND would be dangerous with invisible text around.
18240 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18241 ;; First, try to get out of here as quickly as possible, to reduce overhead
18242 (if (and org-catch-invisible-edits
18243 (or (not (boundp 'visible-mode)) (not visible-mode))
18244 (or (get-char-property (point) 'invisible)
18245 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18246 ;; OK, we need to take a closer look
18247 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18248 (invisible-before-point (if (bobp) nil (get-char-property
18249 (1- (point)) 'invisible)))
18250 (border-and-ok-direction
18252 ;; Check if we are acting predictably before invisible text
18253 (and invisible-at-point (not invisible-before-point)
18254 (memq kind '(insert delete-backward)))
18255 ;; Check if we are acting predictably after invisible text
18256 ;; This works not well, and I have turned it off. It seems
18257 ;; better to always show and stop after invisible text.
18258 ;; (and (not invisible-at-point) invisible-before-point
18259 ;; (memq kind '(insert delete)))
18261 (when (or (memq invisible-at-point '(outline org-hide-block t))
18262 (memq invisible-before-point '(outline org-hide-block t)))
18263 (if (eq org-catch-invisible-edits 'error)
18264 (error "Editing in invisible areas is prohibited - make visible first"))
18265 (if (and org-custom-properties-overlays
18266 (y-or-n-p "Display invisible properties in this buffer? "))
18267 (org-toggle-custom-properties-visibility)
18268 ;; Make the area visible
18269 (save-excursion
18270 (if invisible-before-point
18271 (goto-char (previous-single-char-property-change
18272 (point) 'invisible)))
18273 (org-cycle))
18274 (cond
18275 ((eq org-catch-invisible-edits 'show)
18276 ;; That's it, we do the edit after showing
18277 (message
18278 "Unfolding invisible region around point before editing")
18279 (sit-for 1))
18280 ((and (eq org-catch-invisible-edits 'smart)
18281 border-and-ok-direction)
18282 (message "Unfolding invisible region around point before editing"))
18284 ;; Don't do the edit, make the user repeat it in full visibility
18285 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18287 (defun org-fix-tags-on-the-fly ()
18288 (when (and (equal (char-after (point-at-bol)) ?*)
18289 (org-at-heading-p))
18290 (org-align-tags-here org-tags-column)))
18292 (defun org-delete-backward-char (N)
18293 "Like `delete-backward-char', insert whitespace at field end in tables.
18294 When deleting backwards, in tables this function will insert whitespace in
18295 front of the next \"|\" separator, to keep the table aligned. The table will
18296 still be marked for re-alignment if the field did fill the entire column,
18297 because, in this case the deletion might narrow the column."
18298 (interactive "p")
18299 (org-check-before-invisible-edit 'delete-backward)
18300 (if (and (org-table-p)
18301 (eq N 1)
18302 (string-match "|" (buffer-substring (point-at-bol) (point)))
18303 (looking-at ".*?|"))
18304 (let ((pos (point))
18305 (noalign (looking-at "[^|\n\r]* |"))
18306 (c org-table-may-need-update))
18307 (backward-delete-char N)
18308 (if (not overwrite-mode)
18309 (progn
18310 (skip-chars-forward "^|")
18311 (insert " ")
18312 (goto-char (1- pos))))
18313 ;; noalign: if there were two spaces at the end, this field
18314 ;; does not determine the width of the column.
18315 (if noalign (setq org-table-may-need-update c)))
18316 (backward-delete-char N)
18317 (org-fix-tags-on-the-fly)))
18319 (defun org-delete-char (N)
18320 "Like `delete-char', but insert whitespace at field end in tables.
18321 When deleting characters, in tables this function will insert whitespace in
18322 front of the next \"|\" separator, to keep the table aligned. The table will
18323 still be marked for re-alignment if the field did fill the entire column,
18324 because, in this case the deletion might narrow the column."
18325 (interactive "p")
18326 (org-check-before-invisible-edit 'delete)
18327 (if (and (org-table-p)
18328 (not (bolp))
18329 (not (= (char-after) ?|))
18330 (eq N 1))
18331 (if (looking-at ".*?|")
18332 (let ((pos (point))
18333 (noalign (looking-at "[^|\n\r]* |"))
18334 (c org-table-may-need-update))
18335 (replace-match (concat
18336 (substring (match-string 0) 1 -1)
18337 " |"))
18338 (goto-char pos)
18339 ;; noalign: if there were two spaces at the end, this field
18340 ;; does not determine the width of the column.
18341 (if noalign (setq org-table-may-need-update c)))
18342 (delete-char N))
18343 (delete-char N)
18344 (org-fix-tags-on-the-fly)))
18346 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18347 (put 'org-self-insert-command 'delete-selection t)
18348 (put 'orgtbl-self-insert-command 'delete-selection t)
18349 (put 'org-delete-char 'delete-selection 'supersede)
18350 (put 'org-delete-backward-char 'delete-selection 'supersede)
18351 (put 'org-yank 'delete-selection 'yank)
18353 ;; Make `flyspell-mode' delay after some commands
18354 (put 'org-self-insert-command 'flyspell-delayed t)
18355 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18356 (put 'org-delete-char 'flyspell-delayed t)
18357 (put 'org-delete-backward-char 'flyspell-delayed t)
18359 ;; Make pabbrev-mode expand after org-mode commands
18360 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18361 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18363 ;; How to do this: Measure non-white length of current string
18364 ;; If equal to column width, we should realign.
18366 (defun org-remap (map &rest commands)
18367 "In MAP, remap the functions given in COMMANDS.
18368 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18369 (let (new old)
18370 (while commands
18371 (setq old (pop commands) new (pop commands))
18372 (if (fboundp 'command-remapping)
18373 (org-defkey map (vector 'remap old) new)
18374 (substitute-key-definition old new map global-map)))))
18376 (when (eq org-enable-table-editor 'optimized)
18377 ;; If the user wants maximum table support, we need to hijack
18378 ;; some standard editing functions
18379 (org-remap org-mode-map
18380 'self-insert-command 'org-self-insert-command
18381 'delete-char 'org-delete-char
18382 'delete-backward-char 'org-delete-backward-char)
18383 (org-defkey org-mode-map "|" 'org-force-self-insert))
18385 (defvar org-ctrl-c-ctrl-c-hook nil
18386 "Hook for functions attaching themselves to `C-c C-c'.
18388 This can be used to add additional functionality to the C-c C-c
18389 key which executes context-dependent commands. This hook is run
18390 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18391 run after the last test.
18393 Each function will be called with no arguments. The function
18394 must check if the context is appropriate for it to act. If yes,
18395 it should do its thing and then return a non-nil value. If the
18396 context is wrong, just do nothing and return nil.")
18398 (defvar org-ctrl-c-ctrl-c-final-hook nil
18399 "Hook for functions attaching themselves to `C-c C-c'.
18401 This can be used to add additional functionality to the C-c C-c
18402 key which executes context-dependent commands. This hook is run
18403 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18404 before the first test.
18406 Each function will be called with no arguments. The function
18407 must check if the context is appropriate for it to act. If yes,
18408 it should do its thing and then return a non-nil value. If the
18409 context is wrong, just do nothing and return nil.")
18411 (defvar org-tab-first-hook nil
18412 "Hook for functions to attach themselves to TAB.
18413 See `org-ctrl-c-ctrl-c-hook' for more information.
18414 This hook runs as the first action when TAB is pressed, even before
18415 `org-cycle' messes around with the `outline-regexp' to cater for
18416 inline tasks and plain list item folding.
18417 If any function in this hook returns t, any other actions that
18418 would have been caused by TAB (such as table field motion or visibility
18419 cycling) will not occur.")
18421 (defvar org-tab-after-check-for-table-hook nil
18422 "Hook for functions to attach themselves to TAB.
18423 See `org-ctrl-c-ctrl-c-hook' for more information.
18424 This hook runs after it has been established that the cursor is not in a
18425 table, but before checking if the cursor is in a headline or if global cycling
18426 should be done.
18427 If any function in this hook returns t, not other actions like visibility
18428 cycling will be done.")
18430 (defvar org-tab-after-check-for-cycling-hook nil
18431 "Hook for functions to attach themselves to TAB.
18432 See `org-ctrl-c-ctrl-c-hook' for more information.
18433 This hook runs after it has been established that not table field motion and
18434 not visibility should be done because of current context. This is probably
18435 the place where a package like yasnippets can hook in.")
18437 (defvar org-tab-before-tab-emulation-hook nil
18438 "Hook for functions to attach themselves to TAB.
18439 See `org-ctrl-c-ctrl-c-hook' for more information.
18440 This hook runs after every other options for TAB have been exhausted, but
18441 before indentation and \t insertion takes place.")
18443 (defvar org-metaleft-hook nil
18444 "Hook for functions attaching themselves to `M-left'.
18445 See `org-ctrl-c-ctrl-c-hook' for more information.")
18446 (defvar org-metaright-hook nil
18447 "Hook for functions attaching themselves to `M-right'.
18448 See `org-ctrl-c-ctrl-c-hook' for more information.")
18449 (defvar org-metaup-hook nil
18450 "Hook for functions attaching themselves to `M-up'.
18451 See `org-ctrl-c-ctrl-c-hook' for more information.")
18452 (defvar org-metadown-hook nil
18453 "Hook for functions attaching themselves to `M-down'.
18454 See `org-ctrl-c-ctrl-c-hook' for more information.")
18455 (defvar org-shiftmetaleft-hook nil
18456 "Hook for functions attaching themselves to `M-S-left'.
18457 See `org-ctrl-c-ctrl-c-hook' for more information.")
18458 (defvar org-shiftmetaright-hook nil
18459 "Hook for functions attaching themselves to `M-S-right'.
18460 See `org-ctrl-c-ctrl-c-hook' for more information.")
18461 (defvar org-shiftmetaup-hook nil
18462 "Hook for functions attaching themselves to `M-S-up'.
18463 See `org-ctrl-c-ctrl-c-hook' for more information.")
18464 (defvar org-shiftmetadown-hook nil
18465 "Hook for functions attaching themselves to `M-S-down'.
18466 See `org-ctrl-c-ctrl-c-hook' for more information.")
18467 (defvar org-metareturn-hook nil
18468 "Hook for functions attaching themselves to `M-RET'.
18469 See `org-ctrl-c-ctrl-c-hook' for more information.")
18470 (defvar org-shiftup-hook nil
18471 "Hook for functions attaching themselves to `S-up'.
18472 See `org-ctrl-c-ctrl-c-hook' for more information.")
18473 (defvar org-shiftup-final-hook nil
18474 "Hook for functions attaching themselves to `S-up'.
18475 This one runs after all other options except shift-select have been excluded.
18476 See `org-ctrl-c-ctrl-c-hook' for more information.")
18477 (defvar org-shiftdown-hook nil
18478 "Hook for functions attaching themselves to `S-down'.
18479 See `org-ctrl-c-ctrl-c-hook' for more information.")
18480 (defvar org-shiftdown-final-hook nil
18481 "Hook for functions attaching themselves to `S-down'.
18482 This one runs after all other options except shift-select have been excluded.
18483 See `org-ctrl-c-ctrl-c-hook' for more information.")
18484 (defvar org-shiftleft-hook nil
18485 "Hook for functions attaching themselves to `S-left'.
18486 See `org-ctrl-c-ctrl-c-hook' for more information.")
18487 (defvar org-shiftleft-final-hook nil
18488 "Hook for functions attaching themselves to `S-left'.
18489 This one runs after all other options except shift-select have been excluded.
18490 See `org-ctrl-c-ctrl-c-hook' for more information.")
18491 (defvar org-shiftright-hook nil
18492 "Hook for functions attaching themselves to `S-right'.
18493 See `org-ctrl-c-ctrl-c-hook' for more information.")
18494 (defvar org-shiftright-final-hook nil
18495 "Hook for functions attaching themselves to `S-right'.
18496 This one runs after all other options except shift-select have been excluded.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.")
18499 (defun org-modifier-cursor-error ()
18500 "Throw an error, a modified cursor command was applied in wrong context."
18501 (error "This command is active in special context like tables, headlines or items"))
18503 (defun org-shiftselect-error ()
18504 "Throw an error because Shift-Cursor command was applied in wrong context."
18505 (if (and (boundp 'shift-select-mode) shift-select-mode)
18506 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18507 (error "This command works only in special context like headlines or timestamps")))
18509 (defun org-call-for-shift-select (cmd)
18510 (let ((this-command-keys-shift-translated t))
18511 (call-interactively cmd)))
18513 (defun org-shifttab (&optional arg)
18514 "Global visibility cycling or move to previous table field.
18515 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18516 on context.
18517 See the individual commands for more information."
18518 (interactive "P")
18519 (cond
18520 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18521 ((integerp arg)
18522 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18523 (message "Content view to level: %d" arg)
18524 (org-content (prefix-numeric-value arg2))
18525 (setq org-cycle-global-status 'overview)))
18526 (t (call-interactively 'org-global-cycle))))
18528 (defun org-shiftmetaleft ()
18529 "Promote subtree or delete table column.
18530 Calls `org-promote-subtree', `org-outdent-item-tree', or
18531 `org-table-delete-column', depending on context. See the
18532 individual commands for more information."
18533 (interactive)
18534 (cond
18535 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18536 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18537 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18538 ((if (not (org-region-active-p)) (org-at-item-p)
18539 (save-excursion (goto-char (region-beginning))
18540 (org-at-item-p)))
18541 (call-interactively 'org-outdent-item-tree))
18542 (t (org-modifier-cursor-error))))
18544 (defun org-shiftmetaright ()
18545 "Demote subtree or insert table column.
18546 Calls `org-demote-subtree', `org-indent-item-tree', or
18547 `org-table-insert-column', depending on context. See the
18548 individual commands for more information."
18549 (interactive)
18550 (cond
18551 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18552 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18553 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18554 ((if (not (org-region-active-p)) (org-at-item-p)
18555 (save-excursion (goto-char (region-beginning))
18556 (org-at-item-p)))
18557 (call-interactively 'org-indent-item-tree))
18558 (t (org-modifier-cursor-error))))
18560 (defun org-shiftmetaup (&optional arg)
18561 "Move subtree up or kill table row.
18562 Calls `org-move-subtree-up' or `org-table-kill-row' or
18563 `org-move-item-up' or `org-timestamp-up', depending on context.
18564 See the individual commands for more information."
18565 (interactive "P")
18566 (cond
18567 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18568 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18569 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18570 ((org-at-item-p) (call-interactively 'org-move-item-up))
18571 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18572 (call-interactively 'org-timestamp-up)))
18573 (t (org-modifier-cursor-error))))
18575 (defun org-shiftmetadown (&optional arg)
18576 "Move subtree down or insert table row.
18577 Calls `org-move-subtree-down' or `org-table-insert-row' or
18578 `org-move-item-down' or `org-timestamp-up', depending on context.
18579 See the individual commands for more information."
18580 (interactive "P")
18581 (cond
18582 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18583 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18584 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18585 ((org-at-item-p) (call-interactively 'org-move-item-down))
18586 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18587 (call-interactively 'org-timestamp-down)))
18588 (t (org-modifier-cursor-error))))
18590 (defsubst org-hidden-tree-error ()
18591 (error
18592 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18594 (defun org-metaleft (&optional arg)
18595 "Promote heading or move table column to left.
18596 Calls `org-do-promote' or `org-table-move-column', depending on context.
18597 With no specific context, calls the Emacs default `backward-word'.
18598 See the individual commands for more information."
18599 (interactive "P")
18600 (cond
18601 ((run-hook-with-args-until-success 'org-metaleft-hook))
18602 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18603 ((org-with-limited-levels
18604 (or (org-at-heading-p)
18605 (and (org-region-active-p)
18606 (save-excursion
18607 (goto-char (region-beginning))
18608 (org-at-heading-p)))))
18609 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18610 (call-interactively 'org-do-promote))
18611 ;; At an inline task.
18612 ((org-at-heading-p)
18613 (call-interactively 'org-inlinetask-promote))
18614 ((or (org-at-item-p)
18615 (and (org-region-active-p)
18616 (save-excursion
18617 (goto-char (region-beginning))
18618 (org-at-item-p))))
18619 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18620 (call-interactively 'org-outdent-item))
18621 (t (call-interactively 'backward-word))))
18623 (defun org-metaright (&optional arg)
18624 "Demote a subtree, a list item or move table column to right.
18625 In front of a drawer or a block keyword, indent it correctly.
18626 With no specific context, calls the Emacs default `forward-word'.
18627 See the individual commands for more information."
18628 (interactive "P")
18629 (cond
18630 ((run-hook-with-args-until-success 'org-metaright-hook))
18631 ((org-at-table-p) (call-interactively 'org-table-move-column))
18632 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18633 ((org-at-block-p) (call-interactively 'org-indent-block))
18634 ((org-with-limited-levels
18635 (or (org-at-heading-p)
18636 (and (org-region-active-p)
18637 (save-excursion
18638 (goto-char (region-beginning))
18639 (org-at-heading-p)))))
18640 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18641 (call-interactively 'org-do-demote))
18642 ;; At an inline task.
18643 ((org-at-heading-p)
18644 (call-interactively 'org-inlinetask-demote))
18645 ((or (org-at-item-p)
18646 (and (org-region-active-p)
18647 (save-excursion
18648 (goto-char (region-beginning))
18649 (org-at-item-p))))
18650 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18651 (call-interactively 'org-indent-item))
18652 (t (call-interactively 'forward-word))))
18654 (defun org-check-for-hidden (what)
18655 "Check if there are hidden headlines/items in the current visual line.
18656 WHAT can be either `headlines' or `items'. If the current line is
18657 an outline or item heading and it has a folded subtree below it,
18658 this function returns t, nil otherwise."
18659 (let ((re (cond
18660 ((eq what 'headlines) org-outline-regexp-bol)
18661 ((eq what 'items) (org-item-beginning-re))
18662 (t (error "This should not happen"))))
18663 beg end)
18664 (save-excursion
18665 (catch 'exit
18666 (unless (org-region-active-p)
18667 (setq beg (point-at-bol))
18668 (beginning-of-line 2)
18669 (while (and (not (eobp)) ;; this is like `next-line'
18670 (get-char-property (1- (point)) 'invisible))
18671 (beginning-of-line 2))
18672 (setq end (point))
18673 (goto-char beg)
18674 (goto-char (point-at-eol))
18675 (setq end (max end (point)))
18676 (while (re-search-forward re end t)
18677 (if (get-char-property (match-beginning 0) 'invisible)
18678 (throw 'exit t))))
18679 nil))))
18681 (autoload 'org-element-at-point "org-element")
18682 (autoload 'org-element-type "org-element")
18684 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18685 (declare-function org-element-type "org-element" (element))
18686 (declare-function org-element-contents "org-element" (element))
18687 (declare-function org-element-property "org-element" (property element))
18688 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18689 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18690 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18691 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18692 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18694 (defun org-metaup (&optional arg)
18695 "Move subtree up or move table row up.
18696 Calls `org-move-subtree-up' or `org-table-move-row' or
18697 `org-move-item-up', depending on context. See the individual commands
18698 for more information."
18699 (interactive "P")
18700 (cond
18701 ((run-hook-with-args-until-success 'org-metaup-hook))
18702 ((org-region-active-p)
18703 (let* ((a (min (region-beginning) (region-end)))
18704 (b (1- (max (region-beginning) (region-end))))
18705 (c (save-excursion (goto-char a)
18706 (move-beginning-of-line 0)))
18707 (d (save-excursion (goto-char a)
18708 (move-end-of-line 0) (point))))
18709 (transpose-regions a b c d)
18710 (goto-char c)))
18711 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18712 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18713 ((org-at-item-p) (call-interactively 'org-move-item-up))
18714 (t (org-drag-element-backward))))
18716 (defun org-metadown (&optional arg)
18717 "Move subtree down or move table row down.
18718 Calls `org-move-subtree-down' or `org-table-move-row' or
18719 `org-move-item-down', depending on context. See the individual
18720 commands for more information."
18721 (interactive "P")
18722 (cond
18723 ((run-hook-with-args-until-success 'org-metadown-hook))
18724 ((org-region-active-p)
18725 (let* ((a (min (region-beginning) (region-end)))
18726 (b (max (region-beginning) (region-end)))
18727 (c (save-excursion (goto-char b)
18728 (move-beginning-of-line 1)))
18729 (d (save-excursion (goto-char b)
18730 (move-end-of-line 1) (1+ (point)))))
18731 (transpose-regions a b c d)
18732 (goto-char d)))
18733 ((org-at-table-p) (call-interactively 'org-table-move-row))
18734 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18735 ((org-at-item-p) (call-interactively 'org-move-item-down))
18736 (t (org-drag-element-forward))))
18738 (defun org-shiftup (&optional arg)
18739 "Increase item in timestamp or increase priority of current headline.
18740 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18741 depending on context. See the individual commands for more information."
18742 (interactive "P")
18743 (cond
18744 ((run-hook-with-args-until-success 'org-shiftup-hook))
18745 ((and org-support-shift-select (org-region-active-p))
18746 (org-call-for-shift-select 'previous-line))
18747 ((org-at-timestamp-p t)
18748 (call-interactively (if org-edit-timestamp-down-means-later
18749 'org-timestamp-down 'org-timestamp-up)))
18750 ((and (not (eq org-support-shift-select 'always))
18751 org-enable-priority-commands
18752 (org-at-heading-p))
18753 (call-interactively 'org-priority-up))
18754 ((and (not org-support-shift-select) (org-at-item-p))
18755 (call-interactively 'org-previous-item))
18756 ((org-clocktable-try-shift 'up arg))
18757 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18758 (org-support-shift-select
18759 (org-call-for-shift-select 'previous-line))
18760 (t (org-shiftselect-error))))
18762 (defun org-shiftdown (&optional arg)
18763 "Decrease item in timestamp or decrease priority of current headline.
18764 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18765 depending on context. See the individual commands for more information."
18766 (interactive "P")
18767 (cond
18768 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18769 ((and org-support-shift-select (org-region-active-p))
18770 (org-call-for-shift-select 'next-line))
18771 ((org-at-timestamp-p t)
18772 (call-interactively (if org-edit-timestamp-down-means-later
18773 'org-timestamp-up 'org-timestamp-down)))
18774 ((and (not (eq org-support-shift-select 'always))
18775 org-enable-priority-commands
18776 (org-at-heading-p))
18777 (call-interactively 'org-priority-down))
18778 ((and (not org-support-shift-select) (org-at-item-p))
18779 (call-interactively 'org-next-item))
18780 ((org-clocktable-try-shift 'down arg))
18781 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18782 (org-support-shift-select
18783 (org-call-for-shift-select 'next-line))
18784 (t (org-shiftselect-error))))
18786 (defun org-shiftright (&optional arg)
18787 "Cycle the thing at point or in the current line, depending on context.
18788 Depending on context, this does one of the following:
18790 - switch a timestamp at point one day into the future
18791 - on a headline, switch to the next TODO keyword.
18792 - on an item, switch entire list to the next bullet type
18793 - on a property line, switch to the next allowed value
18794 - on a clocktable definition line, move time block into the future"
18795 (interactive "P")
18796 (cond
18797 ((run-hook-with-args-until-success 'org-shiftright-hook))
18798 ((and org-support-shift-select (org-region-active-p))
18799 (org-call-for-shift-select 'forward-char))
18800 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18801 ((and (not (eq org-support-shift-select 'always))
18802 (org-at-heading-p))
18803 (let ((org-inhibit-logging
18804 (not org-treat-S-cursor-todo-selection-as-state-change))
18805 (org-inhibit-blocking
18806 (not org-treat-S-cursor-todo-selection-as-state-change)))
18807 (org-call-with-arg 'org-todo 'right)))
18808 ((or (and org-support-shift-select
18809 (not (eq org-support-shift-select 'always))
18810 (org-at-item-bullet-p))
18811 (and (not org-support-shift-select) (org-at-item-p)))
18812 (org-call-with-arg 'org-cycle-list-bullet nil))
18813 ((and (not (eq org-support-shift-select 'always))
18814 (org-at-property-p))
18815 (call-interactively 'org-property-next-allowed-value))
18816 ((org-clocktable-try-shift 'right arg))
18817 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18818 (org-support-shift-select
18819 (org-call-for-shift-select 'forward-char))
18820 (t (org-shiftselect-error))))
18822 (defun org-shiftleft (&optional arg)
18823 "Cycle the thing at point or in the current line, depending on context.
18824 Depending on context, this does one of the following:
18826 - switch a timestamp at point one day into the past
18827 - on a headline, switch to the previous TODO keyword.
18828 - on an item, switch entire list to the previous bullet type
18829 - on a property line, switch to the previous allowed value
18830 - on a clocktable definition line, move time block into the past"
18831 (interactive "P")
18832 (cond
18833 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18834 ((and org-support-shift-select (org-region-active-p))
18835 (org-call-for-shift-select 'backward-char))
18836 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18837 ((and (not (eq org-support-shift-select 'always))
18838 (org-at-heading-p))
18839 (let ((org-inhibit-logging
18840 (not org-treat-S-cursor-todo-selection-as-state-change))
18841 (org-inhibit-blocking
18842 (not org-treat-S-cursor-todo-selection-as-state-change)))
18843 (org-call-with-arg 'org-todo 'left)))
18844 ((or (and org-support-shift-select
18845 (not (eq org-support-shift-select 'always))
18846 (org-at-item-bullet-p))
18847 (and (not org-support-shift-select) (org-at-item-p)))
18848 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18849 ((and (not (eq org-support-shift-select 'always))
18850 (org-at-property-p))
18851 (call-interactively 'org-property-previous-allowed-value))
18852 ((org-clocktable-try-shift 'left arg))
18853 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18854 (org-support-shift-select
18855 (org-call-for-shift-select 'backward-char))
18856 (t (org-shiftselect-error))))
18858 (defun org-shiftcontrolright ()
18859 "Switch to next TODO set."
18860 (interactive)
18861 (cond
18862 ((and org-support-shift-select (org-region-active-p))
18863 (org-call-for-shift-select 'forward-word))
18864 ((and (not (eq org-support-shift-select 'always))
18865 (org-at-heading-p))
18866 (org-call-with-arg 'org-todo 'nextset))
18867 (org-support-shift-select
18868 (org-call-for-shift-select 'forward-word))
18869 (t (org-shiftselect-error))))
18871 (defun org-shiftcontrolleft ()
18872 "Switch to previous TODO set."
18873 (interactive)
18874 (cond
18875 ((and org-support-shift-select (org-region-active-p))
18876 (org-call-for-shift-select 'backward-word))
18877 ((and (not (eq org-support-shift-select 'always))
18878 (org-at-heading-p))
18879 (org-call-with-arg 'org-todo 'previousset))
18880 (org-support-shift-select
18881 (org-call-for-shift-select 'backward-word))
18882 (t (org-shiftselect-error))))
18884 (defun org-shiftcontrolup ()
18885 "Change timestamps synchronously up in CLOCK log lines."
18886 (interactive)
18887 (cond ((and (not org-support-shift-select)
18888 (org-at-clock-log-p)
18889 (org-at-timestamp-p t))
18890 (org-clock-timestamps-up))
18891 (t (org-shiftselect-error))))
18893 (defun org-shiftcontroldown ()
18894 "Change timestamps synchronously down in CLOCK log lines."
18895 (interactive)
18896 (cond ((and (not org-support-shift-select)
18897 (org-at-clock-log-p)
18898 (org-at-timestamp-p t))
18899 (org-clock-timestamps-down))
18900 (t (org-shiftselect-error))))
18902 (defun org-ctrl-c-ret ()
18903 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18904 (interactive)
18905 (cond
18906 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18907 (t (call-interactively 'org-insert-heading))))
18909 (defun org-find-visible ()
18910 (let ((s (point)))
18911 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18912 (get-char-property s 'invisible)))
18914 (defun org-find-invisible ()
18915 (let ((s (point)))
18916 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18917 (not (get-char-property s 'invisible))))
18920 (defun org-copy-visible (beg end)
18921 "Copy the visible parts of the region."
18922 (interactive "r")
18923 (let (snippets s)
18924 (save-excursion
18925 (save-restriction
18926 (narrow-to-region beg end)
18927 (setq s (goto-char (point-min)))
18928 (while (not (= (point) (point-max)))
18929 (goto-char (org-find-invisible))
18930 (push (buffer-substring s (point)) snippets)
18931 (setq s (goto-char (org-find-visible))))))
18932 (kill-new (apply 'concat (nreverse snippets)))))
18934 (defun org-copy-special ()
18935 "Copy region in table or copy current subtree.
18936 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18937 See the individual commands for more information."
18938 (interactive)
18939 (call-interactively
18940 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18942 (defun org-cut-special ()
18943 "Cut region in table or cut current subtree.
18944 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18945 See the individual commands for more information."
18946 (interactive)
18947 (call-interactively
18948 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18950 (defun org-paste-special (arg)
18951 "Paste rectangular region into table, or past subtree relative to level.
18952 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18953 See the individual commands for more information."
18954 (interactive "P")
18955 (if (org-at-table-p)
18956 (org-table-paste-rectangle)
18957 (org-paste-subtree arg)))
18959 (defsubst org-in-fixed-width-region-p ()
18960 "Is point in a fixed-width region?"
18961 (save-match-data
18962 (eq 'fixed-width (org-element-type (org-element-at-point)))))
18964 (defun org-edit-special (&optional arg)
18965 "Call a special editor for the stuff at point.
18966 When at a table, call the formula editor with `org-table-edit-formulas'.
18967 When in a source code block, call `org-edit-src-code'.
18968 When in a fixed-width region, call `org-edit-fixed-width-region'.
18969 When in an #+include line, visit the included file.
18970 On a link, call `ffap' to visit the link at point.
18971 Otherwise, return a user error."
18972 (interactive)
18973 ;; possibly prep session before editing source
18974 (when (and (org-in-src-block-p) arg)
18975 (let* ((info (org-babel-get-src-block-info))
18976 (lang (nth 0 info))
18977 (params (nth 2 info))
18978 (session (cdr (assoc :session params))))
18979 (when (and info session) ;; we are in a source-code block with a session
18980 (funcall
18981 (intern (concat "org-babel-prep-session:" lang)) session params))))
18982 (cond ;; proceed with `org-edit-special'
18983 ((save-excursion
18984 (beginning-of-line 1)
18985 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18986 (find-file (org-trim (match-string 1))))
18987 ((or (org-at-table-p)
18988 (save-excursion
18989 (beginning-of-line 1)
18990 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18991 (call-interactively 'org-table-edit-formulas))
18992 ((or (org-in-src-block-p) (org-at-table.el-p)) (org-edit-src-code))
18993 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
18994 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
18995 (t (user-error "No special environment to edit here"))))
18997 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18998 (defun org-ctrl-c-ctrl-c (&optional arg)
18999 "Set tags in headline, or update according to changed information at point.
19001 This command does many different things, depending on context:
19003 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19004 this is what we do.
19006 - If the cursor is on a statistics cookie, update it.
19008 - If the cursor is in a headline, prompt for tags and insert them
19009 into the current line, aligned to `org-tags-column'. When called
19010 with prefix arg, realign all tags in the current buffer.
19012 - If the cursor is in one of the special #+KEYWORD lines, this
19013 triggers scanning the buffer for these lines and updating the
19014 information.
19016 - If the cursor is inside a table, realign the table. This command
19017 works even if the automatic table editor has been turned off.
19019 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19020 the entire table.
19022 - If the cursor is at a footnote reference or definition, jump to
19023 the corresponding definition or references, respectively.
19025 - If the cursor is a the beginning of a dynamic block, update it.
19027 - If the current buffer is a capture buffer, close note and file it.
19029 - If the cursor is on a <<<target>>>, update radio targets and
19030 corresponding links in this buffer.
19032 - If the cursor is on a numbered item in a plain list, renumber the
19033 ordered list.
19035 - If the cursor is on a checkbox, toggle it.
19037 - If the cursor is on a code block, evaluate it. The variable
19038 `org-confirm-babel-evaluate' can be used to control prompting
19039 before code block evaluation, by default every code block
19040 evaluation requires confirmation. Code block evaluation can be
19041 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19042 (interactive "P")
19043 (let ((org-enable-table-editor t))
19044 (cond
19045 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19046 org-occur-highlights
19047 org-latex-fragment-image-overlays)
19048 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19049 (org-remove-occur-highlights)
19050 (org-remove-latex-fragment-image-overlays)
19051 (message "Temporary highlights/overlays removed from current buffer"))
19052 ((and (local-variable-p 'org-finish-function (current-buffer))
19053 (fboundp org-finish-function))
19054 (funcall org-finish-function))
19055 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19056 ((org-in-regexp org-ts-regexp-both)
19057 (org-timestamp-change 0 'day))
19058 ((or (looking-at org-property-start-re)
19059 (org-at-property-p))
19060 (call-interactively 'org-property-action))
19061 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19062 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19063 (or (org-at-heading-p) (org-at-item-p)))
19064 (call-interactively 'org-update-statistics-cookies))
19065 ((org-at-heading-p) (call-interactively 'org-set-tags))
19066 ((org-at-table.el-p)
19067 (message "Use C-c ' to edit table.el tables"))
19068 ((org-at-table-p)
19069 (org-table-maybe-eval-formula)
19070 (if arg
19071 (call-interactively 'org-table-recalculate)
19072 (org-table-maybe-recalculate-line))
19073 (call-interactively 'org-table-align)
19074 (orgtbl-send-table 'maybe))
19075 ((or (org-footnote-at-reference-p)
19076 (org-footnote-at-definition-p))
19077 (call-interactively 'org-footnote-action))
19078 ((org-at-item-checkbox-p)
19079 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19080 ;; list only if at top item.
19081 (let* ((cbox (match-string 1))
19082 (struct (org-list-struct))
19083 (old-struct (copy-tree struct))
19084 (parents (org-list-parents-alist struct))
19085 (orderedp (org-entry-get nil "ORDERED"))
19086 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19087 block-item)
19088 ;; Use a light version of `org-toggle-checkbox' to avoid
19089 ;; computing list structure twice.
19090 (let ((new-box (cond
19091 ((equal arg '(16)) "[-]")
19092 ((equal arg '(4)) nil)
19093 ((equal "[X]" cbox) "[ ]")
19094 (t "[X]"))))
19095 (if (and firstp arg)
19096 ;; If at first item of sub-list, remove check-box from
19097 ;; every item at the same level.
19098 (mapc
19099 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19100 (org-list-get-all-items
19101 (point-at-bol) struct (org-list-prevs-alist struct)))
19102 (org-list-set-checkbox (point-at-bol) struct new-box)))
19103 ;; Replicate `org-list-write-struct', while grabbing a return
19104 ;; value from `org-list-struct-fix-box'.
19105 (org-list-struct-fix-ind struct parents 2)
19106 (org-list-struct-fix-item-end struct)
19107 (let ((prevs (org-list-prevs-alist struct)))
19108 (org-list-struct-fix-bul struct prevs)
19109 (org-list-struct-fix-ind struct parents)
19110 (setq block-item
19111 (org-list-struct-fix-box struct parents prevs orderedp)))
19112 (org-list-struct-apply-struct struct old-struct)
19113 (org-update-checkbox-count-maybe)
19114 (when block-item
19115 (message
19116 "Checkboxes were removed due to unchecked box at line %d"
19117 (org-current-line block-item)))
19118 (when firstp (org-list-send-list 'maybe))))
19119 ((org-at-item-p)
19120 ;; Cursor at an item: repair list. Do checkbox related actions
19121 ;; only if function was called with an argument. Send list only
19122 ;; if at top item.
19123 (let* ((struct (org-list-struct))
19124 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19125 old-struct)
19126 (when arg
19127 (setq old-struct (copy-tree struct))
19128 (if firstp
19129 ;; If at first item of sub-list, add check-box to every
19130 ;; item at the same level.
19131 (mapc
19132 (lambda (pos)
19133 (unless (org-list-get-checkbox pos struct)
19134 (org-list-set-checkbox pos struct "[ ]")))
19135 (org-list-get-all-items
19136 (point-at-bol) struct (org-list-prevs-alist struct)))
19137 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19138 (org-list-write-struct
19139 struct (org-list-parents-alist struct) old-struct)
19140 (when arg (org-update-checkbox-count-maybe))
19141 (when firstp (org-list-send-list 'maybe))))
19142 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19143 ;; Dynamic block
19144 (beginning-of-line 1)
19145 (save-excursion (org-update-dblock)))
19146 ((save-excursion
19147 (let ((case-fold-search t))
19148 (beginning-of-line 1)
19149 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19150 (cond
19151 ((or (equal (match-string 1) "TBLFM")
19152 (equal (match-string 1) "tblfm"))
19153 ;; Recalculate the table before this line
19154 (save-excursion
19155 (beginning-of-line 1)
19156 (skip-chars-backward " \r\n\t")
19157 (if (org-at-table-p)
19158 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19160 (let ((org-inhibit-startup-visibility-stuff t)
19161 (org-startup-align-all-tables nil))
19162 (when (boundp 'org-table-coordinate-overlays)
19163 (mapc 'delete-overlay org-table-coordinate-overlays)
19164 (setq org-table-coordinate-overlays nil))
19165 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19166 (message "Local setup has been refreshed"))))
19167 ((org-clock-update-time-maybe))
19169 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19170 (error "C-c C-c can do nothing useful at this location"))))))
19172 (defun org-mode-restart ()
19173 "Restart Org-mode, to scan again for special lines.
19174 Also updates the keyword regular expressions."
19175 (interactive)
19176 (org-mode)
19177 (message "Org-mode restarted"))
19179 (defun org-kill-note-or-show-branches ()
19180 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19181 (interactive)
19182 (if (not org-finish-function)
19183 (progn
19184 (hide-subtree)
19185 (call-interactively 'show-branches))
19186 (let ((org-note-abort t))
19187 (funcall org-finish-function))))
19189 (defun org-return (&optional indent)
19190 "Goto next table row or insert a newline.
19191 Calls `org-table-next-row' or `newline', depending on context.
19192 See the individual commands for more information."
19193 (interactive)
19194 (let (org-ts-what)
19195 (cond
19196 ((or (bobp) (org-in-src-block-p))
19197 (if indent (newline-and-indent) (newline)))
19198 ((org-at-table-p)
19199 (org-table-justify-field-maybe)
19200 (call-interactively 'org-table-next-row))
19201 ;; when `newline-and-indent' is called within a list, make sure
19202 ;; text moved stays inside the item.
19203 ((and (org-in-item-p) indent)
19204 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19205 (progn
19206 (save-match-data (newline))
19207 (org-indent-line-to (length (match-string 0))))
19208 (let ((ind (org-get-indentation)))
19209 (newline)
19210 (if (org-looking-back org-list-end-re)
19211 (org-indent-line)
19212 (org-indent-line-to ind)))))
19213 ((and org-return-follows-link
19214 (org-at-timestamp-p t)
19215 (not (eq org-ts-what 'after)))
19216 (org-follow-timestamp-link))
19217 ((and org-return-follows-link
19218 (let ((tprop (get-text-property (point) 'face)))
19219 (or (eq tprop 'org-link)
19220 (and (listp tprop) (memq 'org-link tprop)))))
19221 (call-interactively 'org-open-at-point))
19222 ((and (org-at-heading-p)
19223 (looking-at
19224 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19225 (org-show-entry)
19226 (end-of-line 1)
19227 (newline))
19228 (t (if indent (newline-and-indent) (newline))))))
19230 (defun org-return-indent ()
19231 "Goto next table row or insert a newline and indent.
19232 Calls `org-table-next-row' or `newline-and-indent', depending on
19233 context. See the individual commands for more information."
19234 (interactive)
19235 (org-return t))
19237 (defun org-ctrl-c-star ()
19238 "Compute table, or change heading status of lines.
19239 Calls `org-table-recalculate' or `org-toggle-heading',
19240 depending on context."
19241 (interactive)
19242 (cond
19243 ((org-at-table-p)
19244 (call-interactively 'org-table-recalculate))
19246 ;; Convert all lines in region to list items
19247 (call-interactively 'org-toggle-heading))))
19249 (defun org-ctrl-c-minus ()
19250 "Insert separator line in table or modify bullet status of line.
19251 Also turns a plain line or a region of lines into list items.
19252 Calls `org-table-insert-hline', `org-toggle-item', or
19253 `org-cycle-list-bullet', depending on context."
19254 (interactive)
19255 (cond
19256 ((org-at-table-p)
19257 (call-interactively 'org-table-insert-hline))
19258 ((org-region-active-p)
19259 (call-interactively 'org-toggle-item))
19260 ((org-in-item-p)
19261 (call-interactively 'org-cycle-list-bullet))
19263 (call-interactively 'org-toggle-item))))
19265 (defun org-toggle-item (arg)
19266 "Convert headings or normal lines to items, items to normal lines.
19267 If there is no active region, only the current line is considered.
19269 If the first non blank line in the region is an headline, convert
19270 all headlines to items, shifting text accordingly.
19272 If it is an item, convert all items to normal lines.
19274 If it is normal text, change region into an item. With a prefix
19275 argument ARG, change each line in region into an item."
19276 (interactive "P")
19277 (let ((shift-text
19278 (function
19279 ;; Shift text in current section to IND, from point to END.
19280 ;; The function leaves point to END line.
19281 (lambda (ind end)
19282 (let ((min-i 1000) (end (copy-marker end)))
19283 ;; First determine the minimum indentation (MIN-I) of
19284 ;; the text.
19285 (save-excursion
19286 (catch 'exit
19287 (while (< (point) end)
19288 (let ((i (org-get-indentation)))
19289 (cond
19290 ;; Skip blank lines and inline tasks.
19291 ((looking-at "^[ \t]*$"))
19292 ((looking-at org-outline-regexp-bol))
19293 ;; We can't find less than 0 indentation.
19294 ((zerop i) (throw 'exit (setq min-i 0)))
19295 ((< i min-i) (setq min-i i))))
19296 (forward-line))))
19297 ;; Then indent each line so that a line indented to
19298 ;; MIN-I becomes indented to IND. Ignore blank lines
19299 ;; and inline tasks in the process.
19300 (let ((delta (- ind min-i)))
19301 (while (< (point) end)
19302 (unless (or (looking-at "^[ \t]*$")
19303 (looking-at org-outline-regexp-bol))
19304 (org-indent-line-to (+ (org-get-indentation) delta)))
19305 (forward-line)))))))
19306 (skip-blanks
19307 (function
19308 ;; Return beginning of first non-blank line, starting from
19309 ;; line at POS.
19310 (lambda (pos)
19311 (save-excursion
19312 (goto-char pos)
19313 (skip-chars-forward " \r\t\n")
19314 (point-at-bol)))))
19315 beg end)
19316 ;; Determine boundaries of changes.
19317 (if (org-region-active-p)
19318 (setq beg (funcall skip-blanks (region-beginning))
19319 end (copy-marker (region-end)))
19320 (setq beg (funcall skip-blanks (point-at-bol))
19321 end (copy-marker (point-at-eol))))
19322 ;; Depending on the starting line, choose an action on the text
19323 ;; between BEG and END.
19324 (org-with-limited-levels
19325 (save-excursion
19326 (goto-char beg)
19327 (cond
19328 ;; Case 1. Start at an item: de-itemize. Note that it only
19329 ;; happens when a region is active: `org-ctrl-c-minus'
19330 ;; would call `org-cycle-list-bullet' otherwise.
19331 ((org-at-item-p)
19332 (while (< (point) end)
19333 (when (org-at-item-p)
19334 (skip-chars-forward " \t")
19335 (delete-region (point) (match-end 0)))
19336 (forward-line)))
19337 ;; Case 2. Start at an heading: convert to items.
19338 ((org-at-heading-p)
19339 (let* ((bul (org-list-bullet-string "-"))
19340 (bul-len (length bul))
19341 ;; Indentation of the first heading. It should be
19342 ;; relative to the indentation of its parent, if any.
19343 (start-ind (save-excursion
19344 (cond
19345 ((not org-adapt-indentation) 0)
19346 ((not (outline-previous-heading)) 0)
19347 (t (length (match-string 0))))))
19348 ;; Level of first heading. Further headings will be
19349 ;; compared to it to determine hierarchy in the list.
19350 (ref-level (org-reduced-level (org-outline-level))))
19351 (while (< (point) end)
19352 (let* ((level (org-reduced-level (org-outline-level)))
19353 (delta (max 0 (- level ref-level))))
19354 ;; If current headline is less indented than the first
19355 ;; one, set it as reference, in order to preserve
19356 ;; subtrees.
19357 (when (< level ref-level) (setq ref-level level))
19358 (replace-match bul t t)
19359 (org-indent-line-to (+ start-ind (* delta bul-len)))
19360 ;; Ensure all text down to END (or SECTION-END) belongs
19361 ;; to the newly created item.
19362 (let ((section-end (save-excursion
19363 (or (outline-next-heading) (point)))))
19364 (forward-line)
19365 (funcall shift-text
19366 (+ start-ind (* (1+ delta) bul-len))
19367 (min end section-end)))))))
19368 ;; Case 3. Normal line with ARG: turn each non-item line into
19369 ;; an item.
19370 (arg
19371 (while (< (point) end)
19372 (unless (or (org-at-heading-p) (org-at-item-p))
19373 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19374 (replace-match
19375 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19376 (forward-line)))
19377 ;; Case 4. Normal line without ARG: make the first line of
19378 ;; region an item, and shift indentation of others
19379 ;; lines to set them as item's body.
19380 (t (let* ((bul (org-list-bullet-string "-"))
19381 (bul-len (length bul))
19382 (ref-ind (org-get-indentation)))
19383 (skip-chars-forward " \t")
19384 (insert bul)
19385 (forward-line)
19386 (while (< (point) end)
19387 ;; Ensure that lines less indented than first one
19388 ;; still get included in item body.
19389 (funcall shift-text
19390 (+ ref-ind bul-len)
19391 (min end (save-excursion (or (outline-next-heading)
19392 (point)))))
19393 (forward-line)))))))))
19395 (defun org-toggle-heading (&optional nstars)
19396 "Convert headings to normal text, or items or text to headings.
19397 If there is no active region, only the current line is considered.
19399 With a \\[universal-argument] prefix, convert the whole list at
19400 point into heading.
19402 In a region:
19404 - If the first non blank line is an headline, remove the stars
19405 from all headlines in the region.
19407 - If it is a normal line turn each and every normal line (i.e. not an
19408 heading or an item) in the region into a heading.
19410 - If it is a plain list item, turn all plain list items into headings.
19412 When converting a line into a heading, the number of stars is chosen
19413 such that the lines become children of the current entry. However,
19414 when a prefix argument is given, its value determines the number of
19415 stars to add."
19416 (interactive "P")
19417 (let ((skip-blanks
19418 (function
19419 ;; Return beginning of first non-blank line, starting from
19420 ;; line at POS.
19421 (lambda (pos)
19422 (save-excursion
19423 (goto-char pos)
19424 (while (org-at-comment-p) (forward-line))
19425 (skip-chars-forward " \r\t\n")
19426 (point-at-bol)))))
19427 beg end toggled)
19428 ;; Determine boundaries of changes. If a universal prefix has
19429 ;; been given, put the list in a region. If region ends at a bol,
19430 ;; do not consider the last line to be in the region.
19432 (when (and current-prefix-arg (org-at-item-p))
19433 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19434 (org-mark-element))
19436 (if (org-region-active-p)
19437 (setq beg (funcall skip-blanks (region-beginning))
19438 end (copy-marker (save-excursion
19439 (goto-char (region-end))
19440 (if (bolp) (point) (point-at-eol)))))
19441 (setq beg (funcall skip-blanks (point-at-bol))
19442 end (copy-marker (point-at-eol))))
19443 ;; Ensure inline tasks don't count as headings.
19444 (org-with-limited-levels
19445 (save-excursion
19446 (goto-char beg)
19447 (cond
19448 ;; Case 1. Started at an heading: de-star headings.
19449 ((org-at-heading-p)
19450 (while (< (point) end)
19451 (when (org-at-heading-p t)
19452 (looking-at org-outline-regexp) (replace-match "")
19453 (setq toggled t))
19454 (forward-line)))
19455 ;; Case 2. Started at an item: change items into headlines.
19456 ;; One star will be added by `org-list-to-subtree'.
19457 ((org-at-item-p)
19458 (let* ((stars (make-string
19459 (if nstars
19460 ;; subtract the star that will be added again by
19461 ;; `org-list-to-subtree'
19462 (1- (prefix-numeric-value current-prefix-arg))
19463 (or (org-current-level) 0))
19464 ?*))
19465 (add-stars
19466 (cond (nstars "") ; stars from prefix only
19467 ((equal stars "") "") ; before first heading
19468 (org-odd-levels-only "*") ; inside heading, odd
19469 (t "")))) ; inside heading, oddeven
19470 (while (< (point) end)
19471 (when (org-at-item-p)
19472 ;; Pay attention to cases when region ends before list.
19473 (let* ((struct (org-list-struct))
19474 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19475 (save-restriction
19476 (narrow-to-region (point) list-end)
19477 (insert
19478 (org-list-to-subtree
19479 (org-list-parse-list t)
19480 '(:istart (concat stars add-stars (funcall get-stars depth))
19481 :icount (concat stars add-stars (funcall get-stars depth)))))))
19482 (setq toggled t))
19483 (forward-line))))
19484 ;; Case 3. Started at normal text: make every line an heading,
19485 ;; skipping headlines and items.
19486 (t (let* ((stars (make-string
19487 (if nstars
19488 (prefix-numeric-value current-prefix-arg)
19489 (or (org-current-level) 0))
19490 ?*))
19491 (add-stars
19492 (cond (nstars "") ; stars from prefix only
19493 ((equal stars "") "*") ; before first heading
19494 (org-odd-levels-only "**") ; inside heading, odd
19495 (t "*"))) ; inside heading, oddeven
19496 (rpl (concat stars add-stars " ")))
19497 (while (< (point) end)
19498 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19499 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19500 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19501 (forward-line)))))))
19502 (unless toggled (message "Cannot toggle heading from here"))))
19504 (defun org-meta-return (&optional arg)
19505 "Insert a new heading or wrap a region in a table.
19506 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19507 See the individual commands for more information."
19508 (interactive "P")
19509 (cond
19510 ((run-hook-with-args-until-success 'org-metareturn-hook))
19511 ((or (org-at-drawer-p) (org-at-property-p))
19512 (newline-and-indent))
19513 ((org-at-table-p)
19514 (call-interactively 'org-table-wrap-region))
19515 (t (call-interactively 'org-insert-heading))))
19517 ;;; Menu entries
19519 (defsubst org-in-subtree-not-table-p ()
19520 "Are we in a subtree and not in a table?"
19521 (and (not (org-before-first-heading-p))
19522 (not (org-at-table-p))))
19524 ;; Define the Org-mode menus
19525 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19526 '("Tbl"
19527 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19528 ["Next Field" org-cycle (org-at-table-p)]
19529 ["Previous Field" org-shifttab (org-at-table-p)]
19530 ["Next Row" org-return (org-at-table-p)]
19531 "--"
19532 ["Blank Field" org-table-blank-field (org-at-table-p)]
19533 ["Edit Field" org-table-edit-field (org-at-table-p)]
19534 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19535 "--"
19536 ("Column"
19537 ["Move Column Left" org-metaleft (org-at-table-p)]
19538 ["Move Column Right" org-metaright (org-at-table-p)]
19539 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19540 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19541 ("Row"
19542 ["Move Row Up" org-metaup (org-at-table-p)]
19543 ["Move Row Down" org-metadown (org-at-table-p)]
19544 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19545 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19546 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19547 "--"
19548 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19549 ("Rectangle"
19550 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19551 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19552 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19553 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19554 "--"
19555 ("Calculate"
19556 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19557 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19558 ["Edit Formulas" org-edit-special (org-at-table-p)]
19559 "--"
19560 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19561 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19562 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19563 "--"
19564 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19565 "--"
19566 ["Sum Column/Rectangle" org-table-sum
19567 (or (org-at-table-p) (org-region-active-p))]
19568 ["Which Column?" org-table-current-column (org-at-table-p)])
19569 ["Debug Formulas"
19570 org-table-toggle-formula-debugger
19571 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19572 ["Show Col/Row Numbers"
19573 org-table-toggle-coordinate-overlays
19574 :style toggle
19575 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19576 "--"
19577 ["Create" org-table-create (and (not (org-at-table-p))
19578 org-enable-table-editor)]
19579 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19580 ["Import from File" org-table-import (not (org-at-table-p))]
19581 ["Export to File" org-table-export (org-at-table-p)]
19582 "--"
19583 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19585 (easy-menu-define org-org-menu org-mode-map "Org menu"
19586 '("Org"
19587 ("Show/Hide"
19588 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19589 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19590 ["Sparse Tree..." org-sparse-tree t]
19591 ["Reveal Context" org-reveal t]
19592 ["Show All" show-all t]
19593 "--"
19594 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19595 "--"
19596 ["New Heading" org-insert-heading t]
19597 ("Navigate Headings"
19598 ["Up" outline-up-heading t]
19599 ["Next" outline-next-visible-heading t]
19600 ["Previous" outline-previous-visible-heading t]
19601 ["Next Same Level" outline-forward-same-level t]
19602 ["Previous Same Level" outline-backward-same-level t]
19603 "--"
19604 ["Jump" org-goto t])
19605 ("Edit Structure"
19606 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19607 "--"
19608 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19609 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19610 "--"
19611 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19612 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19613 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19614 "--"
19615 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19616 "--"
19617 ["Copy visible text" org-copy-visible t]
19618 "--"
19619 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19620 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19621 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19622 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19623 "--"
19624 ["Sort Region/Children" org-sort t]
19625 "--"
19626 ["Convert to odd levels" org-convert-to-odd-levels t]
19627 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19628 ("Editing"
19629 ["Emphasis..." org-emphasize t]
19630 ["Edit Source Example" org-edit-special t]
19631 "--"
19632 ["Footnote new/jump" org-footnote-action t]
19633 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19634 ("Archive"
19635 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19636 "--"
19637 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19638 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19639 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19641 "--"
19642 ("Hyperlinks"
19643 ["Store Link (Global)" org-store-link t]
19644 ["Find existing link to here" org-occur-link-in-agenda-files t]
19645 ["Insert Link" org-insert-link t]
19646 ["Follow Link" org-open-at-point t]
19647 "--"
19648 ["Next link" org-next-link t]
19649 ["Previous link" org-previous-link t]
19650 "--"
19651 ["Descriptive Links"
19652 org-toggle-link-display
19653 :style radio
19654 :selected org-descriptive-links
19656 ["Literal Links"
19657 org-toggle-link-display
19658 :style radio
19659 :selected (not org-descriptive-links)])
19660 "--"
19661 ("TODO Lists"
19662 ["TODO/DONE/-" org-todo t]
19663 ("Select keyword"
19664 ["Next keyword" org-shiftright (org-at-heading-p)]
19665 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19666 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19667 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19668 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19669 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19670 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19671 "--"
19672 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19673 :selected org-enforce-todo-dependencies :style toggle :active t]
19674 "Settings for tree at point"
19675 ["Do Children sequentially" org-toggle-ordered-property :style radio
19676 :selected (org-entry-get nil "ORDERED")
19677 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19678 ["Do Children parallel" org-toggle-ordered-property :style radio
19679 :selected (not (org-entry-get nil "ORDERED"))
19680 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19681 "--"
19682 ["Set Priority" org-priority t]
19683 ["Priority Up" org-shiftup t]
19684 ["Priority Down" org-shiftdown t]
19685 "--"
19686 ["Get news from all feeds" org-feed-update-all t]
19687 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19688 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19689 ("TAGS and Properties"
19690 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19691 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19692 "--"
19693 ["Set property" org-set-property (not (org-before-first-heading-p))]
19694 ["Column view of properties" org-columns t]
19695 ["Insert Column View DBlock" org-insert-columns-dblock t])
19696 ("Dates and Scheduling"
19697 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19698 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19699 ("Change Date"
19700 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19701 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19702 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19703 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19704 ["Compute Time Range" org-evaluate-time-range t]
19705 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19706 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19707 "--"
19708 ["Custom time format" org-toggle-time-stamp-overlays
19709 :style radio :selected org-display-custom-times]
19710 "--"
19711 ["Goto Calendar" org-goto-calendar t]
19712 ["Date from Calendar" org-date-from-calendar t]
19713 "--"
19714 ["Start/Restart Timer" org-timer-start t]
19715 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19716 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19717 ["Insert Timer String" org-timer t]
19718 ["Insert Timer Item" org-timer-item t])
19719 ("Logging work"
19720 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19721 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19722 ["Clock out" org-clock-out t]
19723 ["Clock cancel" org-clock-cancel t]
19724 "--"
19725 ["Mark as default task" org-clock-mark-default-task t]
19726 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19727 ["Goto running clock" org-clock-goto t]
19728 "--"
19729 ["Display times" org-clock-display t]
19730 ["Create clock table" org-clock-report t]
19731 "--"
19732 ["Record DONE time"
19733 (progn (setq org-log-done (not org-log-done))
19734 (message "Switching to %s will %s record a timestamp"
19735 (car org-done-keywords)
19736 (if org-log-done "automatically" "not")))
19737 :style toggle :selected org-log-done])
19738 "--"
19739 ["Agenda Command..." org-agenda t]
19740 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19741 ("File List for Agenda")
19742 ("Special views current file"
19743 ["TODO Tree" org-show-todo-tree t]
19744 ["Check Deadlines" org-check-deadlines t]
19745 ["Timeline" org-timeline t]
19746 ["Tags/Property tree" org-match-sparse-tree t])
19747 "--"
19748 ["Export/Publish..." org-export t]
19749 ("LaTeX"
19750 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19751 :selected org-cdlatex-mode]
19752 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19753 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19754 ["Modify math symbol" org-cdlatex-math-modify
19755 (org-inside-LaTeX-fragment-p)]
19756 ["Insert citation" org-reftex-citation t]
19757 "--"
19758 ["Template for BEAMER" (progn (require 'org-beamer)
19759 (org-insert-beamer-options-template)) t])
19760 "--"
19761 ("MobileOrg"
19762 ["Push Files and Views" org-mobile-push t]
19763 ["Get Captured and Flagged" org-mobile-pull t]
19764 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19765 "--"
19766 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19767 "--"
19768 ("Documentation"
19769 ["Show Version" org-version t]
19770 ["Info Documentation" org-info t])
19771 ("Customize"
19772 ["Browse Org Group" org-customize t]
19773 "--"
19774 ["Expand This Menu" org-create-customize-menu
19775 (fboundp 'customize-menu-create)])
19776 ["Send bug report" org-submit-bug-report t]
19777 "--"
19778 ("Refresh/Reload"
19779 ["Refresh setup current buffer" org-mode-restart t]
19780 ["Reload Org (after update)" org-reload t]
19781 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19784 (defun org-info (&optional node)
19785 "Read documentation for Org-mode in the info system.
19786 With optional NODE, go directly to that node."
19787 (interactive)
19788 (info (format "(org)%s" (or node ""))))
19790 ;;;###autoload
19791 (defun org-submit-bug-report ()
19792 "Submit a bug report on Org-mode via mail.
19794 Don't hesitate to report any problems or inaccurate documentation.
19796 If you don't have setup sending mail from (X)Emacs, please copy the
19797 output buffer into your mail program, as it gives us important
19798 information about your Org-mode version and configuration."
19799 (interactive)
19800 (require 'reporter)
19801 (org-load-modules-maybe)
19802 (org-require-autoloaded-modules)
19803 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19804 (reporter-submit-bug-report
19805 "emacs-orgmode@gnu.org"
19806 (org-version nil 'full)
19807 (let (list)
19808 (save-window-excursion
19809 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19810 (delete-other-windows)
19811 (erase-buffer)
19812 (insert "You are about to submit a bug report to the Org-mode mailing list.
19814 We would like to add your full Org-mode and Outline configuration to the
19815 bug report. This greatly simplifies the work of the maintainer and
19816 other experts on the mailing list.
19818 HOWEVER, some variables you have customized may contain private
19819 information. The names of customers, colleagues, or friends, might
19820 appear in the form of file names, tags, todo states, or search strings.
19821 If you answer yes to the prompt, you might want to check and remove
19822 such private information before sending the email.")
19823 (add-text-properties (point-min) (point-max) '(face org-warning))
19824 (when (yes-or-no-p "Include your Org-mode configuration ")
19825 (mapatoms
19826 (lambda (v)
19827 (and (boundp v)
19828 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19829 (or (and (symbol-value v)
19830 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19831 (and
19832 (get v 'custom-type) (get v 'standard-value)
19833 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19834 (push v list)))))
19835 (kill-buffer (get-buffer "*Warn about privacy*"))
19836 list))
19837 nil nil
19838 "Remember to cover the basics, that is, what you expected to happen and
19839 what in fact did happen. You don't know how to make a good report? See
19841 http://orgmode.org/manual/Feedback.html#Feedback
19843 Your bug report will be posted to the Org-mode mailing list.
19844 ------------------------------------------------------------------------")
19845 (save-excursion
19846 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19847 (replace-match "\\1Bug: \\3 [\\2]")))))
19850 (defun org-install-agenda-files-menu ()
19851 (let ((bl (buffer-list)))
19852 (save-excursion
19853 (while bl
19854 (set-buffer (pop bl))
19855 (if (derived-mode-p 'org-mode) (setq bl nil)))
19856 (when (derived-mode-p 'org-mode)
19857 (easy-menu-change
19858 '("Org") "File List for Agenda"
19859 (append
19860 (list
19861 ["Edit File List" (org-edit-agenda-file-list) t]
19862 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19863 ["Remove Current File from List" org-remove-file t]
19864 ["Cycle through agenda files" org-cycle-agenda-files t]
19865 ["Occur in all agenda files" org-occur-in-agenda-files t]
19866 "--")
19867 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19869 ;;;; Documentation
19871 (defun org-require-autoloaded-modules ()
19872 (interactive)
19873 (mapc 'require
19874 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19875 org-docbook org-exp org-html org-icalendar
19876 org-id org-latex
19877 org-publish org-remember org-table
19878 org-timer org-xoxo)))
19880 ;;;###autoload
19881 (defun org-reload (&optional uncompiled)
19882 "Reload all org lisp files.
19883 With prefix arg UNCOMPILED, load the uncompiled versions."
19884 (interactive "P")
19885 (require 'find-func)
19886 (let* ((file-re "^org\\(-.*\\)?\\.el")
19887 (dir-org (file-name-directory (org-find-library-dir "org")))
19888 (dir-org-contrib (ignore-errors
19889 (file-name-directory
19890 (org-find-library-dir "org-contribdir"))))
19891 (babel-files
19892 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19893 (append (list nil "comint" "eval" "exp" "keys"
19894 "lob" "ref" "table" "tangle")
19895 (delq nil
19896 (mapcar
19897 (lambda (lang)
19898 (when (cdr lang) (symbol-name (car lang))))
19899 org-babel-load-languages)))))
19900 (files
19901 (append babel-files
19902 (and dir-org-contrib
19903 (directory-files dir-org-contrib t file-re))
19904 (directory-files dir-org t file-re)))
19905 (remove-re (concat (if (featurep 'xemacs)
19906 "org-colview" "org-colview-xemacs")
19907 "\\'")))
19908 (setq files (mapcar 'file-name-sans-extension files))
19909 (setq files (mapcar
19910 (lambda (x) (if (string-match remove-re x) nil x))
19911 files))
19912 (setq files (delq nil files))
19913 (mapc
19914 (lambda (f)
19915 (when (featurep (intern (file-name-nondirectory f)))
19916 (if (and (not uncompiled)
19917 (file-exists-p (concat f ".elc")))
19918 (load (concat f ".elc") nil nil 'nosuffix)
19919 (load (concat f ".el") nil nil 'nosuffix))))
19920 files)
19921 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19922 (org-version nil 'full 'message))
19924 ;;;###autoload
19925 (defun org-customize ()
19926 "Call the customize function with org as argument."
19927 (interactive)
19928 (org-load-modules-maybe)
19929 (org-require-autoloaded-modules)
19930 (customize-browse 'org))
19932 (defun org-create-customize-menu ()
19933 "Create a full customization menu for Org-mode, insert it into the menu."
19934 (interactive)
19935 (org-load-modules-maybe)
19936 (org-require-autoloaded-modules)
19937 (if (fboundp 'customize-menu-create)
19938 (progn
19939 (easy-menu-change
19940 '("Org") "Customize"
19941 `(["Browse Org group" org-customize t]
19942 "--"
19943 ,(customize-menu-create 'org)
19944 ["Set" Custom-set t]
19945 ["Save" Custom-save t]
19946 ["Reset to Current" Custom-reset-current t]
19947 ["Reset to Saved" Custom-reset-saved t]
19948 ["Reset to Standard Settings" Custom-reset-standard t]))
19949 (message "\"Org\"-menu now contains full customization menu"))
19950 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19952 ;;;; Miscellaneous stuff
19954 ;;; Generally useful functions
19956 (defun org-get-at-bol (property)
19957 "Get text property PROPERTY at beginning of line."
19958 (get-text-property (point-at-bol) property))
19960 (defun org-find-text-property-in-string (prop s)
19961 "Return the first non-nil value of property PROP in string S."
19962 (or (get-text-property 0 prop s)
19963 (get-text-property (or (next-single-property-change 0 prop s) 0)
19964 prop s)))
19966 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19967 "Display the given MESSAGE as a warning."
19968 (if (fboundp 'display-warning)
19969 (display-warning 'org message
19970 (if (featurep 'xemacs) 'warning :warning))
19971 (let ((buf (get-buffer-create "*Org warnings*")))
19972 (with-current-buffer buf
19973 (goto-char (point-max))
19974 (insert "Warning (Org): " message)
19975 (unless (bolp)
19976 (newline)))
19977 (display-buffer buf)
19978 (sit-for 0))))
19980 (defun org-eval (form)
19981 "Eval FORM and return result."
19982 (condition-case error
19983 (eval form)
19984 (error (format "%%![Error: %s]" error))))
19986 (defun org-in-clocktable-p ()
19987 "Check if the cursor is in a clocktable."
19988 (let ((pos (point)) start)
19989 (save-excursion
19990 (end-of-line 1)
19991 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19992 (setq start (match-beginning 0))
19993 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19994 (>= (match-end 0) pos)
19995 start))))
19997 (defun org-in-commented-line ()
19998 "Is point in a line starting with `#'?"
19999 (equal (char-after (point-at-bol)) ?#))
20001 (defun org-in-indented-comment-line ()
20002 "Is point in a line starting with `#' after some white space?"
20003 (save-excursion
20004 (save-match-data
20005 (goto-char (point-at-bol))
20006 (looking-at "[ \t]*#"))))
20008 (defun org-in-verbatim-emphasis ()
20009 (save-match-data
20010 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20012 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20013 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20014 (if (and marker (marker-buffer marker)
20015 (buffer-live-p (marker-buffer marker)))
20016 (progn
20017 (org-pop-to-buffer-same-window (marker-buffer marker))
20018 (if (or (> marker (point-max)) (< marker (point-min)))
20019 (widen))
20020 (goto-char marker)
20021 (org-show-context 'org-goto))
20022 (if bookmark
20023 (bookmark-jump bookmark)
20024 (error "Cannot find location"))))
20026 (defun org-quote-csv-field (s)
20027 "Quote field for inclusion in CSV material."
20028 (if (string-match "[\",]" s)
20029 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20032 (defun org-force-self-insert (N)
20033 "Needed to enforce self-insert under remapping."
20034 (interactive "p")
20035 (self-insert-command N))
20037 (defun org-string-width (s)
20038 "Compute width of string, ignoring invisible characters.
20039 This ignores character with invisibility property `org-link', and also
20040 characters with property `org-cwidth', because these will become invisible
20041 upon the next fontification round."
20042 (let (b l)
20043 (when (or (eq t buffer-invisibility-spec)
20044 (assq 'org-link buffer-invisibility-spec))
20045 (while (setq b (text-property-any 0 (length s)
20046 'invisible 'org-link s))
20047 (setq s (concat (substring s 0 b)
20048 (substring s (or (next-single-property-change
20049 b 'invisible s) (length s)))))))
20050 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20051 (setq s (concat (substring s 0 b)
20052 (substring s (or (next-single-property-change
20053 b 'org-cwidth s) (length s))))))
20054 (setq l (string-width s) b -1)
20055 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20056 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20059 (defun org-shorten-string (s maxlength)
20060 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20061 If the string is shorter or has length MAXLENGTH, just return the
20062 original string. If it is longer, the functions finds a space in the
20063 string, breaks this string off at that locations and adds three dots
20064 as ellipsis. Including the ellipsis, the string will not be longer
20065 than MAXLENGTH. If finding a good breaking point in the string does
20066 not work, the string is just chopped off in the middle of a word
20067 if necessary."
20068 (if (<= (length s) maxlength)
20070 (let* ((n (max (- maxlength 4) 1))
20071 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20072 (if (string-match re s)
20073 (concat (match-string 1 s) "...")
20074 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20076 (defun org-get-indentation (&optional line)
20077 "Get the indentation of the current line, interpreting tabs.
20078 When LINE is given, assume it represents a line and compute its indentation."
20079 (if line
20080 (if (string-match "^ *" (org-remove-tabs line))
20081 (match-end 0))
20082 (save-excursion
20083 (beginning-of-line 1)
20084 (skip-chars-forward " \t")
20085 (current-column))))
20087 (defun org-get-string-indentation (s)
20088 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20089 (let ((n -1) (i 0) (w tab-width) c)
20090 (catch 'exit
20091 (while (< (setq n (1+ n)) (length s))
20092 (setq c (aref s n))
20093 (cond ((= c ?\ ) (setq i (1+ i)))
20094 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20095 (t (throw 'exit t)))))
20098 (defun org-remove-tabs (s &optional width)
20099 "Replace tabulators in S with spaces.
20100 Assumes that s is a single line, starting in column 0."
20101 (setq width (or width tab-width))
20102 (while (string-match "\t" s)
20103 (setq s (replace-match
20104 (make-string
20105 (- (* width (/ (+ (match-beginning 0) width) width))
20106 (match-beginning 0)) ?\ )
20107 t t s)))
20110 (defun org-fix-indentation (line ind)
20111 "Fix indentation in LINE.
20112 IND is a cons cell with target and minimum indentation.
20113 If the current indentation in LINE is smaller than the minimum,
20114 leave it alone. If it is larger than ind, set it to the target."
20115 (let* ((l (org-remove-tabs line))
20116 (i (org-get-indentation l))
20117 (i1 (car ind)) (i2 (cdr ind)))
20118 (if (>= i i2) (setq l (substring line i2)))
20119 (if (> i1 0)
20120 (concat (make-string i1 ?\ ) l)
20121 l)))
20123 (defun org-remove-indentation (code &optional n)
20124 "Remove the maximum common indentation from the lines in CODE.
20125 N may optionally be the number of spaces to remove."
20126 (with-temp-buffer
20127 (insert code)
20128 (org-do-remove-indentation n)
20129 (buffer-string)))
20131 (defun org-do-remove-indentation (&optional n)
20132 "Remove the maximum common indentation from the buffer."
20133 (untabify (point-min) (point-max))
20134 (let ((min 10000) re)
20135 (if n
20136 (setq min n)
20137 (goto-char (point-min))
20138 (while (re-search-forward "^ *[^ \n]" nil t)
20139 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20140 (unless (or (= min 0) (= min 10000))
20141 (setq re (format "^ \\{%d\\}" min))
20142 (goto-char (point-min))
20143 (while (re-search-forward re nil t)
20144 (replace-match "")
20145 (end-of-line 1))
20146 min)))
20148 (defun org-fill-template (template alist)
20149 "Find each %key of ALIST in TEMPLATE and replace it."
20150 (let ((case-fold-search nil)
20151 entry key value)
20152 (setq alist (sort (copy-sequence alist)
20153 (lambda (a b) (< (length (car a)) (length (car b))))))
20154 (while (setq entry (pop alist))
20155 (setq template
20156 (replace-regexp-in-string
20157 (concat "%" (regexp-quote (car entry)))
20158 (or (cdr entry) "") template t t)))
20159 template))
20161 (defun org-base-buffer (buffer)
20162 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20163 (if (not buffer)
20164 buffer
20165 (or (buffer-base-buffer buffer)
20166 buffer)))
20168 (defun org-trim (s)
20169 "Remove whitespace at beginning and end of string."
20170 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20171 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20174 (defun org-wrap (string &optional width lines)
20175 "Wrap string to either a number of lines, or a width in characters.
20176 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20177 that costs. If there is a word longer than WIDTH, the text is actually
20178 wrapped to the length of that word.
20179 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20180 many lines, whatever width that takes.
20181 The return value is a list of lines, without newlines at the end."
20182 (let* ((words (org-split-string string "[ \t\n]+"))
20183 (maxword (apply 'max (mapcar 'org-string-width words)))
20184 w ll)
20185 (cond (width
20186 (org-do-wrap words (max maxword width)))
20187 (lines
20188 (setq w maxword)
20189 (setq ll (org-do-wrap words maxword))
20190 (if (<= (length ll) lines)
20192 (setq ll words)
20193 (while (> (length ll) lines)
20194 (setq w (1+ w))
20195 (setq ll (org-do-wrap words w)))
20196 ll))
20197 (t (error "Cannot wrap this")))))
20199 (defun org-do-wrap (words width)
20200 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20201 (let (lines line)
20202 (while words
20203 (setq line (pop words))
20204 (while (and words (< (+ (length line) (length (car words))) width))
20205 (setq line (concat line " " (pop words))))
20206 (setq lines (push line lines)))
20207 (nreverse lines)))
20209 (defun org-split-string (string &optional separators)
20210 "Splits STRING into substrings at SEPARATORS.
20211 No empty strings are returned if there are matches at the beginning
20212 and end of string."
20213 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20214 (start 0)
20215 notfirst
20216 (list nil))
20217 (while (and (string-match rexp string
20218 (if (and notfirst
20219 (= start (match-beginning 0))
20220 (< start (length string)))
20221 (1+ start) start))
20222 (< (match-beginning 0) (length string)))
20223 (setq notfirst t)
20224 (or (eq (match-beginning 0) 0)
20225 (and (eq (match-beginning 0) (match-end 0))
20226 (eq (match-beginning 0) start))
20227 (setq list
20228 (cons (substring string start (match-beginning 0))
20229 list)))
20230 (setq start (match-end 0)))
20231 (or (eq start (length string))
20232 (setq list
20233 (cons (substring string start)
20234 list)))
20235 (nreverse list)))
20237 (defun org-quote-vert (s)
20238 "Replace \"|\" with \"\\vert\"."
20239 (while (string-match "|" s)
20240 (setq s (replace-match "\\vert" t t s)))
20243 (defun org-uuidgen-p (s)
20244 "Is S an ID created by UUIDGEN?"
20245 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20247 (defun org-in-src-block-p (&optional inside)
20248 "Whether point is in a code source block.
20249 When INSIDE is non-nil, don't consider we are within a src block
20250 when point is at #+BEGIN_SRC or #+END_SRC."
20251 (let ((case-fold-search t) ov)
20252 (or (and (setq ov (overlays-at (point)))
20253 (memq 'org-block-background
20254 (overlay-properties (car ov))))
20255 (and (not inside)
20256 (save-match-data
20257 (save-excursion
20258 (beginning-of-line)
20259 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20261 (defun org-context ()
20262 "Return a list of contexts of the current cursor position.
20263 If several contexts apply, all are returned.
20264 Each context entry is a list with a symbol naming the context, and
20265 two positions indicating start and end of the context. Possible
20266 contexts are:
20268 :headline anywhere in a headline
20269 :headline-stars on the leading stars in a headline
20270 :todo-keyword on a TODO keyword (including DONE) in a headline
20271 :tags on the TAGS in a headline
20272 :priority on the priority cookie in a headline
20273 :item on the first line of a plain list item
20274 :item-bullet on the bullet/number of a plain list item
20275 :checkbox on the checkbox in a plain list item
20276 :table in an org-mode table
20277 :table-special on a special filed in a table
20278 :table-table in a table.el table
20279 :clocktable in a clocktable
20280 :src-block in a source block
20281 :link on a hyperlink
20282 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20283 :target on a <<target>>
20284 :radio-target on a <<<radio-target>>>
20285 :latex-fragment on a LaTeX fragment
20286 :latex-preview on a LaTeX fragment with overlaid preview image
20288 This function expects the position to be visible because it uses font-lock
20289 faces as a help to recognize the following contexts: :table-special, :link,
20290 and :keyword."
20291 (let* ((f (get-text-property (point) 'face))
20292 (faces (if (listp f) f (list f)))
20293 (case-fold-search t)
20294 (p (point)) clist o)
20295 ;; First the large context
20296 (cond
20297 ((org-at-heading-p t)
20298 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20299 (when (progn
20300 (beginning-of-line 1)
20301 (looking-at org-todo-line-tags-regexp))
20302 (push (org-point-in-group p 1 :headline-stars) clist)
20303 (push (org-point-in-group p 2 :todo-keyword) clist)
20304 (push (org-point-in-group p 4 :tags) clist))
20305 (goto-char p)
20306 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20307 (if (looking-at "\\[#[A-Z0-9]\\]")
20308 (push (org-point-in-group p 0 :priority) clist)))
20310 ((org-at-item-p)
20311 (push (org-point-in-group p 2 :item-bullet) clist)
20312 (push (list :item (point-at-bol)
20313 (save-excursion (org-end-of-item) (point)))
20314 clist)
20315 (and (org-at-item-checkbox-p)
20316 (push (org-point-in-group p 0 :checkbox) clist)))
20318 ((org-at-table-p)
20319 (push (list :table (org-table-begin) (org-table-end)) clist)
20320 (if (memq 'org-formula faces)
20321 (push (list :table-special
20322 (previous-single-property-change p 'face)
20323 (next-single-property-change p 'face)) clist)))
20324 ((org-at-table-p 'any)
20325 (push (list :table-table) clist)))
20326 (goto-char p)
20328 (let ((case-fold-search t))
20329 ;; New the "medium" contexts: clocktables, source blocks
20330 (cond ((org-in-clocktable-p)
20331 (push (list :clocktable
20332 (and (or (looking-at "#\\+BEGIN: clocktable")
20333 (search-backward "#+BEGIN: clocktable" nil t))
20334 (match-beginning 0))
20335 (and (re-search-forward "#\\+END:?" nil t)
20336 (match-end 0))) clist))
20337 ((org-in-src-block-p)
20338 (push (list :src-block
20339 (and (or (looking-at "#\\+BEGIN_SRC")
20340 (search-backward "#+BEGIN_SRC" nil t))
20341 (match-beginning 0))
20342 (and (search-forward "#+END_SRC" nil t)
20343 (match-beginning 0))) clist))))
20344 (goto-char p)
20346 ;; Now the small context
20347 (cond
20348 ((org-at-timestamp-p)
20349 (push (org-point-in-group p 0 :timestamp) clist))
20350 ((memq 'org-link faces)
20351 (push (list :link
20352 (previous-single-property-change p 'face)
20353 (next-single-property-change p 'face)) clist))
20354 ((memq 'org-special-keyword faces)
20355 (push (list :keyword
20356 (previous-single-property-change p 'face)
20357 (next-single-property-change p 'face)) clist))
20358 ((org-at-target-p)
20359 (push (org-point-in-group p 0 :target) clist)
20360 (goto-char (1- (match-beginning 0)))
20361 (if (looking-at org-radio-target-regexp)
20362 (push (org-point-in-group p 0 :radio-target) clist))
20363 (goto-char p))
20364 ((setq o (car (delq nil
20365 (mapcar
20366 (lambda (x)
20367 (if (memq x org-latex-fragment-image-overlays) x))
20368 (overlays-at (point))))))
20369 (push (list :latex-fragment
20370 (overlay-start o) (overlay-end o)) clist)
20371 (push (list :latex-preview
20372 (overlay-start o) (overlay-end o)) clist))
20373 ((org-inside-LaTeX-fragment-p)
20374 ;; FIXME: positions wrong.
20375 (push (list :latex-fragment (point) (point)) clist)))
20377 (setq clist (nreverse (delq nil clist)))
20378 clist))
20380 ;; FIXME: Compare with at-regexp-p Do we need both?
20381 (defun org-in-regexp (re &optional nlines visually)
20382 "Check if point is inside a match of regexp.
20383 Normally only the current line is checked, but you can include NLINES extra
20384 lines both before and after point into the search.
20385 If VISUALLY is set, require that the cursor is not after the match but
20386 really on, so that the block visually is on the match."
20387 (catch 'exit
20388 (let ((pos (point))
20389 (eol (point-at-eol (+ 1 (or nlines 0))))
20390 (inc (if visually 1 0)))
20391 (save-excursion
20392 (beginning-of-line (- 1 (or nlines 0)))
20393 (while (re-search-forward re eol t)
20394 (if (and (<= (match-beginning 0) pos)
20395 (>= (+ inc (match-end 0)) pos))
20396 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20398 (defun org-at-regexp-p (regexp)
20399 "Is point inside a match of REGEXP in the current line?"
20400 (catch 'exit
20401 (save-excursion
20402 (let ((pos (point)) (end (point-at-eol)))
20403 (beginning-of-line 1)
20404 (while (re-search-forward regexp end t)
20405 (if (and (<= (match-beginning 0) pos)
20406 (>= (match-end 0) pos))
20407 (throw 'exit t)))
20408 nil))))
20410 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20411 "Non-nil when point is between matches of START-RE and END-RE.
20413 Also return a non-nil value when point is on one of the matches.
20415 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20416 buffer positions. Default values are the positions of headlines
20417 surrounding the point.
20419 The functions returns a cons cell whose car (resp. cdr) is the
20420 position before START-RE (resp. after END-RE)."
20421 (save-match-data
20422 (let ((pos (point))
20423 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20424 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20425 beg end)
20426 (save-excursion
20427 ;; Point is on a block when on START-RE or if START-RE can be
20428 ;; found before it...
20429 (and (or (org-at-regexp-p start-re)
20430 (re-search-backward start-re limit-up t))
20431 (setq beg (match-beginning 0))
20432 ;; ... and END-RE after it...
20433 (goto-char (match-end 0))
20434 (re-search-forward end-re limit-down t)
20435 (> (setq end (match-end 0)) pos)
20436 ;; ... without another START-RE in-between.
20437 (goto-char (match-beginning 0))
20438 (not (re-search-backward start-re (1+ beg) t))
20439 ;; Return value.
20440 (cons beg end))))))
20442 (defun org-in-block-p (names)
20443 "Non-nil when point belongs to a block whose name belongs to NAMES.
20445 NAMES is a list of strings containing names of blocks.
20447 Return first block name matched, or nil. Beware that in case of
20448 nested blocks, the returned name may not belong to the closest
20449 block from point."
20450 (save-match-data
20451 (catch 'exit
20452 (let ((case-fold-search t)
20453 (lim-up (save-excursion (outline-previous-heading)))
20454 (lim-down (save-excursion (outline-next-heading))))
20455 (mapc (lambda (name)
20456 (let ((n (regexp-quote name)))
20457 (when (org-between-regexps-p
20458 (concat "^[ \t]*#\\+begin_" n)
20459 (concat "^[ \t]*#\\+end_" n)
20460 lim-up lim-down)
20461 (throw 'exit n))))
20462 names))
20463 nil)))
20465 (defun org-occur-in-agenda-files (regexp &optional nlines)
20466 "Call `multi-occur' with buffers for all agenda files."
20467 (interactive "sOrg-files matching: \np")
20468 (let* ((files (org-agenda-files))
20469 (tnames (mapcar 'file-truename files))
20470 (extra org-agenda-text-search-extra-files)
20472 (when (eq (car extra) 'agenda-archives)
20473 (setq extra (cdr extra))
20474 (setq files (org-add-archive-files files)))
20475 (while (setq f (pop extra))
20476 (unless (member (file-truename f) tnames)
20477 (add-to-list 'files f 'append)
20478 (add-to-list 'tnames (file-truename f) 'append)))
20479 (multi-occur
20480 (mapcar (lambda (x)
20481 (with-current-buffer
20482 (or (get-file-buffer x) (find-file-noselect x))
20483 (widen)
20484 (current-buffer)))
20485 files)
20486 regexp)))
20488 (if (boundp 'occur-mode-find-occurrence-hook)
20489 ;; Emacs 23
20490 (add-hook 'occur-mode-find-occurrence-hook
20491 (lambda ()
20492 (when (derived-mode-p 'org-mode)
20493 (org-reveal))))
20494 ;; Emacs 22
20495 (defadvice occur-mode-goto-occurrence
20496 (after org-occur-reveal activate)
20497 (and (derived-mode-p 'org-mode) (org-reveal)))
20498 (defadvice occur-mode-goto-occurrence-other-window
20499 (after org-occur-reveal activate)
20500 (and (derived-mode-p 'org-mode) (org-reveal)))
20501 (defadvice occur-mode-display-occurrence
20502 (after org-occur-reveal activate)
20503 (when (derived-mode-p 'org-mode)
20504 (let ((pos (occur-mode-find-occurrence)))
20505 (with-current-buffer (marker-buffer pos)
20506 (save-excursion
20507 (goto-char pos)
20508 (org-reveal)))))))
20510 (defun org-occur-link-in-agenda-files ()
20511 "Create a link and search for it in the agendas.
20512 The link is not stored in `org-stored-links', it is just created
20513 for the search purpose."
20514 (interactive)
20515 (let ((link (condition-case nil
20516 (org-store-link nil)
20517 (error "Unable to create a link to here"))))
20518 (org-occur-in-agenda-files (regexp-quote link))))
20520 (defun org-uniquify (list)
20521 "Remove duplicate elements from LIST."
20522 (let (res)
20523 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20524 res))
20526 (defun org-delete-all (elts list)
20527 "Remove all elements in ELTS from LIST."
20528 (while elts
20529 (setq list (delete (pop elts) list)))
20530 list)
20532 (defun org-count (cl-item cl-seq)
20533 "Count the number of occurrences of ITEM in SEQ.
20534 Taken from `count' in cl-seq.el with all keyword arguments removed."
20535 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20536 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20537 (while (< cl-start cl-end)
20538 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20539 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20540 (setq cl-start (1+ cl-start)))
20541 cl-count))
20543 (defun org-remove-if (predicate seq)
20544 "Remove everything from SEQ that fulfills PREDICATE."
20545 (let (res e)
20546 (while seq
20547 (setq e (pop seq))
20548 (if (not (funcall predicate e)) (push e res)))
20549 (nreverse res)))
20551 (defun org-remove-if-not (predicate seq)
20552 "Remove everything from SEQ that does not fulfill PREDICATE."
20553 (let (res e)
20554 (while seq
20555 (setq e (pop seq))
20556 (if (funcall predicate e) (push e res)))
20557 (nreverse res)))
20559 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20560 "Reduce two-argument FUNCTION across SEQ.
20561 Taken from `reduce' in cl-seq.el with all keyword arguments but
20562 \":initial-value\" removed."
20563 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20564 (cadr (memq :initial-value cl-keys)))
20565 (cl-seq (pop cl-seq))
20566 (t (funcall cl-func)))))
20567 (while cl-seq
20568 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20569 cl-accum))
20571 (defun org-back-over-empty-lines ()
20572 "Move backwards over whitespace, to the beginning of the first empty line.
20573 Returns the number of empty lines passed."
20574 (let ((pos (point)))
20575 (if (cdr (assoc 'heading org-blank-before-new-entry))
20576 (skip-chars-backward " \t\n\r")
20577 (unless (eobp)
20578 (forward-line -1)))
20579 (beginning-of-line 2)
20580 (goto-char (min (point) pos))
20581 (count-lines (point) pos)))
20583 (defun org-skip-whitespace ()
20584 (skip-chars-forward " \t\n\r"))
20586 (defun org-point-in-group (point group &optional context)
20587 "Check if POINT is in match-group GROUP.
20588 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20589 match. If the match group does not exist or point is not inside it,
20590 return nil."
20591 (and (match-beginning group)
20592 (>= point (match-beginning group))
20593 (<= point (match-end group))
20594 (if context
20595 (list context (match-beginning group) (match-end group))
20596 t)))
20598 (defun org-switch-to-buffer-other-window (&rest args)
20599 "Switch to buffer in a second window on the current frame.
20600 In particular, do not allow pop-up frames.
20601 Returns the newly created buffer."
20602 (org-no-popups
20603 (apply 'switch-to-buffer-other-window args)))
20605 (defun org-combine-plists (&rest plists)
20606 "Create a single property list from all plists in PLISTS.
20607 The process starts by copying the first list, and then setting properties
20608 from the other lists. Settings in the last list are the most significant
20609 ones and overrule settings in the other lists."
20610 (let ((rtn (copy-sequence (pop plists)))
20611 p v ls)
20612 (while plists
20613 (setq ls (pop plists))
20614 (while ls
20615 (setq p (pop ls) v (pop ls))
20616 (setq rtn (plist-put rtn p v))))
20617 rtn))
20619 (defun org-replace-escapes (string table)
20620 "Replace %-escapes in STRING with values in TABLE.
20621 TABLE is an association list with keys like \"%a\" and string values.
20622 The sequences in STRING may contain normal field width and padding information,
20623 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20624 so values can contain further %-escapes if they are define later in TABLE."
20625 (let ((tbl (copy-alist table))
20626 (case-fold-search nil)
20627 (pchg 0)
20628 e re rpl)
20629 (while (setq e (pop tbl))
20630 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20631 (when (and (cdr e) (string-match re (cdr e)))
20632 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20633 (safe "SREF"))
20634 (add-text-properties 0 3 (list 'sref sref) safe)
20635 (setcdr e (replace-match safe t t (cdr e)))))
20636 (while (string-match re string)
20637 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20638 (cdr e)))
20639 (setq string (replace-match rpl t t string))))
20640 (while (setq pchg (next-property-change pchg string))
20641 (let ((sref (get-text-property pchg 'sref string)))
20642 (when (and sref (string-match "SREF" string pchg))
20643 (setq string (replace-match sref t t string)))))
20644 string))
20646 (defun org-sublist (list start end)
20647 "Return a section of LIST, from START to END.
20648 Counting starts at 1."
20649 (let (rtn (c start))
20650 (setq list (nthcdr (1- start) list))
20651 (while (and list (<= c end))
20652 (push (pop list) rtn)
20653 (setq c (1+ c)))
20654 (nreverse rtn)))
20656 (defun org-find-base-buffer-visiting (file)
20657 "Like `find-buffer-visiting' but always return the base buffer and
20658 not an indirect buffer."
20659 (let ((buf (or (get-file-buffer file)
20660 (find-buffer-visiting file))))
20661 (if buf
20662 (or (buffer-base-buffer buf) buf)
20663 nil)))
20665 (defun org-image-file-name-regexp (&optional extensions)
20666 "Return regexp matching the file names of images.
20667 If EXTENSIONS is given, only match these."
20668 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20669 (image-file-name-regexp)
20670 (let ((image-file-name-extensions
20671 (or extensions
20672 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20673 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20674 (concat "\\."
20675 (regexp-opt (nconc (mapcar 'upcase
20676 image-file-name-extensions)
20677 image-file-name-extensions)
20679 "\\'"))))
20681 (defun org-file-image-p (file &optional extensions)
20682 "Return non-nil if FILE is an image."
20683 (save-match-data
20684 (string-match (org-image-file-name-regexp extensions) file)))
20686 (defun org-get-cursor-date ()
20687 "Return the date at cursor in as a time.
20688 This works in the calendar and in the agenda, anywhere else it just
20689 returns the current time."
20690 (let (date day defd)
20691 (cond
20692 ((eq major-mode 'calendar-mode)
20693 (setq date (calendar-cursor-to-date)
20694 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20695 ((eq major-mode 'org-agenda-mode)
20696 (setq day (get-text-property (point) 'day))
20697 (if day
20698 (setq date (calendar-gregorian-from-absolute day)
20699 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20700 (nth 2 date))))))
20701 (or defd (current-time))))
20703 (defun org-mark-subtree (&optional up)
20704 "Mark the current subtree.
20705 This puts point at the start of the current subtree, and mark at
20706 the end. If a numeric prefix UP is given, move up into the
20707 hierarchy of headlines by UP levels before marking the subtree."
20708 (interactive "P")
20709 (org-with-limited-levels
20710 (cond ((org-at-heading-p) (beginning-of-line))
20711 ((org-before-first-heading-p) (error "Not in a subtree"))
20712 (t (outline-previous-visible-heading 1))))
20713 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20714 (if (org-called-interactively-p 'any)
20715 (call-interactively 'org-mark-element)
20716 (org-mark-element)))
20718 ;;; Indentation
20720 (defun org-indent-line ()
20721 "Indent line depending on context."
20722 (interactive)
20723 (let* ((pos (point))
20724 (itemp (org-at-item-p))
20725 (case-fold-search t)
20726 (org-drawer-regexp (or org-drawer-regexp "\000"))
20727 (inline-task-p (and (featurep 'org-inlinetask)
20728 (org-inlinetask-in-task-p)))
20729 (inline-re (and inline-task-p
20730 (org-inlinetask-outline-regexp)))
20731 column)
20732 (if (and orgstruct-is-++ (eq pos (point)))
20733 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20734 (indent-according-to-mode))
20735 (beginning-of-line 1)
20736 (cond
20737 ;; Headings
20738 ((looking-at org-outline-regexp) (setq column 0))
20739 ;; Included files
20740 ((looking-at "#\\+include:") (setq column 0))
20741 ;; Footnote definition
20742 ((looking-at org-footnote-definition-re) (setq column 0))
20743 ;; Literal examples
20744 ((looking-at "[ \t]*:\\( \\|$\\)")
20745 (setq column (org-get-indentation))) ; do nothing
20746 ;; Lists
20747 ((ignore-errors (goto-char (org-in-item-p)))
20748 (setq column (if itemp
20749 (org-get-indentation)
20750 (org-list-item-body-column (point))))
20751 (goto-char pos))
20752 ;; Drawers
20753 ((and (looking-at "[ \t]*:END:")
20754 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20755 (save-excursion
20756 (goto-char (1- (match-beginning 1)))
20757 (setq column (current-column))))
20758 ;; Special blocks
20759 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20760 (save-excursion
20761 (re-search-backward
20762 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20763 (setq column (org-get-indentation (match-string 0))))
20764 ((and (not (looking-at "[ \t]*#\\+begin_"))
20765 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20766 (save-excursion
20767 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20768 (setq column
20769 (cond ((equal (downcase (match-string 1)) "src")
20770 ;; src blocks: let `org-edit-src-exit' handle them
20771 (org-get-indentation))
20772 ((equal (downcase (match-string 1)) "example")
20773 (max (org-get-indentation)
20774 (org-get-indentation (match-string 0))))
20776 (org-get-indentation (match-string 0))))))
20777 ;; This line has nothing special, look at the previous relevant
20778 ;; line to compute indentation
20780 (beginning-of-line 0)
20781 (while (and (not (bobp))
20782 (not (looking-at org-drawer-regexp))
20783 ;; When point started in an inline task, do not move
20784 ;; above task starting line.
20785 (not (and inline-task-p (looking-at inline-re)))
20786 ;; Skip drawers, blocks, empty lines, verbatim,
20787 ;; comments, tables, footnotes definitions, lists,
20788 ;; inline tasks.
20789 (or (and (looking-at "[ \t]*:END:")
20790 (re-search-backward org-drawer-regexp nil t))
20791 (and (looking-at "[ \t]*#\\+end_")
20792 (re-search-backward "[ \t]*#\\+begin_"nil t))
20793 (looking-at "[ \t]*[\n:#|]")
20794 (looking-at org-footnote-definition-re)
20795 (and (ignore-errors (goto-char (org-in-item-p)))
20796 (goto-char
20797 (org-list-get-top-point (org-list-struct))))
20798 (and (not inline-task-p)
20799 (featurep 'org-inlinetask)
20800 (org-inlinetask-in-task-p)
20801 (or (org-inlinetask-goto-beginning) t))))
20802 (beginning-of-line 0))
20803 (cond
20804 ;; There was an heading above.
20805 ((looking-at "\\*+[ \t]+")
20806 (if (not org-adapt-indentation)
20807 (setq column 0)
20808 (goto-char (match-end 0))
20809 (setq column (current-column))))
20810 ;; A drawer had started and is unfinished
20811 ((looking-at org-drawer-regexp)
20812 (goto-char (1- (match-beginning 1)))
20813 (setq column (current-column)))
20814 ;; Else, nothing noticeable found: get indentation and go on.
20815 (t (setq column (org-get-indentation))))))
20816 ;; Now apply indentation and move cursor accordingly
20817 (goto-char pos)
20818 (if (<= (current-column) (current-indentation))
20819 (org-indent-line-to column)
20820 (save-excursion (org-indent-line-to column)))
20821 ;; Special polishing for properties, see `org-property-format'
20822 (setq column (current-column))
20823 (beginning-of-line 1)
20824 (if (looking-at
20825 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20826 (replace-match (concat (match-string 1)
20827 (format org-property-format
20828 (match-string 2) (match-string 3)))
20829 t t))
20830 (org-move-to-column column))))
20832 (defun org-indent-drawer ()
20833 "Indent the drawer at point."
20834 (interactive)
20835 (let ((p (point))
20836 (e (and (save-excursion (re-search-forward ":END:" nil t))
20837 (match-end 0)))
20838 (folded
20839 (save-excursion
20840 (end-of-line)
20841 (when (overlays-at (point))
20842 (member 'invisible (overlay-properties
20843 (car (overlays-at (point)))))))))
20844 (when folded (org-cycle))
20845 (indent-for-tab-command)
20846 (while (and (move-beginning-of-line 2) (< (point) e))
20847 (indent-for-tab-command))
20848 (goto-char p)
20849 (when folded (org-cycle)))
20850 (message "Drawer at point indented"))
20852 (defun org-indent-block ()
20853 "Indent the block at point."
20854 (interactive)
20855 (let ((p (point))
20856 (case-fold-search t)
20857 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20858 (match-end 0)))
20859 (folded
20860 (save-excursion
20861 (end-of-line)
20862 (when (overlays-at (point))
20863 (member 'invisible (overlay-properties
20864 (car (overlays-at (point)))))))))
20865 (when folded (org-cycle))
20866 (indent-for-tab-command)
20867 (while (and (move-beginning-of-line 2) (< (point) e))
20868 (indent-for-tab-command))
20869 (goto-char p)
20870 (when folded (org-cycle)))
20871 (message "Block at point indented"))
20873 (defun org-indent-region (start end)
20874 "Indent region."
20875 (interactive "r")
20876 (save-excursion
20877 (let ((line-end (org-current-line end)))
20878 (goto-char start)
20879 (while (< (org-current-line) line-end)
20880 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20881 (t (call-interactively 'org-indent-line)))
20882 (move-beginning-of-line 2)))))
20885 ;;; Filling
20887 ;; We use our own fill-paragraph and auto-fill functions.
20889 ;; `org-fill-paragraph' relies on adaptive filling and context
20890 ;; checking. Appropriate `fill-prefix' is computed with
20891 ;; `org-adaptive-fill-function'.
20893 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20894 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20895 ;; `org-adaptive-fill-function' value. Internally,
20896 ;; `org-comment-line-break-function' breaks the line.
20898 ;; `org-setup-filling' installs filling and auto-filling related
20899 ;; variables during `org-mode' initialization.
20901 (defun org-setup-filling ()
20902 (interactive)
20903 ;; Prevent auto-fill from inserting unwanted new items.
20904 (when (boundp 'fill-nobreak-predicate)
20905 (org-set-local
20906 'fill-nobreak-predicate
20907 (org-uniquify
20908 (append fill-nobreak-predicate
20909 '(org-fill-paragraph-separate-nobreak-p
20910 org-fill-line-break-nobreak-p)))))
20911 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20912 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20913 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20914 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20916 (defvar org-element-paragraph-separate) ; org-element.el
20917 (defun org-fill-paragraph-separate-nobreak-p ()
20918 "Non-nil when a line break at point would insert a new item."
20919 (looking-at (substring org-element-paragraph-separate 1)))
20921 (defun org-fill-line-break-nobreak-p ()
20922 "Non-nil when a line break at point would create an Org line break."
20923 (save-excursion
20924 (skip-chars-backward "[ \t]")
20925 (skip-chars-backward "\\\\")
20926 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20928 (declare-function message-in-body-p "message" ())
20929 (defvar org-element--affiliated-re) ; From org-element.el
20930 (defun org-adaptive-fill-function ()
20931 "Compute a fill prefix for the current line.
20932 Return fill prefix, as a string, or nil if current line isn't
20933 meant to be filled."
20934 (org-with-wide-buffer
20935 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20936 ;; FIXME: This is really the job of orgstruct++-mode
20937 (let* ((p (line-beginning-position))
20938 (element (save-excursion (beginning-of-line)
20939 (org-element-at-point)))
20940 (type (org-element-type element))
20941 (post-affiliated
20942 (save-excursion
20943 (goto-char (org-element-property :begin element))
20944 (while (looking-at org-element--affiliated-re) (forward-line))
20945 (point))))
20946 (unless (< p post-affiliated)
20947 (case type
20948 (comment (looking-at "[ \t]*# ?") (match-string 0))
20949 (footnote-definition "")
20950 ((item plain-list)
20951 (make-string (org-list-item-body-column post-affiliated) ? ))
20952 (paragraph
20953 ;; Fill prefix is usually the same as the current line,
20954 ;; except if the paragraph is at the beginning of an item.
20955 (let ((parent (org-element-property :parent element)))
20956 (cond ((eq (org-element-type parent) 'item)
20957 (make-string (org-list-item-body-column
20958 (org-element-property :begin parent))
20959 ? ))
20960 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20961 (match-string 0))
20962 (t ""))))
20963 (comment-block
20964 ;; Only fill contents if P is within block boundaries.
20965 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20966 (forward-line)
20967 (point)))
20968 (cend (save-excursion
20969 (goto-char (org-element-property :end element))
20970 (skip-chars-backward " \r\t\n")
20971 (line-beginning-position))))
20972 (when (and (>= p cbeg) (< p cend))
20973 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20974 (match-string 0)
20975 ""))))))))))
20977 (declare-function message-goto-body "message" ())
20978 (defvar message-cite-prefix-regexp) ; From message.el
20979 (defvar org-element-all-objects) ; From org-element.el
20980 (defun org-fill-paragraph (&optional justify)
20981 "Fill element at point, when applicable.
20983 This function only applies to comment blocks, comments, example
20984 blocks and paragraphs. Also, as a special case, re-align table
20985 when point is at one.
20987 If JUSTIFY is non-nil (interactively, with prefix argument),
20988 justify as well. If `sentence-end-double-space' is non-nil, then
20989 period followed by one space does not end a sentence, so don't
20990 break a line there. The variable `fill-column' controls the
20991 width for filling.
20993 For convenience, when point is at a plain list, an item or
20994 a footnote definition, try to fill the first paragraph within."
20995 (interactive)
20996 (if (and (derived-mode-p 'message-mode)
20997 (or (not (message-in-body-p))
20998 (save-excursion (move-beginning-of-line 1)
20999 (looking-at message-cite-prefix-regexp))))
21000 ;; First ensure filling is correct in message-mode.
21001 (let ((fill-paragraph-function
21002 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21003 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21004 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21005 (paragraph-separate
21006 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21007 (fill-paragraph nil))
21008 (save-excursion
21009 ;; Move to end of line in order to get the first paragraph
21010 ;; within a plain list or a footnote definition.
21011 (end-of-line)
21012 (let ((element (org-element-at-point)))
21013 ;; First check if point is in a blank line at the beginning of
21014 ;; the buffer. In that case, ignore filling.
21015 (if (< (point) (org-element-property :begin element)) t
21016 (case (org-element-type element)
21017 ;; Use major mode filling function is src blocks.
21018 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21019 ;; Align Org tables, leave table.el tables as-is.
21020 (table-row (org-table-align) t)
21021 (table
21022 (when (eq (org-element-property :type element) 'org)
21023 (org-table-align))
21025 (paragraph
21026 ;; Paragraphs may contain `line-break' type objects.
21027 (let ((beg (max (point-min)
21028 (org-element-property :contents-begin element)))
21029 (end (min (point-max)
21030 (org-element-property :contents-end element))))
21031 ;; Do nothing if point is at an affiliated keyword.
21032 (if (< (point) beg) t
21033 (when (derived-mode-p 'message-mode)
21034 ;; In `message-mode', do not fill following
21035 ;; citation in current paragraph nor text before
21036 ;; message body.
21037 (let ((body-start (save-excursion (message-goto-body))))
21038 (when body-start (setq beg (max body-start beg))))
21039 (when (save-excursion
21040 (re-search-forward
21041 (concat "^" message-cite-prefix-regexp) end t))
21042 (setq end (match-beginning 0))))
21043 ;; Fill paragraph, taking line breaks into
21044 ;; consideration. For that, slice the paragraph
21045 ;; using line breaks as separators, and fill the
21046 ;; parts in reverse order to avoid messing with
21047 ;; markers.
21048 (save-excursion
21049 (goto-char end)
21050 (mapc
21051 (lambda (pos)
21052 (fill-region-as-paragraph pos (point) justify)
21053 (goto-char pos))
21054 ;; Find the list of ending positions for line
21055 ;; breaks in the current paragraph. Add paragraph
21056 ;; beginning to include first slice.
21057 (nreverse
21058 (cons
21060 (org-element-map
21061 (org-element--parse-objects
21062 beg end nil org-element-all-objects)
21063 'line-break
21064 (lambda (lb) (org-element-property :end lb)))))))
21065 t)))
21066 ;; Contents of `comment-block' type elements should be
21067 ;; filled as plain text, but only if point is within block
21068 ;; markers.
21069 (comment-block
21070 (let* ((case-fold-search t)
21071 (beg (save-excursion
21072 (goto-char (org-element-property :begin element))
21073 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21074 (forward-line)
21075 (point)))
21076 (end (save-excursion
21077 (goto-char (org-element-property :end element))
21078 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21079 (line-beginning-position))))
21080 (when (and (>= (point) beg) (< (point) end))
21081 (fill-region-as-paragraph
21082 (save-excursion
21083 (end-of-line)
21084 (re-search-backward "^[ \t]*$" beg 'move)
21085 (line-beginning-position))
21086 (save-excursion
21087 (beginning-of-line)
21088 (re-search-forward "^[ \t]*$" end 'move)
21089 (line-beginning-position))
21090 justify)))
21092 ;; Fill comments.
21093 (comment (fill-comment-paragraph justify))
21094 ;; Ignore every other element.
21095 (otherwise t)))))))
21097 (defun org-auto-fill-function ()
21098 "Auto-fill function."
21099 ;; Check if auto-filling is meaningful.
21100 (let ((fc (current-fill-column)))
21101 (when (and fc (> (current-column) fc))
21102 (let* ((fill-prefix (org-adaptive-fill-function))
21103 ;; Enforce empty fill prefix, if required. Otherwise, it
21104 ;; will be computed again.
21105 (adaptive-fill-mode (not (equal fill-prefix ""))))
21106 (when fill-prefix (do-auto-fill))))))
21108 (defun org-comment-line-break-function (&optional soft)
21109 "Break line at point and indent, continuing comment if within one.
21110 The inserted newline is marked hard if variable
21111 `use-hard-newlines' is true, unless optional argument SOFT is
21112 non-nil."
21113 (if soft (insert-and-inherit ?\n) (newline 1))
21114 (save-excursion (forward-char -1) (delete-horizontal-space))
21115 (delete-horizontal-space)
21116 (indent-to-left-margin)
21117 (insert-before-markers-and-inherit fill-prefix))
21120 ;;; Comments
21122 ;; Org comments syntax is quite complex. It requires the entire line
21123 ;; to be just a comment. Also, even with the right syntax at the
21124 ;; beginning of line, some some elements (i.e. verse-block or
21125 ;; example-block) don't accept comments. Usual Emacs comment commands
21126 ;; cannot cope with those requirements. Therefore, Org replaces them.
21128 ;; Org still relies on `comment-dwim', but cannot trust
21129 ;; `comment-only-p'. So, `comment-region-function' and
21130 ;; `uncomment-region-function' both point
21131 ;; to`org-comment-or-uncomment-region'. Eventually,
21132 ;; `org-insert-comment' takes care of insertion of comments at the
21133 ;; beginning of line.
21135 ;; `org-setup-comments-handling' install comments related variables
21136 ;; during `org-mode' initialization.
21138 (defun org-setup-comments-handling ()
21139 (interactive)
21140 (org-set-local 'comment-use-syntax nil)
21141 (org-set-local 'comment-start "# ")
21142 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21143 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21144 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21145 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21147 (defun org-insert-comment ()
21148 "Insert an empty comment above current line.
21149 If the line is empty, insert comment at its beginning."
21150 (beginning-of-line)
21151 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21152 (org-indent-line)
21153 (insert "# "))
21155 (defvar comment-empty-lines) ; From newcomment.el.
21156 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21157 "Comment or uncomment each non-blank line in the region.
21158 Uncomment each non-blank line between BEG and END if it only
21159 contains commented lines. Otherwise, comment them."
21160 (save-restriction
21161 ;; Restrict region
21162 (narrow-to-region (save-excursion (goto-char beg)
21163 (skip-chars-forward " \r\t\n" end)
21164 (line-beginning-position))
21165 (save-excursion (goto-char end)
21166 (skip-chars-backward " \r\t\n" beg)
21167 (line-end-position)))
21168 (let ((uncommentp
21169 ;; UNCOMMENTP is non-nil when every non blank line between
21170 ;; BEG and END is a comment.
21171 (save-excursion
21172 (goto-char (point-min))
21173 (while (and (not (eobp))
21174 (let ((element (org-element-at-point)))
21175 (and (eq (org-element-type element) 'comment)
21176 (goto-char (min (point-max)
21177 (org-element-property
21178 :end element)))))))
21179 (eobp))))
21180 (if uncommentp
21181 ;; Only blank lines and comments in region: uncomment it.
21182 (save-excursion
21183 (goto-char (point-min))
21184 (while (not (eobp))
21185 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21186 (replace-match "" nil nil nil 1))
21187 (forward-line)))
21188 ;; Comment each line in region.
21189 (let ((min-indent (point-max)))
21190 ;; First find the minimum indentation across all lines.
21191 (save-excursion
21192 (goto-char (point-min))
21193 (while (and (not (eobp)) (not (zerop min-indent)))
21194 (unless (looking-at "[ \t]*$")
21195 (setq min-indent (min min-indent (current-indentation))))
21196 (forward-line)))
21197 ;; Then loop over all lines.
21198 (save-excursion
21199 (goto-char (point-min))
21200 (while (not (eobp))
21201 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21202 (org-move-to-column min-indent t)
21203 (insert comment-start))
21204 (forward-line))))))))
21207 ;;; Other stuff.
21209 (defun org-toggle-fixed-width-section (arg)
21210 "Toggle the fixed-width export.
21211 If there is no active region, the QUOTE keyword at the current headline is
21212 inserted or removed. When present, it causes the text between this headline
21213 and the next to be exported as fixed-width text, and unmodified.
21214 If there is an active region, this command adds or removes a colon as the
21215 first character of this line. If the first character of a line is a colon,
21216 this line is also exported in fixed-width font."
21217 (interactive "P")
21218 (let* ((cc 0)
21219 (regionp (org-region-active-p))
21220 (beg (if regionp (region-beginning) (point)))
21221 (end (if regionp (region-end)))
21222 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21223 (case-fold-search nil)
21224 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21225 off)
21226 (if regionp
21227 (save-excursion
21228 (goto-char beg)
21229 (setq cc (current-column))
21230 (beginning-of-line 1)
21231 (setq off (looking-at re))
21232 (while (> nlines 0)
21233 (setq nlines (1- nlines))
21234 (beginning-of-line 1)
21235 (cond
21236 (arg
21237 (org-move-to-column cc t)
21238 (insert ": \n")
21239 (forward-line -1))
21240 ((and off (looking-at re))
21241 (replace-match "" t t nil 1))
21242 ((not off) (org-move-to-column cc t) (insert ": ")))
21243 (forward-line 1)))
21244 (save-excursion
21245 (org-back-to-heading)
21246 (cond
21247 ((looking-at (format org-heading-keyword-regexp-format
21248 org-quote-string))
21249 (goto-char (match-end 1))
21250 (looking-at (concat " +" org-quote-string))
21251 (replace-match "" t t)
21252 (when (eolp) (insert " ")))
21253 ((looking-at org-outline-regexp)
21254 (goto-char (match-end 0))
21255 (insert org-quote-string " ")))))))
21257 (defun org-reftex-citation ()
21258 "Use reftex-citation to insert a citation into the buffer.
21259 This looks for a line like
21261 #+BIBLIOGRAPHY: foo plain option:-d
21263 and derives from it that foo.bib is the bibliography file relevant
21264 for this document. It then installs the necessary environment for RefTeX
21265 to work in this buffer and calls `reftex-citation' to insert a citation
21266 into the buffer.
21268 Export of such citations to both LaTeX and HTML is handled by the contributed
21269 package org-exp-bibtex by Taru Karttunen."
21270 (interactive)
21271 (let ((reftex-docstruct-symbol 'rds)
21272 (reftex-cite-format "\\cite{%l}")
21273 rds bib)
21274 (save-excursion
21275 (save-restriction
21276 (widen)
21277 (let ((case-fold-search t)
21278 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21279 (if (not (save-excursion
21280 (or (re-search-forward re nil t)
21281 (re-search-backward re nil t))))
21282 (error "No bibliography defined in file")
21283 (setq bib (concat (match-string 1) ".bib")
21284 rds (list (list 'bib bib)))))))
21285 (call-interactively 'reftex-citation)))
21287 ;;;; Functions extending outline functionality
21289 (defun org-beginning-of-line (&optional arg)
21290 "Go to the beginning of the current line. If that is invisible, continue
21291 to a visible line beginning. This makes the function of C-a more intuitive.
21292 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21293 first attempt, and only move to after the tags when the cursor is already
21294 beyond the end of the headline."
21295 (interactive "P")
21296 (let ((pos (point))
21297 (special (if (consp org-special-ctrl-a/e)
21298 (car org-special-ctrl-a/e)
21299 org-special-ctrl-a/e))
21300 refpos)
21301 (if (org-bound-and-true-p visual-line-mode)
21302 (beginning-of-visual-line 1)
21303 (beginning-of-line 1))
21304 (if (and arg (fboundp 'move-beginning-of-line))
21305 (call-interactively 'move-beginning-of-line)
21306 (if (bobp)
21308 (backward-char 1)
21309 (if (org-truely-invisible-p)
21310 (while (and (not (bobp)) (org-truely-invisible-p))
21311 (backward-char 1)
21312 (beginning-of-line 1))
21313 (forward-char 1))))
21314 (when special
21315 (cond
21316 ((and (looking-at org-complex-heading-regexp)
21317 (= (char-after (match-end 1)) ?\ ))
21318 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21319 (point-at-eol)))
21320 (goto-char
21321 (if (eq special t)
21322 (cond ((> pos refpos) refpos)
21323 ((= pos (point)) refpos)
21324 (t (point)))
21325 (cond ((> pos (point)) (point))
21326 ((not (eq last-command this-command)) (point))
21327 (t refpos)))))
21328 ((org-at-item-p)
21329 ;; Being at an item and not looking at an the item means point
21330 ;; was previously moved to beginning of a visual line, which
21331 ;; doesn't contain the item. Therefore, do nothing special,
21332 ;; just stay here.
21333 (when (looking-at org-list-full-item-re)
21334 ;; Set special position at first white space character after
21335 ;; bullet, and check-box, if any.
21336 (let ((after-bullet
21337 (let ((box (match-end 3)))
21338 (if (not box) (match-end 1)
21339 (let ((after (char-after box)))
21340 (if (and after (= after ? )) (1+ box) box))))))
21341 ;; Special case: Move point to special position when
21342 ;; currently after it or at beginning of line.
21343 (if (eq special t)
21344 (when (or (> pos after-bullet) (= (point) pos))
21345 (goto-char after-bullet))
21346 ;; Reversed case: Move point to special position when
21347 ;; point was already at beginning of line and command is
21348 ;; repeated.
21349 (when (and (= (point) pos) (eq last-command this-command))
21350 (goto-char after-bullet))))))))
21351 (org-no-warnings
21352 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21354 (defun org-end-of-line (&optional arg)
21355 "Go to the end of the line.
21356 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21357 tags on the first attempt, and only move to after the tags when
21358 the cursor is already beyond the end of the headline."
21359 (interactive "P")
21360 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21361 org-special-ctrl-a/e))
21362 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21363 'end-of-visual-line)
21364 ((fboundp 'move-end-of-line) 'move-end-of-line)
21365 (t 'end-of-line))))
21366 (if (or (not special) arg) (call-interactively move-fun)
21367 (let* ((element (save-excursion (beginning-of-line)
21368 (org-element-at-point)))
21369 (type (org-element-type element)))
21370 (cond
21371 ((memq type '(headline inlinetask))
21372 (let ((pos (point)))
21373 (beginning-of-line 1)
21374 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21375 (if (eq special t)
21376 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21377 (goto-char (match-beginning 1))
21378 (goto-char (match-end 0)))
21379 (if (or (< pos (match-end 0))
21380 (not (eq this-command last-command)))
21381 (goto-char (match-end 0))
21382 (goto-char (match-beginning 1))))
21383 (call-interactively move-fun))))
21384 ((org-element-property :hiddenp element)
21385 ;; If element is hidden, `move-end-of-line' would put point
21386 ;; after it. Use `end-of-line' to stay on current line.
21387 (call-interactively 'end-of-line))
21388 (t (call-interactively move-fun)))))
21389 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21391 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21392 (define-key org-mode-map "\C-e" 'org-end-of-line)
21394 (defun org-backward-sentence (&optional arg)
21395 "Go to beginning of sentence, or beginning of table field.
21396 This will call `backward-sentence' or `org-table-beginning-of-field',
21397 depending on context."
21398 (interactive "P")
21399 (cond
21400 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21401 (t (call-interactively 'backward-sentence))))
21403 (defun org-forward-sentence (&optional arg)
21404 "Go to end of sentence, or end of table field.
21405 This will call `forward-sentence' or `org-table-end-of-field',
21406 depending on context."
21407 (interactive "P")
21408 (cond
21409 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21410 (t (call-interactively 'forward-sentence))))
21412 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21413 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21415 (defun org-kill-line (&optional arg)
21416 "Kill line, to tags or end of line."
21417 (interactive "P")
21418 (cond
21419 ((or (not org-special-ctrl-k)
21420 (bolp)
21421 (not (org-at-heading-p)))
21422 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21423 org-ctrl-k-protect-subtree)
21424 (if (or (eq org-ctrl-k-protect-subtree 'error)
21425 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21426 (error "C-k aborted - would kill hidden subtree")))
21427 (call-interactively
21428 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21429 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21430 (kill-region (point) (match-beginning 1))
21431 (org-set-tags nil t))
21432 (t (kill-region (point) (point-at-eol)))))
21434 (define-key org-mode-map "\C-k" 'org-kill-line)
21436 (defun org-yank (&optional arg)
21437 "Yank. If the kill is a subtree, treat it specially.
21438 This command will look at the current kill and check if is a single
21439 subtree, or a series of subtrees[1]. If it passes the test, and if the
21440 cursor is at the beginning of a line or after the stars of a currently
21441 empty headline, then the yank is handled specially. How exactly depends
21442 on the value of the following variables, both set by default.
21444 org-yank-folded-subtrees
21445 When set, the subtree(s) will be folded after insertion, but only
21446 if doing so would now swallow text after the yanked text.
21448 org-yank-adjusted-subtrees
21449 When set, the subtree will be promoted or demoted in order to
21450 fit into the local outline tree structure, which means that the level
21451 will be adjusted so that it becomes the smaller one of the two
21452 *visible* surrounding headings.
21454 Any prefix to this command will cause `yank' to be called directly with
21455 no special treatment. In particular, a simple \\[universal-argument] prefix \
21456 will just
21457 plainly yank the text as it is.
21459 \[1] The test checks if the first non-white line is a heading
21460 and if there are no other headings with fewer stars."
21461 (interactive "P")
21462 (org-yank-generic 'yank arg))
21464 (defun org-yank-generic (command arg)
21465 "Perform some yank-like command.
21467 This function implements the behavior described in the `org-yank'
21468 documentation. However, it has been generalized to work for any
21469 interactive command with similar behavior."
21471 ;; pretend to be command COMMAND
21472 (setq this-command command)
21474 (if arg
21475 (call-interactively command)
21477 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21478 (and (org-kill-is-subtree-p)
21479 (or (bolp)
21480 (and (looking-at "[ \t]*$")
21481 (string-match
21482 "\\`\\*+\\'"
21483 (buffer-substring (point-at-bol) (point)))))))
21484 swallowp)
21485 (cond
21486 ((and subtreep org-yank-folded-subtrees)
21487 (let ((beg (point))
21488 end)
21489 (if (and subtreep org-yank-adjusted-subtrees)
21490 (org-paste-subtree nil nil 'for-yank)
21491 (call-interactively command))
21493 (setq end (point))
21494 (goto-char beg)
21495 (when (and (bolp) subtreep
21496 (not (setq swallowp
21497 (org-yank-folding-would-swallow-text beg end))))
21498 (org-with-limited-levels
21499 (or (looking-at org-outline-regexp)
21500 (re-search-forward org-outline-regexp-bol end t))
21501 (while (and (< (point) end) (looking-at org-outline-regexp))
21502 (hide-subtree)
21503 (org-cycle-show-empty-lines 'folded)
21504 (condition-case nil
21505 (outline-forward-same-level 1)
21506 (error (goto-char end))))))
21507 (when swallowp
21508 (message
21509 "Inserted text not folded because that would swallow text"))
21511 (goto-char end)
21512 (skip-chars-forward " \t\n\r")
21513 (beginning-of-line 1)
21514 (push-mark beg 'nomsg)))
21515 ((and subtreep org-yank-adjusted-subtrees)
21516 (let ((beg (point-at-bol)))
21517 (org-paste-subtree nil nil 'for-yank)
21518 (push-mark beg 'nomsg)))
21520 (call-interactively command))))))
21522 (defun org-yank-folding-would-swallow-text (beg end)
21523 "Would hide-subtree at BEG swallow any text after END?"
21524 (let (level)
21525 (org-with-limited-levels
21526 (save-excursion
21527 (goto-char beg)
21528 (when (or (looking-at org-outline-regexp)
21529 (re-search-forward org-outline-regexp-bol end t))
21530 (setq level (org-outline-level)))
21531 (goto-char end)
21532 (skip-chars-forward " \t\r\n\v\f")
21533 (if (or (eobp)
21534 (and (bolp) (looking-at org-outline-regexp)
21535 (<= (org-outline-level) level)))
21536 nil ; Nothing would be swallowed
21537 t))))) ; something would swallow
21539 (define-key org-mode-map "\C-y" 'org-yank)
21541 (defun org-truely-invisible-p ()
21542 "Check if point is at a character currently not visible.
21543 This version does not only check the character property, but also
21544 `visible-mode'."
21545 ;; Early versions of noutline don't have `outline-invisible-p'.
21546 (if (org-bound-and-true-p visible-mode)
21548 (outline-invisible-p)))
21550 (defun org-invisible-p2 ()
21551 "Check if point is at a character currently not visible."
21552 (save-excursion
21553 (if (and (eolp) (not (bobp))) (backward-char 1))
21554 ;; Early versions of noutline don't have `outline-invisible-p'.
21555 (outline-invisible-p)))
21557 (defun org-back-to-heading (&optional invisible-ok)
21558 "Call `outline-back-to-heading', but provide a better error message."
21559 (condition-case nil
21560 (outline-back-to-heading invisible-ok)
21561 (error (error "Before first headline at position %d in buffer %s"
21562 (point) (current-buffer)))))
21564 (defun org-before-first-heading-p ()
21565 "Before first heading?"
21566 (save-excursion
21567 (end-of-line)
21568 (null (re-search-backward org-outline-regexp-bol nil t))))
21570 (defun org-at-heading-p (&optional ignored)
21571 (outline-on-heading-p t))
21572 ;; Compatibility alias with Org versions < 7.8.03
21573 (defalias 'org-on-heading-p 'org-at-heading-p)
21575 (defun org-at-comment-p nil
21576 "Is cursor in a line starting with a # character?"
21577 (save-excursion
21578 (beginning-of-line)
21579 (looking-at "^#")))
21581 (defun org-at-drawer-p nil
21582 "Is cursor at a drawer keyword?"
21583 (save-excursion
21584 (move-beginning-of-line 1)
21585 (looking-at org-drawer-regexp)))
21587 (defun org-at-block-p nil
21588 "Is cursor at a block keyword?"
21589 (save-excursion
21590 (move-beginning-of-line 1)
21591 (looking-at org-block-regexp)))
21593 (defun org-point-at-end-of-empty-headline ()
21594 "If point is at the end of an empty headline, return t, else nil.
21595 If the heading only contains a TODO keyword, it is still still considered
21596 empty."
21597 (and (looking-at "[ \t]*$")
21598 (when org-todo-line-regexp
21599 (save-excursion
21600 (beginning-of-line 1)
21601 (let ((case-fold-search nil))
21602 (looking-at org-todo-line-regexp)
21603 (string= (match-string 3) ""))))))
21605 (defun org-at-heading-or-item-p ()
21606 (or (org-at-heading-p) (org-at-item-p)))
21608 (defun org-at-target-p ()
21609 (or (org-in-regexp org-radio-target-regexp)
21610 (org-in-regexp org-target-regexp)))
21611 ;; Compatibility alias with Org versions < 7.8.03
21612 (defalias 'org-on-target-p 'org-at-target-p)
21614 (defun org-up-heading-all (arg)
21615 "Move to the heading line of which the present line is a subheading.
21616 This function considers both visible and invisible heading lines.
21617 With argument, move up ARG levels."
21618 (if (fboundp 'outline-up-heading-all)
21619 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21620 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21622 (defun org-up-heading-safe ()
21623 "Move to the heading line of which the present line is a subheading.
21624 This version will not throw an error. It will return the level of the
21625 headline found, or nil if no higher level is found.
21627 Also, this function will be a lot faster than `outline-up-heading',
21628 because it relies on stars being the outline starters. This can really
21629 make a significant difference in outlines with very many siblings."
21630 (let (start-level re)
21631 (org-back-to-heading t)
21632 (setq start-level (funcall outline-level))
21633 (if (equal start-level 1)
21635 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21636 (if (re-search-backward re nil t)
21637 (funcall outline-level)))))
21639 (defun org-first-sibling-p ()
21640 "Is this heading the first child of its parents?"
21641 (interactive)
21642 (let ((re org-outline-regexp-bol)
21643 level l)
21644 (unless (org-at-heading-p t)
21645 (error "Not at a heading"))
21646 (setq level (funcall outline-level))
21647 (save-excursion
21648 (if (not (re-search-backward re nil t))
21650 (setq l (funcall outline-level))
21651 (< l level)))))
21653 (defun org-goto-sibling (&optional previous)
21654 "Goto the next sibling, even if it is invisible.
21655 When PREVIOUS is set, go to the previous sibling instead. Returns t
21656 when a sibling was found. When none is found, return nil and don't
21657 move point."
21658 (let ((fun (if previous 're-search-backward 're-search-forward))
21659 (pos (point))
21660 (re org-outline-regexp-bol)
21661 level l)
21662 (when (condition-case nil (org-back-to-heading t) (error nil))
21663 (setq level (funcall outline-level))
21664 (catch 'exit
21665 (or previous (forward-char 1))
21666 (while (funcall fun re nil t)
21667 (setq l (funcall outline-level))
21668 (when (< l level) (goto-char pos) (throw 'exit nil))
21669 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21670 (goto-char pos)
21671 nil))))
21673 (defun org-show-siblings ()
21674 "Show all siblings of the current headline."
21675 (save-excursion
21676 (while (org-goto-sibling) (org-flag-heading nil)))
21677 (save-excursion
21678 (while (org-goto-sibling 'previous)
21679 (org-flag-heading nil))))
21681 (defun org-goto-first-child ()
21682 "Goto the first child, even if it is invisible.
21683 Return t when a child was found. Otherwise don't move point and
21684 return nil."
21685 (let (level (pos (point)) (re org-outline-regexp-bol))
21686 (when (condition-case nil (org-back-to-heading t) (error nil))
21687 (setq level (outline-level))
21688 (forward-char 1)
21689 (if (and (re-search-forward re nil t) (> (outline-level) level))
21690 (progn (goto-char (match-beginning 0)) t)
21691 (goto-char pos) nil))))
21693 (defun org-show-hidden-entry ()
21694 "Show an entry where even the heading is hidden."
21695 (save-excursion
21696 (org-show-entry)))
21698 (defun org-flag-heading (flag &optional entry)
21699 "Flag the current heading. FLAG non-nil means make invisible.
21700 When ENTRY is non-nil, show the entire entry."
21701 (save-excursion
21702 (org-back-to-heading t)
21703 ;; Check if we should show the entire entry
21704 (if entry
21705 (progn
21706 (org-show-entry)
21707 (save-excursion
21708 (and (outline-next-heading)
21709 (org-flag-heading nil))))
21710 (outline-flag-region (max (point-min) (1- (point)))
21711 (save-excursion (outline-end-of-heading) (point))
21712 flag))))
21714 (defun org-get-next-sibling ()
21715 "Move to next heading of the same level, and return point.
21716 If there is no such heading, return nil.
21717 This is like outline-next-sibling, but invisible headings are ok."
21718 (let ((level (funcall outline-level)))
21719 (outline-next-heading)
21720 (while (and (not (eobp)) (> (funcall outline-level) level))
21721 (outline-next-heading))
21722 (if (or (eobp) (< (funcall outline-level) level))
21724 (point))))
21726 (defun org-get-last-sibling ()
21727 "Move to previous heading of the same level, and return point.
21728 If there is no such heading, return nil."
21729 (let ((opoint (point))
21730 (level (funcall outline-level)))
21731 (outline-previous-heading)
21732 (when (and (/= (point) opoint) (outline-on-heading-p t))
21733 (while (and (> (funcall outline-level) level)
21734 (not (bobp)))
21735 (outline-previous-heading))
21736 (if (< (funcall outline-level) level)
21738 (point)))))
21740 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21741 "Goto to the end of a subtree."
21742 ;; This contains an exact copy of the original function, but it uses
21743 ;; `org-back-to-heading', to make it work also in invisible
21744 ;; trees. And is uses an invisible-ok argument.
21745 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21746 ;; Furthermore, when used inside Org, finding the end of a large subtree
21747 ;; with many children and grandchildren etc, this can be much faster
21748 ;; than the outline version.
21749 (org-back-to-heading invisible-ok)
21750 (let ((first t)
21751 (level (funcall outline-level)))
21752 (if (and (derived-mode-p 'org-mode) (< level 1000))
21753 ;; A true heading (not a plain list item), in Org-mode
21754 ;; This means we can easily find the end by looking
21755 ;; only for the right number of stars. Using a regexp to do
21756 ;; this is so much faster than using a Lisp loop.
21757 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21758 (forward-char 1)
21759 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21760 ;; something else, do it the slow way
21761 (while (and (not (eobp))
21762 (or first (> (funcall outline-level) level)))
21763 (setq first nil)
21764 (outline-next-heading)))
21765 (unless to-heading
21766 (if (memq (preceding-char) '(?\n ?\^M))
21767 (progn
21768 ;; Go to end of line before heading
21769 (forward-char -1)
21770 (if (memq (preceding-char) '(?\n ?\^M))
21771 ;; leave blank line before heading
21772 (forward-char -1))))))
21773 (point))
21775 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21776 "Use Org version in org-mode, for dramatic speed-up."
21777 (if (derived-mode-p 'org-mode)
21778 (progn
21779 (org-end-of-subtree nil t)
21780 (unless (eobp) (backward-char 1)))
21781 ad-do-it))
21783 (defun org-end-of-meta-data-and-drawers ()
21784 "Jump to the first text after meta data and drawers in the current entry.
21785 This will move over empty lines, lines with planning time stamps,
21786 clocking lines, and drawers."
21787 (org-back-to-heading t)
21788 (let ((end (save-excursion (outline-next-heading) (point)))
21789 (re (concat "\\(" org-drawer-regexp "\\)"
21790 "\\|" "[ \t]*" org-keyword-time-regexp)))
21791 (forward-line 1)
21792 (while (re-search-forward re end t)
21793 (if (not (match-end 1))
21794 ;; empty or planning line
21795 (forward-line 1)
21796 ;; a drawer, find the end
21797 (re-search-forward "^[ \t]*:END:" end 'move)
21798 (forward-line 1)))
21799 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21800 (point)))
21802 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21803 "Move forward to the arg'th subheading at same level as this one.
21804 Stop at the first and last subheadings of a superior heading.
21805 Normally this only looks at visible headings, but when INVISIBLE-OK is
21806 non-nil it will also look at invisible ones."
21807 (interactive "p")
21808 (org-back-to-heading invisible-ok)
21809 (org-at-heading-p)
21810 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21811 (re (format "^\\*\\{1,%d\\} " level))
21813 (forward-char 1)
21814 (while (> arg 0)
21815 (while (and (re-search-forward re nil 'move)
21816 (setq l (- (match-end 0) (match-beginning 0) 1))
21817 (= l level)
21818 (not invisible-ok)
21819 (progn (backward-char 1) (outline-invisible-p)))
21820 (if (< l level) (setq arg 1)))
21821 (setq arg (1- arg)))
21822 (beginning-of-line 1)))
21824 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21825 "Move backward to the arg'th subheading at same level as this one.
21826 Stop at the first and last subheadings of a superior heading."
21827 (interactive "p")
21828 (org-back-to-heading)
21829 (org-at-heading-p)
21830 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21831 (re (format "^\\*\\{1,%d\\} " level))
21833 (while (> arg 0)
21834 (while (and (re-search-backward re nil 'move)
21835 (setq l (- (match-end 0) (match-beginning 0) 1))
21836 (= l level)
21837 (not invisible-ok)
21838 (outline-invisible-p))
21839 (if (< l level) (setq arg 1)))
21840 (setq arg (1- arg)))))
21842 (defun org-forward-element ()
21843 "Move forward by one element.
21844 Move to the next element at the same level, when possible."
21845 (interactive)
21846 (cond ((eobp) (error "Cannot move further down"))
21847 ((org-with-limited-levels (org-at-heading-p))
21848 (let ((origin (point)))
21849 (org-forward-heading-same-level 1)
21850 (unless (org-with-limited-levels (org-at-heading-p))
21851 (goto-char origin)
21852 (error "Cannot move further down"))))
21854 (let* ((elem (org-element-at-point))
21855 (end (org-element-property :end elem))
21856 (parent (org-element-property :parent elem)))
21857 (if (and parent (= (org-element-property :contents-end parent) end))
21858 (goto-char (org-element-property :end parent))
21859 (goto-char end))))))
21861 (defun org-backward-element ()
21862 "Move backward by one element.
21863 Move to the previous element at the same level, when possible."
21864 (interactive)
21865 (cond ((bobp) (error "Cannot move further up"))
21866 ((org-with-limited-levels (org-at-heading-p))
21867 ;; At an headline, move to the previous one, if any, or stay
21868 ;; here.
21869 (let ((origin (point)))
21870 (org-backward-heading-same-level 1)
21871 (unless (org-with-limited-levels (org-at-heading-p))
21872 (goto-char origin)
21873 (error "Cannot move further up"))))
21875 (let* ((trail (org-element-at-point 'keep-trail))
21876 (elem (car trail))
21877 (prev-elem (nth 1 trail))
21878 (beg (org-element-property :begin elem)))
21879 (cond
21880 ;; Move to beginning of current element if point isn't
21881 ;; there already.
21882 ((/= (point) beg) (goto-char beg))
21883 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21884 ((org-before-first-heading-p) (goto-char (point-min)))
21885 (t (org-back-to-heading)))))))
21887 (defun org-up-element ()
21888 "Move to upper element."
21889 (interactive)
21890 (if (org-with-limited-levels (org-at-heading-p))
21891 (unless (org-up-heading-safe) (error "No surrounding element"))
21892 (let* ((elem (org-element-at-point))
21893 (parent (org-element-property :parent elem)))
21894 (if parent (goto-char (org-element-property :begin parent))
21895 (if (org-with-limited-levels (org-before-first-heading-p))
21896 (error "No surrounding element")
21897 (org-with-limited-levels (org-back-to-heading)))))))
21899 (defvar org-element-greater-elements)
21900 (defun org-down-element ()
21901 "Move to inner element."
21902 (interactive)
21903 (let ((element (org-element-at-point)))
21904 (cond
21905 ((memq (org-element-type element) '(plain-list table))
21906 (goto-char (org-element-property :contents-begin element))
21907 (forward-char))
21908 ((memq (org-element-type element) org-element-greater-elements)
21909 ;; If contents are hidden, first disclose them.
21910 (when (org-element-property :hiddenp element) (org-cycle))
21911 (goto-char (or (org-element-property :contents-begin element)
21912 (error "No content for this element"))))
21913 (t (error "No inner element")))))
21915 (defun org-drag-element-backward ()
21916 "Move backward element at point."
21917 (interactive)
21918 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21919 (let* ((trail (org-element-at-point 'keep-trail))
21920 (elem (car trail))
21921 (prev-elem (nth 1 trail)))
21922 ;; Error out if no previous element or previous element is
21923 ;; a parent of the current one.
21924 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21925 (error "Cannot drag element backward")
21926 (let ((pos (point)))
21927 (org-element-swap-A-B prev-elem elem)
21928 (goto-char (+ (org-element-property :begin prev-elem)
21929 (- pos (org-element-property :begin elem)))))))))
21931 (defun org-drag-element-forward ()
21932 "Move forward element at point."
21933 (interactive)
21934 (let* ((pos (point))
21935 (elem (org-element-at-point)))
21936 (when (= (point-max) (org-element-property :end elem))
21937 (error "Cannot drag element forward"))
21938 (goto-char (org-element-property :end elem))
21939 (let ((next-elem (org-element-at-point)))
21940 (when (or (org-element-nested-p elem next-elem)
21941 (and (eq (org-element-type next-elem) 'headline)
21942 (not (eq (org-element-type elem) 'headline))))
21943 (goto-char pos)
21944 (error "Cannot drag element forward"))
21945 ;; Compute new position of point: it's shifted by NEXT-ELEM
21946 ;; body's length (without final blanks) and by the length of
21947 ;; blanks between ELEM and NEXT-ELEM.
21948 (let ((size-next (- (save-excursion
21949 (goto-char (org-element-property :end next-elem))
21950 (skip-chars-backward " \r\t\n")
21951 (forward-line)
21952 ;; Small correction if buffer doesn't end
21953 ;; with a newline character.
21954 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21955 (org-element-property :begin next-elem)))
21956 (size-blank (- (org-element-property :end elem)
21957 (save-excursion
21958 (goto-char (org-element-property :end elem))
21959 (skip-chars-backward " \r\t\n")
21960 (forward-line)
21961 (point)))))
21962 (org-element-swap-A-B elem next-elem)
21963 (goto-char (+ pos size-next size-blank))))))
21965 (defun org-mark-element ()
21966 "Put point at beginning of this element, mark at end.
21968 Interactively, if this command is repeated or (in Transient Mark
21969 mode) if the mark is active, it marks the next element after the
21970 ones already marked."
21971 (interactive)
21972 (let (deactivate-mark)
21973 (if (and (org-called-interactively-p 'any)
21974 (or (and (eq last-command this-command) (mark t))
21975 (and transient-mark-mode mark-active)))
21976 (set-mark
21977 (save-excursion
21978 (goto-char (mark))
21979 (goto-char (org-element-property :end (org-element-at-point)))))
21980 (let ((element (org-element-at-point)))
21981 (end-of-line)
21982 (push-mark (org-element-property :end element) t t)
21983 (goto-char (org-element-property :begin element))))))
21985 (defun org-narrow-to-element ()
21986 "Narrow buffer to current element."
21987 (interactive)
21988 (let ((elem (org-element-at-point)))
21989 (cond
21990 ((eq (car elem) 'headline)
21991 (narrow-to-region
21992 (org-element-property :begin elem)
21993 (org-element-property :end elem)))
21994 ((memq (car elem) org-element-greater-elements)
21995 (narrow-to-region
21996 (org-element-property :contents-begin elem)
21997 (org-element-property :contents-end elem)))
21999 (narrow-to-region
22000 (org-element-property :begin elem)
22001 (org-element-property :end elem))))))
22003 (defun org-transpose-element ()
22004 "Transpose current and previous elements, keeping blank lines between.
22005 Point is moved after both elements."
22006 (interactive)
22007 (org-skip-whitespace)
22008 (let ((end (org-element-property :end (org-element-at-point))))
22009 (org-drag-element-backward)
22010 (goto-char end)))
22012 (defun org-unindent-buffer ()
22013 "Un-indent the visible part of the buffer.
22014 Relative indentation (between items, inside blocks, etc.) isn't
22015 modified."
22016 (interactive)
22017 (unless (eq major-mode 'org-mode)
22018 (error "Cannot un-indent a buffer not in Org mode"))
22019 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22020 unindent-tree ; For byte-compiler.
22021 (unindent-tree
22022 (function
22023 (lambda (contents)
22024 (mapc
22025 (lambda (element)
22026 (if (memq (org-element-type element) '(headline section))
22027 (funcall unindent-tree (org-element-contents element))
22028 (save-excursion
22029 (save-restriction
22030 (narrow-to-region
22031 (org-element-property :begin element)
22032 (org-element-property :end element))
22033 (org-do-remove-indentation)))))
22034 (reverse contents))))))
22035 (funcall unindent-tree (org-element-contents parse-tree))))
22037 (defun org-show-subtree ()
22038 "Show everything after this heading at deeper levels."
22039 (interactive)
22040 (outline-flag-region
22041 (point)
22042 (save-excursion
22043 (org-end-of-subtree t t))
22044 nil))
22046 (defun org-show-entry ()
22047 "Show the body directly following this heading.
22048 Show the heading too, if it is currently invisible."
22049 (interactive)
22050 (save-excursion
22051 (condition-case nil
22052 (progn
22053 (org-back-to-heading t)
22054 (outline-flag-region
22055 (max (point-min) (1- (point)))
22056 (save-excursion
22057 (if (re-search-forward
22058 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22059 (match-beginning 1)
22060 (point-max)))
22061 nil)
22062 (org-cycle-hide-drawers 'children))
22063 (error nil))))
22065 (defun org-make-options-regexp (kwds &optional extra)
22066 "Make a regular expression for keyword lines."
22067 (concat
22068 "^#\\+\\("
22069 (mapconcat 'regexp-quote kwds "\\|")
22070 (if extra (concat "\\|" extra))
22071 "\\):[ \t]*\\(.*\\)"))
22073 ;; Make isearch reveal the necessary context
22074 (defun org-isearch-end ()
22075 "Reveal context after isearch exits."
22076 (when isearch-success ; only if search was successful
22077 (if (featurep 'xemacs)
22078 ;; Under XEmacs, the hook is run in the correct place,
22079 ;; we directly show the context.
22080 (org-show-context 'isearch)
22081 ;; In Emacs the hook runs *before* restoring the overlays.
22082 ;; So we have to use a one-time post-command-hook to do this.
22083 ;; (Emacs 22 has a special variable, see function `org-mode')
22084 (unless (and (boundp 'isearch-mode-end-hook-quit)
22085 isearch-mode-end-hook-quit)
22086 ;; Only when the isearch was not quitted.
22087 (org-add-hook 'post-command-hook 'org-isearch-post-command
22088 'append 'local)))))
22090 (defun org-isearch-post-command ()
22091 "Remove self from hook, and show context."
22092 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22093 (org-show-context 'isearch))
22096 ;;;; Integration with and fixes for other packages
22098 ;;; Imenu support
22100 (defvar org-imenu-markers nil
22101 "All markers currently used by Imenu.")
22102 (make-variable-buffer-local 'org-imenu-markers)
22104 (defun org-imenu-new-marker (&optional pos)
22105 "Return a new marker for use by Imenu, and remember the marker."
22106 (let ((m (make-marker)))
22107 (move-marker m (or pos (point)))
22108 (push m org-imenu-markers)
22111 (defun org-imenu-get-tree ()
22112 "Produce the index for Imenu."
22113 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22114 (setq org-imenu-markers nil)
22115 (let* ((n org-imenu-depth)
22116 (re (concat "^" (org-get-limited-outline-regexp)))
22117 (subs (make-vector (1+ n) nil))
22118 (last-level 0)
22119 m level head)
22120 (save-excursion
22121 (save-restriction
22122 (widen)
22123 (goto-char (point-max))
22124 (while (re-search-backward re nil t)
22125 (setq level (org-reduced-level (funcall outline-level)))
22126 (when (and (<= level n)
22127 (looking-at org-complex-heading-regexp))
22128 (setq head (org-link-display-format
22129 (org-match-string-no-properties 4))
22130 m (org-imenu-new-marker))
22131 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22132 (if (>= level last-level)
22133 (push (cons head m) (aref subs level))
22134 (push (cons head (aref subs (1+ level))) (aref subs level))
22135 (loop for i from (1+ level) to n do (aset subs i nil)))
22136 (setq last-level level)))))
22137 (aref subs 1)))
22139 (eval-after-load "imenu"
22140 '(progn
22141 (add-hook 'imenu-after-jump-hook
22142 (lambda ()
22143 (if (derived-mode-p 'org-mode)
22144 (org-show-context 'org-goto))))))
22146 (defun org-link-display-format (link)
22147 "Replace a link with either the description, or the link target
22148 if no description is present"
22149 (save-match-data
22150 (if (string-match org-bracket-link-analytic-regexp link)
22151 (replace-match (if (match-end 5)
22152 (match-string 5 link)
22153 (concat (match-string 1 link)
22154 (match-string 3 link)))
22155 nil t link)
22156 link)))
22158 (defun org-toggle-link-display ()
22159 "Toggle the literal or descriptive display of links."
22160 (interactive)
22161 (if org-descriptive-links
22162 (progn (org-remove-from-invisibility-spec '(org-link))
22163 (org-restart-font-lock)
22164 (setq org-descriptive-links nil))
22165 (progn (add-to-invisibility-spec '(org-link))
22166 (org-restart-font-lock)
22167 (setq org-descriptive-links t))))
22169 ;; Speedbar support
22171 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22172 "Overlay marking the agenda restriction line in speedbar.")
22173 (overlay-put org-speedbar-restriction-lock-overlay
22174 'face 'org-agenda-restriction-lock)
22175 (overlay-put org-speedbar-restriction-lock-overlay
22176 'help-echo "Agendas are currently limited to this item.")
22177 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22179 (defun org-speedbar-set-agenda-restriction ()
22180 "Restrict future agenda commands to the location at point in speedbar.
22181 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22182 (interactive)
22183 (require 'org-agenda)
22184 (let (p m tp np dir txt)
22185 (cond
22186 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22187 'org-imenu t))
22188 (setq m (get-text-property p 'org-imenu-marker))
22189 (with-current-buffer (marker-buffer m)
22190 (goto-char m)
22191 (org-agenda-set-restriction-lock 'subtree)))
22192 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22193 'speedbar-function 'speedbar-find-file))
22194 (setq tp (previous-single-property-change
22195 (1+ p) 'speedbar-function)
22196 np (next-single-property-change
22197 tp 'speedbar-function)
22198 dir (speedbar-line-directory)
22199 txt (buffer-substring-no-properties (or tp (point-min))
22200 (or np (point-max))))
22201 (with-current-buffer (find-file-noselect
22202 (let ((default-directory dir))
22203 (expand-file-name txt)))
22204 (unless (derived-mode-p 'org-mode)
22205 (error "Cannot restrict to non-Org-mode file"))
22206 (org-agenda-set-restriction-lock 'file)))
22207 (t (error "Don't know how to restrict Org-mode's agenda")))
22208 (move-overlay org-speedbar-restriction-lock-overlay
22209 (point-at-bol) (point-at-eol))
22210 (setq current-prefix-arg nil)
22211 (org-agenda-maybe-redo)))
22213 (eval-after-load "speedbar"
22214 '(progn
22215 (speedbar-add-supported-extension ".org")
22216 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22217 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22218 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22219 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22220 (add-hook 'speedbar-visiting-tag-hook
22221 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22223 ;;; Fixes and Hacks for problems with other packages
22225 ;; Make flyspell not check words in links, to not mess up our keymap
22226 (defun org-mode-flyspell-verify ()
22227 "Don't let flyspell put overlays at active buttons, or on
22228 {todo,all-time,additional-option-like}-keywords."
22229 (let ((pos (max (1- (point)) (point-min)))
22230 (word (thing-at-point 'word)))
22231 (and (not (get-text-property pos 'keymap))
22232 (not (get-text-property pos 'org-no-flyspell))
22233 (not (member word org-todo-keywords-1))
22234 (not (member word org-all-time-keywords))
22235 (not (member word org-options-keywords))
22236 (not (member word (mapcar 'car org-startup-options)))
22237 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22239 (defun org-remove-flyspell-overlays-in (beg end)
22240 "Remove flyspell overlays in region."
22241 (and (org-bound-and-true-p flyspell-mode)
22242 (fboundp 'flyspell-delete-region-overlays)
22243 (flyspell-delete-region-overlays beg end))
22244 (add-text-properties beg end '(org-no-flyspell t)))
22246 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22247 (eval-after-load "bookmark"
22248 '(if (boundp 'bookmark-after-jump-hook)
22249 ;; We can use the hook
22250 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22251 ;; Hook not available, use advice
22252 (defadvice bookmark-jump (after org-make-visible activate)
22253 "Make the position visible."
22254 (org-bookmark-jump-unhide))))
22256 ;; Make sure saveplace shows the location if it was hidden
22257 (eval-after-load "saveplace"
22258 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22259 "Make the position visible."
22260 (org-bookmark-jump-unhide)))
22262 ;; Make sure ecb shows the location if it was hidden
22263 (eval-after-load "ecb"
22264 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22265 "Make hierarchy visible when jumping into location from ECB tree buffer."
22266 (if (derived-mode-p 'org-mode)
22267 (org-show-context))))
22269 (defun org-bookmark-jump-unhide ()
22270 "Unhide the current position, to show the bookmark location."
22271 (and (derived-mode-p 'org-mode)
22272 (or (outline-invisible-p)
22273 (save-excursion (goto-char (max (point-min) (1- (point))))
22274 (outline-invisible-p)))
22275 (org-show-context 'bookmark-jump)))
22277 ;; Make session.el ignore our circular variable
22278 (eval-after-load "session"
22279 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22281 ;;;; Experimental code
22283 (defun org-closed-in-range ()
22284 "Sparse tree of items closed in a certain time range.
22285 Still experimental, may disappear in the future."
22286 (interactive)
22287 ;; Get the time interval from the user.
22288 (let* ((time1 (org-float-time
22289 (org-read-date nil 'to-time nil "Starting date: ")))
22290 (time2 (org-float-time
22291 (org-read-date nil 'to-time nil "End date:")))
22292 ;; callback function
22293 (callback (lambda ()
22294 (let ((time
22295 (org-float-time
22296 (apply 'encode-time
22297 (org-parse-time-string
22298 (match-string 1))))))
22299 ;; check if time in interval
22300 (and (>= time time1) (<= time time2))))))
22301 ;; make tree, check each match with the callback
22302 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22304 ;;;; Finish up
22306 (provide 'org)
22308 (run-hooks 'org-load-hook)
22310 ;;; org.el ends here