Fix commit 83bebfd8808
[org-mode/org-tableheadings.git] / lisp / org.el
blob45de62646472952848afbe0fd135a2f69e55ef2a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-clock-timestamps-up "org-clock" ())
118 (declare-function org-clock-timestamps-down "org-clock" ())
119 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
121 (declare-function orgtbl-mode "org-table" (&optional arg))
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-beamer-mode "org-beamer" ())
124 (declare-function org-table-edit-field "org-table" (arg))
125 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
126 (declare-function org-id-get-create "org-id" (&optional force))
127 (declare-function org-id-find-id-file "org-id" (id))
128 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
129 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
130 (declare-function org-table-align "org-table" ())
131 (declare-function org-table-paste-rectangle "org-table" ())
132 (declare-function org-table-maybe-eval-formula "org-table" ())
133 (declare-function org-table-maybe-recalculate-line "org-table" ())
135 ;; load languages based on value of `org-babel-load-languages'
136 (defvar org-babel-load-languages)
138 ;;;###autoload
139 (defun org-babel-do-load-languages (sym value)
140 "Load the languages defined in `org-babel-load-languages'."
141 (set-default sym value)
142 (mapc (lambda (pair)
143 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
144 (if active
145 (progn
146 (require (intern (concat "ob-" lang))))
147 (progn
148 (funcall 'fmakunbound
149 (intern (concat "org-babel-execute:" lang)))
150 (funcall 'fmakunbound
151 (intern (concat "org-babel-expand-body:" lang)))))))
152 org-babel-load-languages))
154 (defcustom org-babel-load-languages '((emacs-lisp . t))
155 "Languages which can be evaluated in Org-mode buffers.
156 This list can be used to load support for any of the languages
157 below, note that each language will depend on a different set of
158 system executables and/or Emacs modes. When a language is
159 \"loaded\", then code blocks in that language can be evaluated
160 with `org-babel-execute-src-block' bound by default to C-c
161 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
162 be set to remove code block evaluation from the C-c C-c
163 keybinding. By default only Emacs Lisp (which has no
164 requirements) is loaded."
165 :group 'org-babel
166 :set 'org-babel-do-load-languages
167 :version "24.1"
168 :type '(alist :tag "Babel Languages"
169 :key-type
170 (choice
171 (const :tag "Awk" awk)
172 (const :tag "C" C)
173 (const :tag "R" R)
174 (const :tag "Asymptote" asymptote)
175 (const :tag "Calc" calc)
176 (const :tag "Clojure" clojure)
177 (const :tag "CSS" css)
178 (const :tag "Ditaa" ditaa)
179 (const :tag "Dot" dot)
180 (const :tag "Emacs Lisp" emacs-lisp)
181 (const :tag "Fortran" fortran)
182 (const :tag "Gnuplot" gnuplot)
183 (const :tag "Haskell" haskell)
184 (const :tag "IO" io)
185 (const :tag "Java" java)
186 (const :tag "Javascript" js)
187 (const :tag "LaTeX" latex)
188 (const :tag "Ledger" ledger)
189 (const :tag "Lilypond" lilypond)
190 (const :tag "Lisp" lisp)
191 (const :tag "Maxima" maxima)
192 (const :tag "Matlab" matlab)
193 (const :tag "Mscgen" mscgen)
194 (const :tag "Ocaml" ocaml)
195 (const :tag "Octave" octave)
196 (const :tag "Org" org)
197 (const :tag "Perl" perl)
198 (const :tag "Pico Lisp" picolisp)
199 (const :tag "PlantUML" plantuml)
200 (const :tag "Python" python)
201 (const :tag "Ruby" ruby)
202 (const :tag "Sass" sass)
203 (const :tag "Scala" scala)
204 (const :tag "Scheme" scheme)
205 (const :tag "Screen" screen)
206 (const :tag "Shell Script" sh)
207 (const :tag "Shen" shen)
208 (const :tag "Sql" sql)
209 (const :tag "Sqlite" sqlite))
210 :value-type (boolean :tag "Activate" :value t)))
212 ;;;; Customization variables
213 (defcustom org-clone-delete-id nil
214 "Remove ID property of clones of a subtree.
215 When non-nil, clones of a subtree don't inherit the ID property.
216 Otherwise they inherit the ID property with a new unique
217 identifier."
218 :type 'boolean
219 :version "24.1"
220 :group 'org-id)
222 ;;; Version
223 (require 'org-compat)
224 (org-check-version)
226 ;;;###autoload
227 (defun org-version (&optional here full message)
228 "Show the org-mode version in the echo area.
229 With prefix argument HERE, insert it at point.
230 When FULL is non-nil, use a verbose version string.
231 When MESSAGE is non-nil, display a message with the version."
232 (interactive "P")
233 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
234 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
235 (org-trash (or
236 (and (fboundp 'org-release) (fboundp 'org-git-version))
237 (load (concat org-dir "org-version.el")
238 'noerror 'nomessage 'nosuffix)))
239 (org-version (org-release))
240 (git-version (org-git-version))
241 (version (format "Org-mode version %s (%s @ %s)"
242 org-version
243 git-version
244 (if org-install-dir
245 (if (string= org-dir org-install-dir)
246 org-install-dir
247 (concat "mixed installation! " org-install-dir " and " org-dir))
248 "org-loaddefs.el can not be found!")))
249 (_version (if full version org-version)))
250 (if (org-called-interactively-p 'interactive)
251 (if here
252 (insert version)
253 (message version))
254 (if message (message _version))
255 _version)))
257 (defconst org-version (org-version))
259 ;;; Compatibility constants
261 ;;; The custom variables
263 (defgroup org nil
264 "Outline-based notes management and organizer."
265 :tag "Org"
266 :group 'outlines
267 :group 'calendar)
269 (defcustom org-mode-hook nil
270 "Mode hook for Org-mode, run after the mode was turned on."
271 :group 'org
272 :type 'hook)
274 (defcustom org-load-hook nil
275 "Hook that is run after org.el has been loaded."
276 :group 'org
277 :type 'hook)
279 (defcustom org-log-buffer-setup-hook nil
280 "Hook that is run after an Org log buffer is created."
281 :group 'org
282 :version "24.1"
283 :type 'hook)
285 (defvar org-modules) ; defined below
286 (defvar org-modules-loaded nil
287 "Have the modules been loaded already?")
289 (defun org-load-modules-maybe (&optional force)
290 "Load all extensions listed in `org-modules'."
291 (when (or force (not org-modules-loaded))
292 (mapc (lambda (ext)
293 (condition-case nil (require ext)
294 (error (message "Problems while trying to load feature `%s'" ext))))
295 org-modules)
296 (setq org-modules-loaded t)))
298 (defun org-set-modules (var value)
299 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
300 (set var value)
301 (when (featurep 'org)
302 (org-load-modules-maybe 'force)))
304 (when (org-bound-and-true-p org-modules)
305 (let ((a (member 'org-infojs org-modules)))
306 (and a (setcar a 'org-jsinfo))))
308 (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)
309 "Modules that should always be loaded together with org.el.
310 If a description starts with <C>, the file is not part of Emacs
311 and loading it will require that you have downloaded and properly installed
312 the org-mode distribution.
314 You can also use this system to load external packages (i.e. neither Org
315 core modules, nor modules from the CONTRIB directory). Just add symbols
316 to the end of the list. If the package is called org-xyz.el, then you need
317 to add the symbol `xyz', and the package must have a call to
319 (provide 'org-xyz)"
320 :group 'org
321 :set 'org-set-modules
322 :type
323 '(set :greedy t
324 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
325 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
326 (const :tag " crypt: Encryption of subtrees" org-crypt)
327 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
328 (const :tag " docview: Links to doc-view buffers" org-docview)
329 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
330 (const :tag " id: Global IDs for identifying entries" org-id)
331 (const :tag " info: Links to Info nodes" org-info)
332 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
333 (const :tag " habit: Track your consistency with habits" org-habit)
334 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
335 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
336 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
337 (const :tag " mew Links to Mew folders/messages" org-mew)
338 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
339 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
340 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
341 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
342 (const :tag " vm: Links to VM folders/messages" org-vm)
343 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
344 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
345 (const :tag " mouse: Additional mouse support" org-mouse)
346 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
348 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
349 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
350 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
351 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
352 (const :tag "C collector: Collect properties into tables" org-collector)
353 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
354 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
355 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
356 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
357 (const :tag "C eval: Include command output as text" org-eval)
358 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
359 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
360 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
361 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
362 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
364 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
366 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
367 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
368 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
369 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
370 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
371 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
372 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
373 (const :tag "C mtags: Support for muse-like tags" org-mtags)
374 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
375 (const :tag "C registry: A registry for Org-mode links" org-registry)
376 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
377 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
378 (const :tag "C secretary: Team management with org-mode" org-secretary)
379 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
380 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
381 (const :tag "C track: Keep up with Org-mode development" org-track)
382 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
383 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
384 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
386 (defcustom org-support-shift-select nil
387 "Non-nil means make shift-cursor commands select text when possible.
389 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
390 start selecting a region, or enlarge regions started in this way.
391 In Org-mode, in special contexts, these same keys are used for
392 other purposes, important enough to compete with shift selection.
393 Org tries to balance these needs by supporting `shift-select-mode'
394 outside these special contexts, under control of this variable.
396 The default of this variable is nil, to avoid confusing behavior. Shifted
397 cursor keys will then execute Org commands in the following contexts:
398 - on a headline, changing TODO state (left/right) and priority (up/down)
399 - on a time stamp, changing the time
400 - in a plain list item, changing the bullet type
401 - in a property definition line, switching between allowed values
402 - in the BEGIN line of a clock table (changing the time block).
403 Outside these contexts, the commands will throw an error.
405 When this variable is t and the cursor is not in a special
406 context, Org-mode will support shift-selection for making and
407 enlarging regions. To make this more effective, the bullet
408 cycling will no longer happen anywhere in an item line, but only
409 if the cursor is exactly on the bullet.
411 If you set this variable to the symbol `always', then the keys
412 will not be special in headlines, property lines, and item lines,
413 to make shift selection work there as well. If this is what you
414 want, you can use the following alternative commands: `C-c C-t'
415 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
416 can be used to switch TODO sets, `C-c -' to cycle item bullet
417 types, and properties can be edited by hand or in column view.
419 However, when the cursor is on a timestamp, shift-cursor commands
420 will still edit the time stamp - this is just too good to give up.
422 XEmacs user should have this variable set to nil, because
423 `shift-select-mode' is in Emacs 23 or later only."
424 :group 'org
425 :type '(choice
426 (const :tag "Never" nil)
427 (const :tag "When outside special context" t)
428 (const :tag "Everywhere except timestamps" always)))
430 (defcustom org-loop-over-headlines-in-active-region nil
431 "Shall some commands act upon headlines in the active region?
433 When set to `t', some commands will be performed in all headlines
434 within the active region.
436 When set to `start-level', some commands will be performed in all
437 headlines within the active region, provided that these headlines
438 are of the same level than the first one.
440 When set to a string, those commands will be performed on the
441 matching headlines within the active region. Such string must be
442 a tags/property/todo match as it is used in the agenda tags view.
444 The list of commands is: `org-schedule', `org-deadline',
445 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
446 `org-archive-to-archive-sibling'. The archiving commands skip
447 already archived entries."
448 :type '(choice (const :tag "Don't loop" nil)
449 (const :tag "All headlines in active region" t)
450 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
451 (string :tag "Tags/Property/Todo matcher"))
452 :version "24.1"
453 :group 'org-todo
454 :group 'org-archive)
456 (defgroup org-startup nil
457 "Options concerning startup of Org-mode."
458 :tag "Org Startup"
459 :group 'org)
461 (defcustom org-startup-folded t
462 "Non-nil means entering Org-mode will switch to OVERVIEW.
463 This can also be configured on a per-file basis by adding one of
464 the following lines anywhere in the buffer:
466 #+STARTUP: fold (or `overview', this is equivalent)
467 #+STARTUP: nofold (or `showall', this is equivalent)
468 #+STARTUP: content
469 #+STARTUP: showeverything
471 By default, this option is ignored when Org opens agenda files
472 for the first time. If you want the agenda to honor the startup
473 option, set `org-agenda-inhibit-startup' to nil."
474 :group 'org-startup
475 :type '(choice
476 (const :tag "nofold: show all" nil)
477 (const :tag "fold: overview" t)
478 (const :tag "content: all headlines" content)
479 (const :tag "show everything, even drawers" showeverything)))
481 (defcustom org-startup-truncated t
482 "Non-nil means entering Org-mode will set `truncate-lines'.
483 This is useful since some lines containing links can be very long and
484 uninteresting. Also tables look terrible when wrapped."
485 :group 'org-startup
486 :type 'boolean)
488 (defcustom org-startup-indented nil
489 "Non-nil means turn on `org-indent-mode' on startup.
490 This can also be configured on a per-file basis by adding one of
491 the following lines anywhere in the buffer:
493 #+STARTUP: indent
494 #+STARTUP: noindent"
495 :group 'org-structure
496 :type '(choice
497 (const :tag "Not" nil)
498 (const :tag "Globally (slow on startup in large files)" t)))
500 (defcustom org-use-sub-superscripts t
501 "Non-nil means interpret \"_\" and \"^\" for export.
502 When this option is turned on, you can use TeX-like syntax for sub- and
503 superscripts. Several characters after \"_\" or \"^\" will be
504 considered as a single item - so grouping with {} is normally not
505 needed. For example, the following things will be parsed as single
506 sub- or superscripts.
508 10^24 or 10^tau several digits will be considered 1 item.
509 10^-12 or 10^-tau a leading sign with digits or a word
510 x^2-y^3 will be read as x^2 - y^3, because items are
511 terminated by almost any nonword/nondigit char.
512 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
514 Still, ambiguity is possible - so when in doubt use {} to enclose the
515 sub/superscript. If you set this variable to the symbol `{}',
516 the braces are *required* in order to trigger interpretations as
517 sub/superscript. This can be helpful in documents that need \"_\"
518 frequently in plain text.
520 Not all export backends support this, but HTML does.
522 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
523 :group 'org-startup
524 :group 'org-export-translation
525 :version "24.1"
526 :type '(choice
527 (const :tag "Always interpret" t)
528 (const :tag "Only with braces" {})
529 (const :tag "Never interpret" nil)))
531 (if (fboundp 'defvaralias)
532 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
535 (defcustom org-startup-with-beamer-mode nil
536 "Non-nil means turn on `org-beamer-mode' on startup.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
540 #+STARTUP: beamer"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-startup-align-all-tables nil
546 "Non-nil means align all tables when visiting a file.
547 This is useful when the column width in tables is forced with <N> cookies
548 in table fields. Such tables will look correct only after the first re-align.
549 This can also be configured on a per-file basis by adding one of
550 the following lines anywhere in the buffer:
551 #+STARTUP: align
552 #+STARTUP: noalign"
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-startup-with-inline-images nil
557 "Non-nil means show inline images when loading a new Org file.
558 This can also be configured on a per-file basis by adding one of
559 the following lines anywhere in the buffer:
560 #+STARTUP: inlineimages
561 #+STARTUP: noinlineimages"
562 :group 'org-startup
563 :version "24.1"
564 :type 'boolean)
566 (defcustom org-insert-mode-line-in-empty-file nil
567 "Non-nil means insert the first line setting Org-mode in empty files.
568 When the function `org-mode' is called interactively in an empty file, this
569 normally means that the file name does not automatically trigger Org-mode.
570 To ensure that the file will always be in Org-mode in the future, a
571 line enforcing Org-mode will be inserted into the buffer, if this option
572 has been set."
573 :group 'org-startup
574 :type 'boolean)
576 (defcustom org-replace-disputed-keys nil
577 "Non-nil means use alternative key bindings for some keys.
578 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
579 These keys are also used by other packages like shift-selection-mode'
580 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
581 If you want to use Org-mode together with one of these other modes,
582 or more generally if you would like to move some Org-mode commands to
583 other keys, set this variable and configure the keys with the variable
584 `org-disputed-keys'.
586 This option is only relevant at load-time of Org-mode, and must be set
587 *before* org.el is loaded. Changing it requires a restart of Emacs to
588 become effective."
589 :group 'org-startup
590 :type 'boolean)
592 (defcustom org-use-extra-keys nil
593 "Non-nil means use extra key sequence definitions for certain commands.
594 This happens automatically if you run XEmacs or if `window-system'
595 is nil. This variable lets you do the same manually. You must
596 set it before loading org.
598 Example: on Carbon Emacs 22 running graphically, with an external
599 keyboard on a Powerbook, the default way of setting M-left might
600 not work for either Alt or ESC. Setting this variable will make
601 it work for ESC."
602 :group 'org-startup
603 :type 'boolean)
605 (if (fboundp 'defvaralias)
606 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
608 (defcustom org-disputed-keys
609 '(([(shift up)] . [(meta p)])
610 ([(shift down)] . [(meta n)])
611 ([(shift left)] . [(meta -)])
612 ([(shift right)] . [(meta +)])
613 ([(control shift right)] . [(meta shift +)])
614 ([(control shift left)] . [(meta shift -)]))
615 "Keys for which Org-mode and other modes compete.
616 This is an alist, cars are the default keys, second element specifies
617 the alternative to use when `org-replace-disputed-keys' is t.
619 Keys can be specified in any syntax supported by `define-key'.
620 The value of this option takes effect only at Org-mode's startup,
621 therefore you'll have to restart Emacs to apply it after changing."
622 :group 'org-startup
623 :type 'alist)
625 (defun org-key (key)
626 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
627 Or return the original if not disputed.
628 Also apply the translations defined in `org-xemacs-key-equivalents'."
629 (when org-replace-disputed-keys
630 (let* ((nkey (key-description key))
631 (x (org-find-if (lambda (x)
632 (equal (key-description (car x)) nkey))
633 org-disputed-keys)))
634 (setq key (if x (cdr x) key))))
635 (when (featurep 'xemacs)
636 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
637 key)
639 (defun org-find-if (predicate seq)
640 (catch 'exit
641 (while seq
642 (if (funcall predicate (car seq))
643 (throw 'exit (car seq))
644 (pop seq)))))
646 (defun org-defkey (keymap key def)
647 "Define a key, possibly translated, as returned by `org-key'."
648 (define-key keymap (org-key key) def))
650 (defcustom org-ellipsis nil
651 "The ellipsis to use in the Org-mode outline.
652 When nil, just use the standard three dots. When a string, use that instead,
653 When a face, use the standard 3 dots, but with the specified face.
654 The change affects only Org-mode (which will then use its own display table).
655 Changing this requires executing `M-x org-mode' in a buffer to become
656 effective."
657 :group 'org-startup
658 :type '(choice (const :tag "Default" nil)
659 (face :tag "Face" :value org-warning)
660 (string :tag "String" :value "...#")))
662 (defvar org-display-table nil
663 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
665 (defgroup org-keywords nil
666 "Keywords in Org-mode."
667 :tag "Org Keywords"
668 :group 'org)
670 (defcustom org-deadline-string "DEADLINE:"
671 "String to mark deadline entries.
672 A deadline is this string, followed by a time stamp. Should be a word,
673 terminated by a colon. You can insert a schedule keyword and
674 a timestamp with \\[org-deadline].
675 Changes become only effective after restarting Emacs."
676 :group 'org-keywords
677 :type 'string)
679 (defcustom org-scheduled-string "SCHEDULED:"
680 "String to mark scheduled TODO entries.
681 A schedule is this string, followed by a time stamp. Should be a word,
682 terminated by a colon. You can insert a schedule keyword and
683 a timestamp with \\[org-schedule].
684 Changes become only effective after restarting Emacs."
685 :group 'org-keywords
686 :type 'string)
688 (defcustom org-closed-string "CLOSED:"
689 "String used as the prefix for timestamps logging closing a TODO entry."
690 :group 'org-keywords
691 :type 'string)
693 (defcustom org-clock-string "CLOCK:"
694 "String used as prefix for timestamps clocking work hours on an item."
695 :group 'org-keywords
696 :type 'string)
698 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
699 org-scheduled-string "\\|"
700 org-deadline-string "\\|"
701 org-closed-string "\\|"
702 org-clock-string "\\)")
703 "Matches a line with planning or clock info.")
705 (defcustom org-comment-string "COMMENT"
706 "Entries starting with this keyword will never be exported.
707 An entry can be toggled between COMMENT and normal with
708 \\[org-toggle-comment].
709 Changes become only effective after restarting Emacs."
710 :group 'org-keywords
711 :type 'string)
713 (defcustom org-quote-string "QUOTE"
714 "Entries starting with this keyword will be exported in fixed-width font.
715 Quoting applies only to the text in the entry following the headline, and does
716 not extend beyond the next headline, even if that is lower level.
717 An entry can be toggled between QUOTE and normal with
718 \\[org-toggle-fixed-width-section]."
719 :group 'org-keywords
720 :type 'string)
722 (defconst org-repeat-re
723 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
724 "Regular expression for specifying repeated events.
725 After a match, group 1 contains the repeat expression.")
727 (defgroup org-structure nil
728 "Options concerning the general structure of Org-mode files."
729 :tag "Org Structure"
730 :group 'org)
732 (defgroup org-reveal-location nil
733 "Options about how to make context of a location visible."
734 :tag "Org Reveal Location"
735 :group 'org-structure)
737 (defconst org-context-choice
738 '(choice
739 (const :tag "Always" t)
740 (const :tag "Never" nil)
741 (repeat :greedy t :tag "Individual contexts"
742 (cons
743 (choice :tag "Context"
744 (const agenda)
745 (const org-goto)
746 (const occur-tree)
747 (const tags-tree)
748 (const link-search)
749 (const mark-goto)
750 (const bookmark-jump)
751 (const isearch)
752 (const default))
753 (boolean))))
754 "Contexts for the reveal options.")
756 (defcustom org-show-hierarchy-above '((default . t))
757 "Non-nil means show full hierarchy when revealing a location.
758 Org-mode often shows locations in an org-mode file which might have
759 been invisible before. When this is set, the hierarchy of headings
760 above the exposed location is shown.
761 Turning this off for example for sparse trees makes them very compact.
762 Instead of t, this can also be an alist specifying this option for different
763 contexts. Valid contexts are
764 agenda when exposing an entry from the agenda
765 org-goto when using the command `org-goto' on key C-c C-j
766 occur-tree when using the command `org-occur' on key C-c /
767 tags-tree when constructing a sparse tree based on tags matches
768 link-search when exposing search matches associated with a link
769 mark-goto when exposing the jump goal of a mark
770 bookmark-jump when exposing a bookmark location
771 isearch when exiting from an incremental search
772 default default for all contexts not set explicitly"
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-show-following-heading '((default . nil))
777 "Non-nil means show following heading when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the heading following the
780 match is shown.
781 Turning this off for example for sparse trees makes them very compact,
782 but makes it harder to edit the location of the match. In such a case,
783 use the command \\[org-reveal] to show more context.
784 Instead of t, this can also be an alist specifying this option for different
785 contexts. See `org-show-hierarchy-above' for valid contexts."
786 :group 'org-reveal-location
787 :type org-context-choice)
789 (defcustom org-show-siblings '((default . nil) (isearch t))
790 "Non-nil means show all sibling heading when revealing a location.
791 Org-mode often shows locations in an org-mode file which might have
792 been invisible before. When this is set, the sibling of the current entry
793 heading are all made visible. If `org-show-hierarchy-above' is t,
794 the same happens on each level of the hierarchy above the current entry.
796 By default this is on for the isearch context, off for all other contexts.
797 Turning this off for example for sparse trees makes them very compact,
798 but makes it harder to edit the location of the match. In such a case,
799 use the command \\[org-reveal] to show more context.
800 Instead of t, this can also be an alist specifying this option for different
801 contexts. See `org-show-hierarchy-above' for valid contexts."
802 :group 'org-reveal-location
803 :type org-context-choice)
805 (defcustom org-show-entry-below '((default . nil))
806 "Non-nil means show the entry below a headline when revealing a location.
807 Org-mode often shows locations in an org-mode file which might have
808 been invisible before. When this is set, the text below the headline that is
809 exposed is also shown.
811 By default this is off for all contexts.
812 Instead of t, this can also be an alist specifying this option for different
813 contexts. See `org-show-hierarchy-above' for valid contexts."
814 :group 'org-reveal-location
815 :type org-context-choice)
817 (defcustom org-indirect-buffer-display 'other-window
818 "How should indirect tree buffers be displayed?
819 This applies to indirect buffers created with the commands
820 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
821 Valid values are:
822 current-window Display in the current window
823 other-window Just display in another window.
824 dedicated-frame Create one new frame, and re-use it each time.
825 new-frame Make a new frame each time. Note that in this case
826 previously-made indirect buffers are kept, and you need to
827 kill these buffers yourself."
828 :group 'org-structure
829 :group 'org-agenda-windows
830 :type '(choice
831 (const :tag "In current window" current-window)
832 (const :tag "In current frame, other window" other-window)
833 (const :tag "Each time a new frame" new-frame)
834 (const :tag "One dedicated frame" dedicated-frame)))
836 (defcustom org-use-speed-commands nil
837 "Non-nil means activate single letter commands at beginning of a headline.
838 This may also be a function to test for appropriate locations where speed
839 commands should be active."
840 :group 'org-structure
841 :type '(choice
842 (const :tag "Never" nil)
843 (const :tag "At beginning of headline stars" t)
844 (function)))
846 (defcustom org-speed-commands-user nil
847 "Alist of additional speed commands.
848 This list will be checked before `org-speed-commands-default'
849 when the variable `org-use-speed-commands' is non-nil
850 and when the cursor is at the beginning of a headline.
851 The car if each entry is a string with a single letter, which must
852 be assigned to `self-insert-command' in the global map.
853 The cdr is either a command to be called interactively, a function
854 to be called, or a form to be evaluated.
855 An entry that is just a list with a single string will be interpreted
856 as a descriptive headline that will be added when listing the speed
857 commands in the Help buffer using the `?' speed command."
858 :group 'org-structure
859 :type '(repeat :value ("k" . ignore)
860 (choice :value ("k" . ignore)
861 (list :tag "Descriptive Headline" (string :tag "Headline"))
862 (cons :tag "Letter and Command"
863 (string :tag "Command letter")
864 (choice
865 (function)
866 (sexp))))))
868 (defgroup org-cycle nil
869 "Options concerning visibility cycling in Org-mode."
870 :tag "Org Cycle"
871 :group 'org-structure)
873 (defcustom org-cycle-skip-children-state-if-no-children t
874 "Non-nil means skip CHILDREN state in entries that don't have any."
875 :group 'org-cycle
876 :type 'boolean)
878 (defcustom org-cycle-max-level nil
879 "Maximum level which should still be subject to visibility cycling.
880 Levels higher than this will, for cycling, be treated as text, not a headline.
881 When `org-odd-levels-only' is set, a value of N in this variable actually
882 means 2N-1 stars as the limiting headline.
883 When nil, cycle all levels.
884 Note that the limiting level of cycling is also influenced by
885 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
886 `org-inlinetask-min-level' is, cycling will be limited to levels one less
887 than its value."
888 :group 'org-cycle
889 :type '(choice
890 (const :tag "No limit" nil)
891 (integer :tag "Maximum level")))
893 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
894 "Names of drawers. Drawers are not opened by cycling on the headline above.
895 Drawers only open with a TAB on the drawer line itself. A drawer looks like
896 this:
897 :DRAWERNAME:
898 .....
899 :END:
900 The drawer \"PROPERTIES\" is special for capturing properties through
901 the property API.
903 Drawers can be defined on the per-file basis with a line like:
905 #+DRAWERS: HIDDEN STATE PROPERTIES"
906 :group 'org-structure
907 :group 'org-cycle
908 :type '(repeat (string :tag "Drawer Name")))
910 (defcustom org-hide-block-startup nil
911 "Non-nil means entering Org-mode will fold all blocks.
912 This can also be set in on a per-file basis with
914 #+STARTUP: hideblocks
915 #+STARTUP: showblocks"
916 :group 'org-startup
917 :group 'org-cycle
918 :type 'boolean)
920 (defcustom org-cycle-global-at-bob nil
921 "Cycle globally if cursor is at beginning of buffer and not at a headline.
922 This makes it possible to do global cycling without having to use S-TAB or
923 \\[universal-argument] TAB. For this special case to work, the first line
924 of the buffer must not be a headline -- it may be empty or some other text.
925 When used in this way, `org-cycle-hook' is disabled temporarily to make
926 sure the cursor stays at the beginning of the buffer. When this option is
927 nil, don't do anything special at the beginning of the buffer."
928 :group 'org-cycle
929 :type 'boolean)
931 (defcustom org-cycle-level-after-item/entry-creation t
932 "Non-nil means cycle entry level or item indentation in new empty entries.
934 When the cursor is at the end of an empty headline, i.e., with only stars
935 and maybe a TODO keyword, TAB will then switch the entry to become a child,
936 and then all possible ancestor states, before returning to the original state.
937 This makes data entry extremely fast: M-RET to create a new headline,
938 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
940 When the cursor is at the end of an empty plain list item, one TAB will
941 make it a subitem, two or more tabs will back up to make this an item
942 higher up in the item hierarchy."
943 :group 'org-cycle
944 :type 'boolean)
946 (defcustom org-cycle-emulate-tab t
947 "Where should `org-cycle' emulate TAB.
948 nil Never
949 white Only in completely white lines
950 whitestart Only at the beginning of lines, before the first non-white char
951 t Everywhere except in headlines
952 exc-hl-bol Everywhere except at the start of a headline
953 If TAB is used in a place where it does not emulate TAB, the current subtree
954 visibility is cycled."
955 :group 'org-cycle
956 :type '(choice (const :tag "Never" nil)
957 (const :tag "Only in completely white lines" white)
958 (const :tag "Before first char in a line" whitestart)
959 (const :tag "Everywhere except in headlines" t)
960 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
963 (defcustom org-cycle-separator-lines 2
964 "Number of empty lines needed to keep an empty line between collapsed trees.
965 If you leave an empty line between the end of a subtree and the following
966 headline, this empty line is hidden when the subtree is folded.
967 Org-mode will leave (exactly) one empty line visible if the number of
968 empty lines is equal or larger to the number given in this variable.
969 So the default 2 means at least 2 empty lines after the end of a subtree
970 are needed to produce free space between a collapsed subtree and the
971 following headline.
973 If the number is negative, and the number of empty lines is at least -N,
974 all empty lines are shown.
976 Special case: when 0, never leave empty lines in collapsed view."
977 :group 'org-cycle
978 :type 'integer)
979 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
981 (defcustom org-pre-cycle-hook nil
982 "Hook that is run before visibility cycling is happening.
983 The function(s) in this hook must accept a single argument which indicates
984 the new state that will be set right after running this hook. The
985 argument is a symbol. Before a global state change, it can have the values
986 `overview', `content', or `all'. Before a local state change, it can have
987 the values `folded', `children', or `subtree'."
988 :group 'org-cycle
989 :type 'hook)
991 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
992 org-cycle-hide-drawers
993 org-cycle-show-empty-lines
994 org-optimize-window-after-visibility-change)
995 "Hook that is run after `org-cycle' has changed the buffer visibility.
996 The function(s) in this hook must accept a single argument which indicates
997 the new state that was set by the most recent `org-cycle' command. The
998 argument is a symbol. After a global state change, it can have the values
999 `overview', `contents', or `all'. After a local state change, it can have
1000 the values `folded', `children', or `subtree'."
1001 :group 'org-cycle
1002 :type 'hook)
1004 (defgroup org-edit-structure nil
1005 "Options concerning structure editing in Org-mode."
1006 :tag "Org Edit Structure"
1007 :group 'org-structure)
1009 (defcustom org-odd-levels-only nil
1010 "Non-nil means skip even levels and only use odd levels for the outline.
1011 This has the effect that two stars are being added/taken away in
1012 promotion/demotion commands. It also influences how levels are
1013 handled by the exporters.
1014 Changing it requires restart of `font-lock-mode' to become effective
1015 for fontification also in regions already fontified.
1016 You may also set this on a per-file basis by adding one of the following
1017 lines to the buffer:
1019 #+STARTUP: odd
1020 #+STARTUP: oddeven"
1021 :group 'org-edit-structure
1022 :group 'org-appearance
1023 :type 'boolean)
1025 (defcustom org-adapt-indentation t
1026 "Non-nil means adapt indentation to outline node level.
1028 When this variable is set, Org assumes that you write outlines by
1029 indenting text in each node to align with the headline (after the stars).
1030 The following issues are influenced by this variable:
1032 - When this is set and the *entire* text in an entry is indented, the
1033 indentation is increased by one space in a demotion command, and
1034 decreased by one in a promotion command. If any line in the entry
1035 body starts with text at column 0, indentation is not changed at all.
1037 - Property drawers and planning information is inserted indented when
1038 this variable s set. When nil, they will not be indented.
1040 - TAB indents a line relative to context. The lines below a headline
1041 will be indented when this variable is set.
1043 Note that this is all about true indentation, by adding and removing
1044 space characters. See also `org-indent.el' which does level-dependent
1045 indentation in a virtual way, i.e. at display time in Emacs."
1046 :group 'org-edit-structure
1047 :type 'boolean)
1049 (defcustom org-special-ctrl-a/e nil
1050 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1052 When t, `C-a' will bring back the cursor to the beginning of the
1053 headline text, i.e. after the stars and after a possible TODO
1054 keyword. In an item, this will be the position after bullet and
1055 check-box, if any. When the cursor is already at that position,
1056 another `C-a' will bring it to the beginning of the line.
1058 `C-e' will jump to the end of the headline, ignoring the presence
1059 of tags in the headline. A second `C-e' will then jump to the
1060 true end of the line, after any tags. This also means that, when
1061 this variable is non-nil, `C-e' also will never jump beyond the
1062 end of the heading of a folded section, i.e. not after the
1063 ellipses.
1065 When set to the symbol `reversed', the first `C-a' or `C-e' works
1066 normally, going to the true line boundary first. Only a directly
1067 following, identical keypress will bring the cursor to the
1068 special positions.
1070 This may also be a cons cell where the behavior for `C-a' and
1071 `C-e' is set separately."
1072 :group 'org-edit-structure
1073 :type '(choice
1074 (const :tag "off" nil)
1075 (const :tag "on: after stars/bullet and before tags first" t)
1076 (const :tag "reversed: true line boundary first" reversed)
1077 (cons :tag "Set C-a and C-e separately"
1078 (choice :tag "Special C-a"
1079 (const :tag "off" nil)
1080 (const :tag "on: after stars/bullet first" t)
1081 (const :tag "reversed: before stars/bullet first" reversed))
1082 (choice :tag "Special C-e"
1083 (const :tag "off" nil)
1084 (const :tag "on: before tags first" t)
1085 (const :tag "reversed: after tags first" reversed)))))
1086 (if (fboundp 'defvaralias)
1087 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1089 (defcustom org-special-ctrl-k nil
1090 "Non-nil means `C-k' will behave specially in headlines.
1091 When nil, `C-k' will call the default `kill-line' command.
1092 When t, the following will happen while the cursor is in the headline:
1094 - When the cursor is at the beginning of a headline, kill the entire
1095 line and possible the folded subtree below the line.
1096 - When in the middle of the headline text, kill the headline up to the tags.
1097 - When after the headline text, kill the tags."
1098 :group 'org-edit-structure
1099 :type 'boolean)
1101 (defcustom org-ctrl-k-protect-subtree nil
1102 "Non-nil means, do not delete a hidden subtree with C-k.
1103 When set to the symbol `error', simply throw an error when C-k is
1104 used to kill (part-of) a headline that has hidden text behind it.
1105 Any other non-nil value will result in a query to the user, if it is
1106 OK to kill that hidden subtree. When nil, kill without remorse."
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not protect hidden subtrees" nil)
1111 (const :tag "Protect hidden subtrees with a security query" t)
1112 (const :tag "Never kill a hidden subtree with C-k" error)))
1114 (defcustom org-catch-invisible-edits nil
1115 "Check if in invisible region before inserting or deleting a character.
1116 Valid values are:
1118 nil Do not check, so just do invisible edits.
1119 error Throw an error and do nothing.
1120 show Make point visible, and do the requested edit.
1121 show-and-error Make point visible, then throw an error and abort the edit.
1122 smart Make point visible, and do insertion/deletion if it is
1123 adjacent to visible text and the change feels predictable.
1124 Never delete a previously invisible character or add in the
1125 middle or right after an invisible region. Basically, this
1126 allows insertion and backward-delete right before ellipses.
1127 FIXME: maybe in this case we should not even show?"
1128 :group 'org-edit-structure
1129 :version "24.1"
1130 :type '(choice
1131 (const :tag "Do not check" nil)
1132 (const :tag "Throw error when trying to edit" error)
1133 (const :tag "Unhide, but do not do the edit" show-and-error)
1134 (const :tag "Show invisible part and do the edit" show)
1135 (const :tag "Be smart and do the right thing" smart)))
1137 (defcustom org-yank-folded-subtrees t
1138 "Non-nil means when yanking subtrees, fold them.
1139 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1140 it starts with a heading and all other headings in it are either children
1141 or siblings, then fold all the subtrees. However, do this only if no
1142 text after the yank would be swallowed into a folded tree by this action."
1143 :group 'org-edit-structure
1144 :type 'boolean)
1146 (defcustom org-yank-adjusted-subtrees nil
1147 "Non-nil means when yanking subtrees, adjust the level.
1148 With this setting, `org-paste-subtree' is used to insert the subtree, see
1149 this function for details."
1150 :group 'org-edit-structure
1151 :type 'boolean)
1153 (defcustom org-M-RET-may-split-line '((default . t))
1154 "Non-nil means M-RET will split the line at the cursor position.
1155 When nil, it will go to the end of the line before making a
1156 new line.
1157 You may also set this option in a different way for different
1158 contexts. Valid contexts are:
1160 headline when creating a new headline
1161 item when creating a new item
1162 table in a table field
1163 default the value to be used for all contexts not explicitly
1164 customized"
1165 :group 'org-structure
1166 :group 'org-table
1167 :type '(choice
1168 (const :tag "Always" t)
1169 (const :tag "Never" nil)
1170 (repeat :greedy t :tag "Individual contexts"
1171 (cons
1172 (choice :tag "Context"
1173 (const headline)
1174 (const item)
1175 (const table)
1176 (const default))
1177 (boolean)))))
1180 (defcustom org-insert-heading-respect-content nil
1181 "Non-nil means insert new headings after the current subtree.
1182 When nil, the new heading is created directly after the current line.
1183 The commands \\[org-insert-heading-respect-content] and
1184 \\[org-insert-todo-heading-respect-content] turn this variable on
1185 for the duration of the command."
1186 :group 'org-structure
1187 :type 'boolean)
1189 (defcustom org-blank-before-new-entry '((heading . auto)
1190 (plain-list-item . auto))
1191 "Should `org-insert-heading' leave a blank line before new heading/item?
1192 The value is an alist, with `heading' and `plain-list-item' as CAR,
1193 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1194 which case Org will look at the surrounding headings/items and try to
1195 make an intelligent decision whether to insert a blank line or not.
1197 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1198 set, the setting here is ignored and no empty line is inserted, to avoid
1199 breaking the list structure."
1200 :group 'org-edit-structure
1201 :type '(list
1202 (cons (const heading)
1203 (choice (const :tag "Never" nil)
1204 (const :tag "Always" t)
1205 (const :tag "Auto" auto)))
1206 (cons (const plain-list-item)
1207 (choice (const :tag "Never" nil)
1208 (const :tag "Always" t)
1209 (const :tag "Auto" auto)))))
1211 (defcustom org-insert-heading-hook nil
1212 "Hook being run after inserting a new heading."
1213 :group 'org-edit-structure
1214 :type 'hook)
1216 (defcustom org-enable-fixed-width-editor t
1217 "Non-nil means lines starting with \":\" are treated as fixed-width.
1218 This currently only means they are never auto-wrapped.
1219 When nil, such lines will be treated like ordinary lines.
1220 See also the QUOTE keyword."
1221 :group 'org-edit-structure
1222 :type 'boolean)
1224 (defcustom org-goto-auto-isearch t
1225 "Non-nil means typing characters in `org-goto' starts incremental search.
1226 When nil, you can use these keybindings to navigate the buffer:
1228 q Quit the org-goto interface
1229 n Go to the next visible heading
1230 p Go to the previous visible heading
1231 f Go one heading forward on same level
1232 b Go one heading backward on same level
1233 u Go one heading up"
1234 :group 'org-edit-structure
1235 :type 'boolean)
1237 (defgroup org-sparse-trees nil
1238 "Options concerning sparse trees in Org-mode."
1239 :tag "Org Sparse Trees"
1240 :group 'org-structure)
1242 (defcustom org-highlight-sparse-tree-matches t
1243 "Non-nil means highlight all matches that define a sparse tree.
1244 The highlights will automatically disappear the next time the buffer is
1245 changed by an edit command."
1246 :group 'org-sparse-trees
1247 :type 'boolean)
1249 (defcustom org-remove-highlights-with-change t
1250 "Non-nil means any change to the buffer will remove temporary highlights.
1251 Such highlights are created by `org-occur' and `org-clock-display'.
1252 When nil, `C-c C-c needs to be used to get rid of the highlights.
1253 The highlights created by `org-preview-latex-fragment' always need
1254 `C-c C-c' to be removed."
1255 :group 'org-sparse-trees
1256 :group 'org-time
1257 :type 'boolean)
1260 (defcustom org-occur-hook '(org-first-headline-recenter)
1261 "Hook that is run after `org-occur' has constructed a sparse tree.
1262 This can be used to recenter the window to show as much of the structure
1263 as possible."
1264 :group 'org-sparse-trees
1265 :type 'hook)
1267 (defgroup org-imenu-and-speedbar nil
1268 "Options concerning imenu and speedbar in Org-mode."
1269 :tag "Org Imenu and Speedbar"
1270 :group 'org-structure)
1272 (defcustom org-imenu-depth 2
1273 "The maximum level for Imenu access to Org-mode headlines.
1274 This also applied for speedbar access."
1275 :group 'org-imenu-and-speedbar
1276 :type 'integer)
1278 (defgroup org-table nil
1279 "Options concerning tables in Org-mode."
1280 :tag "Org Table"
1281 :group 'org)
1283 (defcustom org-enable-table-editor 'optimized
1284 "Non-nil means lines starting with \"|\" are handled by the table editor.
1285 When nil, such lines will be treated like ordinary lines.
1287 When equal to the symbol `optimized', the table editor will be optimized to
1288 do the following:
1289 - Automatic overwrite mode in front of whitespace in table fields.
1290 This makes the structure of the table stay in tact as long as the edited
1291 field does not exceed the column width.
1292 - Minimize the number of realigns. Normally, the table is aligned each time
1293 TAB or RET are pressed to move to another field. With optimization this
1294 happens only if changes to a field might have changed the column width.
1295 Optimization requires replacing the functions `self-insert-command',
1296 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1297 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1298 very good at guessing when a re-align will be necessary, but you can always
1299 force one with \\[org-ctrl-c-ctrl-c].
1301 If you would like to use the optimized version in Org-mode, but the
1302 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1304 This variable can be used to turn on and off the table editor during a session,
1305 but in order to toggle optimization, a restart is required.
1307 See also the variable `org-table-auto-blank-field'."
1308 :group 'org-table
1309 :type '(choice
1310 (const :tag "off" nil)
1311 (const :tag "on" t)
1312 (const :tag "on, optimized" optimized)))
1314 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1315 (version<= emacs-version "24.1"))
1316 "Non-nil means cluster self-insert commands for undo when possible.
1317 If this is set, then, like in the Emacs command loop, 20 consecutive
1318 characters will be undone together.
1319 This is configurable, because there is some impact on typing performance."
1320 :group 'org-table
1321 :type 'boolean)
1323 (defcustom org-table-tab-recognizes-table.el t
1324 "Non-nil means TAB will automatically notice a table.el table.
1325 When it sees such a table, it moves point into it and - if necessary -
1326 calls `table-recognize-table'."
1327 :group 'org-table-editing
1328 :type 'boolean)
1330 (defgroup org-link nil
1331 "Options concerning links in Org-mode."
1332 :tag "Org Link"
1333 :group 'org)
1335 (defvar org-link-abbrev-alist-local nil
1336 "Buffer-local version of `org-link-abbrev-alist', which see.
1337 The value of this is taken from the #+LINK lines.")
1338 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1340 (defcustom org-link-abbrev-alist nil
1341 "Alist of link abbreviations.
1342 The car of each element is a string, to be replaced at the start of a link.
1343 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1344 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1346 [[linkkey:tag][description]]
1348 The 'linkkey' must be a word word, starting with a letter, followed
1349 by letters, numbers, '-' or '_'.
1351 If REPLACE is a string, the tag will simply be appended to create the link.
1352 If the string contains \"%s\", the tag will be inserted there. If the string
1353 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1354 at that point (see the function `url-hexify-string'). If the string contains
1355 the specifier \"%(my-function)\", then the custom function `my-function' will
1356 be invoked: this function takes the tag as its only argument and must return
1357 a string.
1359 REPLACE may also be a function that will be called with the tag as the
1360 only argument to create the link, which should be returned as a string.
1362 See the manual for examples."
1363 :group 'org-link
1364 :type '(repeat
1365 (cons
1366 (string :tag "Protocol")
1367 (choice
1368 (string :tag "Format")
1369 (function)))))
1371 (defcustom org-descriptive-links t
1372 "Non-nil means Org will display descriptive links.
1373 E.g. [[http://orgmode.org][Org website]] will be displayed as
1374 \"Org Website\", hiding the link itself and just displaying its
1375 description. When set to `nil', Org will display the full links
1376 literally.
1378 You can interactively set the value of this variable by calling
1379 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1380 :group 'org-link
1381 :type 'boolean)
1383 (defcustom org-link-file-path-type 'adaptive
1384 "How the path name in file links should be stored.
1385 Valid values are:
1387 relative Relative to the current directory, i.e. the directory of the file
1388 into which the link is being inserted.
1389 absolute Absolute path, if possible with ~ for home directory.
1390 noabbrev Absolute path, no abbreviation of home directory.
1391 adaptive Use relative path for files in the current directory and sub-
1392 directories of it. For other files, use an absolute path."
1393 :group 'org-link
1394 :type '(choice
1395 (const relative)
1396 (const absolute)
1397 (const noabbrev)
1398 (const adaptive)))
1400 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1401 "Types of links that should be activated in Org-mode files.
1402 This is a list of symbols, each leading to the activation of a certain link
1403 type. In principle, it does not hurt to turn on most link types - there may
1404 be a small gain when turning off unused link types. The types are:
1406 bracket The recommended [[link][description]] or [[link]] links with hiding.
1407 angle Links in angular brackets that may contain whitespace like
1408 <bbdb:Carsten Dominik>.
1409 plain Plain links in normal text, no whitespace, like http://google.com.
1410 radio Text that is matched by a radio target, see manual for details.
1411 tag Tag settings in a headline (link to tag search).
1412 date Time stamps (link to calendar).
1413 footnote Footnote labels.
1415 Changing this variable requires a restart of Emacs to become effective."
1416 :group 'org-link
1417 :type '(set :greedy t
1418 (const :tag "Double bracket links" bracket)
1419 (const :tag "Angular bracket links" angle)
1420 (const :tag "Plain text links" plain)
1421 (const :tag "Radio target matches" radio)
1422 (const :tag "Tags" tag)
1423 (const :tag "Timestamps" date)
1424 (const :tag "Footnotes" footnote)))
1426 (defcustom org-make-link-description-function nil
1427 "Function to use for generating link descriptions from links.
1428 When nil, the link location will be used. This function must take
1429 two parameters: the first one is the link, the second one is the
1430 description generated by `org-insert-link'. The function should
1431 return the description to use."
1432 :group 'org-link
1433 :type 'function)
1435 (defgroup org-link-store nil
1436 "Options concerning storing links in Org-mode."
1437 :tag "Org Store Link"
1438 :group 'org-link)
1440 (defcustom org-url-hexify-p t
1441 "When non-nil, hexify URL when creating a link."
1442 :type 'boolean
1443 :version "24.3"
1444 :group 'org-link-store)
1446 (defcustom org-email-link-description-format "Email %c: %.30s"
1447 "Format of the description part of a link to an email or usenet message.
1448 The following %-escapes will be replaced by corresponding information:
1450 %F full \"From\" field
1451 %f name, taken from \"From\" field, address if no name
1452 %T full \"To\" field
1453 %t first name in \"To\" field, address if no name
1454 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1455 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1456 %s subject
1457 %d date
1458 %m message-id.
1460 You may use normal field width specification between the % and the letter.
1461 This is for example useful to limit the length of the subject.
1463 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1464 :group 'org-link-store
1465 :type 'string)
1467 (defcustom org-from-is-user-regexp
1468 (let (r1 r2)
1469 (when (and user-mail-address (not (string= user-mail-address "")))
1470 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1471 (when (and user-full-name (not (string= user-full-name "")))
1472 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1473 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1474 "Regexp matched against the \"From:\" header of an email or usenet message.
1475 It should match if the message is from the user him/herself."
1476 :group 'org-link-store
1477 :type 'regexp)
1479 (defcustom org-context-in-file-links t
1480 "Non-nil means file links from `org-store-link' contain context.
1481 A search string will be added to the file name with :: as separator and
1482 used to find the context when the link is activated by the command
1483 `org-open-at-point'. When this option is t, the entire active region
1484 will be placed in the search string of the file link. If set to a
1485 positive integer, only the first n lines of context will be stored.
1487 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1488 negates this setting for the duration of the command."
1489 :group 'org-link-store
1490 :type '(choice boolean integer))
1492 (defcustom org-keep-stored-link-after-insertion nil
1493 "Non-nil means keep link in list for entire session.
1495 The command `org-store-link' adds a link pointing to the current
1496 location to an internal list. These links accumulate during a session.
1497 The command `org-insert-link' can be used to insert links into any
1498 Org-mode file (offering completion for all stored links). When this
1499 option is nil, every link which has been inserted once using \\[org-insert-link]
1500 will be removed from the list, to make completing the unused links
1501 more efficient."
1502 :group 'org-link-store
1503 :type 'boolean)
1505 (defgroup org-link-follow nil
1506 "Options concerning following links in Org-mode."
1507 :tag "Org Follow Link"
1508 :group 'org-link)
1510 (defcustom org-link-translation-function nil
1511 "Function to translate links with different syntax to Org syntax.
1512 This can be used to translate links created for example by the Planner
1513 or emacs-wiki packages to Org syntax.
1514 The function must accept two parameters, a TYPE containing the link
1515 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1516 which is everything after the link protocol. It should return a cons
1517 with possibly modified values of type and path.
1518 Org contains a function for this, so if you set this variable to
1519 `org-translate-link-from-planner', you should be able follow many
1520 links created by planner."
1521 :group 'org-link-follow
1522 :type 'function)
1524 (defcustom org-follow-link-hook nil
1525 "Hook that is run after a link has been followed."
1526 :group 'org-link-follow
1527 :type 'hook)
1529 (defcustom org-tab-follows-link nil
1530 "Non-nil means on links TAB will follow the link.
1531 Needs to be set before org.el is loaded.
1532 This really should not be used, it does not make sense, and the
1533 implementation is bad."
1534 :group 'org-link-follow
1535 :type 'boolean)
1537 (defcustom org-return-follows-link nil
1538 "Non-nil means on links RET will follow the link."
1539 :group 'org-link-follow
1540 :type 'boolean)
1542 (defcustom org-mouse-1-follows-link
1543 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1544 "Non-nil means mouse-1 on a link will follow the link.
1545 A longer mouse click will still set point. Does not work on XEmacs.
1546 Needs to be set before org.el is loaded."
1547 :group 'org-link-follow
1548 :type 'boolean)
1550 (defcustom org-mark-ring-length 4
1551 "Number of different positions to be recorded in the ring.
1552 Changing this requires a restart of Emacs to work correctly."
1553 :group 'org-link-follow
1554 :type 'integer)
1556 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1557 "Non-nil means internal links in Org files must exactly match a headline.
1558 When nil, the link search tries to match a phrase with all words
1559 in the search text."
1560 :group 'org-link-follow
1561 :version "24.1"
1562 :type '(choice
1563 (const :tag "Use fuzzy text search" nil)
1564 (const :tag "Match only exact headline" t)
1565 (const :tag "Match exact headline or query to create it"
1566 query-to-create)))
1568 (defcustom org-link-frame-setup
1569 '((vm . vm-visit-folder-other-frame)
1570 (vm-imap . vm-visit-imap-folder-other-frame)
1571 (gnus . org-gnus-no-new-news)
1572 (file . find-file-other-window)
1573 (wl . wl-other-frame))
1574 "Setup the frame configuration for following links.
1575 When following a link with Emacs, it may often be useful to display
1576 this link in another window or frame. This variable can be used to
1577 set this up for the different types of links.
1578 For VM, use any of
1579 `vm-visit-folder'
1580 `vm-visit-folder-other-window'
1581 `vm-visit-folder-other-frame'
1582 For Gnus, use any of
1583 `gnus'
1584 `gnus-other-frame'
1585 `org-gnus-no-new-news'
1586 For FILE, use any of
1587 `find-file'
1588 `find-file-other-window'
1589 `find-file-other-frame'
1590 For Wanderlust use any of
1591 `wl'
1592 `wl-other-frame'
1593 For the calendar, use the variable `calendar-setup'.
1594 For BBDB, it is currently only possible to display the matches in
1595 another window."
1596 :group 'org-link-follow
1597 :type '(list
1598 (cons (const vm)
1599 (choice
1600 (const vm-visit-folder)
1601 (const vm-visit-folder-other-window)
1602 (const vm-visit-folder-other-frame)))
1603 (cons (const gnus)
1604 (choice
1605 (const gnus)
1606 (const gnus-other-frame)
1607 (const org-gnus-no-new-news)))
1608 (cons (const file)
1609 (choice
1610 (const find-file)
1611 (const find-file-other-window)
1612 (const find-file-other-frame)))
1613 (cons (const wl)
1614 (choice
1615 (const wl)
1616 (const wl-other-frame)))))
1618 (defcustom org-display-internal-link-with-indirect-buffer nil
1619 "Non-nil means use indirect buffer to display infile links.
1620 Activating internal links (from one location in a file to another location
1621 in the same file) normally just jumps to the location. When the link is
1622 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1623 is displayed in
1624 another window. When this option is set, the other window actually displays
1625 an indirect buffer clone of the current buffer, to avoid any visibility
1626 changes to the current buffer."
1627 :group 'org-link-follow
1628 :type 'boolean)
1630 (defcustom org-open-non-existing-files nil
1631 "Non-nil means `org-open-file' will open non-existing files.
1632 When nil, an error will be generated.
1633 This variable applies only to external applications because they
1634 might choke on non-existing files. If the link is to a file that
1635 will be opened in Emacs, the variable is ignored."
1636 :group 'org-link-follow
1637 :type 'boolean)
1639 (defcustom org-open-directory-means-index-dot-org nil
1640 "Non-nil means a link to a directory really means to index.org.
1641 When nil, following a directory link will run dired or open a finder/explorer
1642 window on that directory."
1643 :group 'org-link-follow
1644 :type 'boolean)
1646 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1647 "Function and arguments to call for following mailto links.
1648 This is a list with the first element being a Lisp function, and the
1649 remaining elements being arguments to the function. In string arguments,
1650 %a will be replaced by the address, and %s will be replaced by the subject
1651 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1652 :group 'org-link-follow
1653 :type '(choice
1654 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1655 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1656 (const :tag "message-mail" (message-mail "%a" "%s"))
1657 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1659 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1660 "Non-nil means ask for confirmation before executing shell links.
1661 Shell links can be dangerous: just think about a link
1663 [[shell:rm -rf ~/*][Google Search]]
1665 This link would show up in your Org-mode document as \"Google Search\",
1666 but really it would remove your entire home directory.
1667 Therefore we advise against setting this variable to nil.
1668 Just change it to `y-or-n-p' if you want to confirm with a
1669 single keystroke rather than having to type \"yes\"."
1670 :group 'org-link-follow
1671 :type '(choice
1672 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1673 (const :tag "with y-or-n (faster)" y-or-n-p)
1674 (const :tag "no confirmation (dangerous)" nil)))
1675 (put 'org-confirm-shell-link-function
1676 'safe-local-variable
1677 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1679 (defcustom org-confirm-shell-link-not-regexp ""
1680 "A regexp to skip confirmation for shell links."
1681 :group 'org-link-follow
1682 :version "24.1"
1683 :type 'regexp)
1685 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1686 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1687 Elisp links can be dangerous: just think about a link
1689 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1691 This link would show up in your Org-mode document as \"Google Search\",
1692 but really it would remove your entire home directory.
1693 Therefore we advise against setting this variable to nil.
1694 Just change it to `y-or-n-p' if you want to confirm with a
1695 single keystroke rather than having to type \"yes\"."
1696 :group 'org-link-follow
1697 :type '(choice
1698 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1699 (const :tag "with y-or-n (faster)" y-or-n-p)
1700 (const :tag "no confirmation (dangerous)" nil)))
1701 (put 'org-confirm-shell-link-function
1702 'safe-local-variable
1703 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1705 (defcustom org-confirm-elisp-link-not-regexp ""
1706 "A regexp to skip confirmation for Elisp links."
1707 :group 'org-link-follow
1708 :version "24.1"
1709 :type 'regexp)
1711 (defconst org-file-apps-defaults-gnu
1712 '((remote . emacs)
1713 (system . mailcap)
1714 (t . mailcap))
1715 "Default file applications on a UNIX or GNU/Linux system.
1716 See `org-file-apps'.")
1718 (defconst org-file-apps-defaults-macosx
1719 '((remote . emacs)
1720 (t . "open %s")
1721 (system . "open %s")
1722 ("ps.gz" . "gv %s")
1723 ("eps.gz" . "gv %s")
1724 ("dvi" . "xdvi %s")
1725 ("fig" . "xfig %s"))
1726 "Default file applications on a MacOS X system.
1727 The system \"open\" is known as a default, but we use X11 applications
1728 for some files for which the OS does not have a good default.
1729 See `org-file-apps'.")
1731 (defconst org-file-apps-defaults-windowsnt
1732 (list
1733 '(remote . emacs)
1734 (cons t
1735 (list (if (featurep 'xemacs)
1736 'mswindows-shell-execute
1737 'w32-shell-execute)
1738 "open" 'file))
1739 (cons 'system
1740 (list (if (featurep 'xemacs)
1741 'mswindows-shell-execute
1742 'w32-shell-execute)
1743 "open" 'file)))
1744 "Default file applications on a Windows NT system.
1745 The system \"open\" is used for most files.
1746 See `org-file-apps'.")
1748 (defcustom org-file-apps
1750 (auto-mode . emacs)
1751 ("\\.mm\\'" . default)
1752 ("\\.x?html?\\'" . default)
1753 ("\\.pdf\\'" . default)
1755 "External applications for opening `file:path' items in a document.
1756 Org-mode uses system defaults for different file types, but
1757 you can use this variable to set the application for a given file
1758 extension. The entries in this list are cons cells where the car identifies
1759 files and the cdr the corresponding command. Possible values for the
1760 file identifier are
1761 \"string\" A string as a file identifier can be interpreted in different
1762 ways, depending on its contents:
1764 - Alphanumeric characters only:
1765 Match links with this file extension.
1766 Example: (\"pdf\" . \"evince %s\")
1767 to open PDFs with evince.
1769 - Regular expression: Match links where the
1770 filename matches the regexp. If you want to
1771 use groups here, use shy groups.
1773 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1774 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1775 to open *.html and *.xhtml with firefox.
1777 - Regular expression which contains (non-shy) groups:
1778 Match links where the whole link, including \"::\", and
1779 anything after that, matches the regexp.
1780 In a custom command string, %1, %2, etc. are replaced with
1781 the parts of the link that were matched by the groups.
1782 For backwards compatibility, if a command string is given
1783 that does not use any of the group matches, this case is
1784 handled identically to the second one (i.e. match against
1785 file name only).
1786 In a custom lisp form, you can access the group matches with
1787 (match-string n link).
1789 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1790 to open [[file:document.pdf::5]] with evince at page 5.
1792 `directory' Matches a directory
1793 `remote' Matches a remote file, accessible through tramp or efs.
1794 Remote files most likely should be visited through Emacs
1795 because external applications cannot handle such paths.
1796 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1797 so all files Emacs knows how to handle. Using this with
1798 command `emacs' will open most files in Emacs. Beware that this
1799 will also open html files inside Emacs, unless you add
1800 (\"html\" . default) to the list as well.
1801 t Default for files not matched by any of the other options.
1802 `system' The system command to open files, like `open' on Windows
1803 and Mac OS X, and mailcap under GNU/Linux. This is the command
1804 that will be selected if you call `C-c C-o' with a double
1805 \\[universal-argument] \\[universal-argument] prefix.
1807 Possible values for the command are:
1808 `emacs' The file will be visited by the current Emacs process.
1809 `default' Use the default application for this file type, which is the
1810 association for t in the list, most likely in the system-specific
1811 part.
1812 This can be used to overrule an unwanted setting in the
1813 system-specific variable.
1814 `system' Use the system command for opening files, like \"open\".
1815 This command is specified by the entry whose car is `system'.
1816 Most likely, the system-specific version of this variable
1817 does define this command, but you can overrule/replace it
1818 here.
1819 string A command to be executed by a shell; %s will be replaced
1820 by the path to the file.
1821 sexp A Lisp form which will be evaluated. The file path will
1822 be available in the Lisp variable `file'.
1823 For more examples, see the system specific constants
1824 `org-file-apps-defaults-macosx'
1825 `org-file-apps-defaults-windowsnt'
1826 `org-file-apps-defaults-gnu'."
1827 :group 'org-link-follow
1828 :type '(repeat
1829 (cons (choice :value ""
1830 (string :tag "Extension")
1831 (const :tag "System command to open files" system)
1832 (const :tag "Default for unrecognized files" t)
1833 (const :tag "Remote file" remote)
1834 (const :tag "Links to a directory" directory)
1835 (const :tag "Any files that have Emacs modes"
1836 auto-mode))
1837 (choice :value ""
1838 (const :tag "Visit with Emacs" emacs)
1839 (const :tag "Use default" default)
1840 (const :tag "Use the system command" system)
1841 (string :tag "Command")
1842 (sexp :tag "Lisp form")))))
1844 (defcustom org-doi-server-url "http://dx.doi.org/"
1845 "The URL of the DOI server."
1846 :type 'string
1847 :version "24.3"
1848 :group 'org-link-follow)
1850 (defgroup org-refile nil
1851 "Options concerning refiling entries in Org-mode."
1852 :tag "Org Refile"
1853 :group 'org)
1855 (defcustom org-directory "~/org"
1856 "Directory with org files.
1857 This is just a default location to look for Org files. There is no need
1858 at all to put your files into this directory. It is only used in the
1859 following situations:
1861 1. When a capture template specifies a target file that is not an
1862 absolute path. The path will then be interpreted relative to
1863 `org-directory'
1864 2. When a capture note is filed away in an interactive way (when exiting the
1865 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1866 with `org-directory' as the default path."
1867 :group 'org-refile
1868 :group 'org-remember
1869 :group 'org-capture
1870 :type 'directory)
1872 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1873 "Default target for storing notes.
1874 Used as a fall back file for org-remember.el and org-capture.el, for
1875 templates that do not specify a target file."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :group 'org-capture
1879 :type '(choice
1880 (const :tag "Default from remember-data-file" nil)
1881 file))
1883 (defcustom org-goto-interface 'outline
1884 "The default interface to be used for `org-goto'.
1885 Allowed values are:
1886 outline The interface shows an outline of the relevant file
1887 and the correct heading is found by moving through
1888 the outline or by searching with incremental search.
1889 outline-path-completion Headlines in the current buffer are offered via
1890 completion. This is the interface also used by
1891 the refile command."
1892 :group 'org-refile
1893 :type '(choice
1894 (const :tag "Outline" outline)
1895 (const :tag "Outline-path-completion" outline-path-completion)))
1897 (defcustom org-goto-max-level 5
1898 "Maximum target level when running `org-goto' with refile interface."
1899 :group 'org-refile
1900 :type 'integer)
1902 (defcustom org-reverse-note-order nil
1903 "Non-nil means store new notes at the beginning of a file or entry.
1904 When nil, new notes will be filed to the end of a file or entry.
1905 This can also be a list with cons cells of regular expressions that
1906 are matched against file names, and values."
1907 :group 'org-remember
1908 :group 'org-capture
1909 :group 'org-refile
1910 :type '(choice
1911 (const :tag "Reverse always" t)
1912 (const :tag "Reverse never" nil)
1913 (repeat :tag "By file name regexp"
1914 (cons regexp boolean))))
1916 (defcustom org-log-refile nil
1917 "Information to record when a task is refiled.
1919 Possible values are:
1921 nil Don't add anything
1922 time Add a time stamp to the task
1923 note Prompt for a note and add it with template `org-log-note-headings'
1925 This option can also be set with on a per-file-basis with
1927 #+STARTUP: nologrefile
1928 #+STARTUP: logrefile
1929 #+STARTUP: lognoterefile
1931 You can have local logging settings for a subtree by setting the LOGGING
1932 property to one or more of these keywords.
1934 When bulk-refiling from the agenda, the value `note' is forbidden and
1935 will temporarily be changed to `time'."
1936 :group 'org-refile
1937 :group 'org-progress
1938 :version "24.1"
1939 :type '(choice
1940 (const :tag "No logging" nil)
1941 (const :tag "Record timestamp" time)
1942 (const :tag "Record timestamp with note." note)))
1944 (defcustom org-refile-targets nil
1945 "Targets for refiling entries with \\[org-refile].
1946 This is a list of cons cells. Each cell contains:
1947 - a specification of the files to be considered, either a list of files,
1948 or a symbol whose function or variable value will be used to retrieve
1949 a file name or a list of file names. If you use `org-agenda-files' for
1950 that, all agenda files will be scanned for targets. Nil means consider
1951 headings in the current buffer.
1952 - A specification of how to find candidate refile targets. This may be
1953 any of:
1954 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1955 This tag has to be present in all target headlines, inheritance will
1956 not be considered.
1957 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1958 todo keyword.
1959 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1960 headlines that are refiling targets.
1961 - a cons cell (:level . N). Any headline of level N is considered a target.
1962 Note that, when `org-odd-levels-only' is set, level corresponds to
1963 order in hierarchy, not to the number of stars.
1964 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1965 Note that, when `org-odd-levels-only' is set, level corresponds to
1966 order in hierarchy, not to the number of stars.
1968 Each element of this list generates a set of possible targets.
1969 The union of these sets is presented (with completion) to
1970 the user by `org-refile'.
1972 You can set the variable `org-refile-target-verify-function' to a function
1973 to verify each headline found by the simple criteria above.
1975 When this variable is nil, all top-level headlines in the current buffer
1976 are used, equivalent to the value `((nil . (:level . 1))'."
1977 :group 'org-refile
1978 :type '(repeat
1979 (cons
1980 (choice :value org-agenda-files
1981 (const :tag "All agenda files" org-agenda-files)
1982 (const :tag "Current buffer" nil)
1983 (function) (variable) (file))
1984 (choice :tag "Identify target headline by"
1985 (cons :tag "Specific tag" (const :value :tag) (string))
1986 (cons :tag "TODO keyword" (const :value :todo) (string))
1987 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1988 (cons :tag "Level number" (const :value :level) (integer))
1989 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1991 (defcustom org-refile-target-verify-function nil
1992 "Function to verify if the headline at point should be a refile target.
1993 The function will be called without arguments, with point at the
1994 beginning of the headline. It should return t and leave point
1995 where it is if the headline is a valid target for refiling.
1997 If the target should not be selected, the function must return nil.
1998 In addition to this, it may move point to a place from where the search
1999 should be continued. For example, the function may decide that the entire
2000 subtree of the current entry should be excluded and move point to the end
2001 of the subtree."
2002 :group 'org-refile
2003 :type 'function)
2005 (defcustom org-refile-use-cache nil
2006 "Non-nil means cache refile targets to speed up the process.
2007 The cache for a particular file will be updated automatically when
2008 the buffer has been killed, or when any of the marker used for flagging
2009 refile targets no longer points at a live buffer.
2010 If you have added new entries to a buffer that might themselves be targets,
2011 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2012 find that easier, `C-u C-u C-u C-c C-w'."
2013 :group 'org-refile
2014 :version "24.1"
2015 :type 'boolean)
2017 (defcustom org-refile-use-outline-path nil
2018 "Non-nil means provide refile targets as paths.
2019 So a level 3 headline will be available as level1/level2/level3.
2021 When the value is `file', also include the file name (without directory)
2022 into the path. In this case, you can also stop the completion after
2023 the file name, to get entries inserted as top level in the file.
2025 When `full-file-path', include the full file path."
2026 :group 'org-refile
2027 :type '(choice
2028 (const :tag "Not" nil)
2029 (const :tag "Yes" t)
2030 (const :tag "Start with file name" file)
2031 (const :tag "Start with full file path" full-file-path)))
2033 (defcustom org-outline-path-complete-in-steps t
2034 "Non-nil means complete the outline path in hierarchical steps.
2035 When Org-mode uses the refile interface to select an outline path
2036 \(see variable `org-refile-use-outline-path'), the completion of
2037 the path can be done is a single go, or if can be done in steps down
2038 the headline hierarchy. Going in steps is probably the best if you
2039 do not use a special completion package like `ido' or `icicles'.
2040 However, when using these packages, going in one step can be very
2041 fast, while still showing the whole path to the entry."
2042 :group 'org-refile
2043 :type 'boolean)
2045 (defcustom org-refile-allow-creating-parent-nodes nil
2046 "Non-nil means allow to create new nodes as refile targets.
2047 New nodes are then created by adding \"/new node name\" to the completion
2048 of an existing node. When the value of this variable is `confirm',
2049 new node creation must be confirmed by the user (recommended)
2050 When nil, the completion must match an existing entry.
2052 Note that, if the new heading is not seen by the criteria
2053 listed in `org-refile-targets', multiple instances of the same
2054 heading would be created by trying again to file under the new
2055 heading."
2056 :group 'org-refile
2057 :type '(choice
2058 (const :tag "Never" nil)
2059 (const :tag "Always" t)
2060 (const :tag "Prompt for confirmation" confirm)))
2062 (defcustom org-refile-active-region-within-subtree nil
2063 "Non-nil means also refile active region within a subtree.
2065 By default `org-refile' doesn't allow refiling regions if they
2066 don't contain a set of subtrees, but it might be convenient to
2067 do so sometimes: in that case, the first line of the region is
2068 converted to a headline before refiling."
2069 :group 'org-refile
2070 :version "24.1"
2071 :type 'boolean)
2073 (defgroup org-todo nil
2074 "Options concerning TODO items in Org-mode."
2075 :tag "Org TODO"
2076 :group 'org)
2078 (defgroup org-progress nil
2079 "Options concerning Progress logging in Org-mode."
2080 :tag "Org Progress"
2081 :group 'org-time)
2083 (defvar org-todo-interpretation-widgets
2084 '((:tag "Sequence (cycling hits every state)" sequence)
2085 (:tag "Type (cycling directly to DONE)" type))
2086 "The available interpretation symbols for customizing `org-todo-keywords'.
2087 Interested libraries should add to this list.")
2089 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2090 "List of TODO entry keyword sequences and their interpretation.
2091 \\<org-mode-map>This is a list of sequences.
2093 Each sequence starts with a symbol, either `sequence' or `type',
2094 indicating if the keywords should be interpreted as a sequence of
2095 action steps, or as different types of TODO items. The first
2096 keywords are states requiring action - these states will select a headline
2097 for inclusion into the global TODO list Org-mode produces. If one of
2098 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2099 signify that no further action is necessary. If \"|\" is not found,
2100 the last keyword is treated as the only DONE state of the sequence.
2102 The command \\[org-todo] cycles an entry through these states, and one
2103 additional state where no keyword is present. For details about this
2104 cycling, see the manual.
2106 TODO keywords and interpretation can also be set on a per-file basis with
2107 the special #+SEQ_TODO and #+TYP_TODO lines.
2109 Each keyword can optionally specify a character for fast state selection
2110 \(in combination with the variable `org-use-fast-todo-selection')
2111 and specifiers for state change logging, using the same syntax that
2112 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2113 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2114 indicates to record a time stamp each time this state is selected.
2116 Each keyword may also specify if a timestamp or a note should be
2117 recorded when entering or leaving the state, by adding additional
2118 characters in the parenthesis after the keyword. This looks like this:
2119 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2120 record only the time of the state change. With X and Y being either
2121 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2122 Y when leaving the state if and only if the *target* state does not
2123 define X. You may omit any of the fast-selection key or X or /Y,
2124 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2126 For backward compatibility, this variable may also be just a list
2127 of keywords. In this case the interpretation (sequence or type) will be
2128 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2129 :group 'org-todo
2130 :group 'org-keywords
2131 :type '(choice
2132 (repeat :tag "Old syntax, just keywords"
2133 (string :tag "Keyword"))
2134 (repeat :tag "New syntax"
2135 (cons
2136 (choice
2137 :tag "Interpretation"
2138 ;;Quick and dirty way to see
2139 ;;`org-todo-interpretations'. This takes the
2140 ;;place of item arguments
2141 :convert-widget
2142 (lambda (widget)
2143 (widget-put widget
2144 :args (mapcar
2145 #'(lambda (x)
2146 (widget-convert
2147 (cons 'const x)))
2148 org-todo-interpretation-widgets))
2149 widget))
2150 (repeat
2151 (string :tag "Keyword"))))))
2153 (defvar org-todo-keywords-1 nil
2154 "All TODO and DONE keywords active in a buffer.")
2155 (make-variable-buffer-local 'org-todo-keywords-1)
2156 (defvar org-todo-keywords-for-agenda nil)
2157 (defvar org-done-keywords-for-agenda nil)
2158 (defvar org-drawers-for-agenda nil)
2159 (defvar org-todo-keyword-alist-for-agenda nil)
2160 (defvar org-tag-alist-for-agenda nil)
2161 (defvar org-agenda-contributing-files nil)
2162 (defvar org-not-done-keywords nil)
2163 (make-variable-buffer-local 'org-not-done-keywords)
2164 (defvar org-done-keywords nil)
2165 (make-variable-buffer-local 'org-done-keywords)
2166 (defvar org-todo-heads nil)
2167 (make-variable-buffer-local 'org-todo-heads)
2168 (defvar org-todo-sets nil)
2169 (make-variable-buffer-local 'org-todo-sets)
2170 (defvar org-todo-log-states nil)
2171 (make-variable-buffer-local 'org-todo-log-states)
2172 (defvar org-todo-kwd-alist nil)
2173 (make-variable-buffer-local 'org-todo-kwd-alist)
2174 (defvar org-todo-key-alist nil)
2175 (make-variable-buffer-local 'org-todo-key-alist)
2176 (defvar org-todo-key-trigger nil)
2177 (make-variable-buffer-local 'org-todo-key-trigger)
2179 (defcustom org-todo-interpretation 'sequence
2180 "Controls how TODO keywords are interpreted.
2181 This variable is in principle obsolete and is only used for
2182 backward compatibility, if the interpretation of todo keywords is
2183 not given already in `org-todo-keywords'. See that variable for
2184 more information."
2185 :group 'org-todo
2186 :group 'org-keywords
2187 :type '(choice (const sequence)
2188 (const type)))
2190 (defcustom org-use-fast-todo-selection t
2191 "Non-nil means use the fast todo selection scheme with C-c C-t.
2192 This variable describes if and under what circumstances the cycling
2193 mechanism for TODO keywords will be replaced by a single-key, direct
2194 selection scheme.
2196 When nil, fast selection is never used.
2198 When the symbol `prefix', it will be used when `org-todo' is called
2199 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2200 `C-u t' in an agenda buffer.
2202 When t, fast selection is used by default. In this case, the prefix
2203 argument forces cycling instead.
2205 In all cases, the special interface is only used if access keys have
2206 actually been assigned by the user, i.e. if keywords in the configuration
2207 are followed by a letter in parenthesis, like TODO(t)."
2208 :group 'org-todo
2209 :type '(choice
2210 (const :tag "Never" nil)
2211 (const :tag "By default" t)
2212 (const :tag "Only with C-u C-c C-t" prefix)))
2214 (defcustom org-provide-todo-statistics t
2215 "Non-nil means update todo statistics after insert and toggle.
2216 ALL-HEADLINES means update todo statistics by including headlines
2217 with no TODO keyword as well, counting them as not done.
2218 A list of TODO keywords means the same, but skip keywords that are
2219 not in this list.
2221 When this is set, todo statistics is updated in the parent of the
2222 current entry each time a todo state is changed."
2223 :group 'org-todo
2224 :type '(choice
2225 (const :tag "Yes, only for TODO entries" t)
2226 (const :tag "Yes, including all entries" 'all-headlines)
2227 (repeat :tag "Yes, for TODOs in this list"
2228 (string :tag "TODO keyword"))
2229 (other :tag "No TODO statistics" nil)))
2231 (defcustom org-hierarchical-todo-statistics t
2232 "Non-nil means TODO statistics covers just direct children.
2233 When nil, all entries in the subtree are considered.
2234 This has only an effect if `org-provide-todo-statistics' is set.
2235 To set this to nil for only a single subtree, use a COOKIE_DATA
2236 property and include the word \"recursive\" into the value."
2237 :group 'org-todo
2238 :type 'boolean)
2240 (defcustom org-after-todo-state-change-hook nil
2241 "Hook which is run after the state of a TODO item was changed.
2242 The new state (a string with a TODO keyword, or nil) is available in the
2243 Lisp variable `org-state'."
2244 :group 'org-todo
2245 :type 'hook)
2247 (defvar org-blocker-hook nil
2248 "Hook for functions that are allowed to block a state change.
2250 Functions in this hook should not modify the buffer.
2251 Each function gets as its single argument a property list,
2252 see `org-trigger-hook' for more information about this list.
2254 If any of the functions in this hook returns nil, the state change
2255 is blocked.")
2257 (defvar org-trigger-hook nil
2258 "Hook for functions that are triggered by a state change.
2260 Each function gets as its single argument a property list with at
2261 least the following elements:
2263 (:type type-of-change :position pos-at-entry-start
2264 :from old-state :to new-state)
2266 Depending on the type, more properties may be present.
2268 This mechanism is currently implemented for:
2270 TODO state changes
2271 ------------------
2272 :type todo-state-change
2273 :from previous state (keyword as a string), or nil, or a symbol
2274 'todo' or 'done', to indicate the general type of state.
2275 :to new state, like in :from")
2277 (defcustom org-enforce-todo-dependencies nil
2278 "Non-nil means undone TODO entries will block switching the parent to DONE.
2279 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2280 be blocked if any prior sibling is not yet done.
2281 Finally, if the parent is blocked because of ordered siblings of its own,
2282 the child will also be blocked."
2283 :set (lambda (var val)
2284 (set var val)
2285 (if val
2286 (add-hook 'org-blocker-hook
2287 'org-block-todo-from-children-or-siblings-or-parent)
2288 (remove-hook 'org-blocker-hook
2289 'org-block-todo-from-children-or-siblings-or-parent)))
2290 :group 'org-todo
2291 :type 'boolean)
2293 (defcustom org-enforce-todo-checkbox-dependencies nil
2294 "Non-nil means unchecked boxes will block switching the parent to DONE.
2295 When this is nil, checkboxes have no influence on switching TODO states.
2296 When non-nil, you first need to check off all check boxes before the TODO
2297 entry can be switched to DONE.
2298 This variable needs to be set before org.el is loaded, and you need to
2299 restart Emacs after a change to make the change effective. The only way
2300 to change is while Emacs is running is through the customize interface."
2301 :set (lambda (var val)
2302 (set var val)
2303 (if val
2304 (add-hook 'org-blocker-hook
2305 'org-block-todo-from-checkboxes)
2306 (remove-hook 'org-blocker-hook
2307 'org-block-todo-from-checkboxes)))
2308 :group 'org-todo
2309 :type 'boolean)
2311 (defcustom org-treat-insert-todo-heading-as-state-change nil
2312 "Non-nil means inserting a TODO heading is treated as state change.
2313 So when the command \\[org-insert-todo-heading] is used, state change
2314 logging will apply if appropriate. When nil, the new TODO item will
2315 be inserted directly, and no logging will take place."
2316 :group 'org-todo
2317 :type 'boolean)
2319 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2320 "Non-nil means switching TODO states with S-cursor counts as state change.
2321 This is the default behavior. However, setting this to nil allows a
2322 convenient way to select a TODO state and bypass any logging associated
2323 with that."
2324 :group 'org-todo
2325 :type 'boolean)
2327 (defcustom org-todo-state-tags-triggers nil
2328 "Tag changes that should be triggered by TODO state changes.
2329 This is a list. Each entry is
2331 (state-change (tag . flag) .......)
2333 State-change can be a string with a state, and empty string to indicate the
2334 state that has no TODO keyword, or it can be one of the symbols `todo'
2335 or `done', meaning any not-done or done state, respectively."
2336 :group 'org-todo
2337 :group 'org-tags
2338 :type '(repeat
2339 (cons (choice :tag "When changing to"
2340 (const :tag "Not-done state" todo)
2341 (const :tag "Done state" done)
2342 (string :tag "State"))
2343 (repeat
2344 (cons :tag "Tag action"
2345 (string :tag "Tag")
2346 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2348 (defcustom org-log-done nil
2349 "Information to record when a task moves to the DONE state.
2351 Possible values are:
2353 nil Don't add anything, just change the keyword
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologdone
2360 #+STARTUP: logdone
2361 #+STARTUP: lognotedone
2363 You can have local logging settings for a subtree by setting the LOGGING
2364 property to one or more of these keywords."
2365 :group 'org-todo
2366 :group 'org-progress
2367 :type '(choice
2368 (const :tag "No logging" nil)
2369 (const :tag "Record CLOSED timestamp" time)
2370 (const :tag "Record CLOSED timestamp with note." note)))
2372 ;; Normalize old uses of org-log-done.
2373 (cond
2374 ((eq org-log-done t) (setq org-log-done 'time))
2375 ((and (listp org-log-done) (memq 'done org-log-done))
2376 (setq org-log-done 'note)))
2378 (defcustom org-log-reschedule nil
2379 "Information to record when the scheduling date of a tasks is modified.
2381 Possible values are:
2383 nil Don't add anything, just change the date
2384 time Add a time stamp to the task
2385 note Prompt for a note and add it with template `org-log-note-headings'
2387 This option can also be set with on a per-file-basis with
2389 #+STARTUP: nologreschedule
2390 #+STARTUP: logreschedule
2391 #+STARTUP: lognotereschedule"
2392 :group 'org-todo
2393 :group 'org-progress
2394 :type '(choice
2395 (const :tag "No logging" nil)
2396 (const :tag "Record timestamp" time)
2397 (const :tag "Record timestamp with note." note)))
2399 (defcustom org-log-redeadline nil
2400 "Information to record when the deadline date of a tasks is modified.
2402 Possible values are:
2404 nil Don't add anything, just change the date
2405 time Add a time stamp to the task
2406 note Prompt for a note and add it with template `org-log-note-headings'
2408 This option can also be set with on a per-file-basis with
2410 #+STARTUP: nologredeadline
2411 #+STARTUP: logredeadline
2412 #+STARTUP: lognoteredeadline
2414 You can have local logging settings for a subtree by setting the LOGGING
2415 property to one or more of these keywords."
2416 :group 'org-todo
2417 :group 'org-progress
2418 :type '(choice
2419 (const :tag "No logging" nil)
2420 (const :tag "Record timestamp" time)
2421 (const :tag "Record timestamp with note." note)))
2423 (defcustom org-log-note-clock-out nil
2424 "Non-nil means record a note when clocking out of an item.
2425 This can also be configured on a per-file basis by adding one of
2426 the following lines anywhere in the buffer:
2428 #+STARTUP: lognoteclock-out
2429 #+STARTUP: nolognoteclock-out"
2430 :group 'org-todo
2431 :group 'org-progress
2432 :type 'boolean)
2434 (defcustom org-log-done-with-time t
2435 "Non-nil means the CLOSED time stamp will contain date and time.
2436 When nil, only the date will be recorded."
2437 :group 'org-progress
2438 :type 'boolean)
2440 (defcustom org-log-note-headings
2441 '((done . "CLOSING NOTE %t")
2442 (state . "State %-12s from %-12S %t")
2443 (note . "Note taken on %t")
2444 (reschedule . "Rescheduled from %S on %t")
2445 (delschedule . "Not scheduled, was %S on %t")
2446 (redeadline . "New deadline from %S on %t")
2447 (deldeadline . "Removed deadline, was %S on %t")
2448 (refile . "Refiled on %t")
2449 (clock-out . ""))
2450 "Headings for notes added to entries.
2451 The value is an alist, with the car being a symbol indicating the note
2452 context, and the cdr is the heading to be used. The heading may also be the
2453 empty string.
2454 %t in the heading will be replaced by a time stamp.
2455 %T will be an active time stamp instead the default inactive one
2456 %d will be replaced by a short-format time stamp.
2457 %D will be replaced by an active short-format time stamp.
2458 %s will be replaced by the new TODO state, in double quotes.
2459 %S will be replaced by the old TODO state, in double quotes.
2460 %u will be replaced by the user name.
2461 %U will be replaced by the full user name.
2463 In fact, it is not a good idea to change the `state' entry, because
2464 agenda log mode depends on the format of these entries."
2465 :group 'org-todo
2466 :group 'org-progress
2467 :type '(list :greedy t
2468 (cons (const :tag "Heading when closing an item" done) string)
2469 (cons (const :tag
2470 "Heading when changing todo state (todo sequence only)"
2471 state) string)
2472 (cons (const :tag "Heading when just taking a note" note) string)
2473 (cons (const :tag "Heading when clocking out" clock-out) string)
2474 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2475 (cons (const :tag "Heading when rescheduling" reschedule) string)
2476 (cons (const :tag "Heading when changing deadline" redeadline) string)
2477 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2478 (cons (const :tag "Heading when refiling" refile) string)))
2480 (unless (assq 'note org-log-note-headings)
2481 (push '(note . "%t") org-log-note-headings))
2483 (defcustom org-log-into-drawer nil
2484 "Non-nil means insert state change notes and time stamps into a drawer.
2485 When nil, state changes notes will be inserted after the headline and
2486 any scheduling and clock lines, but not inside a drawer.
2488 The value of this variable should be the name of the drawer to use.
2489 LOGBOOK is proposed as the default drawer for this purpose, you can
2490 also set this to a string to define the drawer of your choice.
2492 A value of t is also allowed, representing \"LOGBOOK\".
2494 If this variable is set, `org-log-state-notes-insert-after-drawers'
2495 will be ignored.
2497 You can set the property LOG_INTO_DRAWER to overrule this setting for
2498 a subtree."
2499 :group 'org-todo
2500 :group 'org-progress
2501 :type '(choice
2502 (const :tag "Not into a drawer" nil)
2503 (const :tag "LOGBOOK" t)
2504 (string :tag "Other")))
2506 (if (fboundp 'defvaralias)
2507 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2509 (defun org-log-into-drawer ()
2510 "Return the value of `org-log-into-drawer', but let properties overrule.
2511 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2512 used instead of the default value."
2513 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2514 (cond
2515 ((not p) org-log-into-drawer)
2516 ((equal p "nil") nil)
2517 ((equal p "t") "LOGBOOK")
2518 (t p))))
2520 (defcustom org-log-state-notes-insert-after-drawers nil
2521 "Non-nil means insert state change notes after any drawers in entry.
2522 Only the drawers that *immediately* follow the headline and the
2523 deadline/scheduled line are skipped.
2524 When nil, insert notes right after the heading and perhaps the line
2525 with deadline/scheduling if present.
2527 This variable will have no effect if `org-log-into-drawer' is
2528 set."
2529 :group 'org-todo
2530 :group 'org-progress
2531 :type 'boolean)
2533 (defcustom org-log-states-order-reversed t
2534 "Non-nil means the latest state note will be directly after heading.
2535 When nil, the state change notes will be ordered according to time."
2536 :group 'org-todo
2537 :group 'org-progress
2538 :type 'boolean)
2540 (defcustom org-todo-repeat-to-state nil
2541 "The TODO state to which a repeater should return the repeating task.
2542 By default this is the first task in a TODO sequence, or the previous state
2543 in a TODO_TYP set. But you can specify another task here.
2544 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2545 :group 'org-todo
2546 :version "24.1"
2547 :type '(choice (const :tag "Head of sequence" nil)
2548 (string :tag "Specific state")))
2550 (defcustom org-log-repeat 'time
2551 "Non-nil means record moving through the DONE state when triggering repeat.
2552 An auto-repeating task is immediately switched back to TODO when
2553 marked DONE. If you are not logging state changes (by adding \"@\"
2554 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2555 record a closing note, there will be no record of the task moving
2556 through DONE. This variable forces taking a note anyway.
2558 nil Don't force a record
2559 time Record a time stamp
2560 note Prompt for a note and add it with template `org-log-note-headings'
2562 This option can also be set with on a per-file-basis with
2564 #+STARTUP: nologrepeat
2565 #+STARTUP: logrepeat
2566 #+STARTUP: lognoterepeat
2568 You can have local logging settings for a subtree by setting the LOGGING
2569 property to one or more of these keywords."
2570 :group 'org-todo
2571 :group 'org-progress
2572 :type '(choice
2573 (const :tag "Don't force a record" nil)
2574 (const :tag "Force recording the DONE state" time)
2575 (const :tag "Force recording a note with the DONE state" note)))
2578 (defgroup org-priorities nil
2579 "Priorities in Org-mode."
2580 :tag "Org Priorities"
2581 :group 'org-todo)
2583 (defcustom org-enable-priority-commands t
2584 "Non-nil means priority commands are active.
2585 When nil, these commands will be disabled, so that you never accidentally
2586 set a priority."
2587 :group 'org-priorities
2588 :type 'boolean)
2590 (defcustom org-highest-priority ?A
2591 "The highest priority of TODO items. A character like ?A, ?B etc.
2592 Must have a smaller ASCII number than `org-lowest-priority'."
2593 :group 'org-priorities
2594 :type 'character)
2596 (defcustom org-lowest-priority ?C
2597 "The lowest priority of TODO items. A character like ?A, ?B etc.
2598 Must have a larger ASCII number than `org-highest-priority'."
2599 :group 'org-priorities
2600 :type 'character)
2602 (defcustom org-default-priority ?B
2603 "The default priority of TODO items.
2604 This is the priority an item gets if no explicit priority is given.
2605 When starting to cycle on an empty priority the first step in the cycle
2606 depends on `org-priority-start-cycle-with-default'. The resulting first
2607 step priority must not exceed the range from `org-highest-priority' to
2608 `org-lowest-priority' which means that `org-default-priority' has to be
2609 in this range exclusive or inclusive the range boundaries. Else the
2610 first step refuses to set the default and the second will fall back
2611 to (depending on the command used) the highest or lowest priority."
2612 :group 'org-priorities
2613 :type 'character)
2615 (defcustom org-priority-start-cycle-with-default t
2616 "Non-nil means start with default priority when starting to cycle.
2617 When this is nil, the first step in the cycle will be (depending on the
2618 command used) one higher or lower than the default priority.
2619 See also `org-default-priority'."
2620 :group 'org-priorities
2621 :type 'boolean)
2623 (defcustom org-get-priority-function nil
2624 "Function to extract the priority from a string.
2625 The string is normally the headline. If this is nil Org computes the
2626 priority from the priority cookie like [#A] in the headline. It returns
2627 an integer, increasing by 1000 for each priority level.
2628 The user can set a different function here, which should take a string
2629 as an argument and return the numeric priority."
2630 :group 'org-priorities
2631 :version "24.1"
2632 :type 'function)
2634 (defgroup org-time nil
2635 "Options concerning time stamps and deadlines in Org-mode."
2636 :tag "Org Time"
2637 :group 'org)
2639 (defcustom org-insert-labeled-timestamps-at-point nil
2640 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2641 When nil, these labeled time stamps are forces into the second line of an
2642 entry, just after the headline. When scheduling from the global TODO list,
2643 the time stamp will always be forced into the second line."
2644 :group 'org-time
2645 :type 'boolean)
2647 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2648 "Formats for `format-time-string' which are used for time stamps.
2649 It is not recommended to change this constant.")
2651 (defcustom org-time-stamp-rounding-minutes '(0 5)
2652 "Number of minutes to round time stamps to.
2653 These are two values, the first applies when first creating a time stamp.
2654 The second applies when changing it with the commands `S-up' and `S-down'.
2655 When changing the time stamp, this means that it will change in steps
2656 of N minutes, as given by the second value.
2658 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2659 numbers should be factors of 60, so for example 5, 10, 15.
2661 When this is larger than 1, you can still force an exact time stamp by using
2662 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2663 and by using a prefix arg to `S-up/down' to specify the exact number
2664 of minutes to shift."
2665 :group 'org-time
2666 :get #'(lambda (var) ; Make sure both elements are there
2667 (if (integerp (default-value var))
2668 (list (default-value var) 5)
2669 (default-value var)))
2670 :type '(list
2671 (integer :tag "when inserting times")
2672 (integer :tag "when modifying times")))
2674 ;; Normalize old customizations of this variable.
2675 (when (integerp org-time-stamp-rounding-minutes)
2676 (setq org-time-stamp-rounding-minutes
2677 (list org-time-stamp-rounding-minutes
2678 org-time-stamp-rounding-minutes)))
2680 (defcustom org-display-custom-times nil
2681 "Non-nil means overlay custom formats over all time stamps.
2682 The formats are defined through the variable `org-time-stamp-custom-formats'.
2683 To turn this on on a per-file basis, insert anywhere in the file:
2684 #+STARTUP: customtime"
2685 :group 'org-time
2686 :set 'set-default
2687 :type 'sexp)
2688 (make-variable-buffer-local 'org-display-custom-times)
2690 (defcustom org-time-stamp-custom-formats
2691 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2692 "Custom formats for time stamps. See `format-time-string' for the syntax.
2693 These are overlaid over the default ISO format if the variable
2694 `org-display-custom-times' is set. Time like %H:%M should be at the
2695 end of the second format. The custom formats are also honored by export
2696 commands, if custom time display is turned on at the time of export."
2697 :group 'org-time
2698 :type 'sexp)
2700 (defun org-time-stamp-format (&optional long inactive)
2701 "Get the right format for a time string."
2702 (let ((f (if long (cdr org-time-stamp-formats)
2703 (car org-time-stamp-formats))))
2704 (if inactive
2705 (concat "[" (substring f 1 -1) "]")
2706 f)))
2708 (defcustom org-time-clocksum-format "%d:%02d"
2709 "The format string used when creating CLOCKSUM lines.
2710 This is also used when org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-time-clocksum-use-fractional nil
2715 "If non-nil, \\[org-clock-display] uses fractional times.
2716 org-mode generates a time duration."
2717 :group 'org-time
2718 :type 'boolean)
2720 (defcustom org-time-clocksum-fractional-format "%.2f"
2721 "The format string used when creating CLOCKSUM lines, or when
2722 org-mode generates a time duration."
2723 :group 'org-time
2724 :type 'string)
2726 (defcustom org-deadline-warning-days 14
2727 "No. of days before expiration during which a deadline becomes active.
2728 This variable governs the display in sparse trees and in the agenda.
2729 When 0 or negative, it means use this number (the absolute value of it)
2730 even if a deadline has a different individual lead time specified.
2732 Custom commands can set this variable in the options section."
2733 :group 'org-time
2734 :group 'org-agenda-daily/weekly
2735 :type 'integer)
2737 (defcustom org-read-date-prefer-future t
2738 "Non-nil means assume future for incomplete date input from user.
2739 This affects the following situations:
2740 1. The user gives a month but not a year.
2741 For example, if it is April and you enter \"feb 2\", this will be read
2742 as Feb 2, *next* year. \"May 5\", however, will be this year.
2743 2. The user gives a day, but no month.
2744 For example, if today is the 15th, and you enter \"3\", Org-mode will
2745 read this as the third of *next* month. However, if you enter \"17\",
2746 it will be considered as *this* month.
2748 If you set this variable to the symbol `time', then also the following
2749 will work:
2751 3. If the user gives a time.
2752 If the time is before now, it will be interpreted as tomorrow.
2754 Currently none of this works for ISO week specifications.
2756 When this option is nil, the current day, month and year will always be
2757 used as defaults.
2759 See also `org-agenda-jump-prefer-future'."
2760 :group 'org-time
2761 :type '(choice
2762 (const :tag "Never" nil)
2763 (const :tag "Check month and day" t)
2764 (const :tag "Check month, day, and time" time)))
2766 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2767 "Should the agenda jump command prefer the future for incomplete dates?
2768 The default is to do the same as configured in `org-read-date-prefer-future'.
2769 But you can also set a deviating value here.
2770 This may t or nil, or the symbol `org-read-date-prefer-future'."
2771 :group 'org-agenda
2772 :group 'org-time
2773 :version "24.1"
2774 :type '(choice
2775 (const :tag "Use org-read-date-prefer-future"
2776 org-read-date-prefer-future)
2777 (const :tag "Never" nil)
2778 (const :tag "Always" t)))
2780 (defcustom org-read-date-force-compatible-dates t
2781 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2783 Depending on the system Emacs is running on, certain dates cannot
2784 be represented with the type used internally to represent time.
2785 Dates between 1970-1-1 and 2038-1-1 can always be represented
2786 correctly. Some systems allow for earlier dates, some for later,
2787 some for both. One way to find out it to insert any date into an
2788 Org buffer, putting the cursor on the year and hitting S-up and
2789 S-down to test the range.
2791 When this variable is set to t, the date/time prompt will not let
2792 you specify dates outside the 1970-2037 range, so it is certain that
2793 these dates will work in whatever version of Emacs you are
2794 running, and also that you can move a file from one Emacs implementation
2795 to another. WHenever Org is forcing the year for you, it will display
2796 a message and beep.
2798 When this variable is nil, Org will check if the date is
2799 representable in the specific Emacs implementation you are using.
2800 If not, it will force a year, usually the current year, and beep
2801 to remind you. Currently this setting is not recommended because
2802 the likelihood that you will open your Org files in an Emacs that
2803 has limited date range is not negligible.
2805 A workaround for this problem is to use diary sexp dates for time
2806 stamps outside of this range."
2807 :group 'org-time
2808 :version "24.1"
2809 :type 'boolean)
2811 (defcustom org-read-date-display-live t
2812 "Non-nil means display current interpretation of date prompt live.
2813 This display will be in an overlay, in the minibuffer."
2814 :group 'org-time
2815 :type 'boolean)
2817 (defcustom org-read-date-popup-calendar t
2818 "Non-nil means pop up a calendar when prompting for a date.
2819 In the calendar, the date can be selected with mouse-1. However, the
2820 minibuffer will also be active, and you can simply enter the date as well.
2821 When nil, only the minibuffer will be available."
2822 :group 'org-time
2823 :type 'boolean)
2824 (if (fboundp 'defvaralias)
2825 (defvaralias 'org-popup-calendar-for-date-prompt
2826 'org-read-date-popup-calendar))
2828 (defcustom org-read-date-minibuffer-setup-hook nil
2829 "Hook to be used to set up keys for the date/time interface.
2830 Add key definitions to `minibuffer-local-map', which will be a temporary
2831 copy."
2832 :group 'org-time
2833 :type 'hook)
2835 (defcustom org-extend-today-until 0
2836 "The hour when your day really ends. Must be an integer.
2837 This has influence for the following applications:
2838 - When switching the agenda to \"today\". It it is still earlier than
2839 the time given here, the day recognized as TODAY is actually yesterday.
2840 - When a date is read from the user and it is still before the time given
2841 here, the current date and time will be assumed to be yesterday, 23:59.
2842 Also, timestamps inserted in capture templates follow this rule.
2844 IMPORTANT: This is a feature whose implementation is and likely will
2845 remain incomplete. Really, it is only here because past midnight seems to
2846 be the favorite working time of John Wiegley :-)"
2847 :group 'org-time
2848 :type 'integer)
2850 (defcustom org-use-effective-time nil
2851 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2852 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2853 \"effective time\" of any timestamps between midnight and 8am will be
2854 23:59 of the previous day."
2855 :group 'org-time
2856 :version "24.1"
2857 :type 'boolean)
2859 (defcustom org-edit-timestamp-down-means-later nil
2860 "Non-nil means S-down will increase the time in a time stamp.
2861 When nil, S-up will increase."
2862 :group 'org-time
2863 :type 'boolean)
2865 (defcustom org-calendar-follow-timestamp-change t
2866 "Non-nil means make the calendar window follow timestamp changes.
2867 When a timestamp is modified and the calendar window is visible, it will be
2868 moved to the new date."
2869 :group 'org-time
2870 :type 'boolean)
2872 (defgroup org-tags nil
2873 "Options concerning tags in Org-mode."
2874 :tag "Org Tags"
2875 :group 'org)
2877 (defcustom org-tag-alist nil
2878 "List of tags allowed in Org-mode files.
2879 When this list is nil, Org-mode will base TAG input on what is already in the
2880 buffer.
2881 The value of this variable is an alist, the car of each entry must be a
2882 keyword as a string, the cdr may be a character that is used to select
2883 that tag through the fast-tag-selection interface.
2884 See the manual for details."
2885 :group 'org-tags
2886 :type '(repeat
2887 (choice
2888 (cons (string :tag "Tag name")
2889 (character :tag "Access char"))
2890 (list :tag "Start radio group"
2891 (const :startgroup)
2892 (option (string :tag "Group description")))
2893 (list :tag "End radio group"
2894 (const :endgroup)
2895 (option (string :tag "Group description")))
2896 (const :tag "New line" (:newline)))))
2898 (defcustom org-tag-persistent-alist nil
2899 "List of tags that will always appear in all Org-mode files.
2900 This is in addition to any in buffer settings or customizations
2901 of `org-tag-alist'.
2902 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2903 The value of this variable is an alist, the car of each entry must be a
2904 keyword as a string, the cdr may be a character that is used to select
2905 that tag through the fast-tag-selection interface.
2906 See the manual for details.
2907 To disable these tags on a per-file basis, insert anywhere in the file:
2908 #+STARTUP: noptag"
2909 :group 'org-tags
2910 :type '(repeat
2911 (choice
2912 (cons (string :tag "Tag name")
2913 (character :tag "Access char"))
2914 (const :tag "Start radio group" (:startgroup))
2915 (const :tag "End radio group" (:endgroup))
2916 (const :tag "New line" (:newline)))))
2918 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2919 "If non-nil, always offer completion for all tags of all agenda files.
2920 Instead of customizing this variable directly, you might want to
2921 set it locally for capture buffers, because there no list of
2922 tags in that file can be created dynamically (there are none).
2924 (add-hook 'org-capture-mode-hook
2925 (lambda ()
2926 (set (make-local-variable
2927 'org-complete-tags-always-offer-all-agenda-tags)
2928 t)))"
2929 :group 'org-tags
2930 :version "24.1"
2931 :type 'boolean)
2933 (defvar org-file-tags nil
2934 "List of tags that can be inherited by all entries in the file.
2935 The tags will be inherited if the variable `org-use-tag-inheritance'
2936 says they should be.
2937 This variable is populated from #+FILETAGS lines.")
2939 (defcustom org-use-fast-tag-selection 'auto
2940 "Non-nil means use fast tag selection scheme.
2941 This is a special interface to select and deselect tags with single keys.
2942 When nil, fast selection is never used.
2943 When the symbol `auto', fast selection is used if and only if selection
2944 characters for tags have been configured, either through the variable
2945 `org-tag-alist' or through a #+TAGS line in the buffer.
2946 When t, fast selection is always used and selection keys are assigned
2947 automatically if necessary."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "Always" t)
2951 (const :tag "Never" nil)
2952 (const :tag "When selection characters are configured" 'auto)))
2954 (defcustom org-fast-tag-selection-single-key nil
2955 "Non-nil means fast tag selection exits after first change.
2956 When nil, you have to press RET to exit it.
2957 During fast tag selection, you can toggle this flag with `C-c'.
2958 This variable can also have the value `expert'. In this case, the window
2959 displaying the tags menu is not even shown, until you press C-c again."
2960 :group 'org-tags
2961 :type '(choice
2962 (const :tag "No" nil)
2963 (const :tag "Yes" t)
2964 (const :tag "Expert" expert)))
2966 (defvar org-fast-tag-selection-include-todo nil
2967 "Non-nil means fast tags selection interface will also offer TODO states.
2968 This is an undocumented feature, you should not rely on it.")
2970 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2971 "The column to which tags should be indented in a headline.
2972 If this number is positive, it specifies the column. If it is negative,
2973 it means that the tags should be flushright to that column. For example,
2974 -80 works well for a normal 80 character screen.
2975 When 0, place tags directly after headline text, with only one space in
2976 between."
2977 :group 'org-tags
2978 :type 'integer)
2980 (defcustom org-auto-align-tags t
2981 "Non-nil keeps tags aligned when modifying headlines.
2982 Some operations (i.e. demoting) change the length of a headline and
2983 therefore shift the tags around. With this option turned on, after
2984 each such operation the tags are again aligned to `org-tags-column'."
2985 :group 'org-tags
2986 :type 'boolean)
2988 (defcustom org-use-tag-inheritance t
2989 "Non-nil means tags in levels apply also for sublevels.
2990 When nil, only the tags directly given in a specific line apply there.
2991 This may also be a list of tags that should be inherited, or a regexp that
2992 matches tags that should be inherited. Additional control is possible
2993 with the variable `org-tags-exclude-from-inheritance' which gives an
2994 explicit list of tags to be excluded from inheritance, even if the value of
2995 `org-use-tag-inheritance' would select it for inheritance.
2997 If this option is t, a match early-on in a tree can lead to a large
2998 number of matches in the subtree when constructing the agenda or creating
2999 a sparse tree. If you only want to see the first match in a tree during
3000 a search, check out the variable `org-tags-match-list-sublevels'."
3001 :group 'org-tags
3002 :type '(choice
3003 (const :tag "Not" nil)
3004 (const :tag "Always" t)
3005 (repeat :tag "Specific tags" (string :tag "Tag"))
3006 (regexp :tag "Tags matched by regexp")))
3008 (defcustom org-tags-exclude-from-inheritance nil
3009 "List of tags that should never be inherited.
3010 This is a way to exclude a few tags from inheritance. For way to do
3011 the opposite, to actively allow inheritance for selected tags,
3012 see the variable `org-use-tag-inheritance'."
3013 :group 'org-tags
3014 :type '(repeat (string :tag "Tag")))
3016 (defun org-tag-inherit-p (tag)
3017 "Check if TAG is one that should be inherited."
3018 (cond
3019 ((member tag org-tags-exclude-from-inheritance) nil)
3020 ((eq org-use-tag-inheritance t) t)
3021 ((not org-use-tag-inheritance) nil)
3022 ((stringp org-use-tag-inheritance)
3023 (string-match org-use-tag-inheritance tag))
3024 ((listp org-use-tag-inheritance)
3025 (member tag org-use-tag-inheritance))
3026 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3028 (defcustom org-tags-match-list-sublevels t
3029 "Non-nil means list also sublevels of headlines matching a search.
3030 This variable applies to tags/property searches, and also to stuck
3031 projects because this search is based on a tags match as well.
3033 When set to the symbol `indented', sublevels are indented with
3034 leading dots.
3036 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3037 the sublevels of a headline matching a tag search often also match
3038 the same search. Listing all of them can create very long lists.
3039 Setting this variable to nil causes subtrees of a match to be skipped.
3041 This variable is semi-obsolete and probably should always be true. It
3042 is better to limit inheritance to certain tags using the variables
3043 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3044 :group 'org-tags
3045 :type '(choice
3046 (const :tag "No, don't list them" nil)
3047 (const :tag "Yes, do list them" t)
3048 (const :tag "List them, indented with leading dots" indented)))
3050 (defcustom org-tags-sort-function nil
3051 "When set, tags are sorted using this function as a comparator."
3052 :group 'org-tags
3053 :type '(choice
3054 (const :tag "No sorting" nil)
3055 (const :tag "Alphabetical" string<)
3056 (const :tag "Reverse alphabetical" string>)
3057 (function :tag "Custom function" nil)))
3059 (defvar org-tags-history nil
3060 "History of minibuffer reads for tags.")
3061 (defvar org-last-tags-completion-table nil
3062 "The last used completion table for tags.")
3063 (defvar org-after-tags-change-hook nil
3064 "Hook that is run after the tags in a line have changed.")
3066 (defgroup org-properties nil
3067 "Options concerning properties in Org-mode."
3068 :tag "Org Properties"
3069 :group 'org)
3071 (defcustom org-property-format "%-10s %s"
3072 "How property key/value pairs should be formatted by `indent-line'.
3073 When `indent-line' hits a property definition, it will format the line
3074 according to this format, mainly to make sure that the values are
3075 lined-up with respect to each other."
3076 :group 'org-properties
3077 :type 'string)
3079 (defcustom org-properties-postprocess-alist nil
3080 "Alist of properties and functions to adjust inserted values.
3081 Elements of this alist must be of the form
3083 ([string] [function])
3085 where [string] must be a property name and [function] must be a
3086 lambda expression: this lambda expression must take one argument,
3087 the value to adjust, and return the new value as a string.
3089 For example, this element will allow the property \"Remaining\"
3090 to be updated wrt the relation between the \"Effort\" property
3091 and the clock summary:
3093 ((\"Remaining\" (lambda(value)
3094 (let ((clocksum (org-clock-sum-current-item))
3095 (effort (org-duration-string-to-minutes
3096 (org-entry-get (point) \"Effort\"))))
3097 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3098 :group 'org-properties
3099 :version "24.1"
3100 :type '(alist :key-type (string :tag "Property")
3101 :value-type (function :tag "Function")))
3103 (defcustom org-use-property-inheritance nil
3104 "Non-nil means properties apply also for sublevels.
3106 This setting is chiefly used during property searches. Turning it on can
3107 cause significant overhead when doing a search, which is why it is not
3108 on by default.
3110 When nil, only the properties directly given in the current entry count.
3111 When t, every property is inherited. The value may also be a list of
3112 properties that should have inheritance, or a regular expression matching
3113 properties that should be inherited.
3115 However, note that some special properties use inheritance under special
3116 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3117 and the properties ending in \"_ALL\" when they are used as descriptor
3118 for valid values of a property.
3120 Note for programmers:
3121 When querying an entry with `org-entry-get', you can control if inheritance
3122 should be used. By default, `org-entry-get' looks only at the local
3123 properties. You can request inheritance by setting the inherit argument
3124 to t (to force inheritance) or to `selective' (to respect the setting
3125 in this variable)."
3126 :group 'org-properties
3127 :type '(choice
3128 (const :tag "Not" nil)
3129 (const :tag "Always" t)
3130 (repeat :tag "Specific properties" (string :tag "Property"))
3131 (regexp :tag "Properties matched by regexp")))
3133 (defun org-property-inherit-p (property)
3134 "Check if PROPERTY is one that should be inherited."
3135 (cond
3136 ((eq org-use-property-inheritance t) t)
3137 ((not org-use-property-inheritance) nil)
3138 ((stringp org-use-property-inheritance)
3139 (string-match org-use-property-inheritance property))
3140 ((listp org-use-property-inheritance)
3141 (member property org-use-property-inheritance))
3142 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3144 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3145 "The default column format, if no other format has been defined.
3146 This variable can be set on the per-file basis by inserting a line
3148 #+COLUMNS: %25ITEM ....."
3149 :group 'org-properties
3150 :type 'string)
3152 (defcustom org-columns-ellipses ".."
3153 "The ellipses to be used when a field in column view is truncated.
3154 When this is the empty string, as many characters as possible are shown,
3155 but then there will be no visual indication that the field has been truncated.
3156 When this is a string of length N, the last N characters of a truncated
3157 field are replaced by this string. If the column is narrower than the
3158 ellipses string, only part of the ellipses string will be shown."
3159 :group 'org-properties
3160 :type 'string)
3162 (defcustom org-columns-modify-value-for-display-function nil
3163 "Function that modifies values for display in column view.
3164 For example, it can be used to cut out a certain part from a time stamp.
3165 The function must take 2 arguments:
3167 column-title The title of the column (*not* the property name)
3168 value The value that should be modified.
3170 The function should return the value that should be displayed,
3171 or nil if the normal value should be used."
3172 :group 'org-properties
3173 :type 'function)
3175 (defcustom org-effort-property "Effort"
3176 "The property that is being used to keep track of effort estimates.
3177 Effort estimates given in this property need to have the format H:MM."
3178 :group 'org-properties
3179 :group 'org-progress
3180 :type '(string :tag "Property"))
3182 (defconst org-global-properties-fixed
3183 '(("VISIBILITY_ALL" . "folded children content all")
3184 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3185 "List of property/value pairs that can be inherited by any entry.
3187 These are fixed values, for the preset properties. The user variable
3188 that can be used to add to this list is `org-global-properties'.
3190 The entries in this list are cons cells where the car is a property
3191 name and cdr is a string with the value. If the value represents
3192 multiple items like an \"_ALL\" property, separate the items by
3193 spaces.")
3195 (defcustom org-global-properties nil
3196 "List of property/value pairs that can be inherited by any entry.
3198 This list will be combined with the constant `org-global-properties-fixed'.
3200 The entries in this list are cons cells where the car is a property
3201 name and cdr is a string with the value.
3203 You can set buffer-local values for the same purpose in the variable
3204 `org-file-properties' this by adding lines like
3206 #+PROPERTY: NAME VALUE"
3207 :group 'org-properties
3208 :type '(repeat
3209 (cons (string :tag "Property")
3210 (string :tag "Value"))))
3212 (defvar org-file-properties nil
3213 "List of property/value pairs that can be inherited by any entry.
3214 Valid for the current buffer.
3215 This variable is populated from #+PROPERTY lines.")
3216 (make-variable-buffer-local 'org-file-properties)
3218 (defgroup org-agenda nil
3219 "Options concerning agenda views in Org-mode."
3220 :tag "Org Agenda"
3221 :group 'org)
3223 (defvar org-category nil
3224 "Variable used by org files to set a category for agenda display.
3225 Such files should use a file variable to set it, for example
3227 # -*- mode: org; org-category: \"ELisp\"
3229 or contain a special line
3231 #+CATEGORY: ELisp
3233 If the file does not specify a category, then file's base name
3234 is used instead.")
3235 (make-variable-buffer-local 'org-category)
3236 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3238 (defcustom org-agenda-files nil
3239 "The files to be used for agenda display.
3240 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3241 \\[org-remove-file]. You can also use customize to edit the list.
3243 If an entry is a directory, all files in that directory that are matched by
3244 `org-agenda-file-regexp' will be part of the file list.
3246 If the value of the variable is not a list but a single file name, then
3247 the list of agenda files is actually stored and maintained in that file, one
3248 agenda file per line. In this file paths can be given relative to
3249 `org-directory'. Tilde expansion and environment variable substitution
3250 are also made."
3251 :group 'org-agenda
3252 :type '(choice
3253 (repeat :tag "List of files and directories" file)
3254 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3256 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3257 "Regular expression to match files for `org-agenda-files'.
3258 If any element in the list in that variable contains a directory instead
3259 of a normal file, all files in that directory that are matched by this
3260 regular expression will be included."
3261 :group 'org-agenda
3262 :type 'regexp)
3264 (defcustom org-agenda-text-search-extra-files nil
3265 "List of extra files to be searched by text search commands.
3266 These files will be search in addition to the agenda files by the
3267 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3268 Note that these files will only be searched for text search commands,
3269 not for the other agenda views like todo lists, tag searches or the weekly
3270 agenda. This variable is intended to list notes and possibly archive files
3271 that should also be searched by these two commands.
3272 In fact, if the first element in the list is the symbol `agenda-archives',
3273 than all archive files of all agenda files will be added to the search
3274 scope."
3275 :group 'org-agenda
3276 :type '(set :greedy t
3277 (const :tag "Agenda Archives" agenda-archives)
3278 (repeat :inline t (file))))
3280 (if (fboundp 'defvaralias)
3281 (defvaralias 'org-agenda-multi-occur-extra-files
3282 'org-agenda-text-search-extra-files))
3284 (defcustom org-agenda-skip-unavailable-files nil
3285 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3286 A nil value means to remove them, after a query, from the list."
3287 :group 'org-agenda
3288 :type 'boolean)
3290 (defcustom org-calendar-to-agenda-key [?c]
3291 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3292 The command `org-calendar-goto-agenda' will be bound to this key. The
3293 default is the character `c' because then `c' can be used to switch back and
3294 forth between agenda and calendar."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-calendar-insert-diary-entry-key [?i]
3299 "The key to be installed in `calendar-mode-map' for adding diary entries.
3300 This option is irrelevant until `org-agenda-diary-file' has been configured
3301 to point to an Org-mode file. When that is the case, the command
3302 `org-agenda-diary-entry' will be bound to the key given here, by default
3303 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3304 if you want to continue doing this, you need to change this to a different
3305 key."
3306 :group 'org-agenda
3307 :type 'sexp)
3309 (defcustom org-agenda-diary-file 'diary-file
3310 "File to which to add new entries with the `i' key in agenda and calendar.
3311 When this is the symbol `diary-file', the functionality in the Emacs
3312 calendar will be used to add entries to the `diary-file'. But when this
3313 points to a file, `org-agenda-diary-entry' will be used instead."
3314 :group 'org-agenda
3315 :type '(choice
3316 (const :tag "The standard Emacs diary file" diary-file)
3317 (file :tag "Special Org file diary entries")))
3319 (eval-after-load "calendar"
3320 '(progn
3321 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3322 'org-calendar-goto-agenda)
3323 (add-hook 'calendar-mode-hook
3324 (lambda ()
3325 (unless (eq org-agenda-diary-file 'diary-file)
3326 (define-key calendar-mode-map
3327 org-calendar-insert-diary-entry-key
3328 'org-agenda-diary-entry))))))
3330 (defgroup org-latex nil
3331 "Options for embedding LaTeX code into Org-mode."
3332 :tag "Org LaTeX"
3333 :group 'org)
3335 (defcustom org-format-latex-options
3336 '(:foreground default :background default :scale 1.0
3337 :html-foreground "Black" :html-background "Transparent"
3338 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3339 "Options for creating images from LaTeX fragments.
3340 This is a property list with the following properties:
3341 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3342 `default' means use the foreground of the default face.
3343 :background the background color, or \"Transparent\".
3344 `default' means use the background of the default face.
3345 :scale a scaling factor for the size of the images, to get more pixels
3346 :html-foreground, :html-background, :html-scale
3347 the same numbers for HTML export.
3348 :matchers a list indicating which matchers should be used to
3349 find LaTeX fragments. Valid members of this list are:
3350 \"begin\" find environments
3351 \"$1\" find single characters surrounded by $.$
3352 \"$\" find math expressions surrounded by $...$
3353 \"$$\" find math expressions surrounded by $$....$$
3354 \"\\(\" find math expressions surrounded by \\(...\\)
3355 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3356 :group 'org-latex
3357 :type 'plist)
3359 (defcustom org-format-latex-signal-error t
3360 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3361 When nil, just push out a message."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-latex-to-mathml-jar-file nil
3367 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3368 Use this to specify additional executable file say a jar file.
3370 When using MathToWeb as the converter, specify the full-path to
3371 your mathtoweb.jar file."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (file :tag "JAR file" :must-match t)))
3378 (defcustom org-latex-to-mathml-convert-command nil
3379 "Command to convert LaTeX fragments to MathML.
3380 Replace format-specifiers in the command as noted below and use
3381 `shell-command' to convert LaTeX to MathML.
3382 %j: Executable file in fully expanded form as specified by
3383 `org-latex-to-mathml-jar-file'.
3384 %I: Input LaTeX file in fully expanded form
3385 %o: Output MathML file
3386 This command is used by `org-create-math-formula'.
3388 When using MathToWeb as the converter, set this to
3389 \"java -jar %j -unicode -force -df %o %I\"."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (string :tag "\nShell command")))
3396 (defcustom org-latex-create-formula-image-program 'dvipng
3397 "Program to convert LaTeX fragments with.
3399 dvipng Process the LaTeX fragments to dvi file, then convert
3400 dvi files to png files using dvipng.
3401 This will also include processing of non-math environments.
3402 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3403 to convert pdf files to png files"
3404 :group 'org-latex
3405 :version "24.1"
3406 :type '(choice
3407 (const :tag "dvipng" dvipng)
3408 (const :tag "imagemagick" imagemagick)))
3410 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3411 "Path to store latex preview images. A relative path here creates many
3412 directories relative to the processed org files paths. An absolute path
3413 puts all preview images at the same place."
3414 :group 'org-latex
3415 :version "24.3"
3416 :type 'string)
3418 (defun org-format-latex-mathml-available-p ()
3419 "Return t if `org-latex-to-mathml-convert-command' is usable."
3420 (save-match-data
3421 (when (and (boundp 'org-latex-to-mathml-convert-command)
3422 org-latex-to-mathml-convert-command)
3423 (let ((executable (car (split-string
3424 org-latex-to-mathml-convert-command))))
3425 (when (executable-find executable)
3426 (if (string-match
3427 "%j" org-latex-to-mathml-convert-command)
3428 (file-readable-p org-latex-to-mathml-jar-file)
3429 t))))))
3431 (defcustom org-format-latex-header "\\documentclass{article}
3432 \\usepackage[usenames]{color}
3433 \\usepackage{amsmath}
3434 \\usepackage[mathscr]{eucal}
3435 \\pagestyle{empty} % do not remove
3436 \[PACKAGES]
3437 \[DEFAULT-PACKAGES]
3438 % The settings below are copied from fullpage.sty
3439 \\setlength{\\textwidth}{\\paperwidth}
3440 \\addtolength{\\textwidth}{-3cm}
3441 \\setlength{\\oddsidemargin}{1.5cm}
3442 \\addtolength{\\oddsidemargin}{-2.54cm}
3443 \\setlength{\\evensidemargin}{\\oddsidemargin}
3444 \\setlength{\\textheight}{\\paperheight}
3445 \\addtolength{\\textheight}{-\\headheight}
3446 \\addtolength{\\textheight}{-\\headsep}
3447 \\addtolength{\\textheight}{-\\footskip}
3448 \\addtolength{\\textheight}{-3cm}
3449 \\setlength{\\topmargin}{1.5cm}
3450 \\addtolength{\\topmargin}{-2.54cm}"
3451 "The document header used for processing LaTeX fragments.
3452 It is imperative that this header make sure that no page number
3453 appears on the page. The package defined in the variables
3454 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3455 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3456 will be appended."
3457 :group 'org-latex
3458 :type 'string)
3460 (defvar org-format-latex-header-extra nil)
3462 (defun org-set-packages-alist (var val)
3463 "Set the packages alist and make sure it has 3 elements per entry."
3464 (set var (mapcar (lambda (x)
3465 (if (and (consp x) (= (length x) 2))
3466 (list (car x) (nth 1 x) t)
3468 val)))
3470 (defun org-get-packages-alist (var)
3472 "Get the packages alist and make sure it has 3 elements per entry."
3473 (mapcar (lambda (x)
3474 (if (and (consp x) (= (length x) 2))
3475 (list (car x) (nth 1 x) t)
3477 (default-value var)))
3479 ;; The following variables are defined here because is it also used
3480 ;; when formatting latex fragments. Originally it was part of the
3481 ;; LaTeX exporter, which is why the name includes "export".
3482 (defcustom org-export-latex-default-packages-alist
3483 '(("AUTO" "inputenc" t)
3484 ("T1" "fontenc" t)
3485 ("" "fixltx2e" nil)
3486 ("" "graphicx" t)
3487 ("" "longtable" nil)
3488 ("" "float" nil)
3489 ("" "wrapfig" nil)
3490 ("" "soul" t)
3491 ("" "textcomp" t)
3492 ("" "marvosym" t)
3493 ("" "wasysym" t)
3494 ("" "latexsym" t)
3495 ("" "amssymb" t)
3496 ("" "hyperref" nil)
3497 "\\tolerance=1000"
3499 "Alist of default packages to be inserted in the header.
3500 Change this only if one of the packages here causes an incompatibility
3501 with another package you are using.
3502 The packages in this list are needed by one part or another of Org-mode
3503 to function properly.
3505 - inputenc, fontenc: for basic font and character selection
3506 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3507 for interpreting the entities in `org-entities'. You can skip some of these
3508 packages if you don't use any of the symbols in it.
3509 - graphicx: for including images
3510 - float, wrapfig: for figure placement
3511 - longtable: for long tables
3512 - hyperref: for cross references
3514 Therefore you should not modify this variable unless you know what you
3515 are doing. The one reason to change it anyway is that you might be loading
3516 some other package that conflicts with one of the default packages.
3517 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3518 If SNIPPET-FLAG is t, the package also needs to be included when
3519 compiling LaTeX snippets into images for inclusion into HTML."
3520 :group 'org-export-latex
3521 :set 'org-set-packages-alist
3522 :get 'org-get-packages-alist
3523 :version "24.1"
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3532 (defcustom org-export-latex-packages-alist nil
3533 "Alist of packages to be inserted in every LaTeX header.
3534 These will be inserted after `org-export-latex-default-packages-alist'.
3535 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3536 SNIPPET-FLAG, when t, indicates that this package is also needed when
3537 turning LaTeX snippets into images for inclusion into HTML.
3538 Make sure that you only list packages here which:
3539 - you want in every file
3540 - do not conflict with the default packages in
3541 `org-export-latex-default-packages-alist'
3542 - do not conflict with the setup in `org-format-latex-header'."
3543 :group 'org-export-latex
3544 :set 'org-set-packages-alist
3545 :get 'org-get-packages-alist
3546 :type '(repeat
3547 (choice
3548 (list :tag "options/package pair"
3549 (string :tag "options")
3550 (string :tag "package")
3551 (boolean :tag "Snippet"))
3552 (string :tag "A line of LaTeX"))))
3555 (defgroup org-appearance nil
3556 "Settings for Org-mode appearance."
3557 :tag "Org Appearance"
3558 :group 'org)
3560 (defcustom org-level-color-stars-only nil
3561 "Non-nil means fontify only the stars in each headline.
3562 When nil, the entire headline is fontified.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified."
3565 :group 'org-appearance
3566 :type 'boolean)
3568 (defcustom org-hide-leading-stars nil
3569 "Non-nil means hide the first N-1 stars in a headline.
3570 This works by using the face `org-hide' for these stars. This
3571 face is white for a light background, and black for a dark
3572 background. You may have to customize the face `org-hide' to
3573 make this work.
3574 Changing it requires restart of `font-lock-mode' to become effective
3575 also in regions already fontified.
3576 You may also set this on a per-file basis by adding one of the following
3577 lines to the buffer:
3579 #+STARTUP: hidestars
3580 #+STARTUP: showstars"
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-hidden-keywords nil
3585 "List of symbols corresponding to keywords to be hidden the org buffer.
3586 For example, a value '(title) for this list will make the document's title
3587 appear in the buffer without the initial #+TITLE: keyword."
3588 :group 'org-appearance
3589 :version "24.1"
3590 :type '(set (const :tag "#+AUTHOR" author)
3591 (const :tag "#+DATE" date)
3592 (const :tag "#+EMAIL" email)
3593 (const :tag "#+TITLE" title)))
3595 (defcustom org-custom-properties nil
3596 "List of properties (as strings) with a special meaning.
3597 The default use of these custom properties is to let the user
3598 hide them with `org-toggle-custom-properties-visibility'."
3599 :group 'org-properties
3600 :group 'org-appearance
3601 :version "24.3"
3602 :type '(repeat (string :tag "Property Name")))
3604 (defcustom org-fontify-done-headline nil
3605 "Non-nil means change the face of a headline if it is marked DONE.
3606 Normally, only the TODO/DONE keyword indicates the state of a headline.
3607 When this is non-nil, the headline after the keyword is set to the
3608 `org-headline-done' as an additional indication."
3609 :group 'org-appearance
3610 :type 'boolean)
3612 (defcustom org-fontify-emphasized-text t
3613 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3614 Changing this variable requires a restart of Emacs to take effect."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-fontify-whole-heading-line nil
3619 "Non-nil means fontify the whole line for headings.
3620 This is useful when setting a background color for the
3621 org-level-* faces."
3622 :group 'org-appearance
3623 :type 'boolean)
3625 (defcustom org-highlight-latex-fragments-and-specials nil
3626 "Non-nil means fontify what is treated specially by the exporters."
3627 :group 'org-appearance
3628 :type 'boolean)
3630 (defcustom org-hide-emphasis-markers nil
3631 "Non-nil mean font-lock should hide the emphasis marker characters."
3632 :group 'org-appearance
3633 :type 'boolean)
3635 (defcustom org-pretty-entities nil
3636 "Non-nil means show entities as UTF8 characters.
3637 When nil, the \\name form remains in the buffer."
3638 :group 'org-appearance
3639 :version "24.1"
3640 :type 'boolean)
3642 (defcustom org-pretty-entities-include-sub-superscripts t
3643 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3644 :group 'org-appearance
3645 :version "24.1"
3646 :type 'boolean)
3648 (defvar org-emph-re nil
3649 "Regular expression for matching emphasis.
3650 After a match, the match groups contain these elements:
3651 0 The match of the full regular expression, including the characters
3652 before and after the proper match
3653 1 The character before the proper match, or empty at beginning of line
3654 2 The proper match, including the leading and trailing markers
3655 3 The leading marker like * or /, indicating the type of highlighting
3656 4 The text between the emphasis markers, not including the markers
3657 5 The character after the match, empty at the end of a line")
3658 (defvar org-verbatim-re nil
3659 "Regular expression for matching verbatim text.")
3660 (defvar org-emphasis-regexp-components) ; defined just below
3661 (defvar org-emphasis-alist) ; defined just below
3662 (defun org-set-emph-re (var val)
3663 "Set variable and compute the emphasis regular expression."
3664 (set var val)
3665 (when (and (boundp 'org-emphasis-alist)
3666 (boundp 'org-emphasis-regexp-components)
3667 org-emphasis-alist org-emphasis-regexp-components)
3668 (let* ((e org-emphasis-regexp-components)
3669 (pre (car e))
3670 (post (nth 1 e))
3671 (border (nth 2 e))
3672 (body (nth 3 e))
3673 (nl (nth 4 e))
3674 (body1 (concat body "*?"))
3675 (markers (mapconcat 'car org-emphasis-alist ""))
3676 (vmarkers (mapconcat
3677 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3678 org-emphasis-alist "")))
3679 ;; make sure special characters appear at the right position in the class
3680 (if (string-match "\\^" markers)
3681 (setq markers (concat (replace-match "" t t markers) "^")))
3682 (if (string-match "-" markers)
3683 (setq markers (concat (replace-match "" t t markers) "-")))
3684 (if (string-match "\\^" vmarkers)
3685 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3686 (if (string-match "-" vmarkers)
3687 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3688 (if (> nl 0)
3689 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3690 (int-to-string nl) "\\}")))
3691 ;; Make the regexp
3692 (setq org-emph-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" markers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)"))
3704 (setq org-verbatim-re
3705 (concat "\\([" pre "]\\|^\\)"
3706 "\\("
3707 "\\([" vmarkers "]\\)"
3708 "\\("
3709 "[^" border "]\\|"
3710 "[^" border "]"
3711 body1
3712 "[^" border "]"
3713 "\\)"
3714 "\\3\\)"
3715 "\\([" post "]\\|$\\)")))))
3717 (defcustom org-emphasis-regexp-components
3718 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3719 "Components used to build the regular expression for emphasis.
3720 This is a list with five entries. Terminology: In an emphasis string
3721 like \" *strong word* \", we call the initial space PREMATCH, the final
3722 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3723 and \"trong wor\" is the body. The different components in this variable
3724 specify what is allowed/forbidden in each part:
3726 pre Chars allowed as prematch. Beginning of line will be allowed too.
3727 post Chars allowed as postmatch. End of line will be allowed too.
3728 border The chars *forbidden* as border characters.
3729 body-regexp A regexp like \".\" to match a body character. Don't use
3730 non-shy groups here, and don't allow newline here.
3731 newline The maximum number of newlines allowed in an emphasis exp.
3733 Use customize to modify this, or restart Emacs after changing it."
3734 :group 'org-appearance
3735 :set 'org-set-emph-re
3736 :type '(list
3737 (sexp :tag "Allowed chars in pre ")
3738 (sexp :tag "Allowed chars in post ")
3739 (sexp :tag "Forbidden chars in border ")
3740 (sexp :tag "Regexp for body ")
3741 (integer :tag "number of newlines allowed")
3742 (option (boolean :tag "Please ignore this button"))))
3744 (defcustom org-emphasis-alist
3745 `(("*" bold "<b>" "</b>")
3746 ("/" italic "<i>" "</i>")
3747 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3748 ("=" org-code "<code>" "</code>" verbatim)
3749 ("~" org-verbatim "<code>" "</code>" verbatim)
3750 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3751 "<del>" "</del>")
3753 "Special syntax for emphasized text.
3754 Text starting and ending with a special character will be emphasized, for
3755 example *bold*, _underlined_ and /italic/. This variable sets the marker
3756 characters, the face to be used by font-lock for highlighting in Org-mode
3757 Emacs buffers, and the HTML tags to be used for this.
3758 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3759 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3760 Use customize to modify this, or restart Emacs after changing it."
3761 :group 'org-appearance
3762 :set 'org-set-emph-re
3763 :type '(repeat
3764 (list
3765 (string :tag "Marker character")
3766 (choice
3767 (face :tag "Font-lock-face")
3768 (plist :tag "Face property list"))
3769 (string :tag "HTML start tag")
3770 (string :tag "HTML end tag")
3771 (option (const verbatim)))))
3773 (defvar org-protecting-blocks
3774 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3775 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3776 This is needed for font-lock setup.")
3778 ;;; Miscellaneous options
3780 (defgroup org-completion nil
3781 "Completion in Org-mode."
3782 :tag "Org Completion"
3783 :group 'org)
3785 (defcustom org-completion-use-ido nil
3786 "Non-nil means use ido completion wherever possible.
3787 Note that `ido-mode' must be active for this variable to be relevant.
3788 If you decide to turn this variable on, you might well want to turn off
3789 `org-outline-path-complete-in-steps'.
3790 See also `org-completion-use-iswitchb'."
3791 :group 'org-completion
3792 :type 'boolean)
3794 (defcustom org-completion-use-iswitchb nil
3795 "Non-nil means use iswitchb completion wherever possible.
3796 Note that `iswitchb-mode' must be active for this variable to be relevant.
3797 If you decide to turn this variable on, you might well want to turn off
3798 `org-outline-path-complete-in-steps'.
3799 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3800 :group 'org-completion
3801 :type 'boolean)
3803 (defcustom org-completion-fallback-command 'hippie-expand
3804 "The expansion command called by \\[pcomplete] in normal context.
3805 Normal means, no org-mode-specific context."
3806 :group 'org-completion
3807 :type 'function)
3809 ;;; Functions and variables from their packages
3810 ;; Declared here to avoid compiler warnings
3812 ;; XEmacs only
3813 (defvar outline-mode-menu-heading)
3814 (defvar outline-mode-menu-show)
3815 (defvar outline-mode-menu-hide)
3816 (defvar zmacs-regions) ; XEmacs regions
3818 ;; Emacs only
3819 (defvar mark-active)
3821 ;; Various packages
3822 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3823 (declare-function calendar-forward-day "cal-move" (arg))
3824 (declare-function calendar-goto-date "cal-move" (date))
3825 (declare-function calendar-goto-today "cal-move" ())
3826 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3827 (defvar calc-embedded-close-formula)
3828 (defvar calc-embedded-open-formula)
3829 (declare-function cdlatex-tab "ext:cdlatex" ())
3830 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3831 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3832 (defvar font-lock-unfontify-region-function)
3833 (declare-function iswitchb-read-buffer "iswitchb"
3834 (prompt &optional default require-match start matches-set))
3835 (defvar iswitchb-temp-buflist)
3836 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3837 (defvar org-agenda-tags-todo-honor-ignore-options)
3838 (declare-function org-agenda-skip "org-agenda" ())
3839 (declare-function
3840 org-agenda-format-item "org-agenda"
3841 (extra txt &optional category tags dotime noprefix remove-re habitp))
3842 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3843 (declare-function org-agenda-change-all-lines "org-agenda"
3844 (newhead hdmarker &optional fixface just-this))
3845 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3846 (declare-function org-agenda-maybe-redo "org-agenda" ())
3847 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3848 (beg end))
3849 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3850 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3851 "org-agenda" (&optional end))
3852 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3853 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3854 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3855 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3856 (declare-function org-indent-mode "org-indent" (&optional arg))
3857 (declare-function parse-time-string "parse-time" (string))
3858 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3859 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3860 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3861 (defvar remember-data-file)
3862 (defvar texmathp-why)
3863 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3864 (declare-function table--at-cell-p "table" (position &optional object at-column))
3866 (defvar w3m-current-url)
3867 (defvar w3m-current-title)
3869 (defvar org-latex-regexps)
3871 ;;; Autoload and prepare some org modules
3873 ;; Some table stuff that needs to be defined here, because it is used
3874 ;; by the functions setting up org-mode or checking for table context.
3876 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3877 "Detect an org-type or table-type table.")
3878 (defconst org-table-line-regexp "^[ \t]*|"
3879 "Detect an org-type table line.")
3880 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3881 "Detect an org-type table line.")
3882 (defconst org-table-hline-regexp "^[ \t]*|-"
3883 "Detect an org-type table hline.")
3884 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3885 "Detect a table-type table hline.")
3886 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3887 "Detect the first line outside a table when searching from within it.
3888 This works for both table types.")
3890 ;; Autoload the functions in org-table.el that are needed by functions here.
3892 (eval-and-compile
3893 (org-autoload "org-table"
3894 '(org-table-begin org-table-blank-field org-table-end)))
3896 ;;;###autoload
3897 (defun turn-on-orgtbl ()
3898 "Unconditionally turn on `orgtbl-mode'."
3899 (require 'org-table)
3900 (orgtbl-mode 1))
3902 (defun org-at-table-p (&optional table-type)
3903 "Return t if the cursor is inside an org-type table.
3904 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3905 (if org-enable-table-editor
3906 (save-excursion
3907 (beginning-of-line 1)
3908 (looking-at (if table-type org-table-any-line-regexp
3909 org-table-line-regexp)))
3910 nil))
3911 (defsubst org-table-p () (org-at-table-p))
3913 (defun org-at-table.el-p ()
3914 "Return t if and only if we are at a table.el table."
3915 (and (org-at-table-p 'any)
3916 (save-excursion
3917 (goto-char (org-table-begin 'any))
3918 (looking-at org-table1-hline-regexp))))
3920 (defun org-table-recognize-table.el ()
3921 "If there is a table.el table nearby, recognize it and move into it."
3922 (if org-table-tab-recognizes-table.el
3923 (if (org-at-table.el-p)
3924 (progn
3925 (beginning-of-line 1)
3926 (if (looking-at org-table-dataline-regexp)
3928 (if (looking-at org-table1-hline-regexp)
3929 (progn
3930 (beginning-of-line 2)
3931 (if (looking-at org-table-any-border-regexp)
3932 (beginning-of-line -1)))))
3933 (if (re-search-forward "|" (org-table-end t) t)
3934 (progn
3935 (require 'table)
3936 (if (table--at-cell-p (point))
3938 (message "recognizing table.el table...")
3939 (table-recognize-table)
3940 (message "recognizing table.el table...done")))
3941 (error "This should not happen"))
3943 nil)
3944 nil))
3946 (defun org-at-table-hline-p ()
3947 "Return t if the cursor is inside a hline in a table."
3948 (if org-enable-table-editor
3949 (save-excursion
3950 (beginning-of-line 1)
3951 (looking-at org-table-hline-regexp))
3952 nil))
3954 (defvar org-table-clean-did-remove-column nil)
3955 (defun org-table-map-tables (function &optional quietly)
3956 "Apply FUNCTION to the start of all tables in the buffer."
3957 (save-excursion
3958 (save-restriction
3959 (widen)
3960 (goto-char (point-min))
3961 (while (re-search-forward org-table-any-line-regexp nil t)
3962 (unless quietly
3963 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3964 (beginning-of-line 1)
3965 (when (and (looking-at org-table-line-regexp)
3966 ;; Exclude tables in src/example/verbatim/clocktable blocks
3967 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3968 (save-excursion (funcall function))
3969 (or (looking-at org-table-line-regexp)
3970 (forward-char 1)))
3971 (re-search-forward org-table-any-border-regexp nil 1))))
3972 (unless quietly (message "Mapping tables: done")))
3974 ;; Declare and autoload functions from org-exp.el & Co
3976 (declare-function org-default-export-plist "org-exp")
3977 (declare-function org-infile-export-plist "org-exp")
3978 (declare-function org-get-current-options "org-exp")
3980 ;; Declare and autoload functions from org-agenda.el
3982 (eval-and-compile
3983 (org-autoload "org-agenda"
3984 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3986 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3987 (declare-function org-clock-update-mode-line "org-clock" ())
3988 (declare-function org-resolve-clocks "org-clock"
3989 (&optional also-non-dangling-p prompt last-valid))
3990 (defvar org-clock-start-time)
3991 (defvar org-clock-marker (make-marker)
3992 "Marker recording the last clock-in.")
3993 (defvar org-clock-hd-marker (make-marker)
3994 "Marker recording the last clock-in, but the headline position.")
3995 (defvar org-clock-heading ""
3996 "The heading of the current clock entry.")
3997 (defun org-clock-is-active ()
3998 "Return non-nil if clock is currently running.
3999 The return value is actually the clock marker."
4000 (marker-buffer org-clock-marker))
4002 (eval-and-compile
4003 (org-autoload "org-clock" '(org-clock-remove-overlays
4004 org-clock-update-time-maybe
4005 org-clocktable-shift)))
4007 (defun org-check-running-clock ()
4008 "Check if the current buffer contains the running clock.
4009 If yes, offer to stop it and to save the buffer with the changes."
4010 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4011 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4012 (buffer-name))))
4013 (org-clock-out)
4014 (when (y-or-n-p "Save changed buffer?")
4015 (save-buffer))))
4017 (defun org-clocktable-try-shift (dir n)
4018 "Check if this line starts a clock table, if yes, shift the time block."
4019 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4020 (org-clocktable-shift dir n)))
4022 ;;;###autoload
4023 (defun org-clock-persistence-insinuate ()
4024 "Set up hooks for clock persistence."
4025 (require 'org-clock)
4026 (add-hook 'org-mode-hook 'org-clock-load)
4027 (add-hook 'kill-emacs-hook 'org-clock-save))
4029 ;; Define the variable already here, to make sure we have it.
4030 (defvar org-indent-mode nil
4031 "Non-nil if Org-Indent mode is enabled.
4032 Use the command `org-indent-mode' to change this variable.")
4034 ;; Autoload archiving code
4035 ;; The stuff that is needed for cycling and tags has to be defined here.
4037 (defgroup org-archive nil
4038 "Options concerning archiving in Org-mode."
4039 :tag "Org Archive"
4040 :group 'org-structure)
4042 (defcustom org-archive-location "%s_archive::"
4043 "The location where subtrees should be archived.
4045 The value of this variable is a string, consisting of two parts,
4046 separated by a double-colon. The first part is a filename and
4047 the second part is a headline.
4049 When the filename is omitted, archiving happens in the same file.
4050 %s in the filename will be replaced by the current file
4051 name (without the directory part). Archiving to a different file
4052 is useful to keep archived entries from contributing to the
4053 Org-mode Agenda.
4055 The archived entries will be filed as subtrees of the specified
4056 headline. When the headline is omitted, the subtrees are simply
4057 filed away at the end of the file, as top-level entries. Also in
4058 the heading you can use %s to represent the file name, this can be
4059 useful when using the same archive for a number of different files.
4061 Here are a few examples:
4062 \"%s_archive::\"
4063 If the current file is Projects.org, archive in file
4064 Projects.org_archive, as top-level trees. This is the default.
4066 \"::* Archived Tasks\"
4067 Archive in the current file, under the top-level headline
4068 \"* Archived Tasks\".
4070 \"~/org/archive.org::\"
4071 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4073 \"~/org/archive.org::* From %s\"
4074 Archive in file ~/org/archive.org (absolute path), under headlines
4075 \"From FILENAME\" where file name is the current file name.
4077 \"~/org/datetree.org::datetree/* Finished Tasks\"
4078 The \"datetree/\" string is special, signifying to archive
4079 items to the datetree. Items are placed in either the CLOSED
4080 date of the item, or the current date if there is no CLOSED date.
4081 The heading will be a subentry to the current date. There doesn't
4082 need to be a heading, but there always needs to be a slash after
4083 datetree. For example, to store archived items directly in the
4084 datetree, use \"~/org/datetree.org::datetree/\".
4086 \"basement::** Finished Tasks\"
4087 Archive in file ./basement (relative path), as level 3 trees
4088 below the level 2 heading \"** Finished Tasks\".
4090 You may set this option on a per-file basis by adding to the buffer a
4091 line like
4093 #+ARCHIVE: basement::** Finished Tasks
4095 You may also define it locally for a subtree by setting an ARCHIVE property
4096 in the entry. If such a property is found in an entry, or anywhere up
4097 the hierarchy, it will be used."
4098 :group 'org-archive
4099 :type 'string)
4101 (defcustom org-archive-tag "ARCHIVE"
4102 "The tag that marks a subtree as archived.
4103 An archived subtree does not open during visibility cycling, and does
4104 not contribute to the agenda listings.
4105 After changing this, font-lock must be restarted in the relevant buffers to
4106 get the proper fontification."
4107 :group 'org-archive
4108 :group 'org-keywords
4109 :type 'string)
4111 (defcustom org-agenda-skip-archived-trees t
4112 "Non-nil means the agenda will skip any items located in archived trees.
4113 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4114 variable is no longer recommended, you should leave it at the value t.
4115 Instead, use the key `v' to cycle the archives-mode in the agenda."
4116 :group 'org-archive
4117 :group 'org-agenda-skip
4118 :type 'boolean)
4120 (defcustom org-columns-skip-archived-trees t
4121 "Non-nil means ignore archived trees when creating column view."
4122 :group 'org-archive
4123 :group 'org-properties
4124 :type 'boolean)
4126 (defcustom org-cycle-open-archived-trees nil
4127 "Non-nil means `org-cycle' will open archived trees.
4128 An archived tree is a tree marked with the tag ARCHIVE.
4129 When nil, archived trees will stay folded. You can still open them with
4130 normal outline commands like `show-all', but not with the cycling commands."
4131 :group 'org-archive
4132 :group 'org-cycle
4133 :type 'boolean)
4135 (defcustom org-sparse-tree-open-archived-trees nil
4136 "Non-nil means sparse tree construction shows matches in archived trees.
4137 When nil, matches in these trees are highlighted, but the trees are kept in
4138 collapsed state."
4139 :group 'org-archive
4140 :group 'org-sparse-trees
4141 :type 'boolean)
4143 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4144 "The default date type when building a sparse tree.
4145 When this is nil, a date is a scheduled or a deadline timestamp.
4146 Otherwise, these types are allowed:
4148 all: all timestamps
4149 active: only active timestamps (<...>)
4150 inactive: only inactive timestamps (<...)
4151 scheduled: only scheduled timestamps
4152 deadline: only deadline timestamps"
4153 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4154 (const :tag "All timestamps" all)
4155 (const :tag "Only active timestamps" active)
4156 (const :tag "Only inactive timestamps" inactive)
4157 (const :tag "Only scheduled timestamps" scheduled)
4158 (const :tag "Only deadline timestamps" deadline))
4159 :version "24.3"
4160 :group 'org-sparse-trees)
4162 (defun org-cycle-hide-archived-subtrees (state)
4163 "Re-hide all archived subtrees after a visibility state change."
4164 (when (and (not org-cycle-open-archived-trees)
4165 (not (memq state '(overview folded))))
4166 (save-excursion
4167 (let* ((globalp (memq state '(contents all)))
4168 (beg (if globalp (point-min) (point)))
4169 (end (if globalp (point-max) (org-end-of-subtree t))))
4170 (org-hide-archived-subtrees beg end)
4171 (goto-char beg)
4172 (if (looking-at (concat ".*:" org-archive-tag ":"))
4173 (message "%s" (substitute-command-keys
4174 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4176 (defun org-force-cycle-archived ()
4177 "Cycle subtree even if it is archived."
4178 (interactive)
4179 (setq this-command 'org-cycle)
4180 (let ((org-cycle-open-archived-trees t))
4181 (call-interactively 'org-cycle)))
4183 (defun org-hide-archived-subtrees (beg end)
4184 "Re-hide all archived subtrees after a visibility state change."
4185 (save-excursion
4186 (let* ((re (concat ":" org-archive-tag ":")))
4187 (goto-char beg)
4188 (while (re-search-forward re end t)
4189 (when (org-at-heading-p)
4190 (org-flag-subtree t)
4191 (org-end-of-subtree t))))))
4193 (declare-function outline-end-of-heading "outline" ())
4194 (declare-function outline-flag-region "outline" (from to flag))
4195 (defun org-flag-subtree (flag)
4196 (save-excursion
4197 (org-back-to-heading t)
4198 (outline-end-of-heading)
4199 (outline-flag-region (point)
4200 (progn (org-end-of-subtree t) (point))
4201 flag)))
4203 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4205 (eval-and-compile
4206 (org-autoload "org-archive"
4207 '(org-add-archive-files)))
4209 ;; Autoload Column View Code
4211 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4212 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4213 (declare-function org-columns-compute "org-colview" (property))
4215 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4216 '(org-columns-number-to-string
4217 org-columns-get-format-and-top-level
4218 org-columns-compute
4219 org-columns-remove-overlays))
4221 ;; Autoload ID code
4223 (declare-function org-id-store-link "org-id")
4224 (declare-function org-id-locations-load "org-id")
4225 (declare-function org-id-locations-save "org-id")
4226 (defvar org-id-track-globally)
4227 (org-autoload "org-id"
4228 '(org-id-new
4229 org-id-copy
4230 org-id-get-with-outline-path-completion
4231 org-id-get-with-outline-drilling))
4233 ;;; Variables for pre-computed regular expressions, all buffer local
4235 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4236 "Matches first line of a hidden block.")
4237 (make-variable-buffer-local 'org-drawer-regexp)
4238 (defvar org-todo-regexp nil
4239 "Matches any of the TODO state keywords.")
4240 (make-variable-buffer-local 'org-todo-regexp)
4241 (defvar org-not-done-regexp nil
4242 "Matches any of the TODO state keywords except the last one.")
4243 (make-variable-buffer-local 'org-not-done-regexp)
4244 (defvar org-not-done-heading-regexp nil
4245 "Matches a TODO headline that is not done.")
4246 (make-variable-buffer-local 'org-not-done-regexp)
4247 (defvar org-todo-line-regexp nil
4248 "Matches a headline and puts TODO state into group 2 if present.")
4249 (make-variable-buffer-local 'org-todo-line-regexp)
4250 (defvar org-complex-heading-regexp nil
4251 "Matches a headline and puts everything into groups:
4252 group 1: the stars
4253 group 2: The todo keyword, maybe
4254 group 3: Priority cookie
4255 group 4: True headline
4256 group 5: Tags")
4257 (make-variable-buffer-local 'org-complex-heading-regexp)
4258 (defvar org-complex-heading-regexp-format nil
4259 "Printf format to make regexp to match an exact headline.
4260 This regexp will match the headline of any node which has the
4261 exact headline text that is put into the format, but may have any
4262 TODO state, priority and tags.")
4263 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4264 (defvar org-todo-line-tags-regexp nil
4265 "Matches a headline and puts TODO state into group 2 if present.
4266 Also put tags into group 4 if tags are present.")
4267 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4268 (defvar org-ds-keyword-length 12
4269 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4270 (make-variable-buffer-local 'org-ds-keyword-length)
4271 (defvar org-deadline-regexp nil
4272 "Matches the DEADLINE keyword.")
4273 (make-variable-buffer-local 'org-deadline-regexp)
4274 (defvar org-deadline-time-regexp nil
4275 "Matches the DEADLINE keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-deadline-time-regexp)
4277 (defvar org-deadline-line-regexp nil
4278 "Matches the DEADLINE keyword and the rest of the line.")
4279 (make-variable-buffer-local 'org-deadline-line-regexp)
4280 (defvar org-scheduled-regexp nil
4281 "Matches the SCHEDULED keyword.")
4282 (make-variable-buffer-local 'org-scheduled-regexp)
4283 (defvar org-scheduled-time-regexp nil
4284 "Matches the SCHEDULED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-scheduled-time-regexp)
4286 (defvar org-closed-time-regexp nil
4287 "Matches the CLOSED keyword together with a time stamp.")
4288 (make-variable-buffer-local 'org-closed-time-regexp)
4290 (defvar org-keyword-time-regexp nil
4291 "Matches any of the 4 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-regexp)
4293 (defvar org-keyword-time-not-clock-regexp nil
4294 "Matches any of the 3 keywords, together with the time stamp.")
4295 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4296 (defvar org-maybe-keyword-time-regexp nil
4297 "Matches a timestamp, possibly preceded by a keyword.")
4298 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4299 (defvar org-all-time-keywords nil
4300 "List of time keywords.")
4301 (make-variable-buffer-local 'org-all-time-keywords)
4303 (defconst org-plain-time-of-day-regexp
4304 (concat
4305 "\\(\\<[012]?[0-9]"
4306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4307 "\\(--?"
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\)?")
4311 "Regular expression to match a plain time or time range.
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 1 the first time, range or not
4316 8 the second time, if it is a range.")
4318 (defconst org-plain-time-extension-regexp
4319 (concat
4320 "\\(\\<[012]?[0-9]"
4321 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4322 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4323 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4324 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4325 groups carry important information:
4326 0 the full match
4327 7 hours of duration
4328 9 minutes of duration")
4330 (defconst org-stamp-time-of-day-regexp
4331 (concat
4332 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4333 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4334 "\\(--?"
4335 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4336 "Regular expression to match a timestamp time or time range.
4337 After a match, the following groups carry important information:
4338 0 the full match
4339 1 date plus weekday, for back referencing to make sure both times are on the same day
4340 2 the first time, range or not
4341 4 the second time, if it is a range.")
4343 (defconst org-startup-options
4344 '(("fold" org-startup-folded t)
4345 ("overview" org-startup-folded t)
4346 ("nofold" org-startup-folded nil)
4347 ("showall" org-startup-folded nil)
4348 ("showeverything" org-startup-folded showeverything)
4349 ("content" org-startup-folded content)
4350 ("indent" org-startup-indented t)
4351 ("noindent" org-startup-indented nil)
4352 ("hidestars" org-hide-leading-stars t)
4353 ("showstars" org-hide-leading-stars nil)
4354 ("odd" org-odd-levels-only t)
4355 ("oddeven" org-odd-levels-only nil)
4356 ("align" org-startup-align-all-tables t)
4357 ("noalign" org-startup-align-all-tables nil)
4358 ("inlineimages" org-startup-with-inline-images t)
4359 ("noinlineimages" org-startup-with-inline-images nil)
4360 ("customtime" org-display-custom-times t)
4361 ("logdone" org-log-done time)
4362 ("lognotedone" org-log-done note)
4363 ("nologdone" org-log-done nil)
4364 ("lognoteclock-out" org-log-note-clock-out t)
4365 ("nolognoteclock-out" org-log-note-clock-out nil)
4366 ("logrepeat" org-log-repeat state)
4367 ("lognoterepeat" org-log-repeat note)
4368 ("nologrepeat" org-log-repeat nil)
4369 ("logreschedule" org-log-reschedule time)
4370 ("lognotereschedule" org-log-reschedule note)
4371 ("nologreschedule" org-log-reschedule nil)
4372 ("logredeadline" org-log-redeadline time)
4373 ("lognoteredeadline" org-log-redeadline note)
4374 ("nologredeadline" org-log-redeadline nil)
4375 ("logrefile" org-log-refile time)
4376 ("lognoterefile" org-log-refile note)
4377 ("nologrefile" org-log-refile nil)
4378 ("fninline" org-footnote-define-inline t)
4379 ("nofninline" org-footnote-define-inline nil)
4380 ("fnlocal" org-footnote-section nil)
4381 ("fnauto" org-footnote-auto-label t)
4382 ("fnprompt" org-footnote-auto-label nil)
4383 ("fnconfirm" org-footnote-auto-label confirm)
4384 ("fnplain" org-footnote-auto-label plain)
4385 ("fnadjust" org-footnote-auto-adjust t)
4386 ("nofnadjust" org-footnote-auto-adjust nil)
4387 ("constcgs" constants-unit-system cgs)
4388 ("constSI" constants-unit-system SI)
4389 ("noptag" org-tag-persistent-alist nil)
4390 ("hideblocks" org-hide-block-startup t)
4391 ("nohideblocks" org-hide-block-startup nil)
4392 ("beamer" org-startup-with-beamer-mode t)
4393 ("entitiespretty" org-pretty-entities t)
4394 ("entitiesplain" org-pretty-entities nil))
4395 "Variable associated with STARTUP options for org-mode.
4396 Each element is a list of three items: the startup options (as written
4397 in the #+STARTUP line), the corresponding variable, and the value to set
4398 this variable to if the option is found. An optional forth element PUSH
4399 means to push this value onto the list in the variable.")
4401 (defun org-update-property-plist (key val props)
4402 "Update PROPS with KEY and VAL."
4403 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4404 (key (if appending (substring key 0 (- (length key) 1)) key))
4405 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4406 (previous (cdr (assoc key props))))
4407 (if appending
4408 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4409 (cons (cons key val) remainder))))
4411 (defconst org-block-regexp
4412 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4413 "Regular expression for hiding blocks.")
4414 (defconst org-heading-keyword-regexp-format
4415 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4416 "Printf format for a regexp matching an headline with some keyword.
4417 This regexp will match the headline of any node which has the
4418 exact keyword that is put into the format. The keyword isn't in
4419 any group by default, but the stars and the body are.")
4420 (defconst org-heading-keyword-maybe-regexp-format
4421 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4422 "Printf format for a regexp matching an headline, possibly with some keyword.
4423 This regexp can match any headline with the specified keyword, or
4424 without a keyword. The keyword isn't in any group by default,
4425 but the stars and the body are.")
4427 (defun org-set-regexps-and-options ()
4428 "Precompute regular expressions for current buffer."
4429 (when (derived-mode-p 'org-mode)
4430 (org-set-local 'org-todo-kwd-alist nil)
4431 (org-set-local 'org-todo-key-alist nil)
4432 (org-set-local 'org-todo-key-trigger nil)
4433 (org-set-local 'org-todo-keywords-1 nil)
4434 (org-set-local 'org-done-keywords nil)
4435 (org-set-local 'org-todo-heads nil)
4436 (org-set-local 'org-todo-sets nil)
4437 (org-set-local 'org-todo-log-states nil)
4438 (org-set-local 'org-file-properties nil)
4439 (org-set-local 'org-file-tags nil)
4440 (let ((re (org-make-options-regexp
4441 '("CATEGORY" "TODO" "COLUMNS"
4442 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4443 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4444 "OPTIONS")
4445 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4446 (splitre "[ \t]+")
4447 (scripts org-use-sub-superscripts)
4448 kwds kws0 kwsa key log value cat arch tags const links hw dws
4449 tail sep kws1 prio props ftags drawers beamer-p
4450 ext-setup-or-nil setup-contents (start 0))
4451 (save-excursion
4452 (save-restriction
4453 (widen)
4454 (goto-char (point-min))
4455 (while (or (and ext-setup-or-nil
4456 (string-match re ext-setup-or-nil start)
4457 (setq start (match-end 0)))
4458 (and (setq ext-setup-or-nil nil start 0)
4459 (re-search-forward re nil t)))
4460 (setq key (upcase (match-string 1 ext-setup-or-nil))
4461 value (org-match-string-no-properties 2 ext-setup-or-nil))
4462 (if (stringp value) (setq value (org-trim value)))
4463 (cond
4464 ((equal key "CATEGORY")
4465 (setq cat value))
4466 ((member key '("SEQ_TODO" "TODO"))
4467 (push (cons 'sequence (org-split-string value splitre)) kwds))
4468 ((equal key "TYP_TODO")
4469 (push (cons 'type (org-split-string value splitre)) kwds))
4470 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4471 ;; general TODO-like setup
4472 (push (cons (intern (downcase (match-string 1 key)))
4473 (org-split-string value splitre)) kwds))
4474 ((equal key "TAGS")
4475 (setq tags (append tags (if tags '("\\n") nil)
4476 (org-split-string value splitre))))
4477 ((equal key "COLUMNS")
4478 (org-set-local 'org-columns-default-format value))
4479 ((equal key "LINK")
4480 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4481 (push (cons (match-string 1 value)
4482 (org-trim (match-string 2 value)))
4483 links)))
4484 ((equal key "PRIORITIES")
4485 (setq prio (org-split-string value " +")))
4486 ((equal key "PROPERTY")
4487 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4488 (setq props (org-update-property-plist (match-string 1 value)
4489 (match-string 2 value)
4490 props))))
4491 ((equal key "FILETAGS")
4492 (when (string-match "\\S-" value)
4493 (setq ftags
4494 (append
4495 ftags
4496 (apply 'append
4497 (mapcar (lambda (x) (org-split-string x ":"))
4498 (org-split-string value)))))))
4499 ((equal key "DRAWERS")
4500 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4501 ((equal key "CONSTANTS")
4502 (setq const (append const (org-split-string value splitre))))
4503 ((equal key "STARTUP")
4504 (let ((opts (org-split-string value splitre))
4505 l var val)
4506 (while (setq l (pop opts))
4507 (when (setq l (assoc l org-startup-options))
4508 (setq var (nth 1 l) val (nth 2 l))
4509 (if (not (nth 3 l))
4510 (set (make-local-variable var) val)
4511 (if (not (listp (symbol-value var)))
4512 (set (make-local-variable var) nil))
4513 (set (make-local-variable var) (symbol-value var))
4514 (add-to-list var val))))))
4515 ((equal key "ARCHIVE")
4516 (setq arch value)
4517 (remove-text-properties 0 (length arch)
4518 '(face t fontified t) arch))
4519 ((equal key "LATEX_CLASS")
4520 (setq beamer-p (equal value "beamer")))
4521 ((equal key "OPTIONS")
4522 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4523 (setq scripts (read (match-string 2 value)))))
4524 ((equal key "SETUPFILE")
4525 (setq setup-contents (org-file-contents
4526 (expand-file-name
4527 (org-remove-double-quotes value))
4528 'noerror))
4529 (if (not ext-setup-or-nil)
4530 (setq ext-setup-or-nil setup-contents start 0)
4531 (setq ext-setup-or-nil
4532 (concat (substring ext-setup-or-nil 0 start)
4533 "\n" setup-contents "\n"
4534 (substring ext-setup-or-nil start)))))))
4535 ;; search for property blocks
4536 (goto-char (point-min))
4537 (while (re-search-forward org-block-regexp nil t)
4538 (when (equal "PROPERTY" (upcase (match-string 1)))
4539 (setq value (replace-regexp-in-string
4540 "[\n\r]" " " (match-string 4)))
4541 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4542 (setq props (org-update-property-plist (match-string 1 value)
4543 (match-string 2 value)
4544 props)))))))
4545 (org-set-local 'org-use-sub-superscripts scripts)
4546 (when cat
4547 (org-set-local 'org-category (intern cat))
4548 (push (cons "CATEGORY" cat) props))
4549 (when prio
4550 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4551 (setq prio (mapcar 'string-to-char prio))
4552 (org-set-local 'org-highest-priority (nth 0 prio))
4553 (org-set-local 'org-lowest-priority (nth 1 prio))
4554 (org-set-local 'org-default-priority (nth 2 prio)))
4555 (and props (org-set-local 'org-file-properties (nreverse props)))
4556 (and ftags (org-set-local 'org-file-tags
4557 (mapcar 'org-add-prop-inherited ftags)))
4558 (and drawers (org-set-local 'org-drawers drawers))
4559 (and arch (org-set-local 'org-archive-location arch))
4560 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4561 ;; Process the TODO keywords
4562 (unless kwds
4563 ;; Use the global values as if they had been given locally.
4564 (setq kwds (default-value 'org-todo-keywords))
4565 (if (stringp (car kwds))
4566 (setq kwds (list (cons org-todo-interpretation
4567 (default-value 'org-todo-keywords)))))
4568 (setq kwds (reverse kwds)))
4569 (setq kwds (nreverse kwds))
4570 (let (inter kws kw)
4571 (while (setq kws (pop kwds))
4572 (let ((kws (or
4573 (run-hook-with-args-until-success
4574 'org-todo-setup-filter-hook kws)
4575 kws)))
4576 (setq inter (pop kws) sep (member "|" kws)
4577 kws0 (delete "|" (copy-sequence kws))
4578 kwsa nil
4579 kws1 (mapcar
4580 (lambda (x)
4581 ;; 1 2
4582 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4583 (progn
4584 (setq kw (match-string 1 x)
4585 key (and (match-end 2) (match-string 2 x))
4586 log (org-extract-log-state-settings x))
4587 (push (cons kw (and key (string-to-char key))) kwsa)
4588 (and log (push log org-todo-log-states))
4590 (error "Invalid TODO keyword %s" x)))
4591 kws0)
4592 kwsa (if kwsa (append '((:startgroup))
4593 (nreverse kwsa)
4594 '((:endgroup))))
4595 hw (car kws1)
4596 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4597 tail (list inter hw (car dws) (org-last dws))))
4598 (add-to-list 'org-todo-heads hw 'append)
4599 (push kws1 org-todo-sets)
4600 (setq org-done-keywords (append org-done-keywords dws nil))
4601 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4602 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4603 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4604 (setq org-todo-sets (nreverse org-todo-sets)
4605 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4606 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4607 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4608 ;; Process the constants
4609 (when const
4610 (let (e cst)
4611 (while (setq e (pop const))
4612 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4613 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4614 (setq org-table-formula-constants-local cst)))
4616 ;; Process the tags.
4617 (when tags
4618 (let (e tgs)
4619 (while (setq e (pop tags))
4620 (cond
4621 ((equal e "{") (push '(:startgroup) tgs))
4622 ((equal e "}") (push '(:endgroup) tgs))
4623 ((equal e "\\n") (push '(:newline) tgs))
4624 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4625 (push (cons (match-string 1 e)
4626 (string-to-char (match-string 2 e)))
4627 tgs))
4628 (t (push (list e) tgs))))
4629 (org-set-local 'org-tag-alist nil)
4630 (while (setq e (pop tgs))
4631 (or (and (stringp (car e))
4632 (assoc (car e) org-tag-alist))
4633 (push e org-tag-alist)))))
4635 ;; Compute the regular expressions and other local variables.
4636 ;; Using `org-outline-regexp-bol' would complicate them much,
4637 ;; because of the fixed white space at the end of that string.
4638 (if (not org-done-keywords)
4639 (setq org-done-keywords (and org-todo-keywords-1
4640 (list (org-last org-todo-keywords-1)))))
4641 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4642 (length org-scheduled-string)
4643 (length org-clock-string)
4644 (length org-closed-string)))
4645 org-drawer-regexp
4646 (concat "^[ \t]*:\\("
4647 (mapconcat 'regexp-quote org-drawers "\\|")
4648 "\\):[ \t]*$")
4649 org-not-done-keywords
4650 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4651 org-todo-regexp
4652 (concat "\\("
4653 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4654 "\\)")
4655 org-not-done-regexp
4656 (concat "\\("
4657 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4658 "\\)")
4659 org-not-done-heading-regexp
4660 (format org-heading-keyword-regexp-format org-not-done-regexp)
4661 org-todo-line-regexp
4662 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4663 org-complex-heading-regexp
4664 (concat "^\\(\\*+\\)"
4665 "\\(?: +" org-todo-regexp "\\)?"
4666 "\\(?: +\\(\\[#.\\]\\)\\)?"
4667 "\\(?: +\\(.*?\\)\\)??"
4668 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4669 "[ \t]*$")
4670 org-complex-heading-regexp-format
4671 (concat "^\\(\\*+\\)"
4672 "\\(?: +" org-todo-regexp "\\)?"
4673 "\\(?: +\\(\\[#.\\]\\)\\)?"
4674 "\\(?: +"
4675 ;; Stats cookies can be stuck to body.
4676 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4677 "\\(%s\\)"
4678 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4679 "\\)"
4680 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4681 "[ \t]*$")
4682 org-todo-line-tags-regexp
4683 (concat "^\\(\\*+\\)"
4684 "\\(?: +" org-todo-regexp "\\)?"
4685 "\\(?: +\\(.*?\\)\\)??"
4686 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4687 "[ \t]*$")
4688 org-deadline-regexp (concat "\\<" org-deadline-string)
4689 org-deadline-time-regexp
4690 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4691 org-deadline-line-regexp
4692 (concat "\\<\\(" org-deadline-string "\\).*")
4693 org-scheduled-regexp
4694 (concat "\\<" org-scheduled-string)
4695 org-scheduled-time-regexp
4696 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4697 org-closed-time-regexp
4698 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4699 org-keyword-time-regexp
4700 (concat "\\<\\(" org-scheduled-string
4701 "\\|" org-deadline-string
4702 "\\|" org-closed-string
4703 "\\|" org-clock-string "\\)"
4704 " *[[<]\\([^]>]+\\)[]>]")
4705 org-keyword-time-not-clock-regexp
4706 (concat "\\<\\(" org-scheduled-string
4707 "\\|" org-deadline-string
4708 "\\|" org-closed-string
4709 "\\)"
4710 " *[[<]\\([^]>]+\\)[]>]")
4711 org-maybe-keyword-time-regexp
4712 (concat "\\(\\<\\(" org-scheduled-string
4713 "\\|" org-deadline-string
4714 "\\|" org-closed-string
4715 "\\|" org-clock-string "\\)\\)?"
4716 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4717 org-all-time-keywords
4718 (mapcar (lambda (w) (substring w 0 -1))
4719 (list org-scheduled-string org-deadline-string
4720 org-clock-string org-closed-string))
4722 (org-compute-latex-and-specials-regexp)
4723 (org-set-font-lock-defaults))))
4725 (defun org-file-contents (file &optional noerror)
4726 "Return the contents of FILE, as a string."
4727 (if (or (not file)
4728 (not (file-readable-p file)))
4729 (if noerror
4730 (progn
4731 (message "Cannot read file \"%s\"" file)
4732 (ding) (sit-for 2)
4734 (error "Cannot read file \"%s\"" file))
4735 (with-temp-buffer
4736 (insert-file-contents file)
4737 (buffer-string))))
4739 (defun org-extract-log-state-settings (x)
4740 "Extract the log state setting from a TODO keyword string.
4741 This will extract info from a string like \"WAIT(w@/!)\"."
4742 (let (kw key log1 log2)
4743 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4744 (setq kw (match-string 1 x)
4745 key (and (match-end 2) (match-string 2 x))
4746 log1 (and (match-end 3) (match-string 3 x))
4747 log2 (and (match-end 4) (match-string 4 x)))
4748 (and (or log1 log2)
4749 (list kw
4750 (and log1 (if (equal log1 "!") 'time 'note))
4751 (and log2 (if (equal log2 "!") 'time 'note)))))))
4753 (defun org-remove-keyword-keys (list)
4754 "Remove a pair of parenthesis at the end of each string in LIST."
4755 (mapcar (lambda (x)
4756 (if (string-match "(.*)$" x)
4757 (substring x 0 (match-beginning 0))
4759 list))
4761 (defun org-assign-fast-keys (alist)
4762 "Assign fast keys to a keyword-key alist.
4763 Respect keys that are already there."
4764 (let (new e (alt ?0))
4765 (while (setq e (pop alist))
4766 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4767 (cdr e)) ;; Key already assigned.
4768 (push e new)
4769 (let ((clist (string-to-list (downcase (car e))))
4770 (used (append new alist)))
4771 (when (= (car clist) ?@)
4772 (pop clist))
4773 (while (and clist (rassoc (car clist) used))
4774 (pop clist))
4775 (unless clist
4776 (while (rassoc alt used)
4777 (incf alt)))
4778 (push (cons (car e) (or (car clist) alt)) new))))
4779 (nreverse new)))
4781 ;;; Some variables used in various places
4783 (defvar org-window-configuration nil
4784 "Used in various places to store a window configuration.")
4785 (defvar org-selected-window nil
4786 "Used in various places to store a window configuration.")
4787 (defvar org-finish-function nil
4788 "Function to be called when `C-c C-c' is used.
4789 This is for getting out of special buffers like capture.")
4792 ;; FIXME: Occasionally check by commenting these, to make sure
4793 ;; no other functions uses these, forgetting to let-bind them.
4794 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4795 (defvar org-last-state)
4796 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4798 ;; Defined somewhere in this file, but used before definition.
4799 (defvar org-entities) ;; defined in org-entities.el
4800 (defvar org-struct-menu)
4801 (defvar org-org-menu)
4802 (defvar org-tbl-menu)
4804 ;;;; Define the Org-mode
4806 ;; We use a before-change function to check if a table might need
4807 ;; an update.
4808 (defvar org-table-may-need-update t
4809 "Indicates that a table might need an update.
4810 This variable is set by `org-before-change-function'.
4811 `org-table-align' sets it back to nil.")
4812 (defun org-before-change-function (beg end)
4813 "Every change indicates that a table might need an update."
4814 (setq org-table-may-need-update t))
4815 (defvar org-mode-map)
4816 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4818 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4819 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4820 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4821 (defvar org-table-buffer-is-an nil)
4823 (defvar bidi-paragraph-direction)
4824 (defvar buffer-face-mode-face)
4826 (require 'outline)
4827 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4828 (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"))
4829 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4831 ;; Other stuff we need.
4832 (require 'time-date)
4833 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4834 (require 'easymenu)
4835 (require 'overlay)
4837 (require 'org-macs)
4838 (require 'org-entities)
4839 ;; (require 'org-compat) moved higher up in the file before it is first used
4840 (require 'org-faces)
4841 (require 'org-list)
4842 (require 'org-pcomplete)
4843 (require 'org-src)
4844 (require 'org-footnote)
4846 ;; babel
4847 (require 'ob)
4848 (require 'ob-table)
4849 (require 'ob-lob)
4850 (require 'ob-ref)
4851 (require 'ob-tangle)
4852 (require 'ob-comint)
4853 (require 'ob-keys)
4855 ;;;###autoload
4856 (define-derived-mode org-mode outline-mode "Org"
4857 "Outline-based notes management and organizer, alias
4858 \"Carsten's outline-mode for keeping track of everything.\"
4860 Org-mode develops organizational tasks around a NOTES file which
4861 contains information about projects as plain text. Org-mode is
4862 implemented on top of outline-mode, which is ideal to keep the content
4863 of large files well structured. It supports ToDo items, deadlines and
4864 time stamps, which magically appear in the diary listing of the Emacs
4865 calendar. Tables are easily created with a built-in table editor.
4866 Plain text URL-like links connect to websites, emails (VM), Usenet
4867 messages (Gnus), BBDB entries, and any files related to the project.
4868 For printing and sharing of notes, an Org-mode file (or a part of it)
4869 can be exported as a structured ASCII or HTML file.
4871 The following commands are available:
4873 \\{org-mode-map}"
4875 ;; Get rid of Outline menus, they are not needed
4876 ;; Need to do this here because define-derived-mode sets up
4877 ;; the keymap so late. Still, it is a waste to call this each time
4878 ;; we switch another buffer into org-mode.
4879 (if (featurep 'xemacs)
4880 (when (boundp 'outline-mode-menu-heading)
4881 ;; Assume this is Greg's port, it uses easymenu
4882 (easy-menu-remove outline-mode-menu-heading)
4883 (easy-menu-remove outline-mode-menu-show)
4884 (easy-menu-remove outline-mode-menu-hide))
4885 (define-key org-mode-map [menu-bar headings] 'undefined)
4886 (define-key org-mode-map [menu-bar hide] 'undefined)
4887 (define-key org-mode-map [menu-bar show] 'undefined))
4889 (org-load-modules-maybe)
4890 (easy-menu-add org-org-menu)
4891 (easy-menu-add org-tbl-menu)
4892 (org-install-agenda-files-menu)
4893 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4894 (add-to-invisibility-spec '(org-cwidth))
4895 (add-to-invisibility-spec '(org-hide-block . t))
4896 (when (featurep 'xemacs)
4897 (org-set-local 'line-move-ignore-invisible t))
4898 (org-set-local 'outline-regexp org-outline-regexp)
4899 (org-set-local 'outline-level 'org-outline-level)
4900 (setq bidi-paragraph-direction 'left-to-right)
4901 (when (and org-ellipsis
4902 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4903 (fboundp 'make-glyph-code))
4904 (unless org-display-table
4905 (setq org-display-table (make-display-table)))
4906 (set-display-table-slot
4907 org-display-table 4
4908 (vconcat (mapcar
4909 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4910 org-ellipsis)))
4911 (if (stringp org-ellipsis) org-ellipsis "..."))))
4912 (setq buffer-display-table org-display-table))
4913 (org-set-regexps-and-options)
4914 (when (and org-tag-faces (not org-tags-special-faces-re))
4915 ;; tag faces set outside customize.... force initialization.
4916 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4917 ;; Calc embedded
4918 (org-set-local 'calc-embedded-open-mode "# ")
4919 (modify-syntax-entry ?@ "w")
4920 (if org-startup-truncated (setq truncate-lines t))
4921 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
4922 (org-set-local 'font-lock-unfontify-region-function
4923 'org-unfontify-region)
4924 ;; Activate before-change-function
4925 (org-set-local 'org-table-may-need-update t)
4926 (org-add-hook 'before-change-functions 'org-before-change-function nil
4927 'local)
4928 ;; Check for running clock before killing a buffer
4929 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4930 ;; Indentation.
4931 (org-set-local 'indent-line-function 'org-indent-line)
4932 (org-set-local 'indent-region-function 'org-indent-region)
4933 ;; Initialize radio targets.
4934 (org-update-radio-target-regexp)
4935 ;; Filling and auto-filling.
4936 (org-setup-filling)
4937 ;; Comments.
4938 (org-setup-comments-handling)
4939 ;; Beginning/end of defun
4940 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4941 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4942 ;; Next error for sparse trees
4943 (org-set-local 'next-error-function 'org-occur-next-match)
4944 ;; Make sure dependence stuff works reliably, even for users who set it
4945 ;; too late :-(
4946 (if org-enforce-todo-dependencies
4947 (add-hook 'org-blocker-hook
4948 'org-block-todo-from-children-or-siblings-or-parent)
4949 (remove-hook 'org-blocker-hook
4950 'org-block-todo-from-children-or-siblings-or-parent))
4951 (if org-enforce-todo-checkbox-dependencies
4952 (add-hook 'org-blocker-hook
4953 'org-block-todo-from-checkboxes)
4954 (remove-hook 'org-blocker-hook
4955 'org-block-todo-from-checkboxes))
4957 ;; Align options lines
4958 (org-set-local
4959 'align-mode-rules-list
4960 '((org-in-buffer-settings
4961 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4962 (modes . '(org-mode)))))
4964 ;; Imenu
4965 (org-set-local 'imenu-create-index-function
4966 'org-imenu-get-tree)
4968 ;; Make isearch reveal context
4969 (if (or (featurep 'xemacs)
4970 (not (boundp 'outline-isearch-open-invisible-function)))
4971 ;; Emacs 21 and XEmacs make use of the hook
4972 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4973 ;; Emacs 22 deals with this through a special variable
4974 (org-set-local 'outline-isearch-open-invisible-function
4975 (lambda (&rest ignore) (org-show-context 'isearch))))
4977 ;; Setup the pcomplete hooks
4978 (set (make-local-variable 'pcomplete-command-completion-function)
4979 'org-pcomplete-initial)
4980 (set (make-local-variable 'pcomplete-command-name-function)
4981 'org-command-at-point)
4982 (set (make-local-variable 'pcomplete-default-completion-function)
4983 'ignore)
4984 (set (make-local-variable 'pcomplete-parse-arguments-function)
4985 'org-parse-arguments)
4986 (set (make-local-variable 'pcomplete-termination-string) "")
4987 (when (>= emacs-major-version 23)
4988 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4990 ;; If empty file that did not turn on org-mode automatically, make it to.
4991 (if (and org-insert-mode-line-in-empty-file
4992 (org-called-interactively-p 'any)
4993 (= (point-min) (point-max)))
4994 (insert "# -*- mode: org -*-\n\n"))
4995 (unless org-inhibit-startup
4996 (and org-startup-with-beamer-mode (org-beamer-mode))
4997 (when org-startup-align-all-tables
4998 (let ((bmp (buffer-modified-p)))
4999 (org-table-map-tables 'org-table-align 'quietly)
5000 (set-buffer-modified-p bmp)))
5001 (when org-startup-with-inline-images
5002 (org-display-inline-images))
5003 (unless org-inhibit-startup-visibility-stuff
5004 (org-set-startup-visibility)))
5005 ;; Try to set org-hide correctly
5006 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5008 (when (fboundp 'abbrev-table-put)
5009 (abbrev-table-put org-mode-abbrev-table
5010 :parents (list text-mode-abbrev-table)))
5012 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5015 (defun org-find-invisible-foreground ()
5016 (let ((candidates (remove
5017 "unspecified-bg"
5018 (nconc
5019 (list (face-background 'default)
5020 (face-background 'org-default))
5021 (mapcar
5022 (lambda (alist)
5023 (when (boundp alist)
5024 (cdr (assoc 'background-color (symbol-value alist)))))
5025 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5026 (list (face-foreground 'org-hide))))))
5027 (car (remove nil candidates))))
5029 (defun org-current-time ()
5030 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5031 (if (> (car org-time-stamp-rounding-minutes) 1)
5032 (let ((r (car org-time-stamp-rounding-minutes))
5033 (time (decode-time)))
5034 (apply 'encode-time
5035 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5036 (nthcdr 2 time))))
5037 (current-time)))
5039 (defun org-today ()
5040 "Return today date, considering `org-extend-today-until'."
5041 (time-to-days
5042 (time-subtract (current-time)
5043 (list 0 (* 3600 org-extend-today-until) 0))))
5045 ;;;; Font-Lock stuff, including the activators
5047 (defvar org-mouse-map (make-sparse-keymap))
5048 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5049 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5050 (when org-mouse-1-follows-link
5051 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5052 (when org-tab-follows-link
5053 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5054 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5056 (require 'font-lock)
5058 (defconst org-non-link-chars "]\t\n\r<>")
5059 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5060 "shell" "elisp" "doi" "message"))
5061 (defvar org-link-types-re nil
5062 "Matches a link that has a url-like prefix like \"http:\"")
5063 (defvar org-link-re-with-space nil
5064 "Matches a link with spaces, optional angular brackets around it.")
5065 (defvar org-link-re-with-space2 nil
5066 "Matches a link with spaces, optional angular brackets around it.")
5067 (defvar org-link-re-with-space3 nil
5068 "Matches a link with spaces, only for internal part in bracket links.")
5069 (defvar org-angle-link-re nil
5070 "Matches link with angular brackets, spaces are allowed.")
5071 (defvar org-plain-link-re nil
5072 "Matches plain link, without spaces.")
5073 (defvar org-bracket-link-regexp nil
5074 "Matches a link in double brackets.")
5075 (defvar org-bracket-link-analytic-regexp nil
5076 "Regular expression used to analyze links.
5077 Here is what the match groups contain after a match:
5078 1: http:
5079 2: http
5080 3: path
5081 4: [desc]
5082 5: desc")
5083 (defvar org-bracket-link-analytic-regexp++ nil
5084 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5085 (defvar org-any-link-re nil
5086 "Regular expression matching any link.")
5088 (defcustom org-match-sexp-depth 3
5089 "Number of stacked braces for sub/superscript matching.
5090 This has to be set before loading org.el to be effective."
5091 :group 'org-export-translation ; ??????????????????????????/
5092 :type 'integer)
5094 (defun org-create-multibrace-regexp (left right n)
5095 "Create a regular expression which will match a balanced sexp.
5096 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5097 as single character strings.
5098 The regexp returned will match the entire expression including the
5099 delimiters. It will also define a single group which contains the
5100 match except for the outermost delimiters. The maximum depth of
5101 stacked delimiters is N. Escaping delimiters is not possible."
5102 (let* ((nothing (concat "[^" left right "]*?"))
5103 (or "\\|")
5104 (re nothing)
5105 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5106 (while (> n 1)
5107 (setq n (1- n)
5108 re (concat re or next)
5109 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5110 (concat left "\\(" re "\\)" right)))
5112 (defvar org-match-substring-regexp
5113 (concat
5114 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5115 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5116 "\\|"
5117 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5118 "\\|"
5119 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5120 "The regular expression matching a sub- or superscript.")
5122 (defvar org-match-substring-with-braces-regexp
5123 (concat
5124 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5125 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5126 "\\)")
5127 "The regular expression matching a sub- or superscript, forcing braces.")
5129 (defun org-make-link-regexps ()
5130 "Update the link regular expressions.
5131 This should be called after the variable `org-link-types' has changed."
5132 (setq org-link-types-re
5133 (concat
5134 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5135 org-link-re-with-space
5136 (concat
5137 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5138 "\\([^" org-non-link-chars " ]"
5139 "[^" org-non-link-chars "]*"
5140 "[^" org-non-link-chars " ]\\)>?")
5141 org-link-re-with-space2
5142 (concat
5143 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5144 "\\([^" org-non-link-chars " ]"
5145 "[^\t\n\r]*"
5146 "[^" org-non-link-chars " ]\\)>?")
5147 org-link-re-with-space3
5148 (concat
5149 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5150 "\\([^" org-non-link-chars " ]"
5151 "[^\t\n\r]*\\)")
5152 org-angle-link-re
5153 (concat
5154 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5155 "\\([^" org-non-link-chars " ]"
5156 "[^" org-non-link-chars "]*"
5157 "\\)>")
5158 org-plain-link-re
5159 (concat
5160 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5161 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5162 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5163 org-bracket-link-regexp
5164 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5165 org-bracket-link-analytic-regexp
5166 (concat
5167 "\\[\\["
5168 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5169 "\\([^]]+\\)"
5170 "\\]"
5171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5172 "\\]")
5173 org-bracket-link-analytic-regexp++
5174 (concat
5175 "\\[\\["
5176 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5177 "\\([^]]+\\)"
5178 "\\]"
5179 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5180 "\\]")
5181 org-any-link-re
5182 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5183 org-angle-link-re "\\)\\|\\("
5184 org-plain-link-re "\\)")))
5186 (org-make-link-regexps)
5188 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5189 "Regular expression for fast time stamp matching.")
5190 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5191 "Regular expression for fast time stamp matching.")
5192 (defconst org-ts-regexp0
5193 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5194 "Regular expression matching time strings for analysis.
5195 This one does not require the space after the date, so it can be used
5196 on a string that terminates immediately after the date.")
5197 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5198 "Regular expression matching time strings for analysis.")
5199 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5200 "Regular expression matching time stamps, with groups.")
5201 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5202 "Regular expression matching time stamps (also [..]), with groups.")
5203 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5204 "Regular expression matching a time stamp range.")
5205 (defconst org-tr-regexp-both
5206 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5207 "Regular expression matching a time stamp range.")
5208 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5209 org-ts-regexp "\\)?")
5210 "Regular expression matching a time stamp or time stamp range.")
5211 (defconst org-tsr-regexp-both
5212 (concat "[^][]\\(" ;; Don't activate dates in links
5213 org-ts-regexp-both "\\(--?-?"
5214 org-ts-regexp-both "\\)?\\)")
5215 "Regular expression matching a time stamp or time stamp range.
5216 The time stamps may be either active or inactive.")
5218 (defvar org-emph-face nil)
5220 (defun org-do-emphasis-faces (limit)
5221 "Run through the buffer and add overlays to emphasized strings."
5222 (let (rtn a)
5223 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5224 (if (not (= (char-after (match-beginning 3))
5225 (char-after (match-beginning 4))))
5226 (progn
5227 (setq rtn t)
5228 (setq a (assoc (match-string 3) org-emphasis-alist))
5229 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5230 'face
5231 (nth 1 a))
5232 (and (nth 4 a)
5233 (org-remove-flyspell-overlays-in
5234 (match-beginning 0) (match-end 0)))
5235 (add-text-properties (match-beginning 2) (match-end 2)
5236 '(font-lock-multiline t org-emphasis t))
5237 (when org-hide-emphasis-markers
5238 (add-text-properties (match-end 4) (match-beginning 5)
5239 '(invisible org-link))
5240 (add-text-properties (match-beginning 3) (match-end 3)
5241 '(invisible org-link)))))
5242 (backward-char 1))
5243 rtn))
5245 (defun org-emphasize (&optional char)
5246 "Insert or change an emphasis, i.e. a font like bold or italic.
5247 If there is an active region, change that region to a new emphasis.
5248 If there is no region, just insert the marker characters and position
5249 the cursor between them.
5250 CHAR should be either the marker character, or the first character of the
5251 HTML tag associated with that emphasis. If CHAR is a space, the means
5252 to remove the emphasis of the selected region.
5253 If char is not given (for example in an interactive call) it
5254 will be prompted for."
5255 (interactive)
5256 (let ((eal org-emphasis-alist) e det
5257 (erc org-emphasis-regexp-components)
5258 (prompt "")
5259 (string "") beg end move tag c s)
5260 (if (org-region-active-p)
5261 (setq beg (region-beginning) end (region-end)
5262 string (buffer-substring beg end))
5263 (setq move t))
5265 (while (setq e (pop eal))
5266 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5267 c (aref tag 0))
5268 (push (cons c (string-to-char (car e))) det)
5269 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5270 (substring tag 1)))))
5271 (setq det (nreverse det))
5272 (unless char
5273 (message "%s" (concat "Emphasis marker or tag:" prompt))
5274 (setq char (read-char-exclusive)))
5275 (setq char (or (cdr (assoc char det)) char))
5276 (if (equal char ?\ )
5277 (setq s "" move nil)
5278 (unless (assoc (char-to-string char) org-emphasis-alist)
5279 (error "No such emphasis marker: \"%c\"" char))
5280 (setq s (char-to-string char)))
5281 (while (and (> (length string) 1)
5282 (equal (substring string 0 1) (substring string -1))
5283 (assoc (substring string 0 1) org-emphasis-alist))
5284 (setq string (substring string 1 -1)))
5285 (setq string (concat s string s))
5286 (if beg (delete-region beg end))
5287 (unless (or (bolp)
5288 (string-match (concat "[" (nth 0 erc) "\n]")
5289 (char-to-string (char-before (point)))))
5290 (insert " "))
5291 (unless (or (eobp)
5292 (string-match (concat "[" (nth 1 erc) "\n]")
5293 (char-to-string (char-after (point)))))
5294 (insert " ") (backward-char 1))
5295 (insert string)
5296 (and move (backward-char 1))))
5298 (defconst org-nonsticky-props
5299 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5301 (defsubst org-rear-nonsticky-at (pos)
5302 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5304 (defun org-activate-plain-links (limit)
5305 "Run through the buffer and add overlays to links."
5306 (catch 'exit
5307 (let (f)
5308 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5309 (not (org-in-src-block-p)))
5310 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5311 (setq f (get-text-property (match-beginning 0) 'face))
5312 (unless (or (org-in-src-block-p)
5313 (eq f 'org-tag)
5314 (and (listp f) (memq 'org-tag f)))
5315 (add-text-properties (match-beginning 0) (match-end 0)
5316 (list 'mouse-face 'highlight
5317 'face 'org-link
5318 'keymap org-mouse-map))
5319 (org-rear-nonsticky-at (match-end 0)))
5320 t))))
5322 (defun org-activate-code (limit)
5323 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5324 (progn
5325 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5326 (remove-text-properties (match-beginning 0) (match-end 0)
5327 '(display t invisible t intangible t))
5328 t)))
5330 (defcustom org-src-fontify-natively nil
5331 "When non-nil, fontify code in code blocks."
5332 :type 'boolean
5333 :version "24.1"
5334 :group 'org-appearance
5335 :group 'org-babel)
5337 (defcustom org-allow-promoting-top-level-subtree nil
5338 "When non-nil, allow promoting a top level subtree.
5339 The leading star of the top level headline will be replaced
5340 by a #."
5341 :type 'boolean
5342 :version "24.1"
5343 :group 'org-appearance)
5345 (defun org-fontify-meta-lines-and-blocks (limit)
5346 (condition-case nil
5347 (org-fontify-meta-lines-and-blocks-1 limit)
5348 (error (message "org-mode fontification error"))))
5350 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5351 "Fontify #+ lines and blocks, in the correct ways."
5352 (let ((case-fold-search t))
5353 (if (re-search-forward
5354 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5355 limit t)
5356 (let ((beg (match-beginning 0))
5357 (block-start (match-end 0))
5358 (block-end nil)
5359 (lang (match-string 7))
5360 (beg1 (line-beginning-position 2))
5361 (dc1 (downcase (match-string 2)))
5362 (dc3 (downcase (match-string 3)))
5363 end end1 quoting block-type ovl)
5364 (cond
5365 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5366 ;; a single line of backend-specific content
5367 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5368 (remove-text-properties (match-beginning 0) (match-end 0)
5369 '(display t invisible t intangible t))
5370 (add-text-properties (match-beginning 1) (match-end 3)
5371 '(font-lock-fontified t face org-meta-line))
5372 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5373 '(font-lock-fontified t face org-block))
5374 ; for backend-specific code
5376 ((and (match-end 4) (equal dc3 "+begin"))
5377 ;; Truly a block
5378 (setq block-type (downcase (match-string 5))
5379 quoting (member block-type org-protecting-blocks))
5380 (when (re-search-forward
5381 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5382 nil t) ;; on purpose, we look further than LIMIT
5383 (setq end (min (point-max) (match-end 0))
5384 end1 (min (point-max) (1- (match-beginning 0))))
5385 (setq block-end (match-beginning 0))
5386 (when quoting
5387 (remove-text-properties beg end
5388 '(display t invisible t intangible t)))
5389 (add-text-properties
5390 beg end
5391 '(font-lock-fontified t font-lock-multiline t))
5392 (add-text-properties beg beg1 '(face org-meta-line))
5393 (add-text-properties end1 (min (point-max) (1+ end))
5394 '(face org-meta-line)) ; for end_src
5395 (cond
5396 ((and lang (not (string= lang "")) org-src-fontify-natively)
5397 (org-src-font-lock-fontify-block lang block-start block-end)
5398 ;; remove old background overlays
5399 (mapc (lambda (ov)
5400 (if (eq (overlay-get ov 'face) 'org-block-background)
5401 (delete-overlay ov)))
5402 (overlays-at (/ (+ beg1 block-end) 2)))
5403 ;; add a background overlay
5404 (setq ovl (make-overlay beg1 block-end))
5405 (overlay-put ovl 'face 'org-block-background)
5406 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5407 (quoting
5408 (add-text-properties beg1 (min (point-max) (1+ end1))
5409 '(face org-block))) ; end of source block
5410 ((not org-fontify-quote-and-verse-blocks))
5411 ((string= block-type "quote")
5412 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5413 ((string= block-type "verse")
5414 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5415 (add-text-properties beg beg1 '(face org-block-begin-line))
5416 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5417 '(face org-block-end-line))
5419 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5420 (add-text-properties
5421 beg (match-end 3)
5422 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5423 '(font-lock-fontified t invisible t)
5424 '(font-lock-fontified t face org-document-info-keyword)))
5425 (add-text-properties
5426 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5427 (if (string-equal dc1 "+title:")
5428 '(font-lock-fontified t face org-document-title)
5429 '(font-lock-fontified t face org-document-info))))
5430 ((or (equal dc1 "+results")
5431 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5432 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5433 "+call:" "+header:" "+headers:" "+name:"))
5434 (and (match-end 4) (equal dc3 "+attr")))
5435 (add-text-properties
5436 beg (match-end 0)
5437 '(font-lock-fontified t face org-meta-line))
5439 ((member dc3 '(" " ""))
5440 (add-text-properties
5441 beg (match-end 0)
5442 '(font-lock-fontified t face font-lock-comment-face)))
5443 ((not (member (char-after beg) '(?\ ?\t)))
5444 ;; just any other in-buffer setting, but not indented
5445 (add-text-properties
5446 beg (match-end 0)
5447 '(font-lock-fontified t face org-meta-line))
5449 (t nil))))))
5451 (defun org-activate-angle-links (limit)
5452 "Run through the buffer and add overlays to links."
5453 (if (and (re-search-forward org-angle-link-re limit t)
5454 (not (org-in-src-block-p)))
5455 (progn
5456 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5457 (add-text-properties (match-beginning 0) (match-end 0)
5458 (list 'mouse-face 'highlight
5459 'keymap org-mouse-map))
5460 (org-rear-nonsticky-at (match-end 0))
5461 t)))
5463 (defun org-activate-footnote-links (limit)
5464 "Run through the buffer and add overlays to footnotes."
5465 (let ((fn (org-footnote-next-reference-or-definition limit)))
5466 (when fn
5467 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5468 (org-remove-flyspell-overlays-in beg end)
5469 (add-text-properties beg end
5470 (list 'mouse-face 'highlight
5471 'keymap org-mouse-map
5472 'help-echo
5473 (if (= (point-at-bol) beg)
5474 "Footnote definition"
5475 "Footnote reference")
5476 'font-lock-fontified t
5477 'font-lock-multiline t
5478 'face 'org-footnote))))))
5480 (defun org-activate-bracket-links (limit)
5481 "Run through the buffer and add overlays to bracketed links."
5482 (if (and (re-search-forward org-bracket-link-regexp limit t)
5483 (not (org-in-src-block-p)))
5484 (let* ((help (concat "LINK: "
5485 (org-match-string-no-properties 1)))
5486 ;; FIXME: above we should remove the escapes.
5487 ;; but that requires another match, protecting match data,
5488 ;; a lot of overhead for font-lock.
5489 (ip (org-maybe-intangible
5490 (list 'invisible 'org-link
5491 'keymap org-mouse-map 'mouse-face 'highlight
5492 'font-lock-multiline t 'help-echo help)))
5493 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5494 'font-lock-multiline t 'help-echo help)))
5495 ;; We need to remove the invisible property here. Table narrowing
5496 ;; may have made some of this invisible.
5497 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5498 (remove-text-properties (match-beginning 0) (match-end 0)
5499 '(invisible nil))
5500 (if (match-end 3)
5501 (progn
5502 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5503 (org-rear-nonsticky-at (match-beginning 3))
5504 (add-text-properties (match-beginning 3) (match-end 3) vp)
5505 (org-rear-nonsticky-at (match-end 3))
5506 (add-text-properties (match-end 3) (match-end 0) ip)
5507 (org-rear-nonsticky-at (match-end 0)))
5508 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5509 (org-rear-nonsticky-at (match-beginning 1))
5510 (add-text-properties (match-beginning 1) (match-end 1) vp)
5511 (org-rear-nonsticky-at (match-end 1))
5512 (add-text-properties (match-end 1) (match-end 0) ip)
5513 (org-rear-nonsticky-at (match-end 0)))
5514 t)))
5516 (defun org-activate-dates (limit)
5517 "Run through the buffer and add overlays to dates."
5518 (if (re-search-forward org-tsr-regexp-both limit t)
5519 (progn
5520 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5521 (add-text-properties (match-beginning 1) (match-end 1)
5522 (list 'mouse-face 'highlight
5523 'keymap org-mouse-map))
5524 (org-rear-nonsticky-at (match-end 1))
5525 (when org-display-custom-times
5526 (if (match-end 4)
5527 (org-display-custom-time (match-beginning 4) (match-end 4)))
5528 (org-display-custom-time (match-beginning 2) (match-end 2)))
5529 t)))
5531 (defvar org-target-link-regexp nil
5532 "Regular expression matching radio targets in plain text.")
5533 (make-variable-buffer-local 'org-target-link-regexp)
5534 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5535 "Regular expression matching a link target.")
5536 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5537 "Regular expression matching a radio target.")
5538 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5539 "Regular expression matching any target.")
5541 (defun org-activate-target-links (limit)
5542 "Run through the buffer and add overlays to target matches."
5543 (when org-target-link-regexp
5544 (let ((case-fold-search t))
5545 (if (re-search-forward org-target-link-regexp limit t)
5546 (progn
5547 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5548 (add-text-properties (match-beginning 0) (match-end 0)
5549 (list 'mouse-face 'highlight
5550 'keymap org-mouse-map
5551 'help-echo "Radio target link"
5552 'org-linked-text t))
5553 (org-rear-nonsticky-at (match-end 0))
5554 t)))))
5556 (defun org-update-radio-target-regexp ()
5557 "Find all radio targets in this file and update the regular expression."
5558 (interactive)
5559 (when (memq 'radio org-activate-links)
5560 (setq org-target-link-regexp
5561 (org-make-target-link-regexp (org-all-targets 'radio)))
5562 (org-restart-font-lock)))
5564 (defun org-hide-wide-columns (limit)
5565 (let (s e)
5566 (setq s (text-property-any (point) (or limit (point-max))
5567 'org-cwidth t))
5568 (when s
5569 (setq e (next-single-property-change s 'org-cwidth))
5570 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5571 (goto-char e)
5572 t)))
5574 (defvar org-latex-and-specials-regexp nil
5575 "Regular expression for highlighting export special stuff.")
5576 (defvar org-match-substring-regexp)
5577 (defvar org-match-substring-with-braces-regexp)
5579 ;; This should be with the exporter code, but we also use if for font-locking
5580 (defconst org-export-html-special-string-regexps
5581 '(("\\\\-" . "&shy;")
5582 ("---\\([^-]\\)" . "&mdash;\\1")
5583 ("--\\([^-]\\)" . "&ndash;\\1")
5584 ("\\.\\.\\." . "&hellip;"))
5585 "Regular expressions for special string conversion.")
5588 (defun org-compute-latex-and-specials-regexp ()
5589 "Compute regular expression for stuff treated specially by exporters."
5590 (if (not org-highlight-latex-fragments-and-specials)
5591 (org-set-local 'org-latex-and-specials-regexp nil)
5592 (require 'org-exp)
5593 (let*
5594 ((matchers (plist-get org-format-latex-options :matchers))
5595 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5596 org-latex-regexps)))
5597 (org-export-allow-BIND nil)
5598 (options (org-combine-plists (org-default-export-plist)
5599 (org-infile-export-plist)))
5600 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5601 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5602 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5603 (org-export-html-expand (plist-get options :expand-quoted-html))
5604 (org-export-with-special-strings (plist-get options :special-strings))
5605 (re-sub
5606 (cond
5607 ((equal org-export-with-sub-superscripts '{})
5608 (list org-match-substring-with-braces-regexp))
5609 (org-export-with-sub-superscripts
5610 (list org-match-substring-regexp))))
5611 (re-latex
5612 (if org-export-with-LaTeX-fragments
5613 (mapcar (lambda (x) (nth 1 x)) latexs)))
5614 (re-macros
5615 (if org-export-with-TeX-macros
5616 (list (concat "\\\\"
5617 (regexp-opt
5618 (append
5620 (delq nil
5621 (mapcar 'car-safe
5622 (append org-entities-user
5623 org-entities)))
5624 (if (boundp 'org-latex-entities)
5625 (mapcar (lambda (x)
5626 (or (car-safe x) x))
5627 org-latex-entities)
5628 nil))
5629 'words))) ; FIXME
5631 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5632 (re-special (if org-export-with-special-strings
5633 (mapcar (lambda (x) (car x))
5634 org-export-html-special-string-regexps)))
5635 (re-rest
5636 (delq nil
5637 (list
5638 (if org-export-html-expand "@<[^>\n]+>")
5639 ))))
5640 (org-set-local
5641 'org-latex-and-specials-regexp
5642 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5643 re-rest) "\\|")))))
5645 (defun org-do-latex-and-special-faces (limit)
5646 "Run through the buffer and add overlays to links."
5647 (when org-latex-and-specials-regexp
5648 (let (rtn d)
5649 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5650 limit t))
5651 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5652 'face))
5653 '(org-code org-verbatim underline)))
5654 (progn
5655 (setq rtn t
5656 d (cond ((member (char-after (1+ (match-beginning 0)))
5657 '(?_ ?^)) 1)
5658 (t 0)))
5659 (font-lock-prepend-text-property
5660 (+ d (match-beginning 0)) (match-end 0)
5661 'face 'org-latex-and-export-specials)
5662 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5663 '(font-lock-multiline t)))))
5664 rtn)))
5666 (defun org-restart-font-lock ()
5667 "Restart `font-lock-mode', to force refontification."
5668 (when (and (boundp 'font-lock-mode) font-lock-mode)
5669 (font-lock-mode -1)
5670 (font-lock-mode 1)))
5672 (defun org-all-targets (&optional radio)
5673 "Return a list of all targets in this file.
5674 With optional argument RADIO, only find radio targets."
5675 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5676 rtn)
5677 (save-excursion
5678 (goto-char (point-min))
5679 (while (re-search-forward re nil t)
5680 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5681 rtn)))
5683 (defun org-make-target-link-regexp (targets)
5684 "Make regular expression matching all strings in TARGETS.
5685 The regular expression finds the targets also if there is a line break
5686 between words."
5687 (and targets
5688 (concat
5689 "\\<\\("
5690 (mapconcat
5691 (lambda (x)
5692 (setq x (regexp-quote x))
5693 (while (string-match " +" x)
5694 (setq x (replace-match "\\s-+" t t x)))
5696 targets
5697 "\\|")
5698 "\\)\\>")))
5700 (defun org-activate-tags (limit)
5701 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5702 (progn
5703 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5704 (add-text-properties (match-beginning 1) (match-end 1)
5705 (list 'mouse-face 'highlight
5706 'keymap org-mouse-map))
5707 (org-rear-nonsticky-at (match-end 1))
5708 t)))
5710 (defun org-outline-level ()
5711 "Compute the outline level of the heading at point.
5712 This function assumes that the cursor is at the beginning of a line matched
5713 by `outline-regexp'. Otherwise it returns garbage.
5714 If this is called at a normal headline, the level is the number of stars.
5715 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5716 (save-excursion
5717 (looking-at org-outline-regexp)
5718 (1- (- (match-end 0) (match-beginning 0)))))
5720 (defvar org-font-lock-keywords nil)
5722 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5723 "Regular expression matching a property line.")
5725 (defvar org-font-lock-hook nil
5726 "Functions to be called for special font lock stuff.")
5728 (defvar org-font-lock-set-keywords-hook nil
5729 "Functions that can manipulate `org-font-lock-extra-keywords'.
5730 This is called after `org-font-lock-extra-keywords' is defined, but before
5731 it is installed to be used by font lock. This can be useful if something
5732 needs to be inserted at a specific position in the font-lock sequence.")
5734 (defun org-font-lock-hook (limit)
5735 "Run `org-font-lock-hook' within LIMIT."
5736 (run-hook-with-args 'org-font-lock-hook limit))
5738 (defun org-set-font-lock-defaults ()
5739 "Set font lock defaults for the current buffer."
5740 (let* ((em org-fontify-emphasized-text)
5741 (lk org-activate-links)
5742 (org-font-lock-extra-keywords
5743 (list
5744 ;; Call the hook
5745 '(org-font-lock-hook)
5746 ;; Headlines
5747 `(,(if org-fontify-whole-heading-line
5748 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5749 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5750 (1 (org-get-level-face 1))
5751 (2 (org-get-level-face 2))
5752 (3 (org-get-level-face 3)))
5753 ;; Table lines
5754 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5755 (1 'org-table t))
5756 ;; Table internals
5757 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5758 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5759 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5760 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5761 ;; Drawers
5762 (list org-drawer-regexp '(0 'org-special-keyword t))
5763 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5764 ;; Properties
5765 (list org-property-re
5766 '(1 'org-special-keyword t)
5767 '(3 'org-property-value t))
5768 ;; Links
5769 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5770 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5771 (if (memq 'plain lk) '(org-activate-plain-links))
5772 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5773 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5774 (if (memq 'date lk) '(org-activate-dates (1 'org-date t)))
5775 (if (memq 'footnote lk) '(org-activate-footnote-links))
5776 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5777 '(org-hide-wide-columns (0 nil append))
5778 ;; TODO keyword
5779 (list (format org-heading-keyword-regexp-format
5780 org-todo-regexp)
5781 '(2 (org-get-todo-face 2) t))
5782 ;; DONE
5783 (if org-fontify-done-headline
5784 (list (format org-heading-keyword-regexp-format
5785 (concat
5786 "\\(?:"
5787 (mapconcat 'regexp-quote org-done-keywords "\\|")
5788 "\\)"))
5789 '(2 'org-headline-done t))
5790 nil)
5791 ;; Priorities
5792 '(org-font-lock-add-priority-faces)
5793 ;; Tags
5794 '(org-font-lock-add-tag-faces)
5795 ;; Special keywords
5796 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5798 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5799 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5800 ;; Emphasis
5801 (if em
5802 (if (featurep 'xemacs)
5803 '(org-do-emphasis-faces (0 nil append))
5804 '(org-do-emphasis-faces)))
5805 ;; Checkboxes
5806 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5807 1 'org-checkbox prepend)
5808 (if (cdr (assq 'checkbox org-list-automatic-rules))
5809 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5810 (0 (org-get-checkbox-statistics-face) t)))
5811 ;; Description list items
5812 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5813 1 'org-list-dt prepend)
5814 ;; ARCHIVEd headings
5815 (list (concat
5816 org-outline-regexp-bol
5817 "\\(.*:" org-archive-tag ":.*\\)")
5818 '(1 'org-archived prepend))
5819 ;; Specials
5820 '(org-do-latex-and-special-faces)
5821 '(org-fontify-entities)
5822 '(org-raise-scripts)
5823 ;; Code
5824 '(org-activate-code (1 'org-code t))
5825 ;; COMMENT
5826 (list (format org-heading-keyword-regexp-format
5827 (concat "\\("
5828 org-comment-string "\\|" org-quote-string
5829 "\\)"))
5830 '(2 'org-special-keyword t))
5831 ;; Blocks and meta lines
5832 '(org-fontify-meta-lines-and-blocks)
5834 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5835 (run-hooks 'org-font-lock-set-keywords-hook)
5836 ;; Now set the full font-lock-keywords
5837 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5838 (org-set-local 'font-lock-defaults
5839 '(org-font-lock-keywords t nil nil backward-paragraph))
5840 (kill-local-variable 'font-lock-keywords) nil))
5842 (defun org-toggle-pretty-entities ()
5843 "Toggle the composition display of entities as UTF8 characters."
5844 (interactive)
5845 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5846 (org-restart-font-lock)
5847 (if org-pretty-entities
5848 (message "Entities are displayed as UTF8 characters")
5849 (save-restriction
5850 (widen)
5851 (org-decompose-region (point-min) (point-max))
5852 (message "Entities are displayed plain"))))
5854 (defvar org-custom-properties-overlays nil
5855 "List of overlays used for custom properties.")
5856 (make-variable-buffer-local 'org-custom-properties-overlays)
5858 (defun org-toggle-custom-properties-visibility ()
5859 "Display or hide properties in `org-custom-properties'."
5860 (interactive)
5861 (if org-custom-properties-overlays
5862 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5863 (setq org-custom-properties-overlays nil))
5864 (unless (not org-custom-properties)
5865 (save-excursion
5866 (save-restriction
5867 (widen)
5868 (goto-char (point-min))
5869 (while (re-search-forward org-property-re nil t)
5870 (mapc (lambda(p)
5871 (when (equal p (substring (match-string 1) 1 -1))
5872 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5873 (overlay-put o 'invisible t)
5874 (overlay-put o 'org-custom-property t)
5875 (push o org-custom-properties-overlays))))
5876 org-custom-properties)))))))
5878 (defun org-fontify-entities (limit)
5879 "Find an entity to fontify."
5880 (let (ee)
5881 (when org-pretty-entities
5882 (catch 'match
5883 (while (re-search-forward
5884 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5885 limit t)
5886 (if (and (not (org-in-indented-comment-line))
5887 (setq ee (org-entity-get (match-string 1)))
5888 (= (length (nth 6 ee)) 1))
5889 (let*
5890 ((end (if (equal (match-string 2) "{}")
5891 (match-end 2)
5892 (match-end 1))))
5893 (add-text-properties
5894 (match-beginning 0) end
5895 (list 'font-lock-fontified t))
5896 (compose-region (match-beginning 0) end
5897 (nth 6 ee) nil)
5898 (backward-char 1)
5899 (throw 'match t))))
5900 nil))))
5902 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5903 "Fontify string S like in Org-mode."
5904 (with-temp-buffer
5905 (insert s)
5906 (let ((org-odd-levels-only odd-levels))
5907 (org-mode)
5908 (font-lock-fontify-buffer)
5909 (buffer-string))))
5911 (defvar org-m nil)
5912 (defvar org-l nil)
5913 (defvar org-f nil)
5914 (defun org-get-level-face (n)
5915 "Get the right face for match N in font-lock matching of headlines."
5916 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5917 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5918 (if org-cycle-level-faces
5919 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5920 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5921 (cond
5922 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5923 ((eq n 2) org-f)
5924 (t (if org-level-color-stars-only nil org-f))))
5927 (defun org-get-todo-face (kwd)
5928 "Get the right face for a TODO keyword KWD.
5929 If KWD is a number, get the corresponding match group."
5930 (if (numberp kwd) (setq kwd (match-string kwd)))
5931 (or (org-face-from-face-or-color
5932 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5933 (and (member kwd org-done-keywords) 'org-done)
5934 'org-todo))
5936 (defun org-face-from-face-or-color (context inherit face-or-color)
5937 "Create a face list that inherits INHERIT, but sets the foreground color.
5938 When FACE-OR-COLOR is not a string, just return it."
5939 (if (stringp face-or-color)
5940 (list :inherit inherit
5941 (cdr (assoc context org-faces-easy-properties))
5942 face-or-color)
5943 face-or-color))
5945 (defun org-font-lock-add-tag-faces (limit)
5946 "Add the special tag faces."
5947 (when (and org-tag-faces org-tags-special-faces-re)
5948 (while (re-search-forward org-tags-special-faces-re limit t)
5949 (add-text-properties (match-beginning 1) (match-end 1)
5950 (list 'face (org-get-tag-face 1)
5951 'font-lock-fontified t))
5952 (backward-char 1))))
5954 (defun org-font-lock-add-priority-faces (limit)
5955 "Add the special priority faces."
5956 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5957 (when (save-match-data (org-at-heading-p))
5958 (add-text-properties
5959 (match-beginning 0) (match-end 0)
5960 (list 'face (or (org-face-from-face-or-color
5961 'priority 'org-special-keyword
5962 (cdr (assoc (char-after (match-beginning 1))
5963 org-priority-faces)))
5964 'org-special-keyword)
5965 'font-lock-fontified t)))))
5967 (defun org-get-tag-face (kwd)
5968 "Get the right face for a TODO keyword KWD.
5969 If KWD is a number, get the corresponding match group."
5970 (if (numberp kwd) (setq kwd (match-string kwd)))
5971 (or (org-face-from-face-or-color
5972 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5973 'org-tag))
5975 (defun org-unfontify-region (beg end &optional maybe_loudly)
5976 "Remove fontification and activation overlays from links."
5977 (font-lock-default-unfontify-region beg end)
5978 (let* ((buffer-undo-list t)
5979 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5980 (inhibit-modification-hooks t)
5981 deactivate-mark buffer-file-name buffer-file-truename)
5982 (org-decompose-region beg end)
5983 (remove-text-properties beg end
5984 '(mouse-face t keymap t org-linked-text t
5985 invisible t intangible t
5986 org-no-flyspell t org-emphasis t))
5987 (org-remove-font-lock-display-properties beg end)))
5989 (defconst org-script-display '(((raise -0.3) (height 0.7))
5990 ((raise 0.3) (height 0.7))
5991 ((raise -0.5))
5992 ((raise 0.5)))
5993 "Display properties for showing superscripts and subscripts.")
5995 (defun org-remove-font-lock-display-properties (beg end)
5996 "Remove specific display properties that have been added by font lock.
5997 The will remove the raise properties that are used to show superscripts
5998 and subscripts."
5999 (let (next prop)
6000 (while (< beg end)
6001 (setq next (next-single-property-change beg 'display nil end)
6002 prop (get-text-property beg 'display))
6003 (if (member prop org-script-display)
6004 (put-text-property beg next 'display nil))
6005 (setq beg next))))
6007 (defun org-raise-scripts (limit)
6008 "Add raise properties to sub/superscripts."
6009 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6010 (if (re-search-forward
6011 (if (eq org-use-sub-superscripts t)
6012 org-match-substring-regexp
6013 org-match-substring-with-braces-regexp)
6014 limit t)
6015 (let* ((pos (point)) table-p comment-p
6016 (mpos (match-beginning 3))
6017 (emph-p (get-text-property mpos 'org-emphasis))
6018 (link-p (get-text-property mpos 'mouse-face))
6019 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6020 (goto-char (point-at-bol))
6021 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6022 comment-p (org-looking-at-p "[ \t]*#"))
6023 (goto-char pos)
6024 ;; FIXME: Should we go back one character here, for a_b^c
6025 ;; (goto-char (1- pos)) ;????????????????????
6026 (if (or comment-p emph-p link-p keyw-p)
6028 (put-text-property (match-beginning 3) (match-end 0)
6029 'display
6030 (if (equal (char-after (match-beginning 2)) ?^)
6031 (nth (if table-p 3 1) org-script-display)
6032 (nth (if table-p 2 0) org-script-display)))
6033 (add-text-properties (match-beginning 2) (match-end 2)
6034 (list 'invisible t
6035 'org-dwidth t 'org-dwidth-n 1))
6036 (if (and (eq (char-after (match-beginning 3)) ?{)
6037 (eq (char-before (match-end 3)) ?}))
6038 (progn
6039 (add-text-properties
6040 (match-beginning 3) (1+ (match-beginning 3))
6041 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6042 (add-text-properties
6043 (1- (match-end 3)) (match-end 3)
6044 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6045 t)))))
6047 ;;;; Visibility cycling, including org-goto and indirect buffer
6049 ;;; Cycling
6051 (defvar org-cycle-global-status nil)
6052 (make-variable-buffer-local 'org-cycle-global-status)
6053 (defvar org-cycle-subtree-status nil)
6054 (make-variable-buffer-local 'org-cycle-subtree-status)
6056 (defvar org-inlinetask-min-level)
6058 ;;;###autoload
6059 (defun org-cycle (&optional arg)
6060 "TAB-action and visibility cycling for Org-mode.
6062 This is the command invoked in Org-mode by the TAB key. Its main purpose
6063 is outline visibility cycling, but it also invokes other actions
6064 in special contexts.
6066 - When this function is called with a prefix argument, rotate the entire
6067 buffer through 3 states (global cycling)
6068 1. OVERVIEW: Show only top-level headlines.
6069 2. CONTENTS: Show all headlines of all levels, but no body text.
6070 3. SHOW ALL: Show everything.
6071 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6072 determined by the variable `org-startup-folded', and by any VISIBILITY
6073 properties in the buffer.
6074 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6075 including any drawers.
6077 - When inside a table, re-align the table and move to the next field.
6079 - When point is at the beginning of a headline, rotate the subtree started
6080 by this line through 3 different states (local cycling)
6081 1. FOLDED: Only the main headline is shown.
6082 2. CHILDREN: The main headline and the direct children are shown.
6083 From this state, you can move to one of the children
6084 and zoom in further.
6085 3. SUBTREE: Show the entire subtree, including body text.
6086 If there is no subtree, switch directly from CHILDREN to FOLDED.
6088 - When point is at the beginning of an empty headline and the variable
6089 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6090 of the headline by demoting and promoting it to likely levels. This
6091 speeds up creation document structure by pressing TAB once or several
6092 times right after creating a new headline.
6094 - When there is a numeric prefix, go up to a heading with level ARG, do
6095 a `show-subtree' and return to the previous cursor position. If ARG
6096 is negative, go up that many levels.
6098 - When point is not at the beginning of a headline, execute the global
6099 binding for TAB, which is re-indenting the line. See the option
6100 `org-cycle-emulate-tab' for details.
6102 - Special case: if point is at the beginning of the buffer and there is
6103 no headline in line 1, this function will act as if called with prefix arg
6104 (C-u TAB, same as S-TAB) also when called without prefix arg.
6105 But only if also the variable `org-cycle-global-at-bob' is t."
6106 (interactive "P")
6107 (org-load-modules-maybe)
6108 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6109 (and org-cycle-level-after-item/entry-creation
6110 (or (org-cycle-level)
6111 (org-cycle-item-indentation))))
6112 (let* ((limit-level
6113 (or org-cycle-max-level
6114 (and (boundp 'org-inlinetask-min-level)
6115 org-inlinetask-min-level
6116 (1- org-inlinetask-min-level))))
6117 (nstars (and limit-level
6118 (if org-odd-levels-only
6119 (and limit-level (1- (* limit-level 2)))
6120 limit-level)))
6121 (org-outline-regexp
6122 (if (not (derived-mode-p 'org-mode))
6123 outline-regexp
6124 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6125 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6126 (not (looking-at org-outline-regexp))))
6127 (org-cycle-hook
6128 (if bob-special
6129 (delq 'org-optimize-window-after-visibility-change
6130 (copy-sequence org-cycle-hook))
6131 org-cycle-hook))
6132 (pos (point)))
6134 (if (or bob-special (equal arg '(4)))
6135 ;; special case: use global cycling
6136 (setq arg t))
6138 (cond
6140 ((equal arg '(16))
6141 (setq last-command 'dummy)
6142 (org-set-startup-visibility)
6143 (message "Startup visibility, plus VISIBILITY properties"))
6145 ((equal arg '(64))
6146 (show-all)
6147 (message "Entire buffer visible, including drawers"))
6149 ;; Table: enter it or move to the next field.
6150 ((org-at-table-p 'any)
6151 (if (org-at-table.el-p)
6152 (message "Use C-c ' to edit table.el tables")
6153 (if arg (org-table-edit-field t)
6154 (org-table-justify-field-maybe)
6155 (call-interactively 'org-table-next-field))))
6157 ((run-hook-with-args-until-success
6158 'org-tab-after-check-for-table-hook))
6160 ;; Global cycling: delegate to `org-cycle-internal-global'.
6161 ((eq arg t) (org-cycle-internal-global))
6163 ;; Drawers: delegate to `org-flag-drawer'.
6164 ((and org-drawers org-drawer-regexp
6165 (save-excursion
6166 (beginning-of-line 1)
6167 (looking-at org-drawer-regexp)))
6168 (org-flag-drawer ; toggle block visibility
6169 (not (get-char-property (match-end 0) 'invisible))))
6171 ;; Show-subtree, ARG levels up from here.
6172 ((integerp arg)
6173 (save-excursion
6174 (org-back-to-heading)
6175 (outline-up-heading (if (< arg 0) (- arg)
6176 (- (funcall outline-level) arg)))
6177 (org-show-subtree)))
6179 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6180 ((and (featurep 'org-inlinetask)
6181 (org-inlinetask-at-task-p)
6182 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6183 (org-inlinetask-toggle-visibility))
6185 ((org-try-cdlatex-tab))
6187 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6188 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6189 (save-excursion (beginning-of-line 1)
6190 (looking-at org-outline-regexp)))
6191 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6192 (org-cycle-internal-local))
6194 ;; From there: TAB emulation and template completion.
6195 (buffer-read-only (org-back-to-heading))
6197 ((run-hook-with-args-until-success
6198 'org-tab-after-check-for-cycling-hook))
6200 ((org-try-structure-completion))
6202 ((run-hook-with-args-until-success
6203 'org-tab-before-tab-emulation-hook))
6205 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6206 (or (not (bolp))
6207 (not (looking-at org-outline-regexp))))
6208 (call-interactively (global-key-binding "\t")))
6210 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6211 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6212 (or (and (eq org-cycle-emulate-tab 'white)
6213 (= (match-end 0) (point-at-eol)))
6214 (and (eq org-cycle-emulate-tab 'whitestart)
6215 (>= (match-end 0) pos))))
6217 (eq org-cycle-emulate-tab t))
6218 (call-interactively (global-key-binding "\t")))
6220 (t (save-excursion
6221 (org-back-to-heading)
6222 (org-cycle)))))))
6224 (defun org-cycle-internal-global ()
6225 "Do the global cycling action."
6226 ;; Hack to avoid display of messages for .org attachments in Gnus
6227 (let ((ga (string-match "\\*fontification" (buffer-name))))
6228 (cond
6229 ((and (eq last-command this-command)
6230 (eq org-cycle-global-status 'overview))
6231 ;; We just created the overview - now do table of contents
6232 ;; This can be slow in very large buffers, so indicate action
6233 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6234 (unless ga (message "CONTENTS..."))
6235 (org-content)
6236 (unless ga (message "CONTENTS...done"))
6237 (setq org-cycle-global-status 'contents)
6238 (run-hook-with-args 'org-cycle-hook 'contents))
6240 ((and (eq last-command this-command)
6241 (eq org-cycle-global-status 'contents))
6242 ;; We just showed the table of contents - now show everything
6243 (run-hook-with-args 'org-pre-cycle-hook 'all)
6244 (show-all)
6245 (unless ga (message "SHOW ALL"))
6246 (setq org-cycle-global-status 'all)
6247 (run-hook-with-args 'org-cycle-hook 'all))
6250 ;; Default action: go to overview
6251 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6252 (org-overview)
6253 (unless ga (message "OVERVIEW"))
6254 (setq org-cycle-global-status 'overview)
6255 (run-hook-with-args 'org-cycle-hook 'overview)))))
6257 (defun org-cycle-internal-local ()
6258 "Do the local cycling action."
6259 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6260 ;; First, determine end of headline (EOH), end of subtree or item
6261 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6262 (save-excursion
6263 (if (org-at-item-p)
6264 (progn
6265 (beginning-of-line)
6266 (setq struct (org-list-struct))
6267 (setq eoh (point-at-eol))
6268 (setq eos (org-list-get-item-end-before-blank (point) struct))
6269 (setq has-children (org-list-has-child-p (point) struct)))
6270 (org-back-to-heading)
6271 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6272 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6273 (setq has-children
6274 (or (save-excursion
6275 (let ((level (funcall outline-level)))
6276 (outline-next-heading)
6277 (and (org-at-heading-p t)
6278 (> (funcall outline-level) level))))
6279 (save-excursion
6280 (org-list-search-forward (org-item-beginning-re) eos t)))))
6281 ;; Determine end invisible part of buffer (EOL)
6282 (beginning-of-line 2)
6283 ;; XEmacs doesn't have `next-single-char-property-change'
6284 (if (featurep 'xemacs)
6285 (while (and (not (eobp)) ;; this is like `next-line'
6286 (get-char-property (1- (point)) 'invisible))
6287 (beginning-of-line 2))
6288 (while (and (not (eobp)) ;; this is like `next-line'
6289 (get-char-property (1- (point)) 'invisible))
6290 (goto-char (next-single-char-property-change (point) 'invisible))
6291 (and (eolp) (beginning-of-line 2))))
6292 (setq eol (point)))
6293 ;; Find out what to do next and set `this-command'
6294 (cond
6295 ((= eos eoh)
6296 ;; Nothing is hidden behind this heading
6297 (unless (org-before-first-heading-p)
6298 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6299 (message "EMPTY ENTRY")
6300 (setq org-cycle-subtree-status nil)
6301 (save-excursion
6302 (goto-char eos)
6303 (outline-next-heading)
6304 (if (outline-invisible-p) (org-flag-heading nil))))
6305 ((and (or (>= eol eos)
6306 (not (string-match "\\S-" (buffer-substring eol eos))))
6307 (or has-children
6308 (not (setq children-skipped
6309 org-cycle-skip-children-state-if-no-children))))
6310 ;; Entire subtree is hidden in one line: children view
6311 (unless (org-before-first-heading-p)
6312 (run-hook-with-args 'org-pre-cycle-hook 'children))
6313 (if (org-at-item-p)
6314 (org-list-set-item-visibility (point-at-bol) struct 'children)
6315 (org-show-entry)
6316 (org-with-limited-levels (show-children))
6317 ;; FIXME: This slows down the func way too much.
6318 ;; How keep drawers hidden in subtree anyway?
6319 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6320 ;; (org-cycle-hide-drawers 'subtree))
6322 ;; Fold every list in subtree to top-level items.
6323 (when (eq org-cycle-include-plain-lists 'integrate)
6324 (save-excursion
6325 (org-back-to-heading)
6326 (while (org-list-search-forward (org-item-beginning-re) eos t)
6327 (beginning-of-line 1)
6328 (let* ((struct (org-list-struct))
6329 (prevs (org-list-prevs-alist struct))
6330 (end (org-list-get-bottom-point struct)))
6331 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6332 (org-list-get-all-items (point) struct prevs))
6333 (goto-char end))))))
6334 (message "CHILDREN")
6335 (save-excursion
6336 (goto-char eos)
6337 (outline-next-heading)
6338 (if (outline-invisible-p) (org-flag-heading nil)))
6339 (setq org-cycle-subtree-status 'children)
6340 (unless (org-before-first-heading-p)
6341 (run-hook-with-args 'org-cycle-hook 'children)))
6342 ((or children-skipped
6343 (and (eq last-command this-command)
6344 (eq org-cycle-subtree-status 'children)))
6345 ;; We just showed the children, or no children are there,
6346 ;; now show everything.
6347 (unless (org-before-first-heading-p)
6348 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6349 (outline-flag-region eoh eos nil)
6350 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6351 (setq org-cycle-subtree-status 'subtree)
6352 (unless (org-before-first-heading-p)
6353 (run-hook-with-args 'org-cycle-hook 'subtree)))
6355 ;; Default action: hide the subtree.
6356 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6357 (outline-flag-region eoh eos t)
6358 (message "FOLDED")
6359 (setq org-cycle-subtree-status 'folded)
6360 (unless (org-before-first-heading-p)
6361 (run-hook-with-args 'org-cycle-hook 'folded))))))
6363 ;;;###autoload
6364 (defun org-global-cycle (&optional arg)
6365 "Cycle the global visibility. For details see `org-cycle'.
6366 With \\[universal-argument] prefix arg, switch to startup visibility.
6367 With a numeric prefix, show all headlines up to that level."
6368 (interactive "P")
6369 (let ((org-cycle-include-plain-lists
6370 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6371 (cond
6372 ((integerp arg)
6373 (show-all)
6374 (hide-sublevels arg)
6375 (setq org-cycle-global-status 'contents))
6376 ((equal arg '(4))
6377 (org-set-startup-visibility)
6378 (message "Startup visibility, plus VISIBILITY properties."))
6380 (org-cycle '(4))))))
6382 (defun org-set-startup-visibility ()
6383 "Set the visibility required by startup options and properties."
6384 (cond
6385 ((eq org-startup-folded t)
6386 (org-cycle '(4)))
6387 ((eq org-startup-folded 'content)
6388 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6389 (org-cycle '(4)) (org-cycle '(4)))))
6390 (unless (eq org-startup-folded 'showeverything)
6391 (if org-hide-block-startup (org-hide-block-all))
6392 (org-set-visibility-according-to-property 'no-cleanup)
6393 (org-cycle-hide-archived-subtrees 'all)
6394 (org-cycle-hide-drawers 'all)
6395 (org-cycle-show-empty-lines t)))
6397 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6398 "Switch subtree visibilities according to :VISIBILITY: property."
6399 (interactive)
6400 (let (org-show-entry-below state)
6401 (save-excursion
6402 (goto-char (point-min))
6403 (while (re-search-forward
6404 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6405 nil t)
6406 (setq state (match-string 1))
6407 (save-excursion
6408 (org-back-to-heading t)
6409 (hide-subtree)
6410 (org-reveal)
6411 (cond
6412 ((equal state '("fold" "folded"))
6413 (hide-subtree))
6414 ((equal state "children")
6415 (org-show-hidden-entry)
6416 (show-children))
6417 ((equal state "content")
6418 (save-excursion
6419 (save-restriction
6420 (org-narrow-to-subtree)
6421 (org-content))))
6422 ((member state '("all" "showall"))
6423 (show-subtree)))))
6424 (unless no-cleanup
6425 (org-cycle-hide-archived-subtrees 'all)
6426 (org-cycle-hide-drawers 'all)
6427 (org-cycle-show-empty-lines 'all)))))
6429 ;; This function uses outline-regexp instead of the more fundamental
6430 ;; org-outline-regexp so that org-cycle-global works outside of Org
6431 ;; buffers, where outline-regexp is needed.
6432 (defun org-overview ()
6433 "Switch to overview mode, showing only top-level headlines.
6434 Really, this shows all headlines with level equal or greater than the level
6435 of the first headline in the buffer. This is important, because if the
6436 first headline is not level one, then (hide-sublevels 1) gives confusing
6437 results."
6438 (interactive)
6439 (let ((level (save-excursion
6440 (goto-char (point-min))
6441 (if (re-search-forward (concat "^" outline-regexp) nil t)
6442 (progn
6443 (goto-char (match-beginning 0))
6444 (funcall outline-level))))))
6445 (and level (hide-sublevels level))))
6447 (defun org-content (&optional arg)
6448 "Show all headlines in the buffer, like a table of contents.
6449 With numerical argument N, show content up to level N."
6450 (interactive "P")
6451 (save-excursion
6452 ;; Visit all headings and show their offspring
6453 (and (integerp arg) (org-overview))
6454 (goto-char (point-max))
6455 (catch 'exit
6456 (while (and (progn (condition-case nil
6457 (outline-previous-visible-heading 1)
6458 (error (goto-char (point-min))))
6460 (looking-at org-outline-regexp))
6461 (if (integerp arg)
6462 (show-children (1- arg))
6463 (show-branches))
6464 (if (bobp) (throw 'exit nil))))))
6467 (defun org-optimize-window-after-visibility-change (state)
6468 "Adjust the window after a change in outline visibility.
6469 This function is the default value of the hook `org-cycle-hook'."
6470 (when (get-buffer-window (current-buffer))
6471 (cond
6472 ((eq state 'content) nil)
6473 ((eq state 'all) nil)
6474 ((eq state 'folded) nil)
6475 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6476 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6478 (defun org-remove-empty-overlays-at (pos)
6479 "Remove outline overlays that do not contain non-white stuff."
6480 (mapc
6481 (lambda (o)
6482 (and (eq 'outline (overlay-get o 'invisible))
6483 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6484 (overlay-end o))))
6485 (delete-overlay o)))
6486 (overlays-at pos)))
6488 (defun org-clean-visibility-after-subtree-move ()
6489 "Fix visibility issues after moving a subtree."
6490 ;; First, find a reasonable region to look at:
6491 ;; Start two siblings above, end three below
6492 (let* ((beg (save-excursion
6493 (and (org-get-last-sibling)
6494 (org-get-last-sibling))
6495 (point)))
6496 (end (save-excursion
6497 (and (org-get-next-sibling)
6498 (org-get-next-sibling)
6499 (org-get-next-sibling))
6500 (if (org-at-heading-p)
6501 (point-at-eol)
6502 (point))))
6503 (level (looking-at "\\*+"))
6504 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6505 (save-excursion
6506 (save-restriction
6507 (narrow-to-region beg end)
6508 (when re
6509 ;; Properly fold already folded siblings
6510 (goto-char (point-min))
6511 (while (re-search-forward re nil t)
6512 (if (and (not (outline-invisible-p))
6513 (save-excursion
6514 (goto-char (point-at-eol)) (outline-invisible-p)))
6515 (hide-entry))))
6516 (org-cycle-show-empty-lines 'overview)
6517 (org-cycle-hide-drawers 'overview)))))
6519 (defun org-cycle-show-empty-lines (state)
6520 "Show empty lines above all visible headlines.
6521 The region to be covered depends on STATE when called through
6522 `org-cycle-hook'. Lisp program can use t for STATE to get the
6523 entire buffer covered. Note that an empty line is only shown if there
6524 are at least `org-cycle-separator-lines' empty lines before the headline."
6525 (when (not (= org-cycle-separator-lines 0))
6526 (save-excursion
6527 (let* ((n (abs org-cycle-separator-lines))
6528 (re (cond
6529 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6530 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6531 (t (let ((ns (number-to-string (- n 2))))
6532 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6533 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6534 beg end b e)
6535 (cond
6536 ((memq state '(overview contents t))
6537 (setq beg (point-min) end (point-max)))
6538 ((memq state '(children folded))
6539 (setq beg (point) end (progn (org-end-of-subtree t t)
6540 (beginning-of-line 2)
6541 (point)))))
6542 (when beg
6543 (goto-char beg)
6544 (while (re-search-forward re end t)
6545 (unless (get-char-property (match-end 1) 'invisible)
6546 (setq e (match-end 1))
6547 (if (< org-cycle-separator-lines 0)
6548 (setq b (save-excursion
6549 (goto-char (match-beginning 0))
6550 (org-back-over-empty-lines)
6551 (if (save-excursion
6552 (goto-char (max (point-min) (1- (point))))
6553 (org-at-heading-p))
6554 (1- (point))
6555 (point))))
6556 (setq b (match-beginning 1)))
6557 (outline-flag-region b e nil)))))))
6558 ;; Never hide empty lines at the end of the file.
6559 (save-excursion
6560 (goto-char (point-max))
6561 (outline-previous-heading)
6562 (outline-end-of-heading)
6563 (if (and (looking-at "[ \t\n]+")
6564 (= (match-end 0) (point-max)))
6565 (outline-flag-region (point) (match-end 0) nil))))
6567 (defun org-show-empty-lines-in-parent ()
6568 "Move to the parent and re-show empty lines before visible headlines."
6569 (save-excursion
6570 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6571 (org-cycle-show-empty-lines context))))
6573 (defun org-files-list ()
6574 "Return `org-agenda-files' list, plus all open org-mode files.
6575 This is useful for operations that need to scan all of a user's
6576 open and agenda-wise Org files."
6577 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6578 (dolist (buf (buffer-list))
6579 (with-current-buffer buf
6580 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6581 (let ((file (expand-file-name (buffer-file-name))))
6582 (unless (member file files)
6583 (push file files))))))
6584 files))
6586 (defsubst org-entry-beginning-position ()
6587 "Return the beginning position of the current entry."
6588 (save-excursion (outline-back-to-heading t) (point)))
6590 (defsubst org-entry-end-position ()
6591 "Return the end position of the current entry."
6592 (save-excursion (outline-next-heading) (point)))
6594 (defun org-cycle-hide-drawers (state)
6595 "Re-hide all drawers after a visibility state change."
6596 (when (and (derived-mode-p 'org-mode)
6597 (not (memq state '(overview folded contents))))
6598 (save-excursion
6599 (let* ((globalp (memq state '(contents all)))
6600 (beg (if globalp (point-min) (point)))
6601 (end (if globalp (point-max)
6602 (if (eq state 'children)
6603 (save-excursion (outline-next-heading) (point))
6604 (org-end-of-subtree t)))))
6605 (goto-char beg)
6606 (while (re-search-forward org-drawer-regexp end t)
6607 (org-flag-drawer t))))))
6609 (defun org-flag-drawer (flag)
6610 "When FLAG is non-nil, hide the drawer we are within.
6611 Otherwise make it visible."
6612 (save-excursion
6613 (beginning-of-line 1)
6614 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6615 (let ((b (match-end 0)))
6616 (if (re-search-forward
6617 "^[ \t]*:END:"
6618 (save-excursion (outline-next-heading) (point)) t)
6619 (outline-flag-region b (point-at-eol) flag)
6620 (error ":END: line missing at position %s" b))))))
6622 (defun org-subtree-end-visible-p ()
6623 "Is the end of the current subtree visible?"
6624 (pos-visible-in-window-p
6625 (save-excursion (org-end-of-subtree t) (point))))
6627 (defun org-first-headline-recenter (&optional N)
6628 "Move cursor to the first headline and recenter the headline.
6629 Optional argument N means put the headline into the Nth line of the window."
6630 (goto-char (point-min))
6631 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6632 (beginning-of-line)
6633 (recenter (prefix-numeric-value N))))
6635 ;;; Saving and restoring visibility
6637 (defun org-outline-overlay-data (&optional use-markers)
6638 "Return a list of the locations of all outline overlays.
6639 These are overlays with the `invisible' property value `outline'.
6640 The return value is a list of cons cells, with start and stop
6641 positions for each overlay.
6642 If USE-MARKERS is set, return the positions as markers."
6643 (let (beg end)
6644 (save-excursion
6645 (save-restriction
6646 (widen)
6647 (delq nil
6648 (mapcar (lambda (o)
6649 (when (eq (overlay-get o 'invisible) 'outline)
6650 (setq beg (overlay-start o)
6651 end (overlay-end o))
6652 (and beg end (> end beg)
6653 (if use-markers
6654 (cons (move-marker (make-marker) beg)
6655 (move-marker (make-marker) end))
6656 (cons beg end)))))
6657 (overlays-in (point-min) (point-max))))))))
6659 (defun org-set-outline-overlay-data (data)
6660 "Create visibility overlays for all positions in DATA.
6661 DATA should have been made by `org-outline-overlay-data'."
6662 (let (o)
6663 (save-excursion
6664 (save-restriction
6665 (widen)
6666 (show-all)
6667 (mapc (lambda (c)
6668 (outline-flag-region (car c) (cdr c) t))
6669 data)))))
6671 ;;; Folding of blocks
6673 (defvar org-hide-block-overlays nil
6674 "Overlays hiding blocks.")
6675 (make-variable-buffer-local 'org-hide-block-overlays)
6677 (defun org-block-map (function &optional start end)
6678 "Call FUNCTION at the head of all source blocks in the current buffer.
6679 Optional arguments START and END can be used to limit the range."
6680 (let ((start (or start (point-min)))
6681 (end (or end (point-max))))
6682 (save-excursion
6683 (goto-char start)
6684 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6685 (save-excursion
6686 (save-match-data
6687 (goto-char (match-beginning 0))
6688 (funcall function)))))))
6690 (defun org-hide-block-toggle-all ()
6691 "Toggle the visibility of all blocks in the current buffer."
6692 (org-block-map #'org-hide-block-toggle))
6694 (defun org-hide-block-all ()
6695 "Fold all blocks in the current buffer."
6696 (interactive)
6697 (org-show-block-all)
6698 (org-block-map #'org-hide-block-toggle-maybe))
6700 (defun org-show-block-all ()
6701 "Unfold all blocks in the current buffer."
6702 (interactive)
6703 (mapc 'delete-overlay org-hide-block-overlays)
6704 (setq org-hide-block-overlays nil))
6706 (defun org-hide-block-toggle-maybe ()
6707 "Toggle visibility of block at point."
6708 (interactive)
6709 (let ((case-fold-search t))
6710 (if (save-excursion
6711 (beginning-of-line 1)
6712 (looking-at org-block-regexp))
6713 (progn (org-hide-block-toggle)
6714 t) ;; to signal that we took action
6715 nil))) ;; to signal that we did not
6717 (defun org-hide-block-toggle (&optional force)
6718 "Toggle the visibility of the current block."
6719 (interactive)
6720 (save-excursion
6721 (beginning-of-line)
6722 (if (re-search-forward org-block-regexp nil t)
6723 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6724 (end (match-end 0)) ;; end of entire body
6726 (if (memq t (mapcar (lambda (overlay)
6727 (eq (overlay-get overlay 'invisible)
6728 'org-hide-block))
6729 (overlays-at start)))
6730 (if (or (not force) (eq force 'off))
6731 (mapc (lambda (ov)
6732 (when (member ov org-hide-block-overlays)
6733 (setq org-hide-block-overlays
6734 (delq ov org-hide-block-overlays)))
6735 (when (eq (overlay-get ov 'invisible)
6736 'org-hide-block)
6737 (delete-overlay ov)))
6738 (overlays-at start)))
6739 (setq ov (make-overlay start end))
6740 (overlay-put ov 'invisible 'org-hide-block)
6741 ;; make the block accessible to isearch
6742 (overlay-put
6743 ov 'isearch-open-invisible
6744 (lambda (ov)
6745 (when (member ov org-hide-block-overlays)
6746 (setq org-hide-block-overlays
6747 (delq ov org-hide-block-overlays)))
6748 (when (eq (overlay-get ov 'invisible)
6749 'org-hide-block)
6750 (delete-overlay ov))))
6751 (push ov org-hide-block-overlays)))
6752 (error "Not looking at a source block"))))
6754 ;; org-tab-after-check-for-cycling-hook
6755 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6756 ;; Remove overlays when changing major mode
6757 (add-hook 'org-mode-hook
6758 (lambda () (org-add-hook 'change-major-mode-hook
6759 'org-show-block-all 'append 'local)))
6761 ;;; Org-goto
6763 (defvar org-goto-window-configuration nil)
6764 (defvar org-goto-marker nil)
6765 (defvar org-goto-map)
6766 (defun org-goto-map ()
6767 "Set the keymap `org-goto'."
6768 (setq org-goto-map
6769 (let ((map (make-sparse-keymap)))
6770 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6771 mouse-drag-region universal-argument org-occur))
6772 cmd)
6773 (while (setq cmd (pop cmds))
6774 (substitute-key-definition cmd cmd map global-map)))
6775 (suppress-keymap map)
6776 (org-defkey map "\C-m" 'org-goto-ret)
6777 (org-defkey map [(return)] 'org-goto-ret)
6778 (org-defkey map [(left)] 'org-goto-left)
6779 (org-defkey map [(right)] 'org-goto-right)
6780 (org-defkey map [(control ?g)] 'org-goto-quit)
6781 (org-defkey map "\C-i" 'org-cycle)
6782 (org-defkey map [(tab)] 'org-cycle)
6783 (org-defkey map [(down)] 'outline-next-visible-heading)
6784 (org-defkey map [(up)] 'outline-previous-visible-heading)
6785 (if org-goto-auto-isearch
6786 (if (fboundp 'define-key-after)
6787 (define-key-after map [t] 'org-goto-local-auto-isearch)
6788 nil)
6789 (org-defkey map "q" 'org-goto-quit)
6790 (org-defkey map "n" 'outline-next-visible-heading)
6791 (org-defkey map "p" 'outline-previous-visible-heading)
6792 (org-defkey map "f" 'outline-forward-same-level)
6793 (org-defkey map "b" 'outline-backward-same-level)
6794 (org-defkey map "u" 'outline-up-heading))
6795 (org-defkey map "/" 'org-occur)
6796 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6797 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6798 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6799 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6800 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6801 map)))
6803 (defconst org-goto-help
6804 "Browse buffer copy, to find location or copy text.%s
6805 RET=jump to location C-g=quit and return to previous location
6806 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6808 (defvar org-goto-start-pos) ; dynamically scoped parameter
6810 ;; FIXME: Docstring does not mention both interfaces
6811 (defun org-goto (&optional alternative-interface)
6812 "Look up a different location in the current file, keeping current visibility.
6814 When you want look-up or go to a different location in a
6815 document, the fastest way is often to fold the entire buffer and
6816 then dive into the tree. This method has the disadvantage, that
6817 the previous location will be folded, which may not be what you
6818 want.
6820 This command works around this by showing a copy of the current
6821 buffer in an indirect buffer, in overview mode. You can dive
6822 into the tree in that copy, use org-occur and incremental search
6823 to find a location. When pressing RET or `Q', the command
6824 returns to the original buffer in which the visibility is still
6825 unchanged. After RET it will also jump to the location selected
6826 in the indirect buffer and expose the headline hierarchy above.
6828 With a prefix argument, use the alternative interface: e.g. if
6829 `org-goto-interface' is 'outline use 'outline-path-completion."
6830 (interactive "P")
6831 (org-goto-map)
6832 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6833 (org-refile-use-outline-path t)
6834 (org-refile-target-verify-function nil)
6835 (interface
6836 (if (not alternative-interface)
6837 org-goto-interface
6838 (if (eq org-goto-interface 'outline)
6839 'outline-path-completion
6840 'outline)))
6841 (org-goto-start-pos (point))
6842 (selected-point
6843 (if (eq interface 'outline)
6844 (car (org-get-location (current-buffer) org-goto-help))
6845 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6846 (org-refile-check-position pa)
6847 (nth 3 pa)))))
6848 (if selected-point
6849 (progn
6850 (org-mark-ring-push org-goto-start-pos)
6851 (goto-char selected-point)
6852 (if (or (outline-invisible-p) (org-invisible-p2))
6853 (org-show-context 'org-goto)))
6854 (message "Quit"))))
6856 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6857 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6858 (defvar org-goto-local-auto-isearch-map) ; defined below
6860 (defun org-get-location (buf help)
6861 "Let the user select a location in the Org-mode buffer BUF.
6862 This function uses a recursive edit. It returns the selected position
6863 or nil."
6864 (org-no-popups
6865 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6866 (isearch-hide-immediately nil)
6867 (isearch-search-fun-function
6868 (lambda () 'org-goto-local-search-headings))
6869 (org-goto-selected-point org-goto-exit-command))
6870 (save-excursion
6871 (save-window-excursion
6872 (delete-other-windows)
6873 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6874 (org-pop-to-buffer-same-window
6875 (condition-case nil
6876 (make-indirect-buffer (current-buffer) "*org-goto*")
6877 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6878 (with-output-to-temp-buffer "*Org Help*"
6879 (princ (format help (if org-goto-auto-isearch
6880 " Just type for auto-isearch."
6881 " n/p/f/b/u to navigate, q to quit."))))
6882 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6883 (setq buffer-read-only nil)
6884 (let ((org-startup-truncated t)
6885 (org-startup-folded nil)
6886 (org-startup-align-all-tables nil))
6887 (org-mode)
6888 (org-overview))
6889 (setq buffer-read-only t)
6890 (if (and (boundp 'org-goto-start-pos)
6891 (integer-or-marker-p org-goto-start-pos))
6892 (let ((org-show-hierarchy-above t)
6893 (org-show-siblings t)
6894 (org-show-following-heading t))
6895 (goto-char org-goto-start-pos)
6896 (and (outline-invisible-p) (org-show-context)))
6897 (goto-char (point-min)))
6898 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6899 (message "Select location and press RET")
6900 (use-local-map org-goto-map)
6901 (recursive-edit)))
6902 (kill-buffer "*org-goto*")
6903 (cons org-goto-selected-point org-goto-exit-command))))
6905 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6906 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6907 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6908 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6910 (defun org-goto-local-search-headings (string bound noerror)
6911 "Search and make sure that any matches are in headlines."
6912 (catch 'return
6913 (while (if isearch-forward
6914 (search-forward string bound noerror)
6915 (search-backward string bound noerror))
6916 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6917 (and (member :headline context)
6918 (not (member :tags context))))
6919 (throw 'return (point))))))
6921 (defun org-goto-local-auto-isearch ()
6922 "Start isearch."
6923 (interactive)
6924 (goto-char (point-min))
6925 (let ((keys (this-command-keys)))
6926 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6927 (isearch-mode t)
6928 (isearch-process-search-char (string-to-char keys)))))
6930 (defun org-goto-ret (&optional arg)
6931 "Finish `org-goto' by going to the new location."
6932 (interactive "P")
6933 (setq org-goto-selected-point (point)
6934 org-goto-exit-command 'return)
6935 (throw 'exit nil))
6937 (defun org-goto-left ()
6938 "Finish `org-goto' by going to the new location."
6939 (interactive)
6940 (if (org-at-heading-p)
6941 (progn
6942 (beginning-of-line 1)
6943 (setq org-goto-selected-point (point)
6944 org-goto-exit-command 'left)
6945 (throw 'exit nil))
6946 (error "Not on a heading")))
6948 (defun org-goto-right ()
6949 "Finish `org-goto' by going to the new location."
6950 (interactive)
6951 (if (org-at-heading-p)
6952 (progn
6953 (setq org-goto-selected-point (point)
6954 org-goto-exit-command 'right)
6955 (throw 'exit nil))
6956 (error "Not on a heading")))
6958 (defun org-goto-quit ()
6959 "Finish `org-goto' without cursor motion."
6960 (interactive)
6961 (setq org-goto-selected-point nil)
6962 (setq org-goto-exit-command 'quit)
6963 (throw 'exit nil))
6965 ;;; Indirect buffer display of subtrees
6967 (defvar org-indirect-dedicated-frame nil
6968 "This is the frame being used for indirect tree display.")
6969 (defvar org-last-indirect-buffer nil)
6971 (defun org-tree-to-indirect-buffer (&optional arg)
6972 "Create indirect buffer and narrow it to current subtree.
6973 With a numerical prefix ARG, go up to this level and then take that tree.
6974 If ARG is negative, go up that many levels.
6976 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6977 indirect buffer previously made with this command, to avoid proliferation of
6978 indirect buffers. However, when you call the command with a \
6979 \\[universal-argument] prefix, or
6980 when `org-indirect-buffer-display' is `new-frame', the last buffer
6981 is kept so that you can work with several indirect buffers at the same time.
6982 If `org-indirect-buffer-display' is `dedicated-frame', the \
6983 \\[universal-argument] prefix also
6984 requests that a new frame be made for the new buffer, so that the dedicated
6985 frame is not changed."
6986 (interactive "P")
6987 (let ((cbuf (current-buffer))
6988 (cwin (selected-window))
6989 (pos (point))
6990 beg end level heading ibuf)
6991 (save-excursion
6992 (org-back-to-heading t)
6993 (when (numberp arg)
6994 (setq level (org-outline-level))
6995 (if (< arg 0) (setq arg (+ level arg)))
6996 (while (> (setq level (org-outline-level)) arg)
6997 (org-up-heading-safe)))
6998 (setq beg (point)
6999 heading (org-get-heading))
7000 (org-end-of-subtree t t)
7001 (if (org-at-heading-p) (backward-char 1))
7002 (setq end (point)))
7003 (if (and (buffer-live-p org-last-indirect-buffer)
7004 (not (eq org-indirect-buffer-display 'new-frame))
7005 (not arg))
7006 (kill-buffer org-last-indirect-buffer))
7007 (setq ibuf (org-get-indirect-buffer cbuf)
7008 org-last-indirect-buffer ibuf)
7009 (cond
7010 ((or (eq org-indirect-buffer-display 'new-frame)
7011 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7012 (select-frame (make-frame))
7013 (delete-other-windows)
7014 (org-pop-to-buffer-same-window ibuf)
7015 (org-set-frame-title heading))
7016 ((eq org-indirect-buffer-display 'dedicated-frame)
7017 (raise-frame
7018 (select-frame (or (and org-indirect-dedicated-frame
7019 (frame-live-p org-indirect-dedicated-frame)
7020 org-indirect-dedicated-frame)
7021 (setq org-indirect-dedicated-frame (make-frame)))))
7022 (delete-other-windows)
7023 (org-pop-to-buffer-same-window ibuf)
7024 (org-set-frame-title (concat "Indirect: " heading)))
7025 ((eq org-indirect-buffer-display 'current-window)
7026 (org-pop-to-buffer-same-window ibuf))
7027 ((eq org-indirect-buffer-display 'other-window)
7028 (pop-to-buffer ibuf))
7029 (t (error "Invalid value")))
7030 (if (featurep 'xemacs)
7031 (save-excursion (org-mode) (turn-on-font-lock)))
7032 (narrow-to-region beg end)
7033 (show-all)
7034 (goto-char pos)
7035 (run-hook-with-args 'org-cycle-hook 'all)
7036 (and (window-live-p cwin) (select-window cwin))))
7038 (defun org-get-indirect-buffer (&optional buffer)
7039 (setq buffer (or buffer (current-buffer)))
7040 (let ((n 1) (base (buffer-name buffer)) bname)
7041 (while (buffer-live-p
7042 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7043 (setq n (1+ n)))
7044 (condition-case nil
7045 (make-indirect-buffer buffer bname 'clone)
7046 (error (make-indirect-buffer buffer bname)))))
7048 (defun org-set-frame-title (title)
7049 "Set the title of the current frame to the string TITLE."
7050 ;; FIXME: how to name a single frame in XEmacs???
7051 (unless (featurep 'xemacs)
7052 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7054 ;;;; Structure editing
7056 ;;; Inserting headlines
7058 (defun org-previous-line-empty-p ()
7059 (save-excursion
7060 (and (not (bobp))
7061 (or (beginning-of-line 0) t)
7062 (save-match-data
7063 (looking-at "[ \t]*$")))))
7065 (defun org-insert-heading (&optional force-heading invisible-ok)
7066 "Insert a new heading or item with same depth at point.
7067 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7068 If point is at the beginning of a headline, insert a sibling before the
7069 current headline. If point is not at the beginning, split the line,
7070 create the new headline with the text in the current line after point
7071 \(but see also the variable `org-M-RET-may-split-line').
7073 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7074 This is important for non-interactive uses of the command."
7075 (interactive "P")
7076 (if (or (= (buffer-size) 0)
7077 (and (not (save-excursion
7078 (and (ignore-errors (org-back-to-heading invisible-ok))
7079 (org-at-heading-p))))
7080 (or force-heading (not (org-in-item-p)))))
7081 (progn
7082 (insert "\n* ")
7083 (run-hooks 'org-insert-heading-hook))
7084 (when (or force-heading (not (org-insert-item)))
7085 (let* ((empty-line-p nil)
7086 (level nil)
7087 (on-heading (org-at-heading-p))
7088 (head (save-excursion
7089 (condition-case nil
7090 (progn
7091 (org-back-to-heading invisible-ok)
7092 (when (and (not on-heading)
7093 (featurep 'org-inlinetask)
7094 (integerp org-inlinetask-min-level)
7095 (>= (length (match-string 0))
7096 org-inlinetask-min-level))
7097 ;; Find a heading level before the inline task
7098 (while (and (setq level (org-up-heading-safe))
7099 (>= level org-inlinetask-min-level)))
7100 (if (org-at-heading-p)
7101 (org-back-to-heading invisible-ok)
7102 (error "This should not happen")))
7103 (setq empty-line-p (org-previous-line-empty-p))
7104 (match-string 0))
7105 (error "*"))))
7106 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7107 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7108 pos hide-previous previous-pos)
7109 (cond
7110 ((and (org-at-heading-p) (bolp)
7111 (or (bobp)
7112 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7113 ;; insert before the current line
7114 (open-line (if blank 2 1)))
7115 ((and (bolp)
7116 (not org-insert-heading-respect-content)
7117 (or (bobp)
7118 (save-excursion
7119 (backward-char 1) (not (outline-invisible-p)))))
7120 ;; insert right here
7121 nil)
7123 ;; somewhere in the line
7124 (save-excursion
7125 (setq previous-pos (point-at-bol))
7126 (end-of-line)
7127 (setq hide-previous (outline-invisible-p)))
7128 (and org-insert-heading-respect-content (org-show-subtree))
7129 (let ((split
7130 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7131 (save-excursion
7132 (let ((p (point)))
7133 (goto-char (point-at-bol))
7134 (and (looking-at org-complex-heading-regexp)
7135 (match-beginning 4)
7136 (> p (match-beginning 4)))))))
7137 tags pos)
7138 (cond
7139 (org-insert-heading-respect-content
7140 (org-end-of-subtree nil t)
7141 (when (featurep 'org-inlinetask)
7142 (while (and (not (eobp))
7143 (looking-at "\\(\\*+\\)[ \t]+")
7144 (>= (length (match-string 1))
7145 org-inlinetask-min-level))
7146 (org-end-of-subtree nil t)))
7147 (or (bolp) (newline))
7148 (or (org-previous-line-empty-p)
7149 (and blank (newline)))
7150 (open-line 1))
7151 ((org-at-heading-p)
7152 (when hide-previous
7153 (show-children)
7154 (org-show-entry))
7155 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7156 (setq tags (and (match-end 2) (match-string 2)))
7157 (and (match-end 1)
7158 (delete-region (match-beginning 1) (match-end 1)))
7159 (setq pos (point-at-bol))
7160 (or split (end-of-line 1))
7161 (delete-horizontal-space)
7162 (if (string-match "\\`\\*+\\'"
7163 (buffer-substring (point-at-bol) (point)))
7164 (insert " "))
7165 (newline (if blank 2 1))
7166 (when tags
7167 (save-excursion
7168 (goto-char pos)
7169 (end-of-line 1)
7170 (insert " " tags)
7171 (org-set-tags nil 'align))))
7173 (or split (end-of-line 1))
7174 (newline (if blank 2 1)))))))
7175 (insert head) (just-one-space)
7176 (setq pos (point))
7177 (end-of-line 1)
7178 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7179 (when (and org-insert-heading-respect-content hide-previous)
7180 (save-excursion
7181 (goto-char previous-pos)
7182 (hide-subtree)))
7183 (run-hooks 'org-insert-heading-hook)))))
7185 (defun org-get-heading (&optional no-tags no-todo)
7186 "Return the heading of the current entry, without the stars.
7187 When NO-TAGS is non-nil, don't include tags.
7188 When NO-TODO is non-nil, don't include TODO keywords."
7189 (save-excursion
7190 (org-back-to-heading t)
7191 (cond
7192 ((and no-tags no-todo)
7193 (looking-at org-complex-heading-regexp)
7194 (match-string 4))
7195 (no-tags
7196 (looking-at (concat org-outline-regexp
7197 "\\(.*?\\)"
7198 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7199 (match-string 1))
7200 (no-todo
7201 (looking-at org-todo-line-regexp)
7202 (match-string 3))
7203 (t (looking-at org-heading-regexp)
7204 (match-string 2)))))
7206 (defun org-heading-components ()
7207 "Return the components of the current heading.
7208 This is a list with the following elements:
7209 - the level as an integer
7210 - the reduced level, different if `org-odd-levels-only' is set.
7211 - the TODO keyword, or nil
7212 - the priority character, like ?A, or nil if no priority is given
7213 - the headline text itself, or the tags string if no headline text
7214 - the tags string, or nil."
7215 (save-excursion
7216 (org-back-to-heading t)
7217 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7218 (list (length (match-string 1))
7219 (org-reduced-level (length (match-string 1)))
7220 (org-match-string-no-properties 2)
7221 (and (match-end 3) (aref (match-string 3) 2))
7222 (org-match-string-no-properties 4)
7223 (org-match-string-no-properties 5)))))
7225 (defun org-get-entry ()
7226 "Get the entry text, after heading, entire subtree."
7227 (save-excursion
7228 (org-back-to-heading t)
7229 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7231 (defun org-insert-heading-after-current ()
7232 "Insert a new heading with same level as current, after current subtree."
7233 (interactive)
7234 (org-back-to-heading)
7235 (org-insert-heading)
7236 (org-move-subtree-down)
7237 (end-of-line 1))
7239 (defun org-insert-heading-respect-content (invisible-ok)
7240 "Insert heading with `org-insert-heading-respect-content' set to t."
7241 (interactive "P")
7242 (let ((org-insert-heading-respect-content t))
7243 (org-insert-heading t invisible-ok)))
7245 (defun org-insert-todo-heading-respect-content (&optional force-state)
7246 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7247 (interactive "P")
7248 (let ((org-insert-heading-respect-content t))
7249 (org-insert-todo-heading force-state t)))
7251 (defun org-insert-todo-heading (arg &optional force-heading)
7252 "Insert a new heading with the same level and TODO state as current heading.
7253 If the heading has no TODO state, or if the state is DONE, use the first
7254 state (TODO by default). Also with prefix arg, force first state."
7255 (interactive "P")
7256 (when (or force-heading (not (org-insert-item 'checkbox)))
7257 (org-insert-heading force-heading)
7258 (save-excursion
7259 (org-back-to-heading)
7260 (outline-previous-heading)
7261 (looking-at org-todo-line-regexp))
7262 (let*
7263 ((new-mark-x
7264 (if (or arg
7265 (not (match-beginning 2))
7266 (member (match-string 2) org-done-keywords))
7267 (car org-todo-keywords-1)
7268 (match-string 2)))
7269 (new-mark
7271 (run-hook-with-args-until-success
7272 'org-todo-get-default-hook new-mark-x nil)
7273 new-mark-x)))
7274 (beginning-of-line 1)
7275 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7276 (if org-treat-insert-todo-heading-as-state-change
7277 (org-todo new-mark)
7278 (insert new-mark " "))))
7279 (when org-provide-todo-statistics
7280 (org-update-parent-todo-statistics))))
7282 (defun org-insert-subheading (arg)
7283 "Insert a new subheading and demote it.
7284 Works for outline headings and for plain lists alike."
7285 (interactive "P")
7286 (org-insert-heading arg)
7287 (cond
7288 ((org-at-heading-p) (org-do-demote))
7289 ((org-at-item-p) (org-indent-item))))
7291 (defun org-insert-todo-subheading (arg)
7292 "Insert a new subheading with TODO keyword or checkbox and demote it.
7293 Works for outline headings and for plain lists alike."
7294 (interactive "P")
7295 (org-insert-todo-heading arg)
7296 (cond
7297 ((org-at-heading-p) (org-do-demote))
7298 ((org-at-item-p) (org-indent-item))))
7300 ;;; Promotion and Demotion
7302 (defvar org-after-demote-entry-hook nil
7303 "Hook run after an entry has been demoted.
7304 The cursor will be at the beginning of the entry.
7305 When a subtree is being demoted, the hook will be called for each node.")
7307 (defvar org-after-promote-entry-hook nil
7308 "Hook run after an entry has been promoted.
7309 The cursor will be at the beginning of the entry.
7310 When a subtree is being promoted, the hook will be called for each node.")
7312 (defun org-promote-subtree ()
7313 "Promote the entire subtree.
7314 See also `org-promote'."
7315 (interactive)
7316 (save-excursion
7317 (org-with-limited-levels (org-map-tree 'org-promote)))
7318 (org-fix-position-after-promote))
7320 (defun org-demote-subtree ()
7321 "Demote the entire subtree. See `org-demote'.
7322 See also `org-promote'."
7323 (interactive)
7324 (save-excursion
7325 (org-with-limited-levels (org-map-tree 'org-demote)))
7326 (org-fix-position-after-promote))
7329 (defun org-do-promote ()
7330 "Promote the current heading higher up the tree.
7331 If the region is active in `transient-mark-mode', promote all headings
7332 in the region."
7333 (interactive)
7334 (save-excursion
7335 (if (org-region-active-p)
7336 (org-map-region 'org-promote (region-beginning) (region-end))
7337 (org-promote)))
7338 (org-fix-position-after-promote))
7340 (defun org-do-demote ()
7341 "Demote the current heading lower down the tree.
7342 If the region is active in `transient-mark-mode', demote all headings
7343 in the region."
7344 (interactive)
7345 (save-excursion
7346 (if (org-region-active-p)
7347 (org-map-region 'org-demote (region-beginning) (region-end))
7348 (org-demote)))
7349 (org-fix-position-after-promote))
7351 (defun org-fix-position-after-promote ()
7352 "Make sure that after pro/demotion cursor position is right."
7353 (let ((pos (point)))
7354 (when (save-excursion
7355 (beginning-of-line 1)
7356 (looking-at org-todo-line-regexp)
7357 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7358 (cond ((eobp) (insert " "))
7359 ((eolp) (insert " "))
7360 ((equal (char-after) ?\ ) (forward-char 1))))))
7362 (defun org-current-level ()
7363 "Return the level of the current entry, or nil if before the first headline.
7364 The level is the number of stars at the beginning of the headline."
7365 (save-excursion
7366 (org-with-limited-levels
7367 (if (ignore-errors (org-back-to-heading t))
7368 (funcall outline-level)))))
7370 (defun org-get-previous-line-level ()
7371 "Return the outline depth of the last headline before the current line.
7372 Returns 0 for the first headline in the buffer, and nil if before the
7373 first headline."
7374 (let ((current-level (org-current-level))
7375 (prev-level (when (> (line-number-at-pos) 1)
7376 (save-excursion
7377 (beginning-of-line 0)
7378 (org-current-level)))))
7379 (cond ((null current-level) nil) ; Before first headline
7380 ((null prev-level) 0) ; At first headline
7381 (prev-level))))
7383 (defun org-reduced-level (l)
7384 "Compute the effective level of a heading.
7385 This takes into account the setting of `org-odd-levels-only'."
7386 (cond
7387 ((zerop l) 0)
7388 (org-odd-levels-only (1+ (floor (/ l 2))))
7389 (t l)))
7391 (defun org-level-increment ()
7392 "Return the number of stars that will be added or removed at a
7393 time to headlines when structure editing, based on the value of
7394 `org-odd-levels-only'."
7395 (if org-odd-levels-only 2 1))
7397 (defun org-get-valid-level (level &optional change)
7398 "Rectify a level change under the influence of `org-odd-levels-only'
7399 LEVEL is a current level, CHANGE is by how much the level should be
7400 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7401 even level numbers will become the next higher odd number."
7402 (if org-odd-levels-only
7403 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7404 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7405 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7406 (max 1 (+ level (or change 0)))))
7408 (if (boundp 'define-obsolete-function-alias)
7409 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7410 (define-obsolete-function-alias 'org-get-legal-level
7411 'org-get-valid-level)
7412 (define-obsolete-function-alias 'org-get-legal-level
7413 'org-get-valid-level "23.1")))
7415 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7416 ;; ̀org-with-limited-levels'
7417 (defun org-promote ()
7418 "Promote the current heading higher up the tree.
7419 If the region is active in `transient-mark-mode', promote all headings
7420 in the region."
7421 (org-back-to-heading t)
7422 (let* ((level (save-match-data (funcall outline-level)))
7423 (after-change-functions (remove 'flyspell-after-change-function
7424 after-change-functions))
7425 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7426 (diff (abs (- level (length up-head) -1))))
7427 (cond ((and (= level 1) org-called-with-limited-levels
7428 org-allow-promoting-top-level-subtree)
7429 (replace-match "# " nil t))
7430 ((= level 1)
7431 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7432 (t (replace-match up-head nil t)))
7433 ;; Fixup tag positioning
7434 (unless (= level 1)
7435 (and org-auto-align-tags (org-set-tags nil t))
7436 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7437 (run-hooks 'org-after-promote-entry-hook)))
7439 (defun org-demote ()
7440 "Demote the current heading lower down the tree.
7441 If the region is active in `transient-mark-mode', demote all headings
7442 in the region."
7443 (org-back-to-heading t)
7444 (let* ((level (save-match-data (funcall outline-level)))
7445 (after-change-functions (remove 'flyspell-after-change-function
7446 after-change-functions))
7447 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7448 (diff (abs (- level (length down-head) -1))))
7449 (replace-match down-head nil t)
7450 ;; Fixup tag positioning
7451 (and org-auto-align-tags (org-set-tags nil t))
7452 (if org-adapt-indentation (org-fixup-indentation diff))
7453 (run-hooks 'org-after-demote-entry-hook)))
7455 (defun org-cycle-level ()
7456 "Cycle the level of an empty headline through possible states.
7457 This goes first to child, then to parent, level, then up the hierarchy.
7458 After top level, it switches back to sibling level."
7459 (interactive)
7460 (let ((org-adapt-indentation nil))
7461 (when (org-point-at-end-of-empty-headline)
7462 (setq this-command 'org-cycle-level) ; Only needed for caching
7463 (let ((cur-level (org-current-level))
7464 (prev-level (org-get-previous-line-level)))
7465 (cond
7466 ;; If first headline in file, promote to top-level.
7467 ((= prev-level 0)
7468 (loop repeat (/ (- cur-level 1) (org-level-increment))
7469 do (org-do-promote)))
7470 ;; If same level as prev, demote one.
7471 ((= prev-level cur-level)
7472 (org-do-demote))
7473 ;; If parent is top-level, promote to top level if not already.
7474 ((= prev-level 1)
7475 (loop repeat (/ (- cur-level 1) (org-level-increment))
7476 do (org-do-promote)))
7477 ;; If top-level, return to prev-level.
7478 ((= cur-level 1)
7479 (loop repeat (/ (- prev-level 1) (org-level-increment))
7480 do (org-do-demote)))
7481 ;; If less than prev-level, promote one.
7482 ((< cur-level prev-level)
7483 (org-do-promote))
7484 ;; If deeper than prev-level, promote until higher than
7485 ;; prev-level.
7486 ((> cur-level prev-level)
7487 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7488 do (org-do-promote))))
7489 t))))
7491 (defun org-map-tree (fun)
7492 "Call FUN for every heading underneath the current one."
7493 (org-back-to-heading)
7494 (let ((level (funcall outline-level)))
7495 (save-excursion
7496 (funcall fun)
7497 (while (and (progn
7498 (outline-next-heading)
7499 (> (funcall outline-level) level))
7500 (not (eobp)))
7501 (funcall fun)))))
7503 (defun org-map-region (fun beg end)
7504 "Call FUN for every heading between BEG and END."
7505 (let ((org-ignore-region t))
7506 (save-excursion
7507 (setq end (copy-marker end))
7508 (goto-char beg)
7509 (if (and (re-search-forward org-outline-regexp-bol nil t)
7510 (< (point) end))
7511 (funcall fun))
7512 (while (and (progn
7513 (outline-next-heading)
7514 (< (point) end))
7515 (not (eobp)))
7516 (funcall fun)))))
7518 (defvar org-property-end-re) ; silence byte-compiler
7519 (defun org-fixup-indentation (diff)
7520 "Change the indentation in the current entry by DIFF.
7521 However, if any line in the current entry has no indentation, or if it
7522 would end up with no indentation after the change, nothing at all is done."
7523 (save-excursion
7524 (let ((end (save-excursion (outline-next-heading)
7525 (point-marker)))
7526 (prohibit (if (> diff 0)
7527 "^\\S-"
7528 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7529 col)
7530 (unless (save-excursion (end-of-line 1)
7531 (re-search-forward prohibit end t))
7532 (while (and (< (point) end)
7533 (re-search-forward "^[ \t]+" end t))
7534 (goto-char (match-end 0))
7535 (setq col (current-column))
7536 (if (< diff 0) (replace-match ""))
7537 (org-indent-to-column (+ diff col))))
7538 (move-marker end nil))))
7540 (defun org-convert-to-odd-levels ()
7541 "Convert an org-mode file with all levels allowed to one with odd levels.
7542 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7543 level 5 etc."
7544 (interactive)
7545 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7546 (let ((outline-level 'org-outline-level)
7547 (org-odd-levels-only nil) n)
7548 (save-excursion
7549 (goto-char (point-min))
7550 (while (re-search-forward "^\\*\\*+ " nil t)
7551 (setq n (- (length (match-string 0)) 2))
7552 (while (>= (setq n (1- n)) 0)
7553 (org-demote))
7554 (end-of-line 1))))))
7556 (defun org-convert-to-oddeven-levels ()
7557 "Convert an org-mode file with only odd levels to one with odd/even levels.
7558 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7559 file contains a section with an even level, conversion would
7560 destroy the structure of the file. An error is signaled in this
7561 case."
7562 (interactive)
7563 (goto-char (point-min))
7564 ;; First check if there are no even levels
7565 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7566 (org-show-context t)
7567 (error "Not all levels are odd in this file. Conversion not possible"))
7568 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7569 (let ((outline-regexp org-outline-regexp)
7570 (outline-level 'org-outline-level)
7571 (org-odd-levels-only nil) n)
7572 (save-excursion
7573 (goto-char (point-min))
7574 (while (re-search-forward "^\\*\\*+ " nil t)
7575 (setq n (/ (1- (length (match-string 0))) 2))
7576 (while (>= (setq n (1- n)) 0)
7577 (org-promote))
7578 (end-of-line 1))))))
7580 (defun org-tr-level (n)
7581 "Make N odd if required."
7582 (if org-odd-levels-only (1+ (/ n 2)) n))
7584 ;;; Vertical tree motion, cutting and pasting of subtrees
7586 (defun org-move-subtree-up (&optional arg)
7587 "Move the current subtree up past ARG headlines of the same level."
7588 (interactive "p")
7589 (org-move-subtree-down (- (prefix-numeric-value arg))))
7591 (defun org-move-subtree-down (&optional arg)
7592 "Move the current subtree down past ARG headlines of the same level."
7593 (interactive "p")
7594 (setq arg (prefix-numeric-value arg))
7595 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7596 'org-get-last-sibling))
7597 (ins-point (make-marker))
7598 (cnt (abs arg))
7599 (col (current-column))
7600 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7601 ;; Select the tree
7602 (org-back-to-heading)
7603 (setq beg0 (point))
7604 (save-excursion
7605 (setq ne-beg (org-back-over-empty-lines))
7606 (setq beg (point)))
7607 (save-match-data
7608 (save-excursion (outline-end-of-heading)
7609 (setq folded (outline-invisible-p)))
7610 (outline-end-of-subtree))
7611 (outline-next-heading)
7612 (setq ne-end (org-back-over-empty-lines))
7613 (setq end (point))
7614 (goto-char beg0)
7615 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7616 ;; include less whitespace
7617 (save-excursion
7618 (goto-char beg)
7619 (forward-line (- ne-beg ne-end))
7620 (setq beg (point))))
7621 ;; Find insertion point, with error handling
7622 (while (> cnt 0)
7623 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7624 (progn (goto-char beg0)
7625 (error "Cannot move past superior level or buffer limit")))
7626 (setq cnt (1- cnt)))
7627 (if (> arg 0)
7628 ;; Moving forward - still need to move over subtree
7629 (progn (org-end-of-subtree t t)
7630 (save-excursion
7631 (org-back-over-empty-lines)
7632 (or (bolp) (newline)))))
7633 (setq ne-ins (org-back-over-empty-lines))
7634 (move-marker ins-point (point))
7635 (setq txt (buffer-substring beg end))
7636 (org-save-markers-in-region beg end)
7637 (delete-region beg end)
7638 (org-remove-empty-overlays-at beg)
7639 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7640 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7641 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7642 (let ((bbb (point)))
7643 (insert-before-markers txt)
7644 (org-reinstall-markers-in-region bbb)
7645 (move-marker ins-point bbb))
7646 (or (bolp) (insert "\n"))
7647 (setq ins-end (point))
7648 (goto-char ins-point)
7649 (org-skip-whitespace)
7650 (when (and (< arg 0)
7651 (org-first-sibling-p)
7652 (> ne-ins ne-beg))
7653 ;; Move whitespace back to beginning
7654 (save-excursion
7655 (goto-char ins-end)
7656 (let ((kill-whole-line t))
7657 (kill-line (- ne-ins ne-beg)) (point)))
7658 (insert (make-string (- ne-ins ne-beg) ?\n)))
7659 (move-marker ins-point nil)
7660 (if folded
7661 (hide-subtree)
7662 (org-show-entry)
7663 (show-children)
7664 (org-cycle-hide-drawers 'children))
7665 (org-clean-visibility-after-subtree-move)
7666 ;; move back to the initial column we were at
7667 (move-to-column col)))
7669 (defvar org-subtree-clip ""
7670 "Clipboard for cut and paste of subtrees.
7671 This is actually only a copy of the kill, because we use the normal kill
7672 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7674 (defvar org-subtree-clip-folded nil
7675 "Was the last copied subtree folded?
7676 This is used to fold the tree back after pasting.")
7678 (defun org-cut-subtree (&optional n)
7679 "Cut the current subtree into the clipboard.
7680 With prefix arg N, cut this many sequential subtrees.
7681 This is a short-hand for marking the subtree and then cutting it."
7682 (interactive "p")
7683 (org-copy-subtree n 'cut))
7685 (defun org-copy-subtree (&optional n cut force-store-markers)
7686 "Cut the current subtree into the clipboard.
7687 With prefix arg N, cut this many sequential subtrees.
7688 This is a short-hand for marking the subtree and then copying it.
7689 If CUT is non-nil, actually cut the subtree.
7690 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7691 of some markers in the region, even if CUT is non-nil. This is
7692 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7693 (interactive "p")
7694 (let (beg end folded (beg0 (point)))
7695 (if (org-called-interactively-p 'any)
7696 (org-back-to-heading nil) ; take what looks like a subtree
7697 (org-back-to-heading t)) ; take what is really there
7698 (setq beg (point))
7699 (skip-chars-forward " \t\r\n")
7700 (save-match-data
7701 (save-excursion (outline-end-of-heading)
7702 (setq folded (outline-invisible-p)))
7703 (condition-case nil
7704 (org-forward-heading-same-level (1- n) t)
7705 (error nil))
7706 (org-end-of-subtree t t))
7707 (setq end (point))
7708 (goto-char beg0)
7709 (when (> end beg)
7710 (setq org-subtree-clip-folded folded)
7711 (when (or cut force-store-markers)
7712 (org-save-markers-in-region beg end))
7713 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7714 (setq org-subtree-clip (current-kill 0))
7715 (message "%s: Subtree(s) with %d characters"
7716 (if cut "Cut" "Copied")
7717 (length org-subtree-clip)))))
7719 (defun org-paste-subtree (&optional level tree for-yank)
7720 "Paste the clipboard as a subtree, with modification of headline level.
7721 The entire subtree is promoted or demoted in order to match a new headline
7722 level.
7724 If the cursor is at the beginning of a headline, the same level as
7725 that headline is used to paste the tree
7727 If not, the new level is derived from the *visible* headings
7728 before and after the insertion point, and taken to be the inferior headline
7729 level of the two. So if the previous visible heading is level 3 and the
7730 next is level 4 (or vice versa), level 4 will be used for insertion.
7731 This makes sure that the subtree remains an independent subtree and does
7732 not swallow low level entries.
7734 You can also force a different level, either by using a numeric prefix
7735 argument, or by inserting the heading marker by hand. For example, if the
7736 cursor is after \"*****\", then the tree will be shifted to level 5.
7738 If optional TREE is given, use this text instead of the kill ring.
7740 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7741 move back over whitespace before inserting, and move point to the end of
7742 the inserted text when done."
7743 (interactive "P")
7744 (setq tree (or tree (and kill-ring (current-kill 0))))
7745 (unless (org-kill-is-subtree-p tree)
7746 (error "%s"
7747 (substitute-command-keys
7748 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7749 (org-with-limited-levels
7750 (let* ((visp (not (outline-invisible-p)))
7751 (txt tree)
7752 (^re_ "\\(\\*+\\)[ \t]*")
7753 (old-level (if (string-match org-outline-regexp-bol txt)
7754 (- (match-end 0) (match-beginning 0) 1)
7755 -1))
7756 (force-level (cond (level (prefix-numeric-value level))
7757 ((and (looking-at "[ \t]*$")
7758 (string-match
7759 "^\\*+$" (buffer-substring
7760 (point-at-bol) (point))))
7761 (- (match-end 1) (match-beginning 1)))
7762 ((and (bolp)
7763 (looking-at org-outline-regexp))
7764 (- (match-end 0) (point) 1))))
7765 (previous-level (save-excursion
7766 (condition-case nil
7767 (progn
7768 (outline-previous-visible-heading 1)
7769 (if (looking-at ^re_)
7770 (- (match-end 0) (match-beginning 0) 1)
7772 (error 1))))
7773 (next-level (save-excursion
7774 (condition-case nil
7775 (progn
7776 (or (looking-at org-outline-regexp)
7777 (outline-next-visible-heading 1))
7778 (if (looking-at ^re_)
7779 (- (match-end 0) (match-beginning 0) 1)
7781 (error 1))))
7782 (new-level (or force-level (max previous-level next-level)))
7783 (shift (if (or (= old-level -1)
7784 (= new-level -1)
7785 (= old-level new-level))
7787 (- new-level old-level)))
7788 (delta (if (> shift 0) -1 1))
7789 (func (if (> shift 0) 'org-demote 'org-promote))
7790 (org-odd-levels-only nil)
7791 beg end newend)
7792 ;; Remove the forced level indicator
7793 (if force-level
7794 (delete-region (point-at-bol) (point)))
7795 ;; Paste
7796 (beginning-of-line (if (bolp) 1 2))
7797 (setq beg (point))
7798 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7799 (insert-before-markers txt)
7800 (unless (string-match "\n\\'" txt) (insert "\n"))
7801 (setq newend (point))
7802 (org-reinstall-markers-in-region beg)
7803 (setq end (point))
7804 (goto-char beg)
7805 (skip-chars-forward " \t\n\r")
7806 (setq beg (point))
7807 (if (and (outline-invisible-p) visp)
7808 (save-excursion (outline-show-heading)))
7809 ;; Shift if necessary
7810 (unless (= shift 0)
7811 (save-restriction
7812 (narrow-to-region beg end)
7813 (while (not (= shift 0))
7814 (org-map-region func (point-min) (point-max))
7815 (setq shift (+ delta shift)))
7816 (goto-char (point-min))
7817 (setq newend (point-max))))
7818 (when (or (org-called-interactively-p 'interactive) for-yank)
7819 (message "Clipboard pasted as level %d subtree" new-level))
7820 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7821 kill-ring
7822 (eq org-subtree-clip (current-kill 0))
7823 org-subtree-clip-folded)
7824 ;; The tree was folded before it was killed/copied
7825 (hide-subtree))
7826 (and for-yank (goto-char newend)))))
7828 (defun org-kill-is-subtree-p (&optional txt)
7829 "Check if the current kill is an outline subtree, or a set of trees.
7830 Returns nil if kill does not start with a headline, or if the first
7831 headline level is not the largest headline level in the tree.
7832 So this will actually accept several entries of equal levels as well,
7833 which is OK for `org-paste-subtree'.
7834 If optional TXT is given, check this string instead of the current kill."
7835 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7836 (re (org-get-limited-outline-regexp))
7837 (^re (concat "^" re))
7838 (start-level (and kill
7839 (string-match
7840 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7841 kill)
7842 (- (match-end 2) (match-beginning 2) 1)))
7843 (start (1+ (or (match-beginning 2) -1))))
7844 (if (not start-level)
7845 (progn
7846 nil) ;; does not even start with a heading
7847 (catch 'exit
7848 (while (setq start (string-match ^re kill (1+ start)))
7849 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7850 (throw 'exit nil)))
7851 t))))
7853 (defvar org-markers-to-move nil
7854 "Markers that should be moved with a cut-and-paste operation.
7855 Those markers are stored together with their positions relative to
7856 the start of the region.")
7858 (defun org-save-markers-in-region (beg end)
7859 "Check markers in region.
7860 If these markers are between BEG and END, record their position relative
7861 to BEG, so that after moving the block of text, we can put the markers back
7862 into place.
7863 This function gets called just before an entry or tree gets cut from the
7864 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7865 called immediately, to move the markers with the entries."
7866 (setq org-markers-to-move nil)
7867 (when (featurep 'org-clock)
7868 (org-clock-save-markers-for-cut-and-paste beg end))
7869 (when (featurep 'org-agenda)
7870 (org-agenda-save-markers-for-cut-and-paste beg end)))
7872 (defun org-check-and-save-marker (marker beg end)
7873 "Check if MARKER is between BEG and END.
7874 If yes, remember the marker and the distance to BEG."
7875 (when (and (marker-buffer marker)
7876 (equal (marker-buffer marker) (current-buffer)))
7877 (if (and (>= marker beg) (< marker end))
7878 (push (cons marker (- marker beg)) org-markers-to-move))))
7880 (defun org-reinstall-markers-in-region (beg)
7881 "Move all remembered markers to their position relative to BEG."
7882 (mapc (lambda (x)
7883 (move-marker (car x) (+ beg (cdr x))))
7884 org-markers-to-move)
7885 (setq org-markers-to-move nil))
7887 (defun org-narrow-to-subtree ()
7888 "Narrow buffer to the current subtree."
7889 (interactive)
7890 (save-excursion
7891 (save-match-data
7892 (org-with-limited-levels
7893 (narrow-to-region
7894 (progn (org-back-to-heading t) (point))
7895 (progn (org-end-of-subtree t t)
7896 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7897 (point)))))))
7899 (defun org-narrow-to-block ()
7900 "Narrow buffer to the current block."
7901 (interactive)
7902 (let* ((case-fold-search t)
7903 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7904 "^[ \t]*#\\+end_.*")))
7905 (if blockp
7906 (narrow-to-region (car blockp) (cdr blockp))
7907 (error "Not in a block"))))
7909 (eval-when-compile
7910 (defvar org-property-drawer-re))
7912 (defvar org-property-start-re) ;; defined below
7913 (defun org-clone-subtree-with-time-shift (n &optional shift)
7914 "Clone the task (subtree) at point N times.
7915 The clones will be inserted as siblings.
7917 In interactive use, the user will be prompted for the number of
7918 clones to be produced, and for a time SHIFT, which may be a
7919 repeater as used in time stamps, for example `+3d'.
7921 When a valid repeater is given and the entry contains any time
7922 stamps, the clones will become a sequence in time, with time
7923 stamps in the subtree shifted for each clone produced. If SHIFT
7924 is nil or the empty string, time stamps will be left alone. The
7925 ID property of the original subtree is removed.
7927 If the original subtree did contain time stamps with a repeater,
7928 the following will happen:
7929 - the repeater will be removed in each clone
7930 - an additional clone will be produced, with the current, unshifted
7931 date(s) in the entry.
7932 - the original entry will be placed *after* all the clones, with
7933 repeater intact.
7934 - the start days in the repeater in the original entry will be shifted
7935 to past the last clone.
7936 In this way you can spell out a number of instances of a repeating task,
7937 and still retain the repeater to cover future instances of the task."
7938 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7939 (let (beg end template task idprop
7940 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7941 (drawer-re org-drawer-regexp))
7942 (if (not (and (integerp n) (> n 0)))
7943 (error "Invalid number of replications %s" n))
7944 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7945 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7946 shift)))
7947 (error "Invalid shift specification %s" shift))
7948 (when doshift
7949 (setq shift-n (string-to-number (match-string 1 shift))
7950 shift-what (cdr (assoc (match-string 2 shift)
7951 '(("d" . day) ("w" . week)
7952 ("m" . month) ("y" . year))))))
7953 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7954 (setq nmin 1 nmax n)
7955 (org-back-to-heading t)
7956 (setq beg (point))
7957 (setq idprop (org-entry-get nil "ID"))
7958 (org-end-of-subtree t t)
7959 (or (bolp) (insert "\n"))
7960 (setq end (point))
7961 (setq template (buffer-substring beg end))
7962 (when (and doshift
7963 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7964 (delete-region beg end)
7965 (setq end beg)
7966 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7967 (goto-char end)
7968 (loop for n from nmin to nmax do
7969 ;; prepare clone
7970 (with-temp-buffer
7971 (insert template)
7972 (org-mode)
7973 (goto-char (point-min))
7974 (org-show-subtree)
7975 (and idprop (if org-clone-delete-id
7976 (org-entry-delete nil "ID")
7977 (org-id-get-create t)))
7978 (unless (= n 0)
7979 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7980 (kill-whole-line))
7981 (goto-char (point-min))
7982 (while (re-search-forward drawer-re nil t)
7983 (mapc (lambda (d)
7984 (org-remove-empty-drawer-at d (point))) org-drawers)))
7985 (goto-char (point-min))
7986 (when doshift
7987 (while (re-search-forward org-ts-regexp-both nil t)
7988 (org-timestamp-change (* n shift-n) shift-what))
7989 (unless (= n n-no-remove)
7990 (goto-char (point-min))
7991 (while (re-search-forward org-ts-regexp nil t)
7992 (save-excursion
7993 (goto-char (match-beginning 0))
7994 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7995 (delete-region (match-beginning 1) (match-end 1)))))))
7996 (setq task (buffer-string)))
7997 (insert task))
7998 (goto-char beg)))
8000 ;;; Outline Sorting
8002 (defun org-sort (with-case)
8003 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8004 Optional argument WITH-CASE means sort case-sensitively."
8005 (interactive "P")
8006 (cond
8007 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8008 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8010 (org-call-with-arg 'org-sort-entries with-case))))
8012 (defun org-sort-remove-invisible (s)
8013 (remove-text-properties 0 (length s) org-rm-props s)
8014 (while (string-match org-bracket-link-regexp s)
8015 (setq s (replace-match (if (match-end 2)
8016 (match-string 3 s)
8017 (match-string 1 s)) t t s)))
8020 (defvar org-priority-regexp) ; defined later in the file
8022 (defvar org-after-sorting-entries-or-items-hook nil
8023 "Hook that is run after a bunch of entries or items have been sorted.
8024 When children are sorted, the cursor is in the parent line when this
8025 hook gets called. When a region or a plain list is sorted, the cursor
8026 will be in the first entry of the sorted region/list.")
8028 (defun org-sort-entries
8029 (&optional with-case sorting-type getkey-func compare-func property)
8030 "Sort entries on a certain level of an outline tree.
8031 If there is an active region, the entries in the region are sorted.
8032 Else, if the cursor is before the first entry, sort the top-level items.
8033 Else, the children of the entry at point are sorted.
8035 Sorting can be alphabetically, numerically, by date/time as given by
8036 a time stamp, by a property or by priority.
8038 The command prompts for the sorting type unless it has been given to the
8039 function through the SORTING-TYPE argument, which needs to be a character,
8040 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8041 precise meaning of each character:
8043 n Numerically, by converting the beginning of the entry/item to a number.
8044 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8045 o By order of TODO keywords.
8046 t By date/time, either the first active time stamp in the entry, or, if
8047 none exist, by the first inactive one.
8048 s By the scheduled date/time.
8049 d By deadline date/time.
8050 c By creation time, which is assumed to be the first inactive time stamp
8051 at the beginning of a line.
8052 p By priority according to the cookie.
8053 r By the value of a property.
8055 Capital letters will reverse the sort order.
8057 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8058 called with point at the beginning of the record. It must return either
8059 a string or a number that should serve as the sorting key for that record.
8061 Comparing entries ignores case by default. However, with an optional argument
8062 WITH-CASE, the sorting considers case as well."
8063 (interactive "P")
8064 (let ((case-func (if with-case 'identity 'downcase))
8065 (cmstr
8066 ;; The clock marker is lost when using `sort-subr', let's
8067 ;; store the clocking string.
8068 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8069 (save-excursion
8070 (goto-char org-clock-marker)
8071 (looking-back "^.*") (match-string-no-properties 0))))
8072 start beg end stars re re2
8073 txt what tmp)
8074 ;; Find beginning and end of region to sort
8075 (cond
8076 ((org-region-active-p)
8077 ;; we will sort the region
8078 (setq end (region-end)
8079 what "region")
8080 (goto-char (region-beginning))
8081 (if (not (org-at-heading-p)) (outline-next-heading))
8082 (setq start (point)))
8083 ((or (org-at-heading-p)
8084 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8085 ;; we will sort the children of the current headline
8086 (org-back-to-heading)
8087 (setq start (point)
8088 end (progn (org-end-of-subtree t t)
8089 (or (bolp) (insert "\n"))
8090 (org-back-over-empty-lines)
8091 (point))
8092 what "children")
8093 (goto-char start)
8094 (show-subtree)
8095 (outline-next-heading))
8097 ;; we will sort the top-level entries in this file
8098 (goto-char (point-min))
8099 (or (org-at-heading-p) (outline-next-heading))
8100 (setq start (point))
8101 (goto-char (point-max))
8102 (beginning-of-line 1)
8103 (when (looking-at ".*?\\S-")
8104 ;; File ends in a non-white line
8105 (end-of-line 1)
8106 (insert "\n"))
8107 (setq end (point-max))
8108 (setq what "top-level")
8109 (goto-char start)
8110 (show-all)))
8112 (setq beg (point))
8113 (if (>= beg end) (error "Nothing to sort"))
8115 (looking-at "\\(\\*+\\)")
8116 (setq stars (match-string 1)
8117 re (concat "^" (regexp-quote stars) " +")
8118 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8119 txt (buffer-substring beg end))
8120 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8121 (if (and (not (equal stars "*")) (string-match re2 txt))
8122 (error "Region to sort contains a level above the first entry"))
8124 (unless sorting-type
8125 (message
8126 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8127 [t]ime [s]cheduled [d]eadline [c]reated
8128 A/N/P/R/O/F/T/S/D/C means reversed:"
8129 what)
8130 (setq sorting-type (read-char-exclusive))
8132 (and (= (downcase sorting-type) ?f)
8133 (setq getkey-func
8134 (org-icompleting-read "Sort using function: "
8135 obarray 'fboundp t nil nil))
8136 (setq getkey-func (intern getkey-func)))
8138 (and (= (downcase sorting-type) ?r)
8139 (setq property
8140 (org-icompleting-read "Property: "
8141 (mapcar 'list (org-buffer-property-keys t))
8142 nil t))))
8144 (message "Sorting entries...")
8146 (save-restriction
8147 (narrow-to-region start end)
8148 (let ((dcst (downcase sorting-type))
8149 (case-fold-search nil)
8150 (now (current-time)))
8151 (sort-subr
8152 (/= dcst sorting-type)
8153 ;; This function moves to the beginning character of the "record" to
8154 ;; be sorted.
8155 (lambda nil
8156 (if (re-search-forward re nil t)
8157 (goto-char (match-beginning 0))
8158 (goto-char (point-max))))
8159 ;; This function moves to the last character of the "record" being
8160 ;; sorted.
8161 (lambda nil
8162 (save-match-data
8163 (condition-case nil
8164 (outline-forward-same-level 1)
8165 (error
8166 (goto-char (point-max))))))
8167 ;; This function returns the value that gets sorted against.
8168 (lambda nil
8169 (cond
8170 ((= dcst ?n)
8171 (if (looking-at org-complex-heading-regexp)
8172 (string-to-number (match-string 4))
8173 nil))
8174 ((= dcst ?a)
8175 (if (looking-at org-complex-heading-regexp)
8176 (funcall case-func (match-string 4))
8177 nil))
8178 ((= dcst ?t)
8179 (let ((end (save-excursion (outline-next-heading) (point))))
8180 (if (or (re-search-forward org-ts-regexp end t)
8181 (re-search-forward org-ts-regexp-both end t))
8182 (org-time-string-to-seconds (match-string 0))
8183 (org-float-time now))))
8184 ((= dcst ?c)
8185 (let ((end (save-excursion (outline-next-heading) (point))))
8186 (if (re-search-forward
8187 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8188 end t)
8189 (org-time-string-to-seconds (match-string 0))
8190 (org-float-time now))))
8191 ((= dcst ?s)
8192 (let ((end (save-excursion (outline-next-heading) (point))))
8193 (if (re-search-forward org-scheduled-time-regexp end t)
8194 (org-time-string-to-seconds (match-string 1))
8195 (org-float-time now))))
8196 ((= dcst ?d)
8197 (let ((end (save-excursion (outline-next-heading) (point))))
8198 (if (re-search-forward org-deadline-time-regexp end t)
8199 (org-time-string-to-seconds (match-string 1))
8200 (org-float-time now))))
8201 ((= dcst ?p)
8202 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8203 (string-to-char (match-string 2))
8204 org-default-priority))
8205 ((= dcst ?r)
8206 (or (org-entry-get nil property) ""))
8207 ((= dcst ?o)
8208 (if (looking-at org-complex-heading-regexp)
8209 (- 9999 (length (member (match-string 2)
8210 org-todo-keywords-1)))))
8211 ((= dcst ?f)
8212 (if getkey-func
8213 (progn
8214 (setq tmp (funcall getkey-func))
8215 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8216 tmp)
8217 (error "Invalid key function `%s'" getkey-func)))
8218 (t (error "Invalid sorting type `%c'" sorting-type))))
8220 (cond
8221 ((= dcst ?a) 'string<)
8222 ((= dcst ?f) compare-func)
8223 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8224 (run-hooks 'org-after-sorting-entries-or-items-hook)
8225 ;; Reset the clock marker if needed
8226 (when cmstr
8227 (save-excursion
8228 (goto-char start)
8229 (search-forward cmstr nil t)
8230 (move-marker org-clock-marker (point))))
8231 (message "Sorting entries...done")))
8233 (defun org-do-sort (table what &optional with-case sorting-type)
8234 "Sort TABLE of WHAT according to SORTING-TYPE.
8235 The user will be prompted for the SORTING-TYPE if the call to this
8236 function does not specify it. WHAT is only for the prompt, to indicate
8237 what is being sorted. The sorting key will be extracted from
8238 the car of the elements of the table.
8239 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8240 (unless sorting-type
8241 (message
8242 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8243 what)
8244 (setq sorting-type (read-char-exclusive)))
8245 (let ((dcst (downcase sorting-type))
8246 extractfun comparefun)
8247 ;; Define the appropriate functions
8248 (cond
8249 ((= dcst ?n)
8250 (setq extractfun 'string-to-number
8251 comparefun (if (= dcst sorting-type) '< '>)))
8252 ((= dcst ?a)
8253 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8254 (lambda(x) (downcase (org-sort-remove-invisible x))))
8255 comparefun (if (= dcst sorting-type)
8256 'string<
8257 (lambda (a b) (and (not (string< a b))
8258 (not (string= a b)))))))
8259 ((= dcst ?t)
8260 (setq extractfun
8261 (lambda (x)
8262 (if (or (string-match org-ts-regexp x)
8263 (string-match org-ts-regexp-both x))
8264 (org-float-time
8265 (org-time-string-to-time (match-string 0 x)))
8267 comparefun (if (= dcst sorting-type) '< '>)))
8268 (t (error "Invalid sorting type `%c'" sorting-type)))
8270 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8271 table)
8272 (lambda (a b) (funcall comparefun (car a) (car b))))))
8275 ;;; The orgstruct minor mode
8277 ;; Define a minor mode which can be used in other modes in order to
8278 ;; integrate the org-mode structure editing commands.
8280 ;; This is really a hack, because the org-mode structure commands use
8281 ;; keys which normally belong to the major mode. Here is how it
8282 ;; works: The minor mode defines all the keys necessary to operate the
8283 ;; structure commands, but wraps the commands into a function which
8284 ;; tests if the cursor is currently at a headline or a plain list
8285 ;; item. If that is the case, the structure command is used,
8286 ;; temporarily setting many Org-mode variables like regular
8287 ;; expressions for filling etc. However, when any of those keys is
8288 ;; used at a different location, function uses `key-binding' to look
8289 ;; up if the key has an associated command in another currently active
8290 ;; keymap (minor modes, major mode, global), and executes that
8291 ;; command. There might be problems if any of the keys is otherwise
8292 ;; used as a prefix key.
8294 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8295 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8296 ;; addresses this by checking explicitly for both bindings.
8298 (defvar orgstruct-mode-map (make-sparse-keymap)
8299 "Keymap for the minor `orgstruct-mode'.")
8301 (defvar org-local-vars nil
8302 "List of local variables, for use by `orgstruct-mode'.")
8304 ;;;###autoload
8305 (define-minor-mode orgstruct-mode
8306 "Toggle the minor mode `orgstruct-mode'.
8307 This mode is for using Org-mode structure commands in other
8308 modes. The following keys behave as if Org-mode were active, if
8309 the cursor is on a headline, or on a plain list item (both as
8310 defined by Org-mode).
8312 M-up Move entry/item up
8313 M-down Move entry/item down
8314 M-left Promote
8315 M-right Demote
8316 M-S-up Move entry/item up
8317 M-S-down Move entry/item down
8318 M-S-left Promote subtree
8319 M-S-right Demote subtree
8320 M-q Fill paragraph and items like in Org-mode
8321 C-c ^ Sort entries
8322 C-c - Cycle list bullet
8323 TAB Cycle item visibility
8324 M-RET Insert new heading/item
8325 S-M-RET Insert new TODO heading / Checkbox item
8326 C-c C-c Set tags / toggle checkbox"
8327 nil " OrgStruct" nil
8328 (org-load-modules-maybe)
8329 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8331 ;;;###autoload
8332 (defun turn-on-orgstruct ()
8333 "Unconditionally turn on `orgstruct-mode'."
8334 (orgstruct-mode 1))
8336 (defvar org-fb-vars nil)
8337 (make-variable-buffer-local 'org-fb-vars)
8338 (defun orgstruct++-mode (&optional arg)
8339 "Toggle `orgstruct-mode', the enhanced version of it.
8340 In addition to setting orgstruct-mode, this also exports all
8341 indentation and autofilling variables from org-mode into the
8342 buffer. It will also recognize item context in multiline items."
8343 (interactive "P")
8344 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8345 (if (< arg 1)
8346 (progn (orgstruct-mode -1)
8347 (mapc (lambda(v)
8348 (org-set-local (car v)
8349 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8350 org-fb-vars))
8351 (orgstruct-mode 1)
8352 (setq org-fb-vars nil)
8353 (let (var val)
8354 (mapc
8355 (lambda (x)
8356 (when (string-match
8357 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8358 (symbol-name (car x)))
8359 (setq var (car x) val (nth 1 x))
8360 (push (list var `(quote ,(eval var))) org-fb-vars)
8361 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8362 org-local-vars)
8363 (org-set-local 'orgstruct-is-++ t))))
8365 (defvar orgstruct-is-++ nil
8366 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8367 (make-variable-buffer-local 'orgstruct-is-++)
8369 ;;;###autoload
8370 (defun turn-on-orgstruct++ ()
8371 "Unconditionally turn on `orgstruct++-mode'."
8372 (orgstruct++-mode 1))
8374 (defun orgstruct-error ()
8375 "Error when there is no default binding for a structure key."
8376 (interactive)
8377 (error "This key has no function outside structure elements"))
8379 (defun orgstruct-setup ()
8380 "Setup orgstruct keymaps."
8381 (let ((nfunc 0)
8382 (bindings
8383 (list
8384 '([(meta up)] org-metaup)
8385 '([(meta down)] org-metadown)
8386 '([(meta left)] org-metaleft)
8387 '([(meta right)] org-metaright)
8388 '([(meta shift up)] org-shiftmetaup)
8389 '([(meta shift down)] org-shiftmetadown)
8390 '([(meta shift left)] org-shiftmetaleft)
8391 '([(meta shift right)] org-shiftmetaright)
8392 '([?\e (up)] org-metaup)
8393 '([?\e (down)] org-metadown)
8394 '([?\e (left)] org-metaleft)
8395 '([?\e (right)] org-metaright)
8396 '([?\e (shift up)] org-shiftmetaup)
8397 '([?\e (shift down)] org-shiftmetadown)
8398 '([?\e (shift left)] org-shiftmetaleft)
8399 '([?\e (shift right)] org-shiftmetaright)
8400 '([(shift up)] org-shiftup)
8401 '([(shift down)] org-shiftdown)
8402 '([(shift left)] org-shiftleft)
8403 '([(shift right)] org-shiftright)
8404 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8405 '("\M-q" fill-paragraph)
8406 '("\C-c^" org-sort)
8407 '("\C-c-" org-cycle-list-bullet)))
8408 elt key fun cmd)
8409 (while (setq elt (pop bindings))
8410 (setq nfunc (1+ nfunc))
8411 (setq key (org-key (car elt))
8412 fun (nth 1 elt)
8413 cmd (orgstruct-make-binding fun nfunc key))
8414 (org-defkey orgstruct-mode-map key cmd))
8416 ;; Prevent an error for users who forgot to make autoloads
8417 (require 'org-element)
8419 ;; Special treatment needed for TAB and RET
8420 (org-defkey orgstruct-mode-map [(tab)]
8421 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8422 (org-defkey orgstruct-mode-map "\C-i"
8423 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8425 (org-defkey orgstruct-mode-map "\M-\C-m"
8426 (orgstruct-make-binding 'org-insert-heading 105
8427 "\M-\C-m" [(meta return)]))
8428 (org-defkey orgstruct-mode-map [(meta return)]
8429 (orgstruct-make-binding 'org-insert-heading 106
8430 [(meta return)] "\M-\C-m"))
8432 (org-defkey orgstruct-mode-map [(shift meta return)]
8433 (orgstruct-make-binding 'org-insert-todo-heading 107
8434 [(meta return)] "\M-\C-m"))
8436 (org-defkey orgstruct-mode-map "\e\C-m"
8437 (orgstruct-make-binding 'org-insert-heading 108
8438 "\e\C-m" [?\e (return)]))
8439 (org-defkey orgstruct-mode-map [?\e (return)]
8440 (orgstruct-make-binding 'org-insert-heading 109
8441 [?\e (return)] "\e\C-m"))
8442 (org-defkey orgstruct-mode-map [?\e (shift return)]
8443 (orgstruct-make-binding 'org-insert-todo-heading 110
8444 [?\e (return)] "\e\C-m"))
8446 (unless org-local-vars
8447 (setq org-local-vars (org-get-local-variables)))
8451 (defun orgstruct-make-binding (fun n &rest keys)
8452 "Create a function for binding in the structure minor mode.
8453 FUN is the command to call inside a table. N is used to create a unique
8454 command name. KEYS are keys that should be checked in for a command
8455 to execute outside of tables."
8456 (eval
8457 (list 'defun
8458 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8459 '(arg)
8460 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8461 "Outside of structure, run the binding of `"
8462 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8463 "'.")
8464 '(interactive "p")
8465 (list 'if
8466 `(org-context-p 'headline 'item
8467 (and orgstruct-is-++
8468 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8469 'item-body))
8470 (list 'org-run-like-in-org-mode (list 'quote fun))
8471 (list 'let '(orgstruct-mode)
8472 (list 'call-interactively
8473 (append '(or)
8474 (mapcar (lambda (k)
8475 (list 'key-binding k))
8476 keys)
8477 '('orgstruct-error))))))))
8479 (defun org-contextualize-keys (alist contexts)
8480 "Return valid elements in ALIST depending on CONTEXTS.
8482 `org-agenda-custom-commands' or `org-capture-templates' are the
8483 values used for ALIST, and `org-agenda-custom-commands-contexts'
8484 or `org-capture-templates-contexts' are the associated contexts
8485 definitions."
8486 (let ((contexts
8487 ;; normalize contexts
8488 (mapcar
8489 (lambda(c) (cond ((listp (cadr c))
8490 (list (car c) (car c) (cadr c)))
8491 ((string= "" (cadr c))
8492 (list (car c) (car c) (caddr c)))
8493 (t c))) contexts))
8494 (a alist) c r s)
8495 ;; loop over all commands or templates
8496 (while (setq c (pop a))
8497 (let (vrules repl)
8498 (cond
8499 ((not (assoc (car c) contexts))
8500 (push c r))
8501 ((and (assoc (car c) contexts)
8502 (setq vrules (org-contextualize-validate-key
8503 (car c) contexts)))
8504 (mapc (lambda (vr)
8505 (when (not (equal (car vr) (cadr vr)))
8506 (setq repl vr))) vrules)
8507 (if (not repl) (push c r)
8508 (push (cadr repl) s)
8509 (push
8510 (cons (car c)
8511 (cdr (or (assoc (cadr repl) alist)
8512 (error "Undefined key `%s' as contextual replacement for `%s'"
8513 (cadr repl) (car c)))))
8514 r))))))
8515 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8516 (delq
8518 (delete-dups
8519 (mapcar (lambda (x)
8520 (let ((tpl (car x)))
8521 (when (not (delq
8523 (mapcar (lambda(y)
8524 (equal y tpl)) s))) x)))
8525 (reverse r))))))
8527 (defun org-contextualize-validate-key (key contexts)
8528 "Check CONTEXTS for agenda or capture KEY."
8529 (let (r rr res)
8530 (while (setq r (pop contexts))
8531 (mapc
8532 (lambda (rr)
8533 (when
8534 (and (equal key (car r))
8535 (if (functionp rr) (funcall rr)
8536 (or (and (eq (car rr) 'in-file)
8537 (buffer-file-name)
8538 (string-match (cdr rr) (buffer-file-name)))
8539 (and (eq (car rr) 'in-mode)
8540 (string-match (cdr rr) (symbol-name major-mode)))
8541 (when (and (eq (car rr) 'not-in-file)
8542 (buffer-file-name))
8543 (not (string-match (cdr rr) (buffer-file-name))))
8544 (when (eq (car rr) 'not-in-mode)
8545 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8546 (push r res)))
8547 (car (last r))))
8548 (delete-dups (delq nil res))))
8550 (defun org-context-p (&rest contexts)
8551 "Check if local context is any of CONTEXTS.
8552 Possible values in the list of contexts are `table', `headline', and `item'."
8553 (let ((pos (point)))
8554 (goto-char (point-at-bol))
8555 (prog1 (or (and (memq 'table contexts)
8556 (looking-at "[ \t]*|"))
8557 (and (memq 'headline contexts)
8558 (looking-at org-outline-regexp))
8559 (and (memq 'item contexts)
8560 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8561 (and (memq 'item-body contexts)
8562 (org-in-item-p)))
8563 (goto-char pos))))
8565 (defun org-get-local-variables ()
8566 "Return a list of all local variables in an Org mode buffer."
8567 (let (varlist)
8568 (with-current-buffer (get-buffer-create "*Org tmp*")
8569 (erase-buffer)
8570 (org-mode)
8571 (setq varlist (buffer-local-variables)))
8572 (kill-buffer "*Org tmp*")
8573 (delq nil
8574 (mapcar
8575 (lambda (x)
8576 (setq x
8577 (if (symbolp x)
8578 (list x)
8579 (list (car x) (list 'quote (cdr x)))))
8580 (if (string-match
8581 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8582 (symbol-name (car x)))
8583 x nil))
8584 varlist))))
8586 (defun org-clone-local-variables (from-buffer &optional regexp)
8587 "Clone local variables from FROM-BUFFER.
8588 Optional argument REGEXP selects variables to clone."
8589 (mapc
8590 (lambda (pair)
8591 (and (symbolp (car pair))
8592 (or (null regexp)
8593 (string-match regexp (symbol-name (car pair))))
8594 (set (make-local-variable (car pair))
8595 (cdr pair))))
8596 (buffer-local-variables from-buffer)))
8598 ;;;###autoload
8599 (defun org-run-like-in-org-mode (cmd)
8600 "Run a command, pretending that the current buffer is in Org-mode.
8601 This will temporarily bind local variables that are typically bound in
8602 Org-mode to the values they have in Org-mode, and then interactively
8603 call CMD."
8604 (org-load-modules-maybe)
8605 (unless org-local-vars
8606 (setq org-local-vars (org-get-local-variables)))
8607 (eval (list 'let org-local-vars
8608 (list 'call-interactively (list 'quote cmd)))))
8610 ;;;; Archiving
8612 (defun org-get-category (&optional pos force-refresh)
8613 "Get the category applying to position POS."
8614 (save-match-data
8615 (if force-refresh (org-refresh-category-properties))
8616 (let ((pos (or pos (point))))
8617 (or (get-text-property pos 'org-category)
8618 (progn (org-refresh-category-properties)
8619 (get-text-property pos 'org-category))))))
8621 (defun org-refresh-category-properties ()
8622 "Refresh category text properties in the buffer."
8623 (let ((case-fold-search t)
8624 (inhibit-read-only t)
8625 (def-cat (cond
8626 ((null org-category)
8627 (if buffer-file-name
8628 (file-name-sans-extension
8629 (file-name-nondirectory buffer-file-name))
8630 "???"))
8631 ((symbolp org-category) (symbol-name org-category))
8632 (t org-category)))
8633 beg end cat pos optionp)
8634 (org-unmodified
8635 (save-excursion
8636 (save-restriction
8637 (widen)
8638 (goto-char (point-min))
8639 (put-text-property (point) (point-max) 'org-category def-cat)
8640 (while (re-search-forward
8641 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8642 (setq pos (match-end 0)
8643 optionp (equal (char-after (match-beginning 0)) ?#)
8644 cat (org-trim (match-string 2)))
8645 (if optionp
8646 (setq beg (point-at-bol) end (point-max))
8647 (org-back-to-heading t)
8648 (setq beg (point) end (org-end-of-subtree t t)))
8649 (put-text-property beg end 'org-category cat)
8650 (put-text-property beg end 'org-category-position beg)
8651 (goto-char pos)))))))
8653 (defun org-refresh-properties (dprop tprop)
8654 "Refresh buffer text properties.
8655 DPROP is the drawer property and TPROP is the corresponding text
8656 property to set."
8657 (let ((case-fold-search t)
8658 (inhibit-read-only t) p)
8659 (org-unmodified
8660 (save-excursion
8661 (save-restriction
8662 (widen)
8663 (goto-char (point-min))
8664 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8665 (setq p (org-match-string-no-properties 1))
8666 (save-excursion
8667 (org-back-to-heading t)
8668 (put-text-property
8669 (point-at-bol) (point-at-eol) tprop p))))))))
8672 ;;;; Link Stuff
8674 ;;; Link abbreviations
8676 (defun org-link-expand-abbrev (link)
8677 "Apply replacements as defined in `org-link-abbrev-alist'."
8678 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8679 (let* ((key (match-string 1 link))
8680 (as (or (assoc key org-link-abbrev-alist-local)
8681 (assoc key org-link-abbrev-alist)))
8682 (tag (and (match-end 2) (match-string 3 link)))
8683 rpl)
8684 (if (not as)
8685 link
8686 (setq rpl (cdr as))
8687 (cond
8688 ((symbolp rpl) (funcall rpl tag))
8689 ((string-match "%(\\([^)]+\\))" rpl)
8690 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8691 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8692 ((string-match "%h" rpl)
8693 (replace-match (url-hexify-string (or tag "")) t t rpl))
8694 (t (concat rpl tag)))))
8695 link))
8697 ;;; Storing and inserting links
8699 (defvar org-insert-link-history nil
8700 "Minibuffer history for links inserted with `org-insert-link'.")
8702 (defvar org-stored-links nil
8703 "Contains the links stored with `org-store-link'.")
8705 (defvar org-store-link-plist nil
8706 "Plist with info about the most recently link created with `org-store-link'.")
8708 (defvar org-link-protocols nil
8709 "Link protocols added to Org-mode using `org-add-link-type'.")
8711 (defvar org-store-link-functions nil
8712 "List of functions that are called to create and store a link.
8713 Each function will be called in turn until one returns a non-nil
8714 value. Each function should check if it is responsible for creating
8715 this link (for example by looking at the major mode).
8716 If not, it must exit and return nil.
8717 If yes, it should return a non-nil value after a calling
8718 `org-store-link-props' with a list of properties and values.
8719 Special properties are:
8721 :type The link prefix, like \"http\". This must be given.
8722 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8723 This is obligatory as well.
8724 :description Optional default description for the second pair
8725 of brackets in an Org-mode link. The user can still change
8726 this when inserting this link into an Org-mode buffer.
8728 In addition to these, any additional properties can be specified
8729 and then used in capture templates.")
8731 (defun org-add-link-type (type &optional follow export)
8732 "Add TYPE to the list of `org-link-types'.
8733 Re-compute all regular expressions depending on `org-link-types'
8735 FOLLOW and EXPORT are two functions.
8737 FOLLOW should take the link path as the single argument and do whatever
8738 is necessary to follow the link, for example find a file or display
8739 a mail message.
8741 EXPORT should format the link path for export to one of the export formats.
8742 It should be a function accepting three arguments:
8744 path the path of the link, the text after the prefix (like \"http:\")
8745 desc the description of the link, if any, or a description added by
8746 org-export-normalize-links if there is none
8747 format the export format, a symbol like `html' or `latex' or `ascii'..
8749 The function may use the FORMAT information to return different values
8750 depending on the format. The return value will be put literally into
8751 the exported file. If the return value is nil, this means Org should
8752 do what it normally does with links which do not have EXPORT defined.
8754 Org-mode has a built-in default for exporting links. If you are happy with
8755 this default, there is no need to define an export function for the link
8756 type. For a simple example of an export function, see `org-bbdb.el'."
8757 (add-to-list 'org-link-types type t)
8758 (org-make-link-regexps)
8759 (if (assoc type org-link-protocols)
8760 (setcdr (assoc type org-link-protocols) (list follow export))
8761 (push (list type follow export) org-link-protocols)))
8763 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8764 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8766 ;;;###autoload
8767 (defun org-store-link (arg)
8768 "\\<org-mode-map>Store an org-link to the current location.
8769 This link is added to `org-stored-links' and can later be inserted
8770 into an org-buffer with \\[org-insert-link].
8772 For some link types, a prefix arg is interpreted:
8773 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8774 For file links, arg negates `org-context-in-file-links'."
8775 (interactive "P")
8776 (org-load-modules-maybe)
8777 (setq org-store-link-plist nil) ; reset
8778 (org-with-limited-levels
8779 (let (link cpltxt desc description search txt custom-id agenda-link)
8780 (cond
8782 ((run-hook-with-args-until-success 'org-store-link-functions)
8783 (setq link (plist-get org-store-link-plist :link)
8784 desc (or (plist-get org-store-link-plist :description) link)))
8786 ((org-src-edit-buffer-p)
8787 (let (label gc)
8788 (while (or (not label)
8789 (save-excursion
8790 (save-restriction
8791 (widen)
8792 (goto-char (point-min))
8793 (re-search-forward
8794 (regexp-quote (format org-coderef-label-format label))
8795 nil t))))
8796 (when label (message "Label exists already") (sit-for 2))
8797 (setq label (read-string "Code line label: " label)))
8798 (end-of-line 1)
8799 (setq link (format org-coderef-label-format label))
8800 (setq gc (- 79 (length link)))
8801 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8802 (insert link)
8803 (setq link (concat "(" label ")") desc nil)))
8805 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8806 ;; We are in the agenda, link to referenced location
8807 (let ((m (or (get-text-property (point) 'org-hd-marker)
8808 (get-text-property (point) 'org-marker))))
8809 (when m
8810 (org-with-point-at m
8811 (setq agenda-link
8812 (if (org-called-interactively-p 'any)
8813 (call-interactively 'org-store-link)
8814 (org-store-link nil)))))))
8816 ((eq major-mode 'calendar-mode)
8817 (let ((cd (calendar-cursor-to-date)))
8818 (setq link
8819 (format-time-string
8820 (car org-time-stamp-formats)
8821 (apply 'encode-time
8822 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8823 nil nil nil))))
8824 (org-store-link-props :type "calendar" :date cd)))
8826 ((eq major-mode 'help-mode)
8827 (setq link (concat "help:" (save-excursion
8828 (goto-char (point-min))
8829 (looking-at "^[^ ]+")
8830 (match-string 0))))
8831 (org-store-link-props :type "help"))
8833 ((eq major-mode 'w3-mode)
8834 (setq cpltxt (if (and (buffer-name)
8835 (not (string-match "Untitled" (buffer-name))))
8836 (buffer-name)
8837 (url-view-url t))
8838 link (url-view-url t))
8839 (org-store-link-props :type "w3" :url (url-view-url t)))
8841 ((eq major-mode 'w3m-mode)
8842 (setq cpltxt (or w3m-current-title w3m-current-url)
8843 link w3m-current-url)
8844 (org-store-link-props :type "w3m" :url (url-view-url t)))
8846 ((setq search (run-hook-with-args-until-success
8847 'org-create-file-search-functions))
8848 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8849 "::" search))
8850 (setq cpltxt (or description link)))
8852 ((eq major-mode 'image-mode)
8853 (setq cpltxt (concat "file:"
8854 (abbreviate-file-name buffer-file-name))
8855 link cpltxt)
8856 (org-store-link-props :type "image" :file buffer-file-name))
8858 ((eq major-mode 'dired-mode)
8859 ;; link to the file in the current line
8860 (let ((file (dired-get-filename nil t)))
8861 (setq file (if file
8862 (abbreviate-file-name
8863 (expand-file-name (dired-get-filename nil t)))
8864 ;; otherwise, no file so use current directory.
8865 default-directory))
8866 (setq cpltxt (concat "file:" file)
8867 link cpltxt)))
8869 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8870 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8871 (cond
8872 ((org-in-regexp "<<\\(.*?\\)>>")
8873 (setq cpltxt
8874 (concat "file:"
8875 (abbreviate-file-name
8876 (buffer-file-name (buffer-base-buffer)))
8877 "::" (match-string 1))
8878 link cpltxt))
8879 ((and (featurep 'org-id)
8880 (or (eq org-id-link-to-org-use-id t)
8881 (and (org-called-interactively-p 'any)
8882 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8883 (and (eq org-id-link-to-org-use-id
8884 'create-if-interactive-and-no-custom-id)
8885 (not custom-id))))
8886 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8887 ;; We can make a link using the ID.
8888 (setq link (condition-case nil
8889 (prog1 (org-id-store-link)
8890 (setq desc (plist-get org-store-link-plist :description)))
8891 (error
8892 ;; probably before first headline, link to file only
8893 (concat "file:"
8894 (abbreviate-file-name
8895 (buffer-file-name (buffer-base-buffer))))))))
8897 ;; Just link to current headline
8898 (setq cpltxt (concat "file:"
8899 (abbreviate-file-name
8900 (buffer-file-name (buffer-base-buffer)))))
8901 ;; Add a context search string
8902 (when (org-xor org-context-in-file-links arg)
8903 (setq txt (cond
8904 ((org-at-heading-p) nil)
8905 ((org-region-active-p)
8906 (buffer-substring (region-beginning) (region-end)))))
8907 (when (or (null txt) (string-match "\\S-" txt))
8908 (setq cpltxt
8909 (concat cpltxt "::"
8910 (condition-case nil
8911 (org-make-org-heading-search-string txt)
8912 (error "")))
8913 desc (or (nth 4 (ignore-errors
8914 (org-heading-components))) "NONE"))))
8915 (if (string-match "::\\'" cpltxt)
8916 (setq cpltxt (substring cpltxt 0 -2)))
8917 (setq link cpltxt))))
8919 ((buffer-file-name (buffer-base-buffer))
8920 ;; Just link to this file here.
8921 (setq cpltxt (concat "file:"
8922 (abbreviate-file-name
8923 (buffer-file-name (buffer-base-buffer)))))
8924 ;; Add a context string
8925 (when (org-xor org-context-in-file-links arg)
8926 (setq txt (if (org-region-active-p)
8927 (buffer-substring (region-beginning) (region-end))
8928 (buffer-substring (point-at-bol) (point-at-eol))))
8929 ;; Only use search option if there is some text.
8930 (when (string-match "\\S-" txt)
8931 (setq cpltxt
8932 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8933 desc "NONE")))
8934 (setq link cpltxt))
8936 ((org-called-interactively-p 'interactive)
8937 (error "Cannot link to a buffer which is not visiting a file"))
8939 (t (setq link nil)))
8941 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8942 (setq link (or link cpltxt)
8943 desc (or desc cpltxt))
8944 (if (equal desc "NONE") (setq desc nil))
8946 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8947 (progn
8948 (setq org-stored-links
8949 (cons (list link desc) org-stored-links))
8950 (message "Stored: %s" (or desc link))
8951 (when custom-id
8952 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8953 "::#" custom-id))
8954 (setq org-stored-links
8955 (cons (list link desc) org-stored-links))))
8956 (or agenda-link (and link (org-make-link-string link desc)))))))
8958 (defun org-store-link-props (&rest plist)
8959 "Store link properties, extract names and addresses."
8960 (let (x adr)
8961 (when (setq x (plist-get plist :from))
8962 (setq adr (mail-extract-address-components x))
8963 (setq plist (plist-put plist :fromname (car adr)))
8964 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8965 (when (setq x (plist-get plist :to))
8966 (setq adr (mail-extract-address-components x))
8967 (setq plist (plist-put plist :toname (car adr)))
8968 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8969 (let ((from (plist-get plist :from))
8970 (to (plist-get plist :to)))
8971 (when (and from to org-from-is-user-regexp)
8972 (setq plist
8973 (plist-put plist :fromto
8974 (if (string-match org-from-is-user-regexp from)
8975 (concat "to %t")
8976 (concat "from %f"))))))
8977 (setq org-store-link-plist plist))
8979 (defun org-add-link-props (&rest plist)
8980 "Add these properties to the link property list."
8981 (let (key value)
8982 (while plist
8983 (setq key (pop plist) value (pop plist))
8984 (setq org-store-link-plist
8985 (plist-put org-store-link-plist key value)))))
8987 (defun org-email-link-description (&optional fmt)
8988 "Return the description part of an email link.
8989 This takes information from `org-store-link-plist' and formats it
8990 according to FMT (default from `org-email-link-description-format')."
8991 (setq fmt (or fmt org-email-link-description-format))
8992 (let* ((p org-store-link-plist)
8993 (to (plist-get p :toaddress))
8994 (from (plist-get p :fromaddress))
8995 (table
8996 (list
8997 (cons "%c" (plist-get p :fromto))
8998 (cons "%F" (plist-get p :from))
8999 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9000 (cons "%T" (plist-get p :to))
9001 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9002 (cons "%s" (plist-get p :subject))
9003 (cons "%d" (plist-get p :date))
9004 (cons "%m" (plist-get p :message-id)))))
9005 (when (string-match "%c" fmt)
9006 ;; Check if the user wrote this message
9007 (if (and org-from-is-user-regexp from to
9008 (save-match-data (string-match org-from-is-user-regexp from)))
9009 (setq fmt (replace-match "to %t" t t fmt))
9010 (setq fmt (replace-match "from %f" t t fmt))))
9011 (org-replace-escapes fmt table)))
9013 (defun org-make-org-heading-search-string (&optional string heading)
9014 "Make search string for STRING or current headline."
9015 (interactive)
9016 (let ((s (or string (org-get-heading)))
9017 (lines org-context-in-file-links))
9018 (unless (and string (not heading))
9019 ;; We are using a headline, clean up garbage in there.
9020 (if (string-match org-todo-regexp s)
9021 (setq s (replace-match "" t t s)))
9022 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9023 (setq s (replace-match "" t t s)))
9024 (setq s (org-trim s))
9025 (if (string-match (concat "^\\(" org-quote-string "\\|"
9026 org-comment-string "\\)") s)
9027 (setq s (replace-match "" t t s)))
9028 (while (string-match org-ts-regexp s)
9029 (setq s (replace-match "" t t s))))
9030 (or string (setq s (concat "*" s))) ; Add * for headlines
9031 (when (and string (integerp lines) (> lines 0))
9032 (let ((slines (org-split-string s "\n")))
9033 (when (< lines (length slines))
9034 (setq s (mapconcat
9035 'identity
9036 (reverse (nthcdr (- (length slines) lines)
9037 (reverse slines))) "\n")))))
9038 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9040 (defun org-make-link-string (link &optional description)
9041 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9042 (unless (string-match "\\S-" link)
9043 (error "Empty link"))
9044 (when (and description
9045 (stringp description)
9046 (not (string-match "\\S-" description)))
9047 (setq description nil))
9048 (when (stringp description)
9049 ;; Remove brackets from the description, they are fatal.
9050 (while (string-match "\\[" description)
9051 (setq description (replace-match "{" t t description)))
9052 (while (string-match "\\]" description)
9053 (setq description (replace-match "}" t t description))))
9054 (when (equal link description)
9055 ;; No description needed, it is identical
9056 (setq description nil))
9057 (when (and (not description)
9058 (not (string-match (org-image-file-name-regexp) link))
9059 (not (equal link (org-link-escape link))))
9060 (setq description (org-extract-attributes link)))
9061 (setq link
9062 (cond ((string-match (org-image-file-name-regexp) link) link)
9063 ((string-match org-link-types-re link)
9064 (concat (match-string 1 link)
9065 (org-link-escape (substring link (match-end 1)))))
9066 (t (org-link-escape link))))
9067 (concat "[[" link "]"
9068 (if description (concat "[" description "]") "")
9069 "]"))
9071 (defconst org-link-escape-chars
9072 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9073 "List of characters that should be escaped in link.
9074 This is the list that is used for internal purposes.")
9076 (defconst org-link-escape-chars-browser
9077 '(?\ )
9078 "List of escapes for characters that are problematic in links.
9079 This is the list that is used before handing over to the browser.")
9081 (defun org-link-escape (text &optional table merge)
9082 "Return percent escaped representation of TEXT.
9083 TEXT is a string with the text to escape.
9084 Optional argument TABLE is a list with characters that should be
9085 escaped. When nil, `org-link-escape-chars' is used.
9086 If optional argument MERGE is set, merge TABLE into
9087 `org-link-escape-chars'."
9088 (cond
9089 ((and table merge)
9090 (mapc (lambda (defchr)
9091 (unless (member defchr table)
9092 (setq table (cons defchr table)))) org-link-escape-chars))
9093 ((null table)
9094 (setq table org-link-escape-chars)))
9095 (mapconcat
9096 (lambda (char)
9097 (if (or (member char table)
9098 (and (or (< char 32) (= char 37) (> char 126))
9099 org-url-hexify-p))
9100 (mapconcat (lambda (sequence-element)
9101 (format "%%%.2X" sequence-element))
9102 (or (encode-coding-char char 'utf-8)
9103 (error "Unable to percent escape character: %s"
9104 (char-to-string char))) "")
9105 (char-to-string char))) text ""))
9107 (defun org-link-unescape (str)
9108 "Unhex hexified Unicode strings as returned from the JavaScript function
9109 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9110 (unless (and (null str) (string= "" str))
9111 (let ((pos 0) (case-fold-search t) unhexed)
9112 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9113 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9114 (setq str (replace-match unhexed t t str))
9115 (setq pos (+ pos (length unhexed))))))
9116 str)
9118 (defun org-link-unescape-compound (hex)
9119 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9120 Note: this function also decodes single byte encodings like
9121 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9122 (save-match-data
9123 (let* ((bytes (cdr (split-string hex "%")))
9124 (ret "")
9125 (eat 0)
9126 (sum 0))
9127 (while bytes
9128 (let* ((val (string-to-number (pop bytes) 16))
9129 (shift-xor
9130 (if (= 0 eat)
9131 (cond
9132 ((>= val 252) (cons 6 252))
9133 ((>= val 248) (cons 5 248))
9134 ((>= val 240) (cons 4 240))
9135 ((>= val 224) (cons 3 224))
9136 ((>= val 192) (cons 2 192))
9137 (t (cons 0 0)))
9138 (cons 6 128))))
9139 (if (>= val 192) (setq eat (car shift-xor)))
9140 (setq val (logxor val (cdr shift-xor)))
9141 (setq sum (+ (lsh sum (car shift-xor)) val))
9142 (if (> eat 0) (setq eat (- eat 1)))
9143 (cond
9144 ((= 0 eat) ;multi byte
9145 (setq ret (concat ret (org-char-to-string sum)))
9146 (setq sum 0))
9147 ((not bytes) ; single byte(s)
9148 (setq ret (org-link-unescape-single-byte-sequence hex))))
9149 )) ;; end (while bytes
9150 ret )))
9152 (defun org-link-unescape-single-byte-sequence (hex)
9153 "Unhexify hex-encoded single byte character sequences."
9154 (mapconcat (lambda (byte)
9155 (char-to-string (string-to-number byte 16)))
9156 (cdr (split-string hex "%")) ""))
9158 (defun org-xor (a b)
9159 "Exclusive or."
9160 (if a (not b) b))
9162 (defun org-fixup-message-id-for-http (s)
9163 "Replace special characters in a message id, so it can be used in an http query."
9164 (when (string-match "%" s)
9165 (setq s (mapconcat (lambda (c)
9166 (if (eq c ?%)
9167 "%25"
9168 (char-to-string c)))
9169 s "")))
9170 (while (string-match "<" s)
9171 (setq s (replace-match "%3C" t t s)))
9172 (while (string-match ">" s)
9173 (setq s (replace-match "%3E" t t s)))
9174 (while (string-match "@" s)
9175 (setq s (replace-match "%40" t t s)))
9178 (defun org-link-prettify (link)
9179 "Return a human-readable representation of LINK.
9180 The car of LINK must be a raw link the cdr of LINK must be either
9181 a link description or nil."
9182 (let ((desc (or (cadr link) "<no description>")))
9183 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9184 "<" (car link) ">")))
9186 ;;;###autoload
9187 (defun org-insert-link-global ()
9188 "Insert a link like Org-mode does.
9189 This command can be called in any mode to insert a link in Org-mode syntax."
9190 (interactive)
9191 (org-load-modules-maybe)
9192 (org-run-like-in-org-mode 'org-insert-link))
9194 (defun org-insert-all-links (&optional keep)
9195 "Insert all links in `org-stored-links'."
9196 (interactive "P")
9197 (let ((links (copy-sequence org-stored-links)) l)
9198 (while (setq l (if keep (pop links) (pop org-stored-links)))
9199 (insert "- ")
9200 (org-insert-link nil (car l) (cadr l))
9201 (insert "\n"))))
9203 (defun org-link-fontify-links-to-this-file ()
9204 "Fontify links to the current file in `org-stored-links'."
9205 (let ((f (buffer-file-name)) a b)
9206 (setq a (mapcar (lambda(l)
9207 (let ((ll (car l)))
9208 (when (and (string-match "^file:\\(.+\\)::" ll)
9209 (equal f (expand-file-name (match-string 1 ll))))
9210 ll)))
9211 org-stored-links))
9212 (when (featurep 'org-id)
9213 (setq b (mapcar (lambda(l)
9214 (let ((ll (car l)))
9215 (when (and (string-match "^id:\\(.+\\)$" ll)
9216 (equal f (expand-file-name
9217 (or (org-id-find-id-file
9218 (match-string 1 ll)) ""))))
9219 ll)))
9220 org-stored-links)))
9221 (mapcar (lambda(l)
9222 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9223 (delq nil (append a b)))))
9225 (defvar org-link-links-in-this-file nil)
9226 (defun org-insert-link (&optional complete-file link-location default-description)
9227 "Insert a link. At the prompt, enter the link.
9229 Completion can be used to insert any of the link protocol prefixes like
9230 http or ftp in use.
9232 The history can be used to select a link previously stored with
9233 `org-store-link'. When the empty string is entered (i.e. if you just
9234 press RET at the prompt), the link defaults to the most recently
9235 stored link. As SPC triggers completion in the minibuffer, you need to
9236 use M-SPC or C-q SPC to force the insertion of a space character.
9238 You will also be prompted for a description, and if one is given, it will
9239 be displayed in the buffer instead of the link.
9241 If there is already a link at point, this command will allow you to edit link
9242 and description parts.
9244 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9245 be selected using completion. The path to the file will be relative to the
9246 current directory if the file is in the current directory or a subdirectory.
9247 Otherwise, the link will be the absolute path as completed in the minibuffer
9248 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9249 option `org-link-file-path-type'.
9251 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9252 the current directory or below.
9254 With three \\[universal-argument] prefixes, negate the meaning of
9255 `org-keep-stored-link-after-insertion'.
9257 If `org-make-link-description-function' is non-nil, this function will be
9258 called with the link target, and the result will be the default
9259 link description.
9261 If the LINK-LOCATION parameter is non-nil, this value will be
9262 used as the link location instead of reading one interactively.
9264 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9265 be used as the default description."
9266 (interactive "P")
9267 (let* ((wcf (current-window-configuration))
9268 (region (if (org-region-active-p)
9269 (buffer-substring (region-beginning) (region-end))))
9270 (remove (and region (list (region-beginning) (region-end))))
9271 (desc region)
9272 tmphist ; byte-compile incorrectly complains about this
9273 (link link-location)
9274 (abbrevs org-link-abbrev-alist-local)
9275 entry file all-prefixes auto-desc)
9276 (cond
9277 (link-location) ; specified by arg, just use it.
9278 ((org-in-regexp org-bracket-link-regexp 1)
9279 ;; We do have a link at point, and we are going to edit it.
9280 (setq remove (list (match-beginning 0) (match-end 0)))
9281 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9282 (setq link (read-string "Link: "
9283 (org-link-unescape
9284 (org-match-string-no-properties 1)))))
9285 ((or (org-in-regexp org-angle-link-re)
9286 (org-in-regexp org-plain-link-re))
9287 ;; Convert to bracket link
9288 (setq remove (list (match-beginning 0) (match-end 0))
9289 link (read-string "Link: "
9290 (org-remove-angle-brackets (match-string 0)))))
9291 ((member complete-file '((4) (16)))
9292 ;; Completing read for file names.
9293 (setq link (org-file-complete-link complete-file)))
9295 ;; Read link, with completion for stored links.
9296 (org-link-fontify-links-to-this-file)
9297 (org-switch-to-buffer-other-window "*Org Links*")
9298 (with-current-buffer "*Org Links*"
9299 (erase-buffer)
9300 (insert "Insert a link.
9301 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9302 (when org-stored-links
9303 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9304 (insert (mapconcat 'org-link-prettify
9305 (reverse org-stored-links) "\n")))
9306 (goto-char (point-min)))
9307 (let ((cw (selected-window)))
9308 (select-window (get-buffer-window "*Org Links*" 'visible))
9309 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9310 (unless (pos-visible-in-window-p (point-max))
9311 (org-fit-window-to-buffer))
9312 (and (window-live-p cw) (select-window cw)))
9313 ;; Fake a link history, containing the stored links.
9314 (setq tmphist (append (mapcar 'car org-stored-links)
9315 org-insert-link-history))
9316 (setq all-prefixes (append (mapcar 'car abbrevs)
9317 (mapcar 'car org-link-abbrev-alist)
9318 org-link-types))
9319 (unwind-protect
9320 (progn
9321 (setq link
9322 (let ((org-completion-use-ido nil)
9323 (org-completion-use-iswitchb nil))
9324 (org-completing-read
9325 "Link: "
9326 (append
9327 (mapcar (lambda (x) (list (concat x ":")))
9328 all-prefixes)
9329 (mapcar 'car org-stored-links)
9330 (mapcar 'cadr org-stored-links))
9331 nil nil nil
9332 'tmphist
9333 (caar org-stored-links))))
9334 (if (not (string-match "\\S-" link))
9335 (error "No link selected"))
9336 (mapc (lambda(l)
9337 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9338 org-stored-links)
9339 (if (or (member link all-prefixes)
9340 (and (equal ":" (substring link -1))
9341 (member (substring link 0 -1) all-prefixes)
9342 (setq link (substring link 0 -1))))
9343 (setq link (org-link-try-special-completion link))))
9344 (set-window-configuration wcf)
9345 (kill-buffer "*Org Links*"))
9346 (setq entry (assoc link org-stored-links))
9347 (or entry (push link org-insert-link-history))
9348 (setq desc (or desc (nth 1 entry)))))
9350 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9351 (not org-keep-stored-link-after-insertion))
9352 (setq org-stored-links (delq (assoc link org-stored-links)
9353 org-stored-links)))
9355 (if (string-match org-plain-link-re link)
9356 ;; URL-like link, normalize the use of angular brackets.
9357 (setq link (org-remove-angle-brackets link)))
9359 ;; Check if we are linking to the current file with a search
9360 ;; option If yes, simplify the link by using only the search
9361 ;; option.
9362 (when (and buffer-file-name
9363 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9364 (let* ((path (match-string 1 link))
9365 (case-fold-search nil)
9366 (search (match-string 2 link)))
9367 (save-match-data
9368 (if (equal (file-truename buffer-file-name) (file-truename path))
9369 ;; We are linking to this same file, with a search option
9370 (setq link search)))))
9372 ;; Check if we can/should use a relative path. If yes, simplify the link
9373 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9374 (let* ((type (match-string 1 link))
9375 (path (match-string 2 link))
9376 (origpath path)
9377 (case-fold-search nil))
9378 (cond
9379 ((or (eq org-link-file-path-type 'absolute)
9380 (equal complete-file '(16)))
9381 (setq path (abbreviate-file-name (expand-file-name path))))
9382 ((eq org-link-file-path-type 'noabbrev)
9383 (setq path (expand-file-name path)))
9384 ((eq org-link-file-path-type 'relative)
9385 (setq path (file-relative-name path)))
9387 (save-match-data
9388 (if (string-match (concat "^" (regexp-quote
9389 (expand-file-name
9390 (file-name-as-directory
9391 default-directory))))
9392 (expand-file-name path))
9393 ;; We are linking a file with relative path name.
9394 (setq path (substring (expand-file-name path)
9395 (match-end 0)))
9396 (setq path (abbreviate-file-name (expand-file-name path)))))))
9397 (setq link (concat type path))
9398 (if (equal desc origpath)
9399 (setq desc path))))
9401 (if org-make-link-description-function
9402 (setq desc
9403 (or (condition-case nil
9404 (funcall org-make-link-description-function link desc)
9405 (error (progn (message "Can't get link description from `%s'"
9406 (symbol-name org-make-link-description-function))
9407 (sit-for 2) nil)))
9408 (read-string "Description: " default-description)))
9409 (if default-description (setq desc default-description)
9410 (setq desc (or (and auto-desc desc)
9411 (read-string "Description: " desc)))))
9413 (unless (string-match "\\S-" desc) (setq desc nil))
9414 (if remove (apply 'delete-region remove))
9415 (insert (org-make-link-string link desc))))
9417 (defun org-link-try-special-completion (type)
9418 "If there is completion support for link type TYPE, offer it."
9419 (let ((fun (intern (concat "org-" type "-complete-link"))))
9420 (if (functionp fun)
9421 (funcall fun)
9422 (read-string "Link (no completion support): " (concat type ":")))))
9424 (defun org-file-complete-link (&optional arg)
9425 "Create a file link using completion."
9426 (let (file link)
9427 (setq file (read-file-name "File: "))
9428 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9429 (pwd1 (file-name-as-directory (abbreviate-file-name
9430 (expand-file-name ".")))))
9431 (cond
9432 ((equal arg '(16))
9433 (setq link (concat
9434 "file:"
9435 (abbreviate-file-name (expand-file-name file)))))
9436 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9437 (setq link (concat "file:" (match-string 1 file))))
9438 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9439 (expand-file-name file))
9440 (setq link (concat
9441 "file:" (match-string 1 (expand-file-name file)))))
9442 (t (setq link (concat "file:" file)))))
9443 link))
9445 (defun org-completing-read (&rest args)
9446 "Completing-read with SPACE being a normal character."
9447 (let ((enable-recursive-minibuffers t)
9448 (minibuffer-local-completion-map
9449 (copy-keymap minibuffer-local-completion-map)))
9450 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9451 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9452 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9453 (apply 'org-icompleting-read args)))
9455 (defun org-completing-read-no-i (&rest args)
9456 (let (org-completion-use-ido org-completion-use-iswitchb)
9457 (apply 'org-completing-read args)))
9459 (defun org-iswitchb-completing-read (prompt choices &rest args)
9460 "Use iswitch as a completing-read replacement to choose from choices.
9461 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9462 from."
9463 (let* ((iswitchb-use-virtual-buffers nil)
9464 (iswitchb-make-buflist-hook
9465 (lambda ()
9466 (setq iswitchb-temp-buflist choices))))
9467 (iswitchb-read-buffer prompt)))
9469 (defun org-icompleting-read (&rest args)
9470 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9471 (org-without-partial-completion
9472 (if (and org-completion-use-ido
9473 (fboundp 'ido-completing-read)
9474 (boundp 'ido-mode) ido-mode
9475 (listp (second args)))
9476 (let ((ido-enter-matching-directory nil))
9477 (apply 'ido-completing-read (concat (car args))
9478 (if (consp (car (nth 1 args)))
9479 (mapcar 'car (nth 1 args))
9480 (nth 1 args))
9481 (cddr args)))
9482 (if (and org-completion-use-iswitchb
9483 (boundp 'iswitchb-mode) iswitchb-mode
9484 (listp (second args)))
9485 (apply 'org-iswitchb-completing-read (concat (car args))
9486 (if (consp (car (nth 1 args)))
9487 (mapcar 'car (nth 1 args))
9488 (nth 1 args))
9489 (cddr args))
9490 (apply 'completing-read args)))))
9492 (defun org-extract-attributes (s)
9493 "Extract the attributes cookie from a string and set as text property."
9494 (let (a attr (start 0) key value)
9495 (save-match-data
9496 (when (string-match "{{\\([^}]+\\)}}$" s)
9497 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9498 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9499 (setq key (match-string 1 a) value (match-string 2 a)
9500 start (match-end 0)
9501 attr (plist-put attr (intern key) value))))
9502 (org-add-props s nil 'org-attr attr))
9505 (defun org-extract-attributes-from-string (tag)
9506 (let (key value attr)
9507 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9508 (setq key (match-string 1 tag) value (match-string 2 tag)
9509 tag (replace-match "" t t tag)
9510 attr (plist-put attr (intern key) value)))
9511 (cons tag attr)))
9513 (defun org-attributes-to-string (plist)
9514 "Format a property list into an HTML attribute list."
9515 (let ((s "") key value)
9516 (while plist
9517 (setq key (pop plist) value (pop plist))
9518 (and value
9519 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9522 ;;; Opening/following a link
9524 (defvar org-link-search-failed nil)
9526 (defvar org-open-link-functions nil
9527 "Hook for functions finding a plain text link.
9528 These functions must take a single argument, the link content.
9529 They will be called for links that look like [[link text][description]]
9530 when LINK TEXT does not have a protocol like \"http:\" and does not look
9531 like a filename (e.g. \"./blue.png\").
9533 These functions will be called *before* Org attempts to resolve the
9534 link by doing text searches in the current buffer - so if you want a
9535 link \"[[target]]\" to still find \"<<target>>\", your function should
9536 handle this as a special case.
9538 When the function does handle the link, it must return a non-nil value.
9539 If it decides that it is not responsible for this link, it must return
9540 nil to indicate that that Org-mode can continue with other options
9541 like exact and fuzzy text search.")
9543 (defun org-next-link ()
9544 "Move forward to the next link.
9545 If the link is in hidden text, expose it."
9546 (interactive)
9547 (when (and org-link-search-failed (eq this-command last-command))
9548 (goto-char (point-min))
9549 (message "Link search wrapped back to beginning of buffer"))
9550 (setq org-link-search-failed nil)
9551 (let* ((pos (point))
9552 (ct (org-context))
9553 (a (assoc :link ct)))
9554 (if a (goto-char (nth 2 a)))
9555 (if (re-search-forward org-any-link-re nil t)
9556 (progn
9557 (goto-char (match-beginning 0))
9558 (if (outline-invisible-p) (org-show-context)))
9559 (goto-char pos)
9560 (setq org-link-search-failed t)
9561 (error "No further link found"))))
9563 (defun org-previous-link ()
9564 "Move backward to the previous link.
9565 If the link is in hidden text, expose it."
9566 (interactive)
9567 (when (and org-link-search-failed (eq this-command last-command))
9568 (goto-char (point-max))
9569 (message "Link search wrapped back to end of buffer"))
9570 (setq org-link-search-failed nil)
9571 (let* ((pos (point))
9572 (ct (org-context))
9573 (a (assoc :link ct)))
9574 (if a (goto-char (nth 1 a)))
9575 (if (re-search-backward org-any-link-re nil t)
9576 (progn
9577 (goto-char (match-beginning 0))
9578 (if (outline-invisible-p) (org-show-context)))
9579 (goto-char pos)
9580 (setq org-link-search-failed t)
9581 (error "No further link found"))))
9583 (defun org-translate-link (s)
9584 "Translate a link string if a translation function has been defined."
9585 (if (and org-link-translation-function
9586 (fboundp org-link-translation-function)
9587 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9588 (progn
9589 (setq s (funcall org-link-translation-function
9590 (match-string 1 s) (match-string 2 s)))
9591 (concat (car s) ":" (cdr s)))
9594 (defun org-translate-link-from-planner (type path)
9595 "Translate a link from Emacs Planner syntax so that Org can follow it.
9596 This is still an experimental function, your mileage may vary."
9597 (cond
9598 ((member type '("http" "https" "news" "ftp"))
9599 ;; standard Internet links are the same.
9600 nil)
9601 ((and (equal type "irc") (string-match "^//" path))
9602 ;; Planner has two / at the beginning of an irc link, we have 1.
9603 ;; We should have zero, actually....
9604 (setq path (substring path 1)))
9605 ((and (equal type "lisp") (string-match "^/" path))
9606 ;; Planner has a slash, we do not.
9607 (setq type "elisp" path (substring path 1)))
9608 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9609 ;; A typical message link. Planner has the id after the final slash,
9610 ;; we separate it with a hash mark
9611 (setq path (concat (match-string 1 path) "#"
9612 (org-remove-angle-brackets (match-string 2 path)))))
9614 (cons type path))
9616 (defun org-find-file-at-mouse (ev)
9617 "Open file link or URL at mouse."
9618 (interactive "e")
9619 (mouse-set-point ev)
9620 (org-open-at-point 'in-emacs))
9622 (defun org-open-at-mouse (ev)
9623 "Open file link or URL at mouse.
9624 See the docstring of `org-open-file' for details."
9625 (interactive "e")
9626 (mouse-set-point ev)
9627 (if (eq major-mode 'org-agenda-mode)
9628 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9629 (org-open-at-point))
9631 (defvar org-window-config-before-follow-link nil
9632 "The window configuration before following a link.
9633 This is saved in case the need arises to restore it.")
9635 (defvar org-open-link-marker (make-marker)
9636 "Marker pointing to the location where `org-open-at-point; was called.")
9638 ;;;###autoload
9639 (defun org-open-at-point-global ()
9640 "Follow a link like Org-mode does.
9641 This command can be called in any mode to follow a link that has
9642 Org-mode syntax."
9643 (interactive)
9644 (org-run-like-in-org-mode 'org-open-at-point))
9646 ;;;###autoload
9647 (defun org-open-link-from-string (s &optional arg reference-buffer)
9648 "Open a link in the string S, as if it was in Org-mode."
9649 (interactive "sLink: \nP")
9650 (let ((reference-buffer (or reference-buffer (current-buffer))))
9651 (with-temp-buffer
9652 (let ((org-inhibit-startup (not reference-buffer)))
9653 (org-mode)
9654 (insert s)
9655 (goto-char (point-min))
9656 (when reference-buffer
9657 (setq org-link-abbrev-alist-local
9658 (with-current-buffer reference-buffer
9659 org-link-abbrev-alist-local)))
9660 (org-open-at-point arg reference-buffer)))))
9662 (defvar org-open-at-point-functions nil
9663 "Hook that is run when following a link at point.
9665 Functions in this hook must return t if they identify and follow
9666 a link at point. If they don't find anything interesting at point,
9667 they must return nil.")
9669 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9670 (defun org-open-at-point (&optional arg reference-buffer)
9671 "Open link at or after point.
9672 If there is no link at point, this function will search forward up to
9673 the end of the current line.
9674 Normally, files will be opened by an appropriate application. If the
9675 optional prefix argument ARG is non-nil, Emacs will visit the file.
9676 With a double prefix argument, try to open outside of Emacs, in the
9677 application the system uses for this file type."
9678 (interactive "P")
9679 ;; if in a code block, then open the block's results
9680 (unless (call-interactively #'org-babel-open-src-block-result)
9681 (org-load-modules-maybe)
9682 (move-marker org-open-link-marker (point))
9683 (setq org-window-config-before-follow-link (current-window-configuration))
9684 (org-remove-occur-highlights nil nil t)
9685 (cond
9686 ((and (org-at-heading-p)
9687 (not (org-at-timestamp-p t))
9688 (not (org-in-regexp
9689 (concat org-plain-link-re "\\|"
9690 org-bracket-link-regexp "\\|"
9691 org-angle-link-re "\\|"
9692 "[ \t]:[^ \t\n]+:[ \t]*$")))
9693 (not (get-text-property (point) 'org-linked-text)))
9694 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9695 (lk0 (car lkall))
9696 (lk (if (stringp lk0) (list lk0) lk0))
9697 (lkend (cdr lkall)))
9698 (mapcar (lambda(l)
9699 (search-forward l nil lkend)
9700 (goto-char (match-beginning 0))
9701 (org-open-at-point))
9702 lk))
9703 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9704 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9705 ((and (org-at-timestamp-p t)
9706 (not (org-in-regexp org-bracket-link-regexp)))
9707 (org-follow-timestamp-link))
9708 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9709 (not (org-in-regexp org-any-link-re)))
9710 (org-footnote-action))
9712 (let (type path link line search (pos (point)))
9713 (catch 'match
9714 (save-excursion
9715 (skip-chars-forward "^]\n\r")
9716 (when (org-in-regexp org-bracket-link-regexp 1)
9717 (setq link (org-extract-attributes
9718 (org-link-unescape (org-match-string-no-properties 1))))
9719 (while (string-match " *\n *" link)
9720 (setq link (replace-match " " t t link)))
9721 (setq link (org-link-expand-abbrev link))
9722 (cond
9723 ((or (file-name-absolute-p link)
9724 (string-match "^\\.\\.?/" link))
9725 (setq type "file" path link))
9726 ((string-match org-link-re-with-space3 link)
9727 (setq type (match-string 1 link) path (match-string 2 link)))
9728 ((string-match "^help:+\\(.+\\)" link)
9729 (setq type "help" path (match-string 1 link)))
9730 (t (setq type "thisfile" path link)))
9731 (throw 'match t)))
9733 (when (get-text-property (point) 'org-linked-text)
9734 (setq type "thisfile"
9735 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9736 (1+ (point)) (point))
9737 path (buffer-substring
9738 (or (previous-single-property-change pos 'org-linked-text)
9739 (point-min))
9740 (or (next-single-property-change pos 'org-linked-text)
9741 (point-max))))
9742 (throw 'match t))
9744 (save-excursion
9745 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9746 (when (or (org-in-regexp org-angle-link-re)
9747 (and plinkpos (goto-char (car plinkpos))
9748 (save-match-data (not (looking-back "\\[\\[")))))
9749 (setq type (match-string 1)
9750 path (org-link-unescape (match-string 2)))
9751 (throw 'match t))))
9752 (save-excursion
9753 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9754 (setq type "tags"
9755 path (match-string 1))
9756 (while (string-match ":" path)
9757 (setq path (replace-match "+" t t path)))
9758 (throw 'match t)))
9759 (when (org-in-regexp "<\\([^><\n]+\\)>")
9760 (setq type "tree-match"
9761 path (match-string 1))
9762 (throw 'match t)))
9763 (unless path
9764 (user-error "No link found"))
9766 ;; switch back to reference buffer
9767 ;; needed when if called in a temporary buffer through
9768 ;; org-open-link-from-string
9769 (with-current-buffer (or reference-buffer (current-buffer))
9771 ;; Remove any trailing spaces in path
9772 (if (string-match " +\\'" path)
9773 (setq path (replace-match "" t t path)))
9774 (if (and org-link-translation-function
9775 (fboundp org-link-translation-function))
9776 ;; Check if we need to translate the link
9777 (let ((tmp (funcall org-link-translation-function type path)))
9778 (setq type (car tmp) path (cdr tmp))))
9780 (cond
9782 ((assoc type org-link-protocols)
9783 (funcall (nth 1 (assoc type org-link-protocols)) path))
9785 ((equal type "help")
9786 (let ((f-or-v (intern path)))
9787 (cond ((fboundp f-or-v)
9788 (describe-function f-or-v))
9789 ((boundp f-or-v)
9790 (describe-variable f-or-v))
9791 (t (error "Not a known function or variable")))))
9793 ((equal type "mailto")
9794 (let ((cmd (car org-link-mailto-program))
9795 (args (cdr org-link-mailto-program)) args1
9796 (address path) (subject "") a)
9797 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9798 (setq address (match-string 1 path)
9799 subject (org-link-escape (match-string 2 path))))
9800 (while args
9801 (cond
9802 ((not (stringp (car args))) (push (pop args) args1))
9803 (t (setq a (pop args))
9804 (if (string-match "%a" a)
9805 (setq a (replace-match address t t a)))
9806 (if (string-match "%s" a)
9807 (setq a (replace-match subject t t a)))
9808 (push a args1))))
9809 (apply cmd (nreverse args1))))
9811 ((member type '("http" "https" "ftp" "news"))
9812 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9813 (org-link-escape
9814 path org-link-escape-chars-browser)
9815 path))))
9817 ((string= type "doi")
9818 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9819 (org-link-escape
9820 path org-link-escape-chars-browser)
9821 path))))
9823 ((member type '("message"))
9824 (browse-url (concat type ":" path)))
9826 ((string= type "tags")
9827 (org-tags-view arg path))
9829 ((string= type "tree-match")
9830 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9832 ((string= type "file")
9833 (if (string-match "::\\([0-9]+\\)\\'" path)
9834 (setq line (string-to-number (match-string 1 path))
9835 path (substring path 0 (match-beginning 0)))
9836 (if (string-match "::\\(.+\\)\\'" path)
9837 (setq search (match-string 1 path)
9838 path (substring path 0 (match-beginning 0)))))
9839 (if (string-match "[*?{]" (file-name-nondirectory path))
9840 (dired path)
9841 (org-open-file path arg line search)))
9843 ((string= type "shell")
9844 (let ((buf (generate-new-buffer "*Org Shell Output"))
9845 (cmd path))
9846 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9847 (string-match org-confirm-shell-link-not-regexp cmd))
9848 (not org-confirm-shell-link-function)
9849 (funcall org-confirm-shell-link-function
9850 (format "Execute \"%s\" in shell? "
9851 (org-add-props cmd nil
9852 'face 'org-warning))))
9853 (progn
9854 (message "Executing %s" cmd)
9855 (shell-command cmd buf)
9856 (if (featurep 'midnight)
9857 (setq clean-buffer-list-kill-buffer-names
9858 (cons buf clean-buffer-list-kill-buffer-names))))
9859 (error "Abort"))))
9861 ((string= type "elisp")
9862 (let ((cmd path))
9863 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9864 (string-match org-confirm-elisp-link-not-regexp cmd))
9865 (not org-confirm-elisp-link-function)
9866 (funcall org-confirm-elisp-link-function
9867 (format "Execute \"%s\" as elisp? "
9868 (org-add-props cmd nil
9869 'face 'org-warning))))
9870 (message "%s => %s" cmd
9871 (if (equal (string-to-char cmd) ?\()
9872 (eval (read cmd))
9873 (call-interactively (read cmd))))
9874 (error "Abort"))))
9876 ((and (string= type "thisfile")
9877 (run-hook-with-args-until-success
9878 'org-open-link-functions path)))
9880 ((string= type "thisfile")
9881 (if arg
9882 (switch-to-buffer-other-window
9883 (org-get-buffer-for-internal-link (current-buffer)))
9884 (org-mark-ring-push))
9885 (let ((cmd `(org-link-search
9886 ,path
9887 ,(cond ((equal arg '(4)) ''occur)
9888 ((equal arg '(16)) ''org-occur))
9889 ,pos)))
9890 (condition-case nil (let ((org-link-search-inhibit-query t))
9891 (eval cmd))
9892 (error (progn (widen) (eval cmd))))))
9894 (t (browse-url-at-point)))))))
9895 (move-marker org-open-link-marker nil)
9896 (run-hook-with-args 'org-follow-link-hook)))
9898 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9899 "Offer links in the current entry and return the selected link.
9900 If there is only one link, return it.
9901 If NTH is an integer, return the NTH link found.
9902 If ZERO is a string, check also this string for a link, and if
9903 there is one, return it."
9904 (with-current-buffer buffer
9905 (save-excursion
9906 (save-restriction
9907 (widen)
9908 (goto-char marker)
9909 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9910 "\\(" org-angle-link-re "\\)\\|"
9911 "\\(" org-plain-link-re "\\)"))
9912 (cnt ?0)
9913 (in-emacs (if (integerp nth) nil nth))
9914 have-zero end links link c)
9915 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9916 (push (match-string 0 zero) links)
9917 (setq cnt (1- cnt) have-zero t))
9918 (save-excursion
9919 (org-back-to-heading t)
9920 (setq end (save-excursion (outline-next-heading) (point)))
9921 (while (re-search-forward re end t)
9922 (push (match-string 0) links))
9923 (setq links (org-uniquify (reverse links))))
9924 (cond
9925 ((null links)
9926 (message "No links"))
9927 ((equal (length links) 1)
9928 (setq link (car links)))
9929 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9930 (setq link (nth (if have-zero nth (1- nth)) links)))
9931 (t ; we have to select a link
9932 (save-excursion
9933 (save-window-excursion
9934 (delete-other-windows)
9935 (with-output-to-temp-buffer "*Select Link*"
9936 (mapc (lambda (l)
9937 (if (not (string-match org-bracket-link-regexp l))
9938 (princ (format "[%c] %s\n" (incf cnt)
9939 (org-remove-angle-brackets l)))
9940 (if (match-end 3)
9941 (princ (format "[%c] %s (%s)\n" (incf cnt)
9942 (match-string 3 l) (match-string 1 l)))
9943 (princ (format "[%c] %s\n" (incf cnt)
9944 (match-string 1 l))))))
9945 links))
9946 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9947 (message "Select link to open, RET to open all:")
9948 (setq c (read-char-exclusive))
9949 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9950 (when (equal c ?q) (error "Abort"))
9951 (if (equal c ?\C-m)
9952 (setq link links)
9953 (setq nth (- c ?0))
9954 (if have-zero (setq nth (1+ nth)))
9955 (unless (and (integerp nth) (>= (length links) nth))
9956 (error "Invalid link selection"))
9957 (setq link (nth (1- nth) links)))))
9958 (cons link end))))))
9960 ;; Add special file links that specify the way of opening
9962 (org-add-link-type "file+sys" 'org-open-file-with-system)
9963 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9964 (defun org-open-file-with-system (path)
9965 "Open file at PATH using the system way of opening it."
9966 (org-open-file path 'system))
9967 (defun org-open-file-with-emacs (path)
9968 "Open file at PATH in Emacs."
9969 (org-open-file path 'emacs))
9970 (defun org-remove-file-link-modifiers ()
9971 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9972 (goto-char (point-min))
9973 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9974 (org-if-unprotected
9975 (replace-match "file:" t t))))
9976 (eval-after-load "org-exp"
9977 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9978 'org-remove-file-link-modifiers))
9980 ;;; File search
9982 (defvar org-create-file-search-functions nil
9983 "List of functions to construct the right search string for a file link.
9984 These functions are called in turn with point at the location to
9985 which the link should point.
9987 A function in the hook should first test if it would like to
9988 handle this file type, for example by checking the `major-mode'
9989 or the file extension. If it decides not to handle this file, it
9990 should just return nil to give other functions a chance. If it
9991 does handle the file, it must return the search string to be used
9992 when following the link. The search string will be part of the
9993 file link, given after a double colon, and `org-open-at-point'
9994 will automatically search for it. If special measures must be
9995 taken to make the search successful, another function should be
9996 added to the companion hook `org-execute-file-search-functions',
9997 which see.
9999 A function in this hook may also use `setq' to set the variable
10000 `description' to provide a suggestion for the descriptive text to
10001 be used for this link when it gets inserted into an Org-mode
10002 buffer with \\[org-insert-link].")
10004 (defvar org-execute-file-search-functions nil
10005 "List of functions to execute a file search triggered by a link.
10007 Functions added to this hook must accept a single argument, the
10008 search string that was part of the file link, the part after the
10009 double colon. The function must first check if it would like to
10010 handle this search, for example by checking the `major-mode' or
10011 the file extension. If it decides not to handle this search, it
10012 should just return nil to give other functions a chance. If it
10013 does handle the search, it must return a non-nil value to keep
10014 other functions from trying.
10016 Each function can access the current prefix argument through the
10017 variable `current-prefix-argument'. Note that a single prefix is
10018 used to force opening a link in Emacs, so it may be good to only
10019 use a numeric or double prefix to guide the search function.
10021 In case this is needed, a function in this hook can also restore
10022 the window configuration before `org-open-at-point' was called using:
10024 (set-window-configuration org-window-config-before-follow-link)")
10026 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10027 (defun org-link-search (s &optional type avoid-pos stealth)
10028 "Search for a link search option.
10029 If S is surrounded by forward slashes, it is interpreted as a
10030 regular expression. In org-mode files, this will create an `org-occur'
10031 sparse tree. In ordinary files, `occur' will be used to list matches.
10032 If the current buffer is in `dired-mode', grep will be used to search
10033 in all files. If AVOID-POS is given, ignore matches near that position.
10035 When optional argument STEALTH is non-nil, do not modify
10036 visibility around point, thus ignoring
10037 `org-show-hierarchy-above', `org-show-following-heading' and
10038 `org-show-siblings' variables."
10039 (let ((case-fold-search t)
10040 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10041 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10042 (append '(("") (" ") ("\t") ("\n"))
10043 org-emphasis-alist)
10044 "\\|") "\\)"))
10045 (pos (point))
10046 (pre nil) (post nil)
10047 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10048 (cond
10049 ;; First check if there are any special search functions
10050 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10051 ;; Now try the builtin stuff
10052 ((and (equal (string-to-char s0) ?#)
10053 (> (length s0) 1)
10054 (save-excursion
10055 (goto-char (point-min))
10056 (and
10057 (re-search-forward
10058 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10059 (setq type 'dedicated
10060 pos (match-beginning 0))))
10061 ;; There is an exact target for this
10062 (goto-char pos)
10063 (org-back-to-heading t)))
10064 ((save-excursion
10065 (goto-char (point-min))
10066 (and
10067 (re-search-forward
10068 (concat "<<" (regexp-quote s0) ">>") nil t)
10069 (setq type 'dedicated
10070 pos (match-beginning 0))))
10071 ;; There is an exact target for this
10072 (goto-char pos))
10073 ((save-excursion
10074 (goto-char (point-min))
10075 (and
10076 (re-search-forward
10077 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10078 (setq type 'dedicated pos (match-beginning 0))))
10079 ;; Found an invisible target.
10080 (goto-char pos))
10081 ((save-excursion
10082 (goto-char (point-min))
10083 (and
10084 (re-search-forward
10085 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10086 (setq type 'dedicated pos (match-beginning 0))))
10087 ;; Found an element with a matching #+name affiliated keyword.
10088 (goto-char pos))
10089 ((and (string-match "^(\\(.*\\))$" s0)
10090 (save-excursion
10091 (goto-char (point-min))
10092 (and
10093 (re-search-forward
10094 (concat "[^[]" (regexp-quote
10095 (format org-coderef-label-format
10096 (match-string 1 s0))))
10097 nil t)
10098 (setq type 'dedicated
10099 pos (1+ (match-beginning 0))))))
10100 ;; There is a coderef target for this
10101 (goto-char pos))
10102 ((string-match "^/\\(.*\\)/$" s)
10103 ;; A regular expression
10104 (cond
10105 ((derived-mode-p 'org-mode)
10106 (org-occur (match-string 1 s)))
10107 ;;((eq major-mode 'dired-mode)
10108 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10109 (t (org-do-occur (match-string 1 s)))))
10110 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10111 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10112 (goto-char (point-min))
10113 (cond
10114 ((let (case-fold-search)
10115 (re-search-forward (format org-complex-heading-regexp-format
10116 (regexp-quote s))
10117 nil t))
10118 ;; OK, found a match
10119 (setq type 'dedicated)
10120 (goto-char (match-beginning 0)))
10121 ((and (not org-link-search-inhibit-query)
10122 (eq org-link-search-must-match-exact-headline 'query-to-create)
10123 (y-or-n-p "No match - create this as a new heading? "))
10124 (goto-char (point-max))
10125 (or (bolp) (newline))
10126 (insert "* " s "\n")
10127 (beginning-of-line 0))
10129 (goto-char pos)
10130 (error "No match"))))
10132 ;; A normal search string
10133 (when (equal (string-to-char s) ?*)
10134 ;; Anchor on headlines, post may include tags.
10135 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10136 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10137 s (substring s 1)))
10138 (remove-text-properties
10139 0 (length s)
10140 '(face nil mouse-face nil keymap nil fontified nil) s)
10141 ;; Make a series of regular expressions to find a match
10142 (setq words (org-split-string s "[ \n\r\t]+")
10144 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10145 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10146 "\\)" markers)
10147 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10148 re2a (concat "[ \t\r\n]" re2a_)
10149 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10150 re4 (concat "[^a-zA-Z_]" re4_)
10152 re1 (concat pre re2 post)
10153 re3 (concat pre (if pre re4_ re4) post)
10154 re5 (concat pre ".*" re4)
10155 re2 (concat pre re2)
10156 re2a (concat pre (if pre re2a_ re2a))
10157 re4 (concat pre (if pre re4_ re4))
10158 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10159 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10160 re5 "\\)"
10162 (cond
10163 ((eq type 'org-occur) (org-occur reall))
10164 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10165 (t (goto-char (point-min))
10166 (setq type 'fuzzy)
10167 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10168 (org-search-not-self 1 re1 nil t)
10169 (org-search-not-self 1 re2 nil t)
10170 (org-search-not-self 1 re2a nil t)
10171 (org-search-not-self 1 re3 nil t)
10172 (org-search-not-self 1 re4 nil t)
10173 (org-search-not-self 1 re5 nil t)
10175 (goto-char (match-beginning 1))
10176 (goto-char pos)
10177 (error "No match"))))))
10178 (and (derived-mode-p 'org-mode)
10179 (not stealth)
10180 (org-show-context 'link-search))
10181 type))
10183 (defun org-search-not-self (group &rest args)
10184 "Execute `re-search-forward', but only accept matches that do not
10185 enclose the position of `org-open-link-marker'."
10186 (let ((m org-open-link-marker))
10187 (catch 'exit
10188 (while (apply 're-search-forward args)
10189 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10190 (goto-char (match-end group))
10191 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10192 (> (match-beginning 0) (marker-position m))
10193 (< (match-end 0) (marker-position m)))
10194 (save-match-data
10195 (or (not (org-in-regexp
10196 org-bracket-link-analytic-regexp 1))
10197 (not (match-end 4)) ; no description
10198 (and (<= (match-beginning 4) (point))
10199 (>= (match-end 4) (point))))))
10200 (throw 'exit (point))))))))
10202 (defun org-get-buffer-for-internal-link (buffer)
10203 "Return a buffer to be used for displaying the link target of internal links."
10204 (cond
10205 ((not org-display-internal-link-with-indirect-buffer)
10206 buffer)
10207 ((string-match "(Clone)$" (buffer-name buffer))
10208 (message "Buffer is already a clone, not making another one")
10209 ;; we also do not modify visibility in this case
10210 buffer)
10211 (t ; make a new indirect buffer for displaying the link
10212 (let* ((bn (buffer-name buffer))
10213 (ibn (concat bn "(Clone)"))
10214 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10215 (with-current-buffer ib (org-overview))
10216 ib))))
10218 (defun org-do-occur (regexp &optional cleanup)
10219 "Call the Emacs command `occur'.
10220 If CLEANUP is non-nil, remove the printout of the regular expression
10221 in the *Occur* buffer. This is useful if the regex is long and not useful
10222 to read."
10223 (occur regexp)
10224 (when cleanup
10225 (let ((cwin (selected-window)) win beg end)
10226 (when (setq win (get-buffer-window "*Occur*"))
10227 (select-window win))
10228 (goto-char (point-min))
10229 (when (re-search-forward "match[a-z]+" nil t)
10230 (setq beg (match-end 0))
10231 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10232 (setq end (1- (match-beginning 0)))))
10233 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10234 (goto-char (point-min))
10235 (select-window cwin))))
10237 ;;; The mark ring for links jumps
10239 (defvar org-mark-ring nil
10240 "Mark ring for positions before jumps in Org-mode.")
10241 (defvar org-mark-ring-last-goto nil
10242 "Last position in the mark ring used to go back.")
10243 ;; Fill and close the ring
10244 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10245 (loop for i from 1 to org-mark-ring-length do
10246 (push (make-marker) org-mark-ring))
10247 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10248 org-mark-ring)
10250 (defun org-mark-ring-push (&optional pos buffer)
10251 "Put the current position or POS into the mark ring and rotate it."
10252 (interactive)
10253 (setq pos (or pos (point)))
10254 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10255 (move-marker (car org-mark-ring)
10256 (or pos (point))
10257 (or buffer (current-buffer)))
10258 (message "%s"
10259 (substitute-command-keys
10260 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10262 (defun org-mark-ring-goto (&optional n)
10263 "Jump to the previous position in the mark ring.
10264 With prefix arg N, jump back that many stored positions. When
10265 called several times in succession, walk through the entire ring.
10266 Org-mode commands jumping to a different position in the current file,
10267 or to another Org-mode file, automatically push the old position
10268 onto the ring."
10269 (interactive "p")
10270 (let (p m)
10271 (if (eq last-command this-command)
10272 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10273 (setq p org-mark-ring))
10274 (setq org-mark-ring-last-goto p)
10275 (setq m (car p))
10276 (org-pop-to-buffer-same-window (marker-buffer m))
10277 (goto-char m)
10278 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10280 (defun org-remove-angle-brackets (s)
10281 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10282 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10284 (defun org-add-angle-brackets (s)
10285 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10286 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10288 (defun org-remove-double-quotes (s)
10289 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10290 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10293 ;;; Following specific links
10295 (defun org-follow-timestamp-link ()
10296 "Open an agenda view for the time-stamp date/range at point."
10297 (cond
10298 ((org-at-date-range-p t)
10299 (let ((org-agenda-start-on-weekday)
10300 (t1 (match-string 1))
10301 (t2 (match-string 2)) tt1 tt2)
10302 (setq tt1 (time-to-days (org-time-string-to-time t1))
10303 tt2 (time-to-days (org-time-string-to-time t2)))
10304 (let ((org-agenda-buffer-tmp-name
10305 (format "*Org Agenda(a:%s)"
10306 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10307 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10308 ((org-at-timestamp-p t)
10309 (let ((org-agenda-buffer-tmp-name
10310 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10311 (org-agenda-list nil (time-to-days (org-time-string-to-time
10312 (substring (match-string 1) 0 10)))
10313 1)))
10314 (t (error "This should not happen"))))
10317 ;;; Following file links
10318 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10319 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10320 (declare-function mailcap-mime-info
10321 "mailcap" (string &optional request no-decode))
10322 (defvar org-wait nil)
10323 (defun org-open-file (path &optional in-emacs line search)
10324 "Open the file at PATH.
10325 First, this expands any special file name abbreviations. Then the
10326 configuration variable `org-file-apps' is checked if it contains an
10327 entry for this file type, and if yes, the corresponding command is launched.
10329 If no application is found, Emacs simply visits the file.
10331 With optional prefix argument IN-EMACS, Emacs will visit the file.
10332 With a double \\[universal-argument] \\[universal-argument] \
10333 prefix arg, Org tries to avoid opening in Emacs
10334 and to use an external application to visit the file.
10336 Optional LINE specifies a line to go to, optional SEARCH a string
10337 to search for. If LINE or SEARCH is given, the file will be
10338 opened in Emacs, unless an entry from org-file-apps that makes
10339 use of groups in a regexp matches.
10341 If you want to change the way frames are used when following a
10342 link, please customize `org-link-frame-setup'.
10344 If the file does not exist, an error is thrown."
10345 (let* ((file (if (equal path "")
10346 buffer-file-name
10347 (substitute-in-file-name (expand-file-name path))))
10348 (file-apps (append org-file-apps (org-default-apps)))
10349 (apps (org-remove-if
10350 'org-file-apps-entry-match-against-dlink-p file-apps))
10351 (apps-dlink (org-remove-if-not
10352 'org-file-apps-entry-match-against-dlink-p file-apps))
10353 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10354 (dirp (if remp nil (file-directory-p file)))
10355 (file (if (and dirp org-open-directory-means-index-dot-org)
10356 (concat (file-name-as-directory file) "index.org")
10357 file))
10358 (a-m-a-p (assq 'auto-mode apps))
10359 (dfile (downcase file))
10360 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10361 (link (cond ((and (eq line nil)
10362 (eq search nil))
10363 file)
10364 (line
10365 (concat file "::" (number-to-string line)))
10366 (search
10367 (concat file "::" search))))
10368 (dlink (downcase link))
10369 (old-buffer (current-buffer))
10370 (old-pos (point))
10371 (old-mode major-mode)
10372 ext cmd link-match-data)
10373 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10374 (setq ext (match-string 1 dfile))
10375 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10376 (setq ext (match-string 1 dfile))))
10377 (cond
10378 ((member in-emacs '((16) system))
10379 (setq cmd (cdr (assoc 'system apps))))
10380 (in-emacs (setq cmd 'emacs))
10382 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10383 (and dirp (cdr (assoc 'directory apps)))
10384 ; first, try matching against apps-dlink
10385 ; if we get a match here, store the match data for later
10386 (let ((match (assoc-default dlink apps-dlink
10387 'string-match)))
10388 (if match
10389 (progn (setq link-match-data (match-data))
10390 match)
10391 (progn (setq in-emacs (or in-emacs line search))
10392 nil))) ; if we have no match in apps-dlink,
10393 ; always open the file in emacs if line or search
10394 ; is given (for backwards compatibility)
10395 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10396 'string-match)
10397 (cdr (assoc ext apps))
10398 (cdr (assoc t apps))))))
10399 (when (eq cmd 'system)
10400 (setq cmd (cdr (assoc 'system apps))))
10401 (when (eq cmd 'default)
10402 (setq cmd (cdr (assoc t apps))))
10403 (when (eq cmd 'mailcap)
10404 (require 'mailcap)
10405 (mailcap-parse-mailcaps)
10406 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10407 (command (mailcap-mime-info mime-type)))
10408 (if (stringp command)
10409 (setq cmd command)
10410 (setq cmd 'emacs))))
10411 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10412 (not (file-exists-p file))
10413 (not org-open-non-existing-files))
10414 (error "No such file: %s" file))
10415 (cond
10416 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10417 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10418 (while (string-match "['\"]%s['\"]" cmd)
10419 (setq cmd (replace-match "%s" t t cmd)))
10420 (while (string-match "%s" cmd)
10421 (setq cmd (replace-match
10422 (save-match-data
10423 (shell-quote-argument
10424 (convert-standard-filename file)))
10425 t t cmd)))
10427 ;; Replace "%1", "%2" etc. in command with group matches from regex
10428 (save-match-data
10429 (let ((match-index 1)
10430 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10431 (set-match-data link-match-data)
10432 (while (<= match-index number-of-groups)
10433 (let ((regex (concat "%" (number-to-string match-index)))
10434 (replace-with (match-string match-index dlink)))
10435 (while (string-match regex cmd)
10436 (setq cmd (replace-match replace-with t t cmd))))
10437 (setq match-index (+ match-index 1)))))
10439 (save-window-excursion
10440 (start-process-shell-command cmd nil cmd)
10441 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10443 ((or (stringp cmd)
10444 (eq cmd 'emacs))
10445 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10446 (widen)
10447 (if line (org-goto-line line)
10448 (if search (org-link-search search))))
10449 ((consp cmd)
10450 (let ((file (convert-standard-filename file)))
10451 (save-match-data
10452 (set-match-data link-match-data)
10453 (eval cmd))))
10454 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10455 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10456 (or (not (equal old-buffer (current-buffer)))
10457 (not (equal old-pos (point))))
10458 (org-mark-ring-push old-pos old-buffer))))
10460 (defun org-file-apps-entry-match-against-dlink-p (entry)
10461 "This function returns non-nil if `entry' uses a regular
10462 expression which should be matched against the whole link by
10463 org-open-file.
10465 It assumes that is the case when the entry uses a regular
10466 expression which has at least one grouping construct and the
10467 action is either a lisp form or a command string containing
10468 '%1', i.e. using at least one subexpression match as a
10469 parameter."
10470 (let ((selector (car entry))
10471 (action (cdr entry)))
10472 (if (stringp selector)
10473 (and (> (regexp-opt-depth selector) 0)
10474 (or (and (stringp action)
10475 (string-match "%[0-9]" action))
10476 (consp action)))
10477 nil)))
10479 (defun org-default-apps ()
10480 "Return the default applications for this operating system."
10481 (cond
10482 ((eq system-type 'darwin)
10483 org-file-apps-defaults-macosx)
10484 ((eq system-type 'windows-nt)
10485 org-file-apps-defaults-windowsnt)
10486 (t org-file-apps-defaults-gnu)))
10488 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10489 "Convert extensions to regular expressions in the cars of LIST.
10490 Also, weed out any non-string entries, because the return value is used
10491 only for regexp matching.
10492 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10493 point to the symbol `emacs', indicating that the file should
10494 be opened in Emacs."
10495 (append
10496 (delq nil
10497 (mapcar (lambda (x)
10498 (if (not (stringp (car x)))
10500 (if (string-match "\\W" (car x))
10502 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10503 list))
10504 (if add-auto-mode
10505 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10507 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10508 (defun org-file-remote-p (file)
10509 "Test whether FILE specifies a location on a remote system.
10510 Return non-nil if the location is indeed remote.
10512 For example, the filename \"/user@host:/foo\" specifies a location
10513 on the system \"/user@host:\"."
10514 (cond ((fboundp 'file-remote-p)
10515 (file-remote-p file))
10516 ((fboundp 'tramp-handle-file-remote-p)
10517 (tramp-handle-file-remote-p file))
10518 ((and (boundp 'ange-ftp-name-format)
10519 (string-match (car ange-ftp-name-format) file))
10520 t)))
10523 ;;;; Refiling
10525 (defun org-get-org-file ()
10526 "Read a filename, with default directory `org-directory'."
10527 (let ((default (or org-default-notes-file remember-data-file)))
10528 (read-file-name (format "File name [%s]: " default)
10529 (file-name-as-directory org-directory)
10530 default)))
10532 (defun org-notes-order-reversed-p ()
10533 "Check if the current file should receive notes in reversed order."
10534 (cond
10535 ((not org-reverse-note-order) nil)
10536 ((eq t org-reverse-note-order) t)
10537 ((not (listp org-reverse-note-order)) nil)
10538 (t (catch 'exit
10539 (let ((all org-reverse-note-order)
10540 entry)
10541 (while (setq entry (pop all))
10542 (if (string-match (car entry) buffer-file-name)
10543 (throw 'exit (cdr entry))))
10544 nil)))))
10546 (defvar org-refile-target-table nil
10547 "The list of refile targets, created by `org-refile'.")
10549 (defvar org-agenda-new-buffers nil
10550 "Buffers created to visit agenda files.")
10552 (defvar org-refile-cache nil
10553 "Cache for refile targets.")
10555 (defvar org-refile-markers nil
10556 "All the markers used for caching refile locations.")
10558 (defun org-refile-marker (pos)
10559 "Get a new refile marker, but only if caching is in use."
10560 (if (not org-refile-use-cache)
10562 (let ((m (make-marker)))
10563 (move-marker m pos)
10564 (push m org-refile-markers)
10565 m)))
10567 (defun org-refile-cache-clear ()
10568 "Clear the refile cache and disable all the markers."
10569 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10570 (setq org-refile-markers nil)
10571 (setq org-refile-cache nil)
10572 (message "Refile cache has been cleared"))
10574 (defun org-refile-cache-check-set (set)
10575 "Check if all the markers in the cache still have live buffers."
10576 (let (marker)
10577 (catch 'exit
10578 (while (and set (setq marker (nth 3 (pop set))))
10579 ;; if org-refile-use-outline-path is 'file, marker may be nil
10580 (when (and marker (null (marker-buffer marker)))
10581 (message "not found") (sit-for 3)
10582 (throw 'exit nil)))
10583 t)))
10585 (defun org-refile-cache-put (set &rest identifiers)
10586 "Push the refile targets SET into the cache, under IDENTIFIERS."
10587 (let* ((key (sha1 (prin1-to-string identifiers)))
10588 (entry (assoc key org-refile-cache)))
10589 (if entry
10590 (setcdr entry set)
10591 (push (cons key set) org-refile-cache))))
10593 (defun org-refile-cache-get (&rest identifiers)
10594 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10595 (cond
10596 ((not org-refile-cache) nil)
10597 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10599 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10600 org-refile-cache))))
10601 (and set (org-refile-cache-check-set set) set)))))
10603 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10604 "Produce a table with refile targets."
10605 (let ((case-fold-search nil)
10606 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10607 (entries (or org-refile-targets '((nil . (:level . 1)))))
10608 targets tgs txt re files f desc descre fast-path-p level pos0)
10609 (message "Getting targets...")
10610 (with-current-buffer (or default-buffer (current-buffer))
10611 (while (setq entry (pop entries))
10612 (setq files (car entry) desc (cdr entry))
10613 (setq fast-path-p nil)
10614 (cond
10615 ((null files) (setq files (list (current-buffer))))
10616 ((eq files 'org-agenda-files)
10617 (setq files (org-agenda-files 'unrestricted)))
10618 ((and (symbolp files) (fboundp files))
10619 (setq files (funcall files)))
10620 ((and (symbolp files) (boundp files))
10621 (setq files (symbol-value files))))
10622 (if (stringp files) (setq files (list files)))
10623 (cond
10624 ((eq (car desc) :tag)
10625 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10626 ((eq (car desc) :todo)
10627 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10628 ((eq (car desc) :regexp)
10629 (setq descre (cdr desc)))
10630 ((eq (car desc) :level)
10631 (setq descre (concat "^\\*\\{" (number-to-string
10632 (if org-odd-levels-only
10633 (1- (* 2 (cdr desc)))
10634 (cdr desc)))
10635 "\\}[ \t]")))
10636 ((eq (car desc) :maxlevel)
10637 (setq fast-path-p t)
10638 (setq descre (concat "^\\*\\{1," (number-to-string
10639 (if org-odd-levels-only
10640 (1- (* 2 (cdr desc)))
10641 (cdr desc)))
10642 "\\}[ \t]")))
10643 (t (error "Bad refiling target description %s" desc)))
10644 (while (setq f (pop files))
10645 (with-current-buffer
10646 (if (bufferp f) f (org-get-agenda-file-buffer f))
10648 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10649 (progn
10650 (if (bufferp f) (setq f (buffer-file-name
10651 (buffer-base-buffer f))))
10652 (setq f (and f (expand-file-name f)))
10653 (if (eq org-refile-use-outline-path 'file)
10654 (push (list (file-name-nondirectory f) f nil nil) tgs))
10655 (save-excursion
10656 (save-restriction
10657 (widen)
10658 (goto-char (point-min))
10659 (while (re-search-forward descre nil t)
10660 (goto-char (setq pos0 (point-at-bol)))
10661 (catch 'next
10662 (when org-refile-target-verify-function
10663 (save-match-data
10664 (or (funcall org-refile-target-verify-function)
10665 (throw 'next t))))
10666 (when (and (looking-at org-complex-heading-regexp)
10667 (not (member (match-string 4) excluded-entries))
10668 (match-string 4))
10669 (setq level (org-reduced-level
10670 (- (match-end 1) (match-beginning 1)))
10671 txt (org-link-display-format (match-string 4))
10672 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10673 re (format org-complex-heading-regexp-format
10674 (regexp-quote (match-string 4))))
10675 (when org-refile-use-outline-path
10676 (setq txt (mapconcat
10677 'org-protect-slash
10678 (append
10679 (if (eq org-refile-use-outline-path
10680 'file)
10681 (list (file-name-nondirectory
10682 (buffer-file-name
10683 (buffer-base-buffer))))
10684 (if (eq org-refile-use-outline-path
10685 'full-file-path)
10686 (list (buffer-file-name
10687 (buffer-base-buffer)))))
10688 (org-get-outline-path fast-path-p
10689 level txt)
10690 (list txt))
10691 "/")))
10692 (push (list txt f re (org-refile-marker (point)))
10693 tgs)))
10694 (when (= (point) pos0)
10695 ;; verification function has not moved point
10696 (goto-char (point-at-eol))))))))
10697 (when org-refile-use-cache
10698 (org-refile-cache-put tgs (buffer-file-name) descre))
10699 (setq targets (append tgs targets))
10700 ))))
10701 (message "Getting targets...done")
10702 (nreverse targets)))
10704 (defun org-protect-slash (s)
10705 (while (string-match "/" s)
10706 (setq s (replace-match "\\" t t s)))
10709 (defvar org-olpa (make-vector 20 nil))
10711 (defun org-get-outline-path (&optional fastp level heading)
10712 "Return the outline path to the current entry, as a list.
10714 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10715 routine which makes outline path derivations for an entire file,
10716 avoiding backtracing. Refile target collection makes use of that."
10717 (if fastp
10718 (progn
10719 (if (> level 19)
10720 (error "Outline path failure, more than 19 levels"))
10721 (loop for i from level upto 19 do
10722 (aset org-olpa i nil))
10723 (prog1
10724 (delq nil (append org-olpa nil))
10725 (aset org-olpa level heading)))
10726 (let (rtn case-fold-search)
10727 (save-excursion
10728 (save-restriction
10729 (widen)
10730 (while (org-up-heading-safe)
10731 (when (looking-at org-complex-heading-regexp)
10732 (push (org-match-string-no-properties 4) rtn)))
10733 rtn)))))
10735 (defun org-format-outline-path (path &optional width prefix)
10736 "Format the outline path PATH for display.
10737 Width is the maximum number of characters that is available.
10738 Prefix is a prefix to be included in the returned string,
10739 such as the file name."
10740 (setq width (or width 79))
10741 (if prefix (setq width (- width (length prefix))))
10742 (if (not path)
10743 (or prefix "")
10744 (let* ((nsteps (length path))
10745 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10746 (maxwidth (if (<= total-width width)
10747 10000 ;; everything fits
10748 ;; we need to shorten the level headings
10749 (/ (- width nsteps) nsteps)))
10750 (org-odd-levels-only nil)
10751 (n 0)
10752 (total (1+ (length prefix))))
10753 (setq maxwidth (max maxwidth 10))
10754 (concat prefix
10755 (mapconcat
10756 (lambda (h)
10757 (setq n (1+ n))
10758 (if (and (= n nsteps) (< maxwidth 10000))
10759 (setq maxwidth (- total-width total)))
10760 (if (< (length h) maxwidth)
10761 (progn (setq total (+ total (length h) 1)) h)
10762 (setq h (substring h 0 (- maxwidth 2))
10763 total (+ total maxwidth 1))
10764 (if (string-match "[ \t]+\\'" h)
10765 (setq h (substring h 0 (match-beginning 0))))
10766 (setq h (concat h "..")))
10767 (org-add-props h nil 'face
10768 (nth (% (1- n) org-n-level-faces)
10769 org-level-faces))
10771 path "/")))))
10773 (defun org-display-outline-path (&optional file current)
10774 "Display the current outline path in the echo area."
10775 (interactive "P")
10776 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10777 (case-fold-search nil)
10778 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10779 (if current (setq path (append path
10780 (save-excursion
10781 (org-back-to-heading t)
10782 (if (looking-at org-complex-heading-regexp)
10783 (list (match-string 4)))))))
10784 (message "%s"
10785 (org-format-outline-path
10786 path
10787 (1- (frame-width))
10788 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10790 (defvar org-refile-history nil
10791 "History for refiling operations.")
10793 (defvar org-after-refile-insert-hook nil
10794 "Hook run after `org-refile' has inserted its stuff at the new location.
10795 Note that this is still *before* the stuff will be removed from
10796 the *old* location.")
10798 (defvar org-capture-last-stored-marker)
10799 (defun org-refile (&optional goto default-buffer rfloc)
10800 "Move the entry or entries at point to another heading.
10801 The list of target headings is compiled using the information in
10802 `org-refile-targets', which see.
10804 At the target location, the entry is filed as a subitem of the target
10805 heading. Depending on `org-reverse-note-order', the new subitem will
10806 either be the first or the last subitem.
10808 If there is an active region, all entries in that region will be moved.
10809 However, the region must fulfill the requirement that the first heading
10810 is the first one sets the top-level of the moved text - at most siblings
10811 below it are allowed.
10813 With prefix arg GOTO, the command will only visit the target location
10814 and not actually move anything.
10816 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10817 go to the location where the last refiling operation has put the subtree.
10818 With a prefix argument of `2', refile to the running clock.
10820 RFLOC can be a refile location obtained in a different way.
10822 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10824 If you are using target caching (see `org-refile-use-cache'),
10825 you have to clear the target cache in order to find new targets.
10826 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10827 prefix argument (`C-u C-u C-u C-c C-w')."
10829 (interactive "P")
10830 (if (member goto '(0 (64)))
10831 (org-refile-cache-clear)
10832 (let* ((cbuf (current-buffer))
10833 (regionp (org-region-active-p))
10834 (region-start (and regionp (region-beginning)))
10835 (region-end (and regionp (region-end)))
10836 (region-length (and regionp (- region-end region-start)))
10837 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10838 pos it nbuf file re level reversed)
10839 (setq last-command nil)
10840 (when regionp
10841 (goto-char region-start)
10842 (or (bolp) (goto-char (point-at-bol)))
10843 (setq region-start (point))
10844 (unless (or (org-kill-is-subtree-p
10845 (buffer-substring region-start region-end))
10846 (prog1 org-refile-active-region-within-subtree
10847 (org-toggle-heading)))
10848 (error "The region is not a (sequence of) subtree(s)")))
10849 (if (equal goto '(16))
10850 (org-refile-goto-last-stored)
10851 (when (or
10852 (and (equal goto 2)
10853 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10854 (prog1
10855 (setq it (list (or org-clock-heading "running clock")
10856 (buffer-file-name
10857 (marker-buffer org-clock-hd-marker))
10859 (marker-position org-clock-hd-marker)))
10860 (setq goto nil)))
10861 (setq it (or rfloc
10862 (let (heading-text)
10863 (save-excursion
10864 (unless goto
10865 (org-back-to-heading t)
10866 (setq heading-text
10867 (nth 4 (org-heading-components))))
10868 (org-refile-get-location
10869 (cond (goto "Goto")
10870 (regionp "Refile region to")
10871 (t (concat "Refile subtree \""
10872 heading-text "\" to")))
10873 default-buffer
10874 (and (not (equal '(4) goto))
10875 org-refile-allow-creating-parent-nodes)
10876 goto))))))
10877 (setq file (nth 1 it)
10878 re (nth 2 it)
10879 pos (nth 3 it))
10880 (if (and (not goto)
10882 (equal (buffer-file-name) file)
10883 (if regionp
10884 (and (>= pos region-start)
10885 (<= pos region-end))
10886 (and (>= pos (point))
10887 (< pos (save-excursion
10888 (org-end-of-subtree t t))))))
10889 (error "Cannot refile to position inside the tree or region"))
10891 (setq nbuf (or (find-buffer-visiting file)
10892 (find-file-noselect file)))
10893 (if goto
10894 (progn
10895 (org-pop-to-buffer-same-window nbuf)
10896 (goto-char pos)
10897 (org-show-context 'org-goto))
10898 (if regionp
10899 (progn
10900 (org-kill-new (buffer-substring region-start region-end))
10901 (org-save-markers-in-region region-start region-end))
10902 (org-copy-subtree 1 nil t))
10903 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10904 (find-file-noselect file)))
10905 (setq reversed (org-notes-order-reversed-p))
10906 (save-excursion
10907 (save-restriction
10908 (widen)
10909 (if pos
10910 (progn
10911 (goto-char pos)
10912 (looking-at org-outline-regexp)
10913 (setq level (org-get-valid-level (funcall outline-level) 1))
10914 (goto-char
10915 (if reversed
10916 (or (outline-next-heading) (point-max))
10917 (or (save-excursion (org-get-next-sibling))
10918 (org-end-of-subtree t t)
10919 (point-max)))))
10920 (setq level 1)
10921 (if (not reversed)
10922 (goto-char (point-max))
10923 (goto-char (point-min))
10924 (or (outline-next-heading) (goto-char (point-max)))))
10925 (if (not (bolp)) (newline))
10926 (org-paste-subtree level)
10927 (when org-log-refile
10928 (org-add-log-setup 'refile nil nil 'findpos
10929 org-log-refile)
10930 (unless (eq org-log-refile 'note)
10931 (save-excursion (org-add-log-note))))
10932 (and org-auto-align-tags
10933 (let ((org-loop-over-headlines-in-active-region nil))
10934 (org-set-tags nil t)))
10935 (with-demoted-errors
10936 (bookmark-set "org-refile-last-stored"))
10937 ;; If we are refiling for capture, make sure that the
10938 ;; last-capture pointers point here
10939 (when (org-bound-and-true-p org-refile-for-capture)
10940 (with-demoted-errors
10941 (bookmark-set "org-capture-last-stored-marker"))
10942 (move-marker org-capture-last-stored-marker (point)))
10943 (if (fboundp 'deactivate-mark) (deactivate-mark))
10944 (run-hooks 'org-after-refile-insert-hook))))
10945 (if regionp
10946 (delete-region (point) (+ (point) region-length))
10947 (org-cut-subtree))
10948 (when (featurep 'org-inlinetask)
10949 (org-inlinetask-remove-END-maybe))
10950 (setq org-markers-to-move nil)
10951 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10953 (defun org-refile-goto-last-stored ()
10954 "Go to the location where the last refile was stored."
10955 (interactive)
10956 (bookmark-jump "org-refile-last-stored")
10957 (message "This is the location of the last refile"))
10959 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10960 no-exclude)
10961 "Prompt the user for a refile location, using PROMPT.
10962 PROMPT should not be suffixed with a colon and a space, because
10963 this function appends the default value from
10964 `org-refile-history' automatically, if that is not empty.
10965 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10966 this is used for the GOTO interface."
10967 (let ((org-refile-targets org-refile-targets)
10968 (org-refile-use-outline-path org-refile-use-outline-path)
10969 excluded-entries)
10970 (when (and (derived-mode-p 'org-mode)
10971 (not org-refile-use-cache)
10972 (not no-exclude))
10973 (org-map-tree
10974 (lambda()
10975 (setq excluded-entries
10976 (append excluded-entries (list (org-get-heading t t)))))))
10977 (setq org-refile-target-table
10978 (org-refile-get-targets default-buffer excluded-entries)))
10979 (unless org-refile-target-table
10980 (error "No refile targets"))
10981 (let* ((prompt (concat prompt
10982 (and (car org-refile-history)
10983 (concat " (default " (car org-refile-history) ")"))
10984 ": "))
10985 (cbuf (current-buffer))
10986 (partial-completion-mode nil)
10987 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10988 (cfunc (if (and org-refile-use-outline-path
10989 org-outline-path-complete-in-steps)
10990 'org-olpath-completing-read
10991 'org-icompleting-read))
10992 (extra (if org-refile-use-outline-path "/" ""))
10993 (filename (and cfn (expand-file-name cfn)))
10994 (tbl (mapcar
10995 (lambda (x)
10996 (if (and (not (member org-refile-use-outline-path
10997 '(file full-file-path)))
10998 (not (equal filename (nth 1 x))))
10999 (cons (concat (car x) extra " ("
11000 (file-name-nondirectory (nth 1 x)) ")")
11001 (cdr x))
11002 (cons (concat (car x) extra) (cdr x))))
11003 org-refile-target-table))
11004 (completion-ignore-case t)
11005 pa answ parent-target child parent old-hist)
11006 (setq old-hist org-refile-history)
11007 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11008 nil 'org-refile-history (car org-refile-history)))
11009 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11010 (org-refile-check-position pa)
11011 (if pa
11012 (progn
11013 (when (or (not org-refile-history)
11014 (not (eq old-hist org-refile-history))
11015 (not (equal (car pa) (car org-refile-history))))
11016 (setq org-refile-history
11017 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11018 org-refile-history
11019 (cdr org-refile-history))))
11020 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11021 (pop org-refile-history)))
11023 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11024 (progn
11025 (setq parent (match-string 1 answ)
11026 child (match-string 2 answ))
11027 (setq parent-target (or (assoc parent tbl)
11028 (assoc (concat parent "/") tbl)))
11029 (when (and parent-target
11030 (or (eq new-nodes t)
11031 (and (eq new-nodes 'confirm)
11032 (y-or-n-p (format "Create new node \"%s\"? "
11033 child)))))
11034 (org-refile-new-child parent-target child)))
11035 (error "Invalid target location")))))
11037 (declare-function org-string-nw-p "org-macs" (s))
11038 (defun org-refile-check-position (refile-pointer)
11039 "Check if the refile pointer matches the headline to which it points."
11040 (let* ((file (nth 1 refile-pointer))
11041 (re (nth 2 refile-pointer))
11042 (pos (nth 3 refile-pointer))
11043 buffer)
11044 (if (and (not (markerp pos)) (not file))
11045 (error "Please save the buffer to a file before refiling")
11046 (when (org-string-nw-p re)
11047 (setq buffer (if (markerp pos)
11048 (marker-buffer pos)
11049 (or (find-buffer-visiting file)
11050 (find-file-noselect file))))
11051 (with-current-buffer buffer
11052 (save-excursion
11053 (save-restriction
11054 (widen)
11055 (goto-char pos)
11056 (beginning-of-line 1)
11057 (unless (org-looking-at-p re)
11058 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11060 (defun org-refile-new-child (parent-target child)
11061 "Use refile target PARENT-TARGET to add new CHILD below it."
11062 (unless parent-target
11063 (error "Cannot find parent for new node"))
11064 (let ((file (nth 1 parent-target))
11065 (pos (nth 3 parent-target))
11066 level)
11067 (with-current-buffer (or (find-buffer-visiting file)
11068 (find-file-noselect file))
11069 (save-excursion
11070 (save-restriction
11071 (widen)
11072 (if pos
11073 (goto-char pos)
11074 (goto-char (point-max))
11075 (if (not (bolp)) (newline)))
11076 (when (looking-at org-outline-regexp)
11077 (setq level (funcall outline-level))
11078 (org-end-of-subtree t t))
11079 (org-back-over-empty-lines)
11080 (insert "\n" (make-string
11081 (if pos (org-get-valid-level level 1) 1) ?*)
11082 " " child "\n")
11083 (beginning-of-line 0)
11084 (list (concat (car parent-target) "/" child) file "" (point)))))))
11086 (defun org-olpath-completing-read (prompt collection &rest args)
11087 "Read an outline path like a file name."
11088 (let ((thetable collection)
11089 (org-completion-use-ido nil) ; does not work with ido.
11090 (org-completion-use-iswitchb nil)) ; or iswitchb
11091 (apply
11092 'org-icompleting-read prompt
11093 (lambda (string predicate &optional flag)
11094 (let (rtn r f (l (length string)))
11095 (cond
11096 ((eq flag nil)
11097 ;; try completion
11098 (try-completion string thetable))
11099 ((eq flag t)
11100 ;; all-completions
11101 (setq rtn (all-completions string thetable predicate))
11102 (mapcar
11103 (lambda (x)
11104 (setq r (substring x l))
11105 (if (string-match " ([^)]*)$" x)
11106 (setq f (match-string 0 x))
11107 (setq f ""))
11108 (if (string-match "/" r)
11109 (concat string (substring r 0 (match-end 0)) f)
11111 rtn))
11112 ((eq flag 'lambda)
11113 ;; exact match?
11114 (assoc string thetable)))))
11115 args)))
11117 ;;;; Dynamic blocks
11119 (defun org-find-dblock (name)
11120 "Find the first dynamic block with name NAME in the buffer.
11121 If not found, stay at current position and return nil."
11122 (let ((case-fold-search t) pos)
11123 (save-excursion
11124 (goto-char (point-min))
11125 (setq pos (and (re-search-forward
11126 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11127 (match-beginning 0))))
11128 (if pos (goto-char pos))
11129 pos))
11131 (defconst org-dblock-start-re
11132 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11133 "Matches the start line of a dynamic block, with parameters.")
11135 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11136 "Matches the end of a dynamic block.")
11138 (defun org-create-dblock (plist)
11139 "Create a dynamic block section, with parameters taken from PLIST.
11140 PLIST must contain a :name entry which is used as name of the block."
11141 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11142 (end-of-line 1)
11143 (newline))
11144 (let ((col (current-column))
11145 (name (plist-get plist :name)))
11146 (insert "#+BEGIN: " name)
11147 (while plist
11148 (if (eq (car plist) :name)
11149 (setq plist (cddr plist))
11150 (insert " " (prin1-to-string (pop plist)))))
11151 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11152 (beginning-of-line -2)))
11154 (defun org-prepare-dblock ()
11155 "Prepare dynamic block for refresh.
11156 This empties the block, puts the cursor at the insert position and returns
11157 the property list including an extra property :name with the block name."
11158 (unless (looking-at org-dblock-start-re)
11159 (error "Not at a dynamic block"))
11160 (let* ((begdel (1+ (match-end 0)))
11161 (name (org-no-properties (match-string 1)))
11162 (params (append (list :name name)
11163 (read (concat "(" (match-string 3) ")")))))
11164 (save-excursion
11165 (beginning-of-line 1)
11166 (skip-chars-forward " \t")
11167 (setq params (plist-put params :indentation-column (current-column))))
11168 (unless (re-search-forward org-dblock-end-re nil t)
11169 (error "Dynamic block not terminated"))
11170 (setq params
11171 (append params
11172 (list :content (buffer-substring
11173 begdel (match-beginning 0)))))
11174 (delete-region begdel (match-beginning 0))
11175 (goto-char begdel)
11176 (open-line 1)
11177 params))
11179 (defun org-map-dblocks (&optional command)
11180 "Apply COMMAND to all dynamic blocks in the current buffer.
11181 If COMMAND is not given, use `org-update-dblock'."
11182 (let ((cmd (or command 'org-update-dblock)))
11183 (save-excursion
11184 (goto-char (point-min))
11185 (while (re-search-forward org-dblock-start-re nil t)
11186 (goto-char (match-beginning 0))
11187 (save-excursion
11188 (condition-case nil
11189 (funcall cmd)
11190 (error (message "Error during update of dynamic block"))))
11191 (unless (re-search-forward org-dblock-end-re nil t)
11192 (error "Dynamic block not terminated"))))))
11194 (defun org-dblock-update (&optional arg)
11195 "User command for updating dynamic blocks.
11196 Update the dynamic block at point. With prefix ARG, update all dynamic
11197 blocks in the buffer."
11198 (interactive "P")
11199 (if arg
11200 (org-update-all-dblocks)
11201 (or (looking-at org-dblock-start-re)
11202 (org-beginning-of-dblock))
11203 (org-update-dblock)))
11205 (defun org-update-dblock ()
11206 "Update the dynamic block at point.
11207 This means to empty the block, parse for parameters and then call
11208 the correct writing function."
11209 (interactive)
11210 (save-window-excursion
11211 (let* ((pos (point))
11212 (line (org-current-line))
11213 (params (org-prepare-dblock))
11214 (name (plist-get params :name))
11215 (indent (plist-get params :indentation-column))
11216 (cmd (intern (concat "org-dblock-write:" name))))
11217 (message "Updating dynamic block `%s' at line %d..." name line)
11218 (funcall cmd params)
11219 (message "Updating dynamic block `%s' at line %d...done" name line)
11220 (goto-char pos)
11221 (when (and indent (> indent 0))
11222 (setq indent (make-string indent ?\ ))
11223 (save-excursion
11224 (org-beginning-of-dblock)
11225 (forward-line 1)
11226 (while (not (looking-at org-dblock-end-re))
11227 (insert indent)
11228 (beginning-of-line 2))
11229 (when (looking-at org-dblock-end-re)
11230 (and (looking-at "[ \t]+")
11231 (replace-match ""))
11232 (insert indent)))))))
11234 (defun org-beginning-of-dblock ()
11235 "Find the beginning of the dynamic block at point.
11236 Error if there is no such block at point."
11237 (let ((pos (point))
11238 beg)
11239 (end-of-line 1)
11240 (if (and (re-search-backward org-dblock-start-re nil t)
11241 (setq beg (match-beginning 0))
11242 (re-search-forward org-dblock-end-re nil t)
11243 (> (match-end 0) pos))
11244 (goto-char beg)
11245 (goto-char pos)
11246 (error "Not in a dynamic block"))))
11248 (defun org-update-all-dblocks ()
11249 "Update all dynamic blocks in the buffer.
11250 This function can be used in a hook."
11251 (interactive)
11252 (when (derived-mode-p 'org-mode)
11253 (org-map-dblocks 'org-update-dblock)))
11256 ;;;; Completion
11258 (defconst org-additional-option-like-keywords
11259 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11260 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11261 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11262 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11263 "BEGIN:" "END:"
11264 "ORGTBL" "TBLFM:" "TBLNAME:"
11265 "BEGIN_EXAMPLE" "END_EXAMPLE"
11266 "BEGIN_VERBATIM" "END_VERBATIM"
11267 "BEGIN_QUOTE" "END_QUOTE"
11268 "BEGIN_VERSE" "END_VERSE"
11269 "BEGIN_CENTER" "END_CENTER"
11270 "BEGIN_SRC" "END_SRC"
11271 "BEGIN_RESULT" "END_RESULT"
11272 "BEGIN_lstlisting" "END_lstlisting"
11273 "NAME:" "RESULTS:"
11274 "HEADER:" "HEADERS:"
11275 "COLUMNS:" "PROPERTY:"
11276 "CAPTION:" "LABEL:"
11277 "SETUPFILE:"
11278 "INCLUDE:" "INDEX:"
11279 "BIND:"
11280 "MACRO:"))
11282 (defconst org-options-keywords
11283 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11284 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11285 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11286 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11287 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11288 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11289 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11291 (defconst org-additional-option-like-keywords-for-flyspell
11292 (delete-dups
11293 (split-string
11294 (mapconcat (lambda(k)
11295 (replace-regexp-in-string
11296 "_\\|:" " "
11297 (concat k " " (downcase k) " " (upcase k))))
11298 (append org-options-keywords org-additional-option-like-keywords)
11299 " ")
11300 " +" t)))
11302 (defcustom org-structure-template-alist
11303 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11304 "<src lang=\"?\">\n\n</src>")
11305 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11306 "<example>\n?\n</example>")
11307 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11308 "<quote>\n?\n</quote>")
11309 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11310 "<verse>\n?\n</verse>")
11311 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11312 "<verbatim>\n?\n</verbatim>")
11313 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11314 "<center>\n?\n</center>")
11315 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11316 "<literal style=\"latex\">\n?\n</literal>")
11317 ("L" "#+LaTeX: "
11318 "<literal style=\"latex\">?</literal>")
11319 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11320 "<literal style=\"html\">\n?\n</literal>")
11321 ("H" "#+HTML: "
11322 "<literal style=\"html\">?</literal>")
11323 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11324 ("A" "#+ASCII: ")
11325 ("i" "#+INDEX: ?"
11326 "#+INDEX: ?")
11327 ("I" "#+INCLUDE: %file ?"
11328 "<include file=%file markup=\"?\">"))
11329 "Structure completion elements.
11330 This is a list of abbreviation keys and values. The value gets inserted
11331 if you type `<' followed by the key and then press the completion key,
11332 usually `M-TAB'. %file will be replaced by a file name after prompting
11333 for the file using completion. The cursor will be placed at the position
11334 of the `?` in the template.
11335 There are two templates for each key, the first uses the original Org syntax,
11336 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11337 the default when the /org-mtags.el/ module has been loaded. See also the
11338 variable `org-mtags-prefer-muse-templates'."
11339 :group 'org-completion
11340 :type '(repeat
11341 (string :tag "Key")
11342 (string :tag "Template")
11343 (string :tag "Muse Template")))
11345 (defun org-try-structure-completion ()
11346 "Try to complete a structure template before point.
11347 This looks for strings like \"<e\" on an otherwise empty line and
11348 expands them."
11349 (let ((l (buffer-substring (point-at-bol) (point)))
11351 (when (and (looking-at "[ \t]*$")
11352 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11353 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11354 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11355 (match-beginning 1)) a)
11356 t)))
11358 (defun org-complete-expand-structure-template (start cell)
11359 "Expand a structure template."
11360 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11361 (rpl (nth (if musep 2 1) cell))
11362 (ind ""))
11363 (delete-region start (point))
11364 (when (string-match "\\`#\\+" rpl)
11365 (cond
11366 ((bolp))
11367 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11368 (setq ind (buffer-substring (point-at-bol) (point))))
11369 (t (newline))))
11370 (setq start (point))
11371 (if (string-match "%file" rpl)
11372 (setq rpl (replace-match
11373 (concat
11374 "\""
11375 (save-match-data
11376 (abbreviate-file-name (read-file-name "Include file: ")))
11377 "\"")
11378 t t rpl)))
11379 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11380 (concat "\n" ind)))
11381 (insert rpl)
11382 (if (re-search-backward "\\?" start t) (delete-char 1))))
11384 ;;;; TODO, DEADLINE, Comments
11386 (defun org-toggle-comment ()
11387 "Change the COMMENT state of an entry."
11388 (interactive)
11389 (save-excursion
11390 (org-back-to-heading)
11391 (let (case-fold-search)
11392 (cond
11393 ((looking-at (format org-heading-keyword-regexp-format
11394 org-comment-string))
11395 (goto-char (match-end 1))
11396 (looking-at (concat " +" org-comment-string))
11397 (replace-match "" t t)
11398 (when (eolp) (insert " ")))
11399 ((looking-at org-outline-regexp)
11400 (goto-char (match-end 0))
11401 (insert org-comment-string " "))))))
11403 (defvar org-last-todo-state-is-todo nil
11404 "This is non-nil when the last TODO state change led to a TODO state.
11405 If the last change removed the TODO tag or switched to DONE, then
11406 this is nil.")
11408 (defvar org-setting-tags nil) ; dynamically skipped
11410 (defvar org-todo-setup-filter-hook nil
11411 "Hook for functions that pre-filter todo specs.
11412 Each function takes a todo spec and returns either nil or the spec
11413 transformed into canonical form." )
11415 (defvar org-todo-get-default-hook nil
11416 "Hook for functions that get a default item for todo.
11417 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11418 nil or a string to be used for the todo mark." )
11420 (defvar org-agenda-headline-snapshot-before-repeat)
11422 (defun org-current-effective-time ()
11423 "Return current time adjusted for `org-extend-today-until' variable."
11424 (let* ((ct (org-current-time))
11425 (dct (decode-time ct))
11426 (ct1
11427 (if (and org-use-effective-time
11428 (< (nth 2 dct) org-extend-today-until))
11429 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11430 ct)))
11431 ct1))
11433 (defun org-todo-yesterday (&optional arg)
11434 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11435 (interactive "P")
11436 (if (eq major-mode 'org-agenda-mode)
11437 (apply 'org-agenda-todo-yesterday arg)
11438 (let* ((hour (third (decode-time
11439 (org-current-time))))
11440 (org-extend-today-until (1+ hour)))
11441 (org-todo arg))))
11443 (defun org-todo (&optional arg)
11444 "Change the TODO state of an item.
11445 The state of an item is given by a keyword at the start of the heading,
11446 like
11447 *** TODO Write paper
11448 *** DONE Call mom
11450 The different keywords are specified in the variable `org-todo-keywords'.
11451 By default the available states are \"TODO\" and \"DONE\".
11452 So for this example: when the item starts with TODO, it is changed to DONE.
11453 When it starts with DONE, the DONE is removed. And when neither TODO nor
11454 DONE are present, add TODO at the beginning of the heading.
11456 With \\[universal-argument] prefix arg, use completion to determine the new \
11457 state.
11458 With numeric prefix arg, switch to that state.
11459 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11460 keywords (nextset).
11461 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11462 With a numeric prefix arg of 0, inhibit note taking for the change.
11464 For calling through lisp, arg is also interpreted in the following way:
11465 'none -> empty state
11466 \"\"(empty string) -> switch to empty state
11467 'done -> switch to DONE
11468 'nextset -> switch to the next set of keywords
11469 'previousset -> switch to the previous set of keywords
11470 \"WAITING\" -> switch to the specified keyword, but only if it
11471 really is a member of `org-todo-keywords'."
11472 (interactive "P")
11473 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11474 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11475 'region-start-level 'region))
11476 org-loop-over-headlines-in-active-region)
11477 (org-map-entries
11478 `(org-todo ,arg)
11479 org-loop-over-headlines-in-active-region
11480 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11481 (if (equal arg '(16)) (setq arg 'nextset))
11482 (let ((org-blocker-hook org-blocker-hook)
11483 commentp
11484 case-fold-search)
11485 (when (equal arg '(64))
11486 (setq arg nil org-blocker-hook nil))
11487 (when (and org-blocker-hook
11488 (or org-inhibit-blocking
11489 (org-entry-get nil "NOBLOCKING")))
11490 (setq org-blocker-hook nil))
11491 (save-excursion
11492 (catch 'exit
11493 (org-back-to-heading t)
11494 (when (looking-at (concat "^\\*+ " org-comment-string))
11495 (org-toggle-comment)
11496 (setq commentp t))
11497 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11498 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11499 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11500 (let* ((match-data (match-data))
11501 (startpos (point-at-bol))
11502 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11503 (org-log-done org-log-done)
11504 (org-log-repeat org-log-repeat)
11505 (org-todo-log-states org-todo-log-states)
11506 (org-inhibit-logging
11507 (if (equal arg 0)
11508 (progn (setq arg nil) 'note) org-inhibit-logging))
11509 (this (match-string 1))
11510 (hl-pos (match-beginning 0))
11511 (head (org-get-todo-sequence-head this))
11512 (ass (assoc head org-todo-kwd-alist))
11513 (interpret (nth 1 ass))
11514 (done-word (nth 3 ass))
11515 (final-done-word (nth 4 ass))
11516 (org-last-state (or this ""))
11517 (completion-ignore-case t)
11518 (member (member this org-todo-keywords-1))
11519 (tail (cdr member))
11520 (org-state (cond
11521 ((and org-todo-key-trigger
11522 (or (and (equal arg '(4))
11523 (eq org-use-fast-todo-selection 'prefix))
11524 (and (not arg) org-use-fast-todo-selection
11525 (not (eq org-use-fast-todo-selection
11526 'prefix)))))
11527 ;; Use fast selection
11528 (org-fast-todo-selection))
11529 ((and (equal arg '(4))
11530 (or (not org-use-fast-todo-selection)
11531 (not org-todo-key-trigger)))
11532 ;; Read a state with completion
11533 (org-icompleting-read
11534 "State: " (mapcar (lambda(x) (list x))
11535 org-todo-keywords-1)
11536 nil t))
11537 ((eq arg 'right)
11538 (if this
11539 (if tail (car tail) nil)
11540 (car org-todo-keywords-1)))
11541 ((eq arg 'left)
11542 (if (equal member org-todo-keywords-1)
11544 (if this
11545 (nth (- (length org-todo-keywords-1)
11546 (length tail) 2)
11547 org-todo-keywords-1)
11548 (org-last org-todo-keywords-1))))
11549 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11550 (setq arg nil))) ; hack to fall back to cycling
11551 (arg
11552 ;; user or caller requests a specific state
11553 (cond
11554 ((equal arg "") nil)
11555 ((eq arg 'none) nil)
11556 ((eq arg 'done) (or done-word (car org-done-keywords)))
11557 ((eq arg 'nextset)
11558 (or (car (cdr (member head org-todo-heads)))
11559 (car org-todo-heads)))
11560 ((eq arg 'previousset)
11561 (let ((org-todo-heads (reverse org-todo-heads)))
11562 (or (car (cdr (member head org-todo-heads)))
11563 (car org-todo-heads))))
11564 ((car (member arg org-todo-keywords-1)))
11565 ((stringp arg)
11566 (error "State `%s' not valid in this file" arg))
11567 ((nth (1- (prefix-numeric-value arg))
11568 org-todo-keywords-1))))
11569 ((null member) (or head (car org-todo-keywords-1)))
11570 ((equal this final-done-word) nil) ;; -> make empty
11571 ((null tail) nil) ;; -> first entry
11572 ((memq interpret '(type priority))
11573 (if (eq this-command last-command)
11574 (car tail)
11575 (if (> (length tail) 0)
11576 (or done-word (car org-done-keywords))
11577 nil)))
11579 (car tail))))
11580 (org-state (or
11581 (run-hook-with-args-until-success
11582 'org-todo-get-default-hook org-state org-last-state)
11583 org-state))
11584 (next (if org-state (concat " " org-state " ") " "))
11585 (change-plist (list :type 'todo-state-change :from this :to org-state
11586 :position startpos))
11587 dolog now-done-p)
11588 (when org-blocker-hook
11589 (setq org-last-todo-state-is-todo
11590 (not (member this org-done-keywords)))
11591 (unless (save-excursion
11592 (save-match-data
11593 (org-with-wide-buffer
11594 (run-hook-with-args-until-failure
11595 'org-blocker-hook change-plist))))
11596 (if (org-called-interactively-p 'interactive)
11597 (error "TODO state change from %s to %s blocked" this org-state)
11598 ;; fail silently
11599 (message "TODO state change from %s to %s blocked" this org-state)
11600 (throw 'exit nil))))
11601 (store-match-data match-data)
11602 (replace-match next t t)
11603 (unless (pos-visible-in-window-p hl-pos)
11604 (message "TODO state changed to %s" (org-trim next)))
11605 (unless head
11606 (setq head (org-get-todo-sequence-head org-state)
11607 ass (assoc head org-todo-kwd-alist)
11608 interpret (nth 1 ass)
11609 done-word (nth 3 ass)
11610 final-done-word (nth 4 ass)))
11611 (when (memq arg '(nextset previousset))
11612 (message "Keyword-Set %d/%d: %s"
11613 (- (length org-todo-sets) -1
11614 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11615 (length org-todo-sets)
11616 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11617 (setq org-last-todo-state-is-todo
11618 (not (member org-state org-done-keywords)))
11619 (setq now-done-p (and (member org-state org-done-keywords)
11620 (not (member this org-done-keywords))))
11621 (and logging (org-local-logging logging))
11622 (when (and (or org-todo-log-states org-log-done)
11623 (not (eq org-inhibit-logging t))
11624 (not (memq arg '(nextset previousset))))
11625 ;; we need to look at recording a time and note
11626 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11627 (nth 2 (assoc this org-todo-log-states))))
11628 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11629 (setq dolog 'time))
11630 (when (and org-state
11631 (member org-state org-not-done-keywords)
11632 (not (member this org-not-done-keywords)))
11633 ;; This is now a todo state and was not one before
11634 ;; If there was a CLOSED time stamp, get rid of it.
11635 (org-add-planning-info nil nil 'closed))
11636 (when (and now-done-p org-log-done)
11637 ;; It is now done, and it was not done before
11638 (org-add-planning-info 'closed (org-current-effective-time))
11639 (if (and (not dolog) (eq 'note org-log-done))
11640 (org-add-log-setup 'done org-state this 'findpos 'note)))
11641 (when (and org-state dolog)
11642 ;; This is a non-nil state, and we need to log it
11643 (org-add-log-setup 'state org-state this 'findpos dolog)))
11644 ;; Fixup tag positioning
11645 (org-todo-trigger-tag-changes org-state)
11646 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11647 (when org-provide-todo-statistics
11648 (org-update-parent-todo-statistics))
11649 (run-hooks 'org-after-todo-state-change-hook)
11650 (if (and arg (not (member org-state org-done-keywords)))
11651 (setq head (org-get-todo-sequence-head org-state)))
11652 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11653 ;; Do we need to trigger a repeat?
11654 (when now-done-p
11655 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11656 ;; This is for the agenda, take a snapshot of the headline.
11657 (save-match-data
11658 (setq org-agenda-headline-snapshot-before-repeat
11659 (org-get-heading))))
11660 (org-auto-repeat-maybe org-state))
11661 ;; Fixup cursor location if close to the keyword
11662 (if (and (outline-on-heading-p)
11663 (not (bolp))
11664 (save-excursion (beginning-of-line 1)
11665 (looking-at org-todo-line-regexp))
11666 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11667 (progn
11668 (goto-char (or (match-end 2) (match-end 1)))
11669 (and (looking-at " ") (just-one-space))))
11670 (when org-trigger-hook
11671 (save-excursion
11672 (run-hook-with-args 'org-trigger-hook change-plist)))
11673 (when commentp (org-toggle-comment))))))))
11675 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11676 "Block turning an entry into a TODO, using the hierarchy.
11677 This checks whether the current task should be blocked from state
11678 changes. Such blocking occurs when:
11680 1. The task has children which are not all in a completed state.
11682 2. A task has a parent with the property :ORDERED:, and there
11683 are siblings prior to the current task with incomplete
11684 status.
11686 3. The parent of the task is blocked because it has siblings that should
11687 be done first, or is child of a block grandparent TODO entry."
11689 (if (not org-enforce-todo-dependencies)
11690 t ; if locally turned off don't block
11691 (catch 'dont-block
11692 ;; If this is not a todo state change, or if this entry is already DONE,
11693 ;; do not block
11694 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11695 (member (plist-get change-plist :from)
11696 (cons 'done org-done-keywords))
11697 (member (plist-get change-plist :to)
11698 (cons 'todo org-not-done-keywords))
11699 (not (plist-get change-plist :to)))
11700 (throw 'dont-block t))
11701 ;; If this task has children, and any are undone, it's blocked
11702 (save-excursion
11703 (org-back-to-heading t)
11704 (let ((this-level (funcall outline-level)))
11705 (outline-next-heading)
11706 (let ((child-level (funcall outline-level)))
11707 (while (and (not (eobp))
11708 (> child-level this-level))
11709 ;; this todo has children, check whether they are all
11710 ;; completed
11711 (if (and (not (org-entry-is-done-p))
11712 (org-entry-is-todo-p))
11713 (throw 'dont-block nil))
11714 (outline-next-heading)
11715 (setq child-level (funcall outline-level))))))
11716 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11717 ;; any previous siblings are undone, it's blocked
11718 (save-excursion
11719 (org-back-to-heading t)
11720 (let* ((pos (point))
11721 (parent-pos (and (org-up-heading-safe) (point))))
11722 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11723 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11724 (forward-line 1)
11725 (re-search-forward org-not-done-heading-regexp pos t))
11726 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11727 ;; Search further up the hierarchy, to see if an ancestor is blocked
11728 (while t
11729 (goto-char parent-pos)
11730 (if (not (looking-at org-not-done-heading-regexp))
11731 (throw 'dont-block t)) ; do not block, parent is not a TODO
11732 (setq pos (point))
11733 (setq parent-pos (and (org-up-heading-safe) (point)))
11734 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11735 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11736 (forward-line 1)
11737 (re-search-forward org-not-done-heading-regexp pos t))
11738 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11740 (defcustom org-track-ordered-property-with-tag nil
11741 "Should the ORDERED property also be shown as a tag?
11742 The ORDERED property decides if an entry should require subtasks to be
11743 completed in sequence. Since a property is not very visible, setting
11744 this option means that toggling the ORDERED property with the command
11745 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11746 not relevant for the behavior, but it makes things more visible.
11748 Note that toggling the tag with tags commands will not change the property
11749 and therefore not influence behavior!
11751 This can be t, meaning the tag ORDERED should be used, It can also be a
11752 string to select a different tag for this task."
11753 :group 'org-todo
11754 :type '(choice
11755 (const :tag "No tracking" nil)
11756 (const :tag "Track with ORDERED tag" t)
11757 (string :tag "Use other tag")))
11759 (defun org-toggle-ordered-property ()
11760 "Toggle the ORDERED property of the current entry.
11761 For better visibility, you can track the value of this property with a tag.
11762 See variable `org-track-ordered-property-with-tag'."
11763 (interactive)
11764 (let* ((t1 org-track-ordered-property-with-tag)
11765 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11766 (save-excursion
11767 (org-back-to-heading)
11768 (if (org-entry-get nil "ORDERED")
11769 (progn
11770 (org-delete-property "ORDERED")
11771 (and tag (org-toggle-tag tag 'off))
11772 (message "Subtasks can be completed in arbitrary order"))
11773 (org-entry-put nil "ORDERED" "t")
11774 (and tag (org-toggle-tag tag 'on))
11775 (message "Subtasks must be completed in sequence")))))
11777 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11778 (defun org-block-todo-from-checkboxes (change-plist)
11779 "Block turning an entry into a TODO, using checkboxes.
11780 This checks whether the current task should be blocked from state
11781 changes because there are unchecked boxes in this entry."
11782 (if (not org-enforce-todo-checkbox-dependencies)
11783 t ; if locally turned off don't block
11784 (catch 'dont-block
11785 ;; If this is not a todo state change, or if this entry is already DONE,
11786 ;; do not block
11787 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11788 (member (plist-get change-plist :from)
11789 (cons 'done org-done-keywords))
11790 (member (plist-get change-plist :to)
11791 (cons 'todo org-not-done-keywords))
11792 (not (plist-get change-plist :to)))
11793 (throw 'dont-block t))
11794 ;; If this task has checkboxes that are not checked, it's blocked
11795 (save-excursion
11796 (org-back-to-heading t)
11797 (let ((beg (point)) end)
11798 (outline-next-heading)
11799 (setq end (point))
11800 (goto-char beg)
11801 (if (org-list-search-forward
11802 (concat (org-item-beginning-re)
11803 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11804 "\\[[- ]\\]")
11805 end t)
11806 (progn
11807 (if (boundp 'org-blocked-by-checkboxes)
11808 (setq org-blocked-by-checkboxes t))
11809 (throw 'dont-block nil)))))
11810 t))) ; do not block
11812 (defun org-entry-blocked-p ()
11813 "Is the current entry blocked?"
11814 (org-with-buffer-modified-unmodified
11815 (if (org-entry-get nil "NOBLOCKING")
11816 nil ;; Never block this entry
11817 (not
11818 (run-hook-with-args-until-failure
11819 'org-blocker-hook
11820 (list :type 'todo-state-change
11821 :position (point)
11822 :from 'todo
11823 :to 'done))))))
11825 (defun org-update-statistics-cookies (all)
11826 "Update the statistics cookie, either from TODO or from checkboxes.
11827 This should be called with the cursor in a line with a statistics cookie."
11828 (interactive "P")
11829 (if all
11830 (progn
11831 (org-update-checkbox-count 'all)
11832 (org-map-entries 'org-update-parent-todo-statistics))
11833 (if (not (org-at-heading-p))
11834 (org-update-checkbox-count)
11835 (let ((pos (point-marker))
11836 end l1 l2)
11837 (ignore-errors (org-back-to-heading t))
11838 (if (not (org-at-heading-p))
11839 (org-update-checkbox-count)
11840 (setq l1 (org-outline-level))
11841 (setq end (save-excursion
11842 (outline-next-heading)
11843 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11844 (point)))
11845 (if (and (save-excursion
11846 (re-search-forward
11847 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11848 (not (save-excursion (re-search-forward
11849 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11850 (org-update-checkbox-count)
11851 (if (and l2 (> l2 l1))
11852 (progn
11853 (goto-char end)
11854 (org-update-parent-todo-statistics))
11855 (goto-char pos)
11856 (beginning-of-line 1)
11857 (while (re-search-forward
11858 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11859 (point-at-eol) t)
11860 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11861 (goto-char pos)
11862 (move-marker pos nil)))))
11864 (defvar org-entry-property-inherited-from) ;; defined below
11865 (defun org-update-parent-todo-statistics ()
11866 "Update any statistics cookie in the parent of the current headline.
11867 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11868 the entire subtree and this will travel up the hierarchy and update
11869 statistics everywhere."
11870 (let* ((prop (save-excursion (org-up-heading-safe)
11871 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11872 (recursive (or (not org-hierarchical-todo-statistics)
11873 (and prop (string-match "\\<recursive\\>" prop))))
11874 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11876 (first t)
11877 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11878 level ltoggle l1 new ndel
11879 (cnt-all 0) (cnt-done 0) is-percent kwd
11880 checkbox-beg ov ovs ove cookie-present)
11881 (catch 'exit
11882 (save-excursion
11883 (beginning-of-line 1)
11884 (setq ltoggle (funcall outline-level))
11885 ;; Three situations are to consider:
11887 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11888 ;; to the top-level ancestor on the headline;
11890 ;; 2. If parent has "recursive" property, repeat up to the
11891 ;; headline setting that property, taking inheritance into
11892 ;; account;
11894 ;; 3. Else, move up to direct parent and proceed only once.
11895 (while (and (setq level (org-up-heading-safe))
11896 (or recursive first)
11897 (>= (point) lim))
11898 (setq first nil cookie-present nil)
11899 (unless (and level
11900 (not (string-match
11901 "\\<checkbox\\>"
11902 (downcase (or (org-entry-get nil "COOKIE_DATA")
11903 "")))))
11904 (throw 'exit nil))
11905 (while (re-search-forward box-re (point-at-eol) t)
11906 (setq cnt-all 0 cnt-done 0 cookie-present t)
11907 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11908 (save-match-data
11909 (unless (outline-next-heading) (throw 'exit nil))
11910 (while (and (looking-at org-complex-heading-regexp)
11911 (> (setq l1 (length (match-string 1))) level))
11912 (setq kwd (and (or recursive (= l1 ltoggle))
11913 (match-string 2)))
11914 (if (or (eq org-provide-todo-statistics 'all-headlines)
11915 (and (listp org-provide-todo-statistics)
11916 (or (member kwd org-provide-todo-statistics)
11917 (member kwd org-done-keywords))))
11918 (setq cnt-all (1+ cnt-all))
11919 (if (eq org-provide-todo-statistics t)
11920 (and kwd (setq cnt-all (1+ cnt-all)))))
11921 (and (member kwd org-done-keywords)
11922 (setq cnt-done (1+ cnt-done)))
11923 (outline-next-heading)))
11924 (setq new
11925 (if is-percent
11926 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11927 (format "[%d/%d]" cnt-done cnt-all))
11928 ndel (- (match-end 0) checkbox-beg))
11929 ;; handle overlays when updating cookie from column view
11930 (when (setq ov (car (overlays-at checkbox-beg)))
11931 (setq ovs (overlay-start ov) ove (overlay-end ov))
11932 (delete-overlay ov))
11933 (goto-char checkbox-beg)
11934 (insert new)
11935 (delete-region (point) (+ (point) ndel))
11936 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11937 (when ov (move-overlay ov ovs ove)))
11938 (when cookie-present
11939 (run-hook-with-args 'org-after-todo-statistics-hook
11940 cnt-done (- cnt-all cnt-done))))))
11941 (run-hooks 'org-todo-statistics-hook)))
11943 (defvar org-after-todo-statistics-hook nil
11944 "Hook that is called after a TODO statistics cookie has been updated.
11945 Each function is called with two arguments: the number of not-done entries
11946 and the number of done entries.
11948 For example, the following function, when added to this hook, will switch
11949 an entry to DONE when all children are done, and back to TODO when new
11950 entries are set to a TODO status. Note that this hook is only called
11951 when there is a statistics cookie in the headline!
11953 (defun org-summary-todo (n-done n-not-done)
11954 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11955 (let (org-log-done org-log-states) ; turn off logging
11956 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11959 (defvar org-todo-statistics-hook nil
11960 "Hook that is run whenever Org thinks TODO statistics should be updated.
11961 This hook runs even if there is no statistics cookie present, in which case
11962 `org-after-todo-statistics-hook' would not run.")
11964 (defun org-todo-trigger-tag-changes (state)
11965 "Apply the changes defined in `org-todo-state-tags-triggers'."
11966 (let ((l org-todo-state-tags-triggers)
11967 changes)
11968 (when (or (not state) (equal state ""))
11969 (setq changes (append changes (cdr (assoc "" l)))))
11970 (when (and (stringp state) (> (length state) 0))
11971 (setq changes (append changes (cdr (assoc state l)))))
11972 (when (member state org-not-done-keywords)
11973 (setq changes (append changes (cdr (assoc 'todo l)))))
11974 (when (member state org-done-keywords)
11975 (setq changes (append changes (cdr (assoc 'done l)))))
11976 (dolist (c changes)
11977 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11979 (defun org-local-logging (value)
11980 "Get logging settings from a property VALUE."
11981 (let* (words w a)
11982 ;; directly set the variables, they are already local.
11983 (setq org-log-done nil
11984 org-log-repeat nil
11985 org-todo-log-states nil)
11986 (setq words (org-split-string value))
11987 (while (setq w (pop words))
11988 (cond
11989 ((setq a (assoc w org-startup-options))
11990 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11991 (set (nth 1 a) (nth 2 a))))
11992 ((setq a (org-extract-log-state-settings w))
11993 (and (member (car a) org-todo-keywords-1)
11994 (push a org-todo-log-states)))))))
11996 (defun org-get-todo-sequence-head (kwd)
11997 "Return the head of the TODO sequence to which KWD belongs.
11998 If KWD is not set, check if there is a text property remembering the
11999 right sequence."
12000 (let (p)
12001 (cond
12002 ((not kwd)
12003 (or (get-text-property (point-at-bol) 'org-todo-head)
12004 (progn
12005 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12006 nil (point-at-eol)))
12007 (get-text-property p 'org-todo-head))))
12008 ((not (member kwd org-todo-keywords-1))
12009 (car org-todo-keywords-1))
12010 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12012 (defun org-fast-todo-selection ()
12013 "Fast TODO keyword selection with single keys.
12014 Returns the new TODO keyword, or nil if no state change should occur."
12015 (let* ((fulltable org-todo-key-alist)
12016 (done-keywords org-done-keywords) ;; needed for the faces.
12017 (maxlen (apply 'max (mapcar
12018 (lambda (x)
12019 (if (stringp (car x)) (string-width (car x)) 0))
12020 fulltable)))
12021 (expert nil)
12022 (fwidth (+ maxlen 3 1 3))
12023 (ncol (/ (- (window-width) 4) fwidth))
12024 tg cnt e c tbl
12025 groups ingroup)
12026 (save-excursion
12027 (save-window-excursion
12028 (if expert
12029 (set-buffer (get-buffer-create " *Org todo*"))
12030 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12031 (erase-buffer)
12032 (org-set-local 'org-done-keywords done-keywords)
12033 (setq tbl fulltable cnt 0)
12034 (while (setq e (pop tbl))
12035 (cond
12036 ((equal e '(:startgroup))
12037 (push '() groups) (setq ingroup t)
12038 (when (not (= cnt 0))
12039 (setq cnt 0)
12040 (insert "\n"))
12041 (insert "{ "))
12042 ((equal e '(:endgroup))
12043 (setq ingroup nil cnt 0)
12044 (insert "}\n"))
12045 ((equal e '(:newline))
12046 (when (not (= cnt 0))
12047 (setq cnt 0)
12048 (insert "\n")
12049 (setq e (car tbl))
12050 (while (equal (car tbl) '(:newline))
12051 (insert "\n")
12052 (setq tbl (cdr tbl)))))
12054 (setq tg (car e) c (cdr e))
12055 (if ingroup (push tg (car groups)))
12056 (setq tg (org-add-props tg nil 'face
12057 (org-get-todo-face tg)))
12058 (if (and (= cnt 0) (not ingroup)) (insert " "))
12059 (insert "[" c "] " tg (make-string
12060 (- fwidth 4 (length tg)) ?\ ))
12061 (when (= (setq cnt (1+ cnt)) ncol)
12062 (insert "\n")
12063 (if ingroup (insert " "))
12064 (setq cnt 0)))))
12065 (insert "\n")
12066 (goto-char (point-min))
12067 (if (not expert) (org-fit-window-to-buffer))
12068 (message "[a-z..]:Set [SPC]:clear")
12069 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12070 (cond
12071 ((or (= c ?\C-g)
12072 (and (= c ?q) (not (rassoc c fulltable))))
12073 (setq quit-flag t))
12074 ((= c ?\ ) nil)
12075 ((setq e (rassoc c fulltable) tg (car e))
12077 (t (setq quit-flag t)))))))
12079 (defun org-entry-is-todo-p ()
12080 (member (org-get-todo-state) org-not-done-keywords))
12082 (defun org-entry-is-done-p ()
12083 (member (org-get-todo-state) org-done-keywords))
12085 (defun org-get-todo-state ()
12086 (save-excursion
12087 (org-back-to-heading t)
12088 (and (looking-at org-todo-line-regexp)
12089 (match-end 2)
12090 (match-string 2))))
12092 (defun org-at-date-range-p (&optional inactive-ok)
12093 "Is the cursor inside a date range?"
12094 (interactive)
12095 (save-excursion
12096 (catch 'exit
12097 (let ((pos (point)))
12098 (skip-chars-backward "^[<\r\n")
12099 (skip-chars-backward "<[")
12100 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12101 (>= (match-end 0) pos)
12102 (throw 'exit t))
12103 (skip-chars-backward "^<[\r\n")
12104 (skip-chars-backward "<[")
12105 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12106 (>= (match-end 0) pos)
12107 (throw 'exit t)))
12108 nil)))
12110 (defun org-get-repeat (&optional tagline)
12111 "Check if there is a deadline/schedule with repeater in this entry."
12112 (save-match-data
12113 (save-excursion
12114 (org-back-to-heading t)
12115 (and (re-search-forward (if tagline
12116 (concat tagline "\\s-*" org-repeat-re)
12117 org-repeat-re)
12118 (org-entry-end-position) t)
12119 (match-string-no-properties 1)))))
12121 (defvar org-last-changed-timestamp)
12122 (defvar org-last-inserted-timestamp)
12123 (defvar org-log-post-message)
12124 (defvar org-log-note-purpose)
12125 (defvar org-log-note-how)
12126 (defvar org-log-note-extra)
12127 (defun org-auto-repeat-maybe (done-word)
12128 "Check if the current headline contains a repeated deadline/schedule.
12129 If yes, set TODO state back to what it was and change the base date
12130 of repeating deadline/scheduled time stamps to new date.
12131 This function is run automatically after each state change to a DONE state."
12132 ;; last-state is dynamically scoped into this function
12133 (let* ((repeat (org-get-repeat))
12134 (aa (assoc org-last-state org-todo-kwd-alist))
12135 (interpret (nth 1 aa))
12136 (head (nth 2 aa))
12137 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12138 (msg "Entry repeats: ")
12139 (org-log-done nil)
12140 (org-todo-log-states nil)
12141 re type n what ts time to-state)
12142 (when repeat
12143 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12144 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12145 org-todo-repeat-to-state))
12146 (unless (and to-state (member to-state org-todo-keywords-1))
12147 (setq to-state (if (eq interpret 'type) org-last-state head)))
12148 (org-todo to-state)
12149 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12150 (org-entry-put nil "LAST_REPEAT" (format-time-string
12151 (org-time-stamp-format t t))))
12152 (when org-log-repeat
12153 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12154 (memq 'org-add-log-note post-command-hook))
12155 ;; OK, we are already setup for some record
12156 (if (eq org-log-repeat 'note)
12157 ;; make sure we take a note, not only a time stamp
12158 (setq org-log-note-how 'note))
12159 ;; Set up for taking a record
12160 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12161 org-last-state
12162 'findpos org-log-repeat)))
12163 (org-back-to-heading t)
12164 (org-add-planning-info nil nil 'closed)
12165 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12166 org-deadline-time-regexp "\\)\\|\\("
12167 org-ts-regexp "\\)"))
12168 (while (re-search-forward
12169 re (save-excursion (outline-next-heading) (point)) t)
12170 (setq type (if (match-end 1) org-scheduled-string
12171 (if (match-end 3) org-deadline-string "Plain:"))
12172 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12173 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12174 (setq n (string-to-number (match-string 2 ts))
12175 what (match-string 3 ts))
12176 (if (equal what "w") (setq n (* n 7) what "d"))
12177 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12178 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12179 ;; Preparation, see if we need to modify the start date for the change
12180 (when (match-end 1)
12181 (setq time (save-match-data (org-time-string-to-time ts)))
12182 (cond
12183 ((equal (match-string 1 ts) ".")
12184 ;; Shift starting date to today
12185 (org-timestamp-change
12186 (- (org-today) (time-to-days time))
12187 'day))
12188 ((equal (match-string 1 ts) "+")
12189 (let ((nshiftmax 10) (nshift 0))
12190 (while (or (= nshift 0)
12191 (<= (time-to-days time)
12192 (time-to-days (current-time))))
12193 (when (= (incf nshift) nshiftmax)
12194 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12195 (error "Abort")))
12196 (org-timestamp-change n (cdr (assoc what whata)))
12197 (org-at-timestamp-p t)
12198 (setq ts (match-string 1))
12199 (setq time (save-match-data (org-time-string-to-time ts)))))
12200 (org-timestamp-change (- n) (cdr (assoc what whata)))
12201 ;; rematch, so that we have everything in place for the real shift
12202 (org-at-timestamp-p t)
12203 (setq ts (match-string 1))
12204 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12205 (org-timestamp-change n (cdr (assoc what whata)))
12206 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12207 (setq org-log-post-message msg)
12208 (message "%s" msg))))
12210 (defun org-show-todo-tree (arg)
12211 "Make a compact tree which shows all headlines marked with TODO.
12212 The tree will show the lines where the regexp matches, and all higher
12213 headlines above the match.
12214 With a \\[universal-argument] prefix, prompt for a regexp to match.
12215 With a numeric prefix N, construct a sparse tree for the Nth element
12216 of `org-todo-keywords-1'."
12217 (interactive "P")
12218 (let ((case-fold-search nil)
12219 (kwd-re
12220 (cond ((null arg) org-not-done-regexp)
12221 ((equal arg '(4))
12222 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12223 (mapcar 'list org-todo-keywords-1))))
12224 (concat "\\("
12225 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12226 "\\)\\>")))
12227 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12228 (regexp-quote (nth (1- (prefix-numeric-value arg))
12229 org-todo-keywords-1)))
12230 (t (error "Invalid prefix argument: %s" arg)))))
12231 (message "%d TODO entries found"
12232 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12234 (defun org-deadline (&optional remove time)
12235 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12236 With argument REMOVE, remove any deadline from the item.
12237 With argument TIME, set the deadline at the corresponding date. TIME
12238 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12239 (interactive "P")
12240 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12241 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12242 'region-start-level 'region))
12243 org-loop-over-headlines-in-active-region)
12244 (org-map-entries
12245 `(org-deadline ',remove ,time)
12246 org-loop-over-headlines-in-active-region
12247 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12248 (let* ((old-date (org-entry-get nil "DEADLINE"))
12249 (repeater (and old-date
12250 (string-match
12251 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12252 old-date)
12253 (match-string 1 old-date))))
12254 (if remove
12255 (progn
12256 (when (and old-date org-log-redeadline)
12257 (org-add-log-setup 'deldeadline nil old-date 'findpos
12258 org-log-redeadline))
12259 (org-remove-timestamp-with-keyword org-deadline-string)
12260 (message "Item no longer has a deadline."))
12261 (org-add-planning-info 'deadline time 'closed)
12262 (when (and old-date org-log-redeadline
12263 (not (equal old-date
12264 (substring org-last-inserted-timestamp 1 -1))))
12265 (org-add-log-setup 'redeadline nil old-date 'findpos
12266 org-log-redeadline))
12267 (when repeater
12268 (save-excursion
12269 (org-back-to-heading t)
12270 (when (re-search-forward (concat org-deadline-string " "
12271 org-last-inserted-timestamp)
12272 (save-excursion
12273 (outline-next-heading) (point)) t)
12274 (goto-char (1- (match-end 0)))
12275 (insert " " repeater)
12276 (setq org-last-inserted-timestamp
12277 (concat (substring org-last-inserted-timestamp 0 -1)
12278 " " repeater
12279 (substring org-last-inserted-timestamp -1))))))
12280 (message "Deadline on %s" org-last-inserted-timestamp)))))
12282 (defun org-schedule (&optional remove time)
12283 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12284 With argument REMOVE, remove any scheduling date from the item.
12285 With argument TIME, scheduled at the corresponding date. TIME can
12286 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12287 (interactive "P")
12288 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12289 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12290 'region-start-level 'region))
12291 org-loop-over-headlines-in-active-region)
12292 (org-map-entries
12293 `(org-schedule ',remove ,time)
12294 org-loop-over-headlines-in-active-region
12295 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12296 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12297 (repeater (and old-date
12298 (string-match
12299 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12300 old-date)
12301 (match-string 1 old-date))))
12302 (if remove
12303 (progn
12304 (when (and old-date org-log-reschedule)
12305 (org-add-log-setup 'delschedule nil old-date 'findpos
12306 org-log-reschedule))
12307 (org-remove-timestamp-with-keyword org-scheduled-string)
12308 (message "Item is no longer scheduled."))
12309 (org-add-planning-info 'scheduled time 'closed)
12310 (when (and old-date org-log-reschedule
12311 (not (equal old-date
12312 (substring org-last-inserted-timestamp 1 -1))))
12313 (org-add-log-setup 'reschedule nil old-date 'findpos
12314 org-log-reschedule))
12315 (when repeater
12316 (save-excursion
12317 (org-back-to-heading t)
12318 (when (re-search-forward (concat org-scheduled-string " "
12319 org-last-inserted-timestamp)
12320 (save-excursion
12321 (outline-next-heading) (point)) t)
12322 (goto-char (1- (match-end 0)))
12323 (insert " " repeater)
12324 (setq org-last-inserted-timestamp
12325 (concat (substring org-last-inserted-timestamp 0 -1)
12326 " " repeater
12327 (substring org-last-inserted-timestamp -1))))))
12328 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12330 (defun org-get-scheduled-time (pom &optional inherit)
12331 "Get the scheduled time as a time tuple, of a format suitable
12332 for calling org-schedule with, or if there is no scheduling,
12333 returns nil."
12334 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12335 (when time
12336 (apply 'encode-time (org-parse-time-string time)))))
12338 (defun org-get-deadline-time (pom &optional inherit)
12339 "Get the deadline as a time tuple, of a format suitable for
12340 calling org-deadline with, or if there is no scheduling, returns
12341 nil."
12342 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12343 (when time
12344 (apply 'encode-time (org-parse-time-string time)))))
12346 (defun org-remove-timestamp-with-keyword (keyword)
12347 "Remove all time stamps with KEYWORD in the current entry."
12348 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12349 beg)
12350 (save-excursion
12351 (org-back-to-heading t)
12352 (setq beg (point))
12353 (outline-next-heading)
12354 (while (re-search-backward re beg t)
12355 (replace-match "")
12356 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12357 (equal (char-before) ?\ ))
12358 (backward-delete-char 1)
12359 (if (string-match "^[ \t]*$" (buffer-substring
12360 (point-at-bol) (point-at-eol)))
12361 (delete-region (point-at-bol)
12362 (min (point-max) (1+ (point-at-eol))))))))))
12364 (defun org-add-planning-info (what &optional time &rest remove)
12365 "Insert new timestamp with keyword in the line directly after the headline.
12366 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12367 If non is given, the user is prompted for a date.
12368 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12369 be removed."
12370 (interactive)
12371 (let (org-time-was-given org-end-time-was-given ts
12372 end default-time default-input)
12374 (catch 'exit
12375 (when (and (memq what '(scheduled deadline))
12376 (or (not time)
12377 (and (stringp time)
12378 (string-match "^[-+]+[0-9]" time))))
12379 ;; Try to get a default date/time from existing timestamp
12380 (save-excursion
12381 (org-back-to-heading t)
12382 (setq end (save-excursion (outline-next-heading) (point)))
12383 (when (re-search-forward (if (eq what 'scheduled)
12384 org-scheduled-time-regexp
12385 org-deadline-time-regexp)
12386 end t)
12387 (setq ts (match-string 1)
12388 default-time
12389 (apply 'encode-time (org-parse-time-string ts))
12390 default-input (and ts (org-get-compact-tod ts))))))
12391 (when what
12392 (setq time
12393 (if (stringp time)
12394 ;; This is a string (relative or absolute), set proper date
12395 (apply 'encode-time
12396 (org-read-date-analyze
12397 time default-time (decode-time default-time)))
12398 ;; If necessary, get the time from the user
12399 (or time (org-read-date nil 'to-time nil nil
12400 default-time default-input)))))
12402 (when (and org-insert-labeled-timestamps-at-point
12403 (member what '(scheduled deadline)))
12404 (insert
12405 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12406 (org-insert-time-stamp time org-time-was-given
12407 nil nil nil (list org-end-time-was-given))
12408 (setq what nil))
12409 (save-excursion
12410 (save-restriction
12411 (let (col list elt ts buffer-invisibility-spec)
12412 (org-back-to-heading t)
12413 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12414 (goto-char (match-end 1))
12415 (setq col (current-column))
12416 (goto-char (match-end 0))
12417 (if (eobp) (insert "\n") (forward-char 1))
12418 (when (and (not what)
12419 (not (looking-at
12420 (concat "[ \t]*"
12421 org-keyword-time-not-clock-regexp))))
12422 ;; Nothing to add, nothing to remove...... :-)
12423 (throw 'exit nil))
12424 (if (and (not (looking-at org-outline-regexp))
12425 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12426 "[^\r\n]*"))
12427 (not (equal (match-string 1) org-clock-string)))
12428 (narrow-to-region (match-beginning 0) (match-end 0))
12429 (insert-before-markers "\n")
12430 (backward-char 1)
12431 (narrow-to-region (point) (point))
12432 (and org-adapt-indentation (org-indent-to-column col)))
12433 ;; Check if we have to remove something.
12434 (setq list (cons what remove))
12435 (while list
12436 (setq elt (pop list))
12437 (when (or (and (eq elt 'scheduled)
12438 (re-search-forward org-scheduled-time-regexp nil t))
12439 (and (eq elt 'deadline)
12440 (re-search-forward org-deadline-time-regexp nil t))
12441 (and (eq elt 'closed)
12442 (re-search-forward org-closed-time-regexp nil t)))
12443 (replace-match "")
12444 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12445 (and (looking-at "[ \t]+") (replace-match ""))
12446 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12447 (when what
12448 (insert
12449 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12450 (cond ((eq what 'scheduled) org-scheduled-string)
12451 ((eq what 'deadline) org-deadline-string)
12452 ((eq what 'closed) org-closed-string))
12453 " ")
12454 (setq ts (org-insert-time-stamp
12455 time
12456 (or org-time-was-given
12457 (and (eq what 'closed) org-log-done-with-time))
12458 (eq what 'closed)
12459 nil nil (list org-end-time-was-given)))
12460 (insert
12461 (if (not (or (bolp) (eq (char-before) ?\ )
12462 (memq (char-after) '(32 10))
12463 (eobp))) " " ""))
12464 (end-of-line 1))
12465 (goto-char (point-min))
12466 (widen)
12467 (if (and (looking-at "[ \t]*\n")
12468 (equal (char-before) ?\n))
12469 (delete-region (1- (point)) (point-at-eol)))
12470 ts))))))
12472 (defvar org-log-note-marker (make-marker))
12473 (defvar org-log-note-purpose nil)
12474 (defvar org-log-note-state nil)
12475 (defvar org-log-note-previous-state nil)
12476 (defvar org-log-note-how nil)
12477 (defvar org-log-note-extra nil)
12478 (defvar org-log-note-window-configuration nil)
12479 (defvar org-log-note-return-to (make-marker))
12480 (defvar org-log-note-effective-time nil
12481 "Remembered current time so that dynamically scoped
12482 `org-extend-today-until' affects tha timestamps in state change
12483 log")
12485 (defvar org-log-post-message nil
12486 "Message to be displayed after a log note has been stored.
12487 The auto-repeater uses this.")
12489 (defun org-add-note ()
12490 "Add a note to the current entry.
12491 This is done in the same way as adding a state change note."
12492 (interactive)
12493 (org-add-log-setup 'note nil nil 'findpos nil))
12495 (defvar org-property-end-re)
12496 (defun org-add-log-setup (&optional purpose state prev-state
12497 findpos how extra)
12498 "Set up the post command hook to take a note.
12499 If this is about to TODO state change, the new state is expected in STATE.
12500 When FINDPOS is non-nil, find the correct position for the note in
12501 the current entry. If not, assume that it can be inserted at point.
12502 HOW is an indicator what kind of note should be created.
12503 EXTRA is additional text that will be inserted into the notes buffer."
12504 (let* ((org-log-into-drawer (org-log-into-drawer))
12505 (drawer (cond ((stringp org-log-into-drawer)
12506 org-log-into-drawer)
12507 (org-log-into-drawer "LOGBOOK"))))
12508 (save-restriction
12509 (save-excursion
12510 (when findpos
12511 (org-back-to-heading t)
12512 (narrow-to-region (point) (save-excursion
12513 (outline-next-heading) (point)))
12514 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12515 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12516 "[^\r\n]*\\)?"))
12517 (goto-char (match-end 0))
12518 (cond
12519 (drawer
12520 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12521 nil t)
12522 (progn
12523 (goto-char (match-end 0))
12524 (or org-log-states-order-reversed
12525 (and (re-search-forward org-property-end-re nil t)
12526 (goto-char (1- (match-beginning 0))))))
12527 (insert "\n:" drawer ":\n:END:")
12528 (beginning-of-line 0)
12529 (org-indent-line)
12530 (beginning-of-line 2)
12531 (org-indent-line)
12532 (end-of-line 0)))
12533 ((and org-log-state-notes-insert-after-drawers
12534 (save-excursion
12535 (forward-line) (looking-at org-drawer-regexp)))
12536 (forward-line)
12537 (while (looking-at org-drawer-regexp)
12538 (goto-char (match-end 0))
12539 (re-search-forward org-property-end-re (point-max) t)
12540 (forward-line))
12541 (forward-line -1)))
12542 (unless org-log-states-order-reversed
12543 (and (= (char-after) ?\n) (forward-char 1))
12544 (org-skip-over-state-notes)
12545 (skip-chars-backward " \t\n\r")))
12546 (move-marker org-log-note-marker (point))
12547 (setq org-log-note-purpose purpose
12548 org-log-note-state state
12549 org-log-note-previous-state prev-state
12550 org-log-note-how how
12551 org-log-note-extra extra
12552 org-log-note-effective-time (org-current-effective-time))
12553 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12555 (defun org-skip-over-state-notes ()
12556 "Skip past the list of State notes in an entry."
12557 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12558 (when (ignore-errors (goto-char (org-in-item-p)))
12559 (let* ((struct (org-list-struct))
12560 (prevs (org-list-prevs-alist struct)))
12561 (while (looking-at "[ \t]*- State")
12562 (goto-char (or (org-list-get-next-item (point) struct prevs)
12563 (org-list-get-item-end (point) struct)))))))
12565 (defun org-add-log-note (&optional purpose)
12566 "Pop up a window for taking a note, and add this note later at point."
12567 (remove-hook 'post-command-hook 'org-add-log-note)
12568 (setq org-log-note-window-configuration (current-window-configuration))
12569 (delete-other-windows)
12570 (move-marker org-log-note-return-to (point))
12571 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12572 (goto-char org-log-note-marker)
12573 (org-switch-to-buffer-other-window "*Org Note*")
12574 (erase-buffer)
12575 (if (memq org-log-note-how '(time state))
12576 (let (current-prefix-arg) (org-store-log-note))
12577 (let ((org-inhibit-startup t)) (org-mode))
12578 (insert (format "# Insert note for %s.
12579 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12580 (cond
12581 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12582 ((eq org-log-note-purpose 'done) "closed todo item")
12583 ((eq org-log-note-purpose 'state)
12584 (format "state change from \"%s\" to \"%s\""
12585 (or org-log-note-previous-state "")
12586 (or org-log-note-state "")))
12587 ((eq org-log-note-purpose 'reschedule)
12588 "rescheduling")
12589 ((eq org-log-note-purpose 'delschedule)
12590 "no longer scheduled")
12591 ((eq org-log-note-purpose 'redeadline)
12592 "changing deadline")
12593 ((eq org-log-note-purpose 'deldeadline)
12594 "removing deadline")
12595 ((eq org-log-note-purpose 'refile)
12596 "refiling")
12597 ((eq org-log-note-purpose 'note)
12598 "this entry")
12599 (t (error "This should not happen")))))
12600 (if org-log-note-extra (insert org-log-note-extra))
12601 (org-set-local 'org-finish-function 'org-store-log-note)
12602 (run-hooks 'org-log-buffer-setup-hook)))
12604 (defvar org-note-abort nil) ; dynamically scoped
12605 (defun org-store-log-note ()
12606 "Finish taking a log note, and insert it to where it belongs."
12607 (let ((txt (buffer-string))
12608 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12609 lines ind bul)
12610 (kill-buffer (current-buffer))
12611 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12612 (setq txt (replace-match "" t t txt)))
12613 (if (string-match "\\s-+\\'" txt)
12614 (setq txt (replace-match "" t t txt)))
12615 (setq lines (org-split-string txt "\n"))
12616 (when (and note (string-match "\\S-" note))
12617 (setq note
12618 (org-replace-escapes
12619 note
12620 (list (cons "%u" (user-login-name))
12621 (cons "%U" user-full-name)
12622 (cons "%t" (format-time-string
12623 (org-time-stamp-format 'long 'inactive)
12624 org-log-note-effective-time))
12625 (cons "%T" (format-time-string
12626 (org-time-stamp-format 'long nil)
12627 org-log-note-effective-time))
12628 (cons "%d" (format-time-string
12629 (org-time-stamp-format nil 'inactive)
12630 org-log-note-effective-time))
12631 (cons "%D" (format-time-string
12632 (org-time-stamp-format nil nil)
12633 org-log-note-effective-time))
12634 (cons "%s" (if org-log-note-state
12635 (concat "\"" org-log-note-state "\"")
12636 ""))
12637 (cons "%S" (if org-log-note-previous-state
12638 (concat "\"" org-log-note-previous-state "\"")
12639 "\"\"")))))
12640 (if lines (setq note (concat note " \\\\")))
12641 (push note lines))
12642 (when (or current-prefix-arg org-note-abort)
12643 (when org-log-into-drawer
12644 (org-remove-empty-drawer-at
12645 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12646 org-log-note-marker))
12647 (setq lines nil))
12648 (when lines
12649 (with-current-buffer (marker-buffer org-log-note-marker)
12650 (save-excursion
12651 (goto-char org-log-note-marker)
12652 (move-marker org-log-note-marker nil)
12653 (end-of-line 1)
12654 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12655 (setq ind (save-excursion
12656 (if (ignore-errors (goto-char (org-in-item-p)))
12657 (let ((struct (org-list-struct)))
12658 (org-list-get-ind
12659 (org-list-get-top-point struct) struct))
12660 (skip-chars-backward " \r\t\n")
12661 (cond
12662 ((and (org-at-heading-p)
12663 org-adapt-indentation)
12664 (1+ (org-current-level)))
12665 ((org-at-heading-p) 0)
12666 (t (org-get-indentation))))))
12667 (setq bul (org-list-bullet-string "-"))
12668 (org-indent-line-to ind)
12669 (insert bul (pop lines))
12670 (let ((ind-body (+ (length bul) ind)))
12671 (while lines
12672 (insert "\n")
12673 (org-indent-line-to ind-body)
12674 (insert (pop lines))))
12675 (message "Note stored")
12676 (org-back-to-heading t)
12677 (org-cycle-hide-drawers 'children)))))
12678 (set-window-configuration org-log-note-window-configuration)
12679 (with-current-buffer (marker-buffer org-log-note-return-to)
12680 (goto-char org-log-note-return-to))
12681 (move-marker org-log-note-return-to nil)
12682 (and org-log-post-message (message "%s" org-log-post-message)))
12684 (defun org-remove-empty-drawer-at (drawer pos)
12685 "Remove an empty drawer DRAWER at position POS.
12686 POS may also be a marker."
12687 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12688 (save-excursion
12689 (save-restriction
12690 (widen)
12691 (goto-char pos)
12692 (if (org-in-regexp
12693 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12694 (replace-match ""))))))
12696 (defvar org-ts-type nil)
12697 (defun org-sparse-tree (&optional arg type)
12698 "Create a sparse tree, prompt for the details.
12699 This command can create sparse trees. You first need to select the type
12700 of match used to create the tree:
12702 t Show all TODO entries.
12703 T Show entries with a specific TODO keyword.
12704 m Show entries selected by a tags/property match.
12705 p Enter a property name and its value (both with completion on existing
12706 names/values) and show entries with that property.
12707 r Show entries matching a regular expression (`/' can be used as well).
12708 b Show deadlines and scheduled items before a date.
12709 a Show deadlines and scheduled items after a date.
12710 d Show deadlines due within `org-deadline-warning-days'.
12711 D Show deadlines and scheduled items between a date range."
12712 (interactive "P")
12713 (let (ans kwd value ts-type)
12714 (setq type (or type org-sparse-tree-default-date-type))
12715 (setq org-ts-type type)
12716 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12717 (cond ((eq type 'all) "all timestamps")
12718 ((eq type 'scheduled) "only scheduled")
12719 ((eq type 'deadline) "only deadline")
12720 ((eq type 'active) "only active timestamps")
12721 ((eq type 'inactive) "only inactive timestamps")
12722 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12723 (t "scheduled/deadline")))
12724 (setq ans (read-char-exclusive))
12725 (cond
12726 ((equal ans ?c)
12727 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12728 ((equal ans ?d)
12729 (call-interactively 'org-check-deadlines))
12730 ((equal ans ?b)
12731 (call-interactively 'org-check-before-date))
12732 ((equal ans ?a)
12733 (call-interactively 'org-check-after-date))
12734 ((equal ans ?D)
12735 (call-interactively 'org-check-dates-range))
12736 ((equal ans ?t)
12737 (call-interactively 'org-show-todo-tree))
12738 ((equal ans ?T)
12739 (org-show-todo-tree '(4)))
12740 ((member ans '(?T ?m))
12741 (call-interactively 'org-match-sparse-tree))
12742 ((member ans '(?p ?P))
12743 (setq kwd (org-icompleting-read "Property: "
12744 (mapcar 'list (org-buffer-property-keys))))
12745 (setq value (org-icompleting-read "Value: "
12746 (mapcar 'list (org-property-values kwd))))
12747 (unless (string-match "\\`{.*}\\'" value)
12748 (setq value (concat "\"" value "\"")))
12749 (org-match-sparse-tree arg (concat kwd "=" value)))
12750 ((member ans '(?r ?R ?/))
12751 (call-interactively 'org-occur))
12752 (t (error "No such sparse tree command \"%c\"" ans)))))
12754 (defvar org-occur-highlights nil
12755 "List of overlays used for occur matches.")
12756 (make-variable-buffer-local 'org-occur-highlights)
12757 (defvar org-occur-parameters nil
12758 "Parameters of the active org-occur calls.
12759 This is a list, each call to org-occur pushes as cons cell,
12760 containing the regular expression and the callback, onto the list.
12761 The list can contain several entries if `org-occur' has been called
12762 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12763 will only contain one set of parameters. When the highlights are
12764 removed (for example with `C-c C-c', or with the next edit (depending
12765 on `org-remove-highlights-with-change'), this variable is emptied
12766 as well.")
12767 (make-variable-buffer-local 'org-occur-parameters)
12769 (defun org-occur (regexp &optional keep-previous callback)
12770 "Make a compact tree which shows all matches of REGEXP.
12771 The tree will show the lines where the regexp matches, and all higher
12772 headlines above the match. It will also show the heading after the match,
12773 to make sure editing the matching entry is easy.
12774 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12775 call to `org-occur' will be kept, to allow stacking of calls to this
12776 command.
12777 If CALLBACK is non-nil, it is a function which is called to confirm
12778 that the match should indeed be shown."
12779 (interactive "sRegexp: \nP")
12780 (when (equal regexp "")
12781 (error "Regexp cannot be empty"))
12782 (unless keep-previous
12783 (org-remove-occur-highlights nil nil t))
12784 (push (cons regexp callback) org-occur-parameters)
12785 (let ((cnt 0))
12786 (save-excursion
12787 (goto-char (point-min))
12788 (if (or (not keep-previous) ; do not want to keep
12789 (not org-occur-highlights)) ; no previous matches
12790 ;; hide everything
12791 (org-overview))
12792 (while (re-search-forward regexp nil t)
12793 (when (or (not callback)
12794 (save-match-data (funcall callback)))
12795 (setq cnt (1+ cnt))
12796 (when org-highlight-sparse-tree-matches
12797 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12798 (org-show-context 'occur-tree))))
12799 (when org-remove-highlights-with-change
12800 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12801 nil 'local))
12802 (unless org-sparse-tree-open-archived-trees
12803 (org-hide-archived-subtrees (point-min) (point-max)))
12804 (run-hooks 'org-occur-hook)
12805 (if (org-called-interactively-p 'interactive)
12806 (message "%d match(es) for regexp %s" cnt regexp))
12807 cnt))
12809 (defun org-occur-next-match (&optional n reset)
12810 "Function for `next-error-function' to find sparse tree matches.
12811 N is the number of matches to move, when negative move backwards.
12812 RESET is entirely ignored - this function always goes back to the
12813 starting point when no match is found."
12814 (let* ((limit (if (< n 0) (point-min) (point-max)))
12815 (search-func (if (< n 0)
12816 'previous-single-char-property-change
12817 'next-single-char-property-change))
12818 (n (abs n))
12819 (pos (point))
12821 (catch 'exit
12822 (while (setq p1 (funcall search-func (point) 'org-type))
12823 (when (equal p1 limit)
12824 (goto-char pos)
12825 (error "No more matches"))
12826 (when (equal (get-char-property p1 'org-type) 'org-occur)
12827 (setq n (1- n))
12828 (when (= n 0)
12829 (goto-char p1)
12830 (throw 'exit (point))))
12831 (goto-char p1))
12832 (goto-char p1)
12833 (error "No more matches"))))
12835 (defun org-show-context (&optional key)
12836 "Make sure point and context are visible.
12837 How much context is shown depends upon the variables
12838 `org-show-hierarchy-above', `org-show-following-heading',
12839 `org-show-entry-below' and `org-show-siblings'."
12840 (let ((heading-p (org-at-heading-p t))
12841 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12842 (following-p (org-get-alist-option org-show-following-heading key))
12843 (entry-p (org-get-alist-option org-show-entry-below key))
12844 (siblings-p (org-get-alist-option org-show-siblings key)))
12845 (catch 'exit
12846 ;; Show heading or entry text
12847 (if (and heading-p (not entry-p))
12848 (org-flag-heading nil) ; only show the heading
12849 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12850 (org-show-hidden-entry))) ; show entire entry
12851 (when following-p
12852 ;; Show next sibling, or heading below text
12853 (save-excursion
12854 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12855 (org-flag-heading nil))))
12856 (when siblings-p (org-show-siblings))
12857 (when hierarchy-p
12858 ;; show all higher headings, possibly with siblings
12859 (save-excursion
12860 (while (and (condition-case nil
12861 (progn (org-up-heading-all 1) t)
12862 (error nil))
12863 (not (bobp)))
12864 (org-flag-heading nil)
12865 (when siblings-p (org-show-siblings))))))))
12867 (defvar org-reveal-start-hook nil
12868 "Hook run before revealing a location.")
12870 (defun org-reveal (&optional siblings)
12871 "Show current entry, hierarchy above it, and the following headline.
12872 This can be used to show a consistent set of context around locations
12873 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12874 not t for the search context.
12876 With optional argument SIBLINGS, on each level of the hierarchy all
12877 siblings are shown. This repairs the tree structure to what it would
12878 look like when opened with hierarchical calls to `org-cycle'.
12879 With double optional argument \\[universal-argument] \\[universal-argument], \
12880 go to the parent and show the
12881 entire tree."
12882 (interactive "P")
12883 (run-hooks 'org-reveal-start-hook)
12884 (let ((org-show-hierarchy-above t)
12885 (org-show-following-heading t)
12886 (org-show-siblings (if siblings t org-show-siblings)))
12887 (org-show-context nil))
12888 (when (equal siblings '(16))
12889 (save-excursion
12890 (when (org-up-heading-safe)
12891 (org-show-subtree)
12892 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12894 (defun org-highlight-new-match (beg end)
12895 "Highlight from BEG to END and mark the highlight is an occur headline."
12896 (let ((ov (make-overlay beg end)))
12897 (overlay-put ov 'face 'secondary-selection)
12898 (overlay-put ov 'org-type 'org-occur)
12899 (push ov org-occur-highlights)))
12901 (defun org-remove-occur-highlights (&optional beg end noremove)
12902 "Remove the occur highlights from the buffer.
12903 BEG and END are ignored. If NOREMOVE is nil, remove this function
12904 from the `before-change-functions' in the current buffer."
12905 (interactive)
12906 (unless org-inhibit-highlight-removal
12907 (mapc 'delete-overlay org-occur-highlights)
12908 (setq org-occur-highlights nil)
12909 (setq org-occur-parameters nil)
12910 (unless noremove
12911 (remove-hook 'before-change-functions
12912 'org-remove-occur-highlights 'local))))
12914 ;;;; Priorities
12916 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12917 "Regular expression matching the priority indicator.")
12919 (defvar org-remove-priority-next-time nil)
12921 (defun org-priority-up ()
12922 "Increase the priority of the current item."
12923 (interactive)
12924 (org-priority 'up))
12926 (defun org-priority-down ()
12927 "Decrease the priority of the current item."
12928 (interactive)
12929 (org-priority 'down))
12931 (defun org-priority (&optional action show)
12932 "Change the priority of an item.
12933 ACTION can be `set', `up', `down', or a character."
12934 (interactive "P")
12935 (if (equal action '(4))
12936 (org-show-priority)
12937 (unless org-enable-priority-commands
12938 (error "Priority commands are disabled"))
12939 (setq action (or action 'set))
12940 (let (current new news have remove)
12941 (save-excursion
12942 (org-back-to-heading t)
12943 (if (looking-at org-priority-regexp)
12944 (setq current (string-to-char (match-string 2))
12945 have t))
12946 (cond
12947 ((eq action 'remove)
12948 (setq remove t new ?\ ))
12949 ((or (eq action 'set)
12950 (if (featurep 'xemacs) (characterp action) (integerp action)))
12951 (if (not (eq action 'set))
12952 (setq new action)
12953 (message "Priority %c-%c, SPC to remove: "
12954 org-highest-priority org-lowest-priority)
12955 (save-match-data
12956 (setq new (read-char-exclusive))))
12957 (if (and (= (upcase org-highest-priority) org-highest-priority)
12958 (= (upcase org-lowest-priority) org-lowest-priority))
12959 (setq new (upcase new)))
12960 (cond ((equal new ?\ ) (setq remove t))
12961 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12962 (error "Priority must be between `%c' and `%c'"
12963 org-highest-priority org-lowest-priority))))
12964 ((eq action 'up)
12965 (setq new (if have
12966 (1- current) ; normal cycling
12967 ;; last priority was empty
12968 (if (eq last-command this-command)
12969 org-lowest-priority ; wrap around empty to lowest
12970 ;; default
12971 (if org-priority-start-cycle-with-default
12972 org-default-priority
12973 (1- org-default-priority))))))
12974 ((eq action 'down)
12975 (setq new (if have
12976 (1+ current) ; normal cycling
12977 ;; last priority was empty
12978 (if (eq last-command this-command)
12979 org-highest-priority ; wrap around empty to highest
12980 ;; default
12981 (if org-priority-start-cycle-with-default
12982 org-default-priority
12983 (1+ org-default-priority))))))
12984 (t (error "Invalid action")))
12985 (if (or (< (upcase new) org-highest-priority)
12986 (> (upcase new) org-lowest-priority))
12987 (if (and (memq action '(up down))
12988 (not have) (not (eq last-command this-command)))
12989 ;; `new' is from default priority
12990 (error
12991 "The default can not be set, see `org-default-priority' why")
12992 ;; normal cycling: `new' is beyond highest/lowest priority
12993 ;; and is wrapped around to the empty priority
12994 (setq remove t)))
12995 (setq news (format "%c" new))
12996 (if have
12997 (if remove
12998 (replace-match "" t t nil 1)
12999 (replace-match news t t nil 2))
13000 (if remove
13001 (error "No priority cookie found in line")
13002 (let ((case-fold-search nil))
13003 (looking-at org-todo-line-regexp))
13004 (if (match-end 2)
13005 (progn
13006 (goto-char (match-end 2))
13007 (insert " [#" news "]"))
13008 (goto-char (match-beginning 3))
13009 (insert "[#" news "] "))))
13010 (org-preserve-lc (org-set-tags nil 'align)))
13011 (if remove
13012 (message "Priority removed")
13013 (message "Priority of current item set to %s" news)))))
13015 (defun org-show-priority ()
13016 "Show the priority of the current item.
13017 This priority is composed of the main priority given with the [#A] cookies,
13018 and by additional input from the age of a schedules or deadline entry."
13019 (interactive)
13020 (let ((pri (if (eq major-mode 'org-agenda-mode)
13021 (org-get-at-bol 'priority)
13022 (save-excursion
13023 (save-match-data
13024 (beginning-of-line)
13025 (and (looking-at org-heading-regexp)
13026 (org-get-priority (match-string 0))))))))
13027 (message "Priority is %d" (if pri pri -1000))))
13029 (defun org-get-priority (s)
13030 "Find priority cookie and return priority."
13031 (save-match-data
13032 (if (functionp org-get-priority-function)
13033 (funcall org-get-priority-function)
13034 (if (not (string-match org-priority-regexp s))
13035 (* 1000 (- org-lowest-priority org-default-priority))
13036 (* 1000 (- org-lowest-priority
13037 (string-to-char (match-string 2 s))))))))
13039 ;;;; Tags
13041 (defvar org-agenda-archives-mode)
13042 (defvar org-map-continue-from nil
13043 "Position from where mapping should continue.
13044 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13046 (defvar org-scanner-tags nil
13047 "The current tag list while the tags scanner is running.")
13048 (defvar org-trust-scanner-tags nil
13049 "Should `org-get-tags-at' use the tags for the scanner.
13050 This is for internal dynamical scoping only.
13051 When this is non-nil, the function `org-get-tags-at' will return the value
13052 of `org-scanner-tags' instead of building the list by itself. This
13053 can lead to large speed-ups when the tags scanner is used in a file with
13054 many entries, and when the list of tags is retrieved, for example to
13055 obtain a list of properties. Building the tags list for each entry in such
13056 a file becomes an N^2 operation - but with this variable set, it scales
13057 as N.")
13059 (defun org-scan-tags (action matcher todo-only &optional start-level)
13060 "Scan headline tags with inheritance and produce output ACTION.
13062 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13063 or `agenda' to produce an entry list for an agenda view. It can also be
13064 a Lisp form or a function that should be called at each matched headline, in
13065 this case the return value is a list of all return values from these calls.
13067 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13068 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13069 only lines with a not-done TODO keyword are included in the output.
13070 This should be the same variable that was scoped into
13071 and set by `org-make-tags-matcher' when it constructed MATCHER.
13073 START-LEVEL can be a string with asterisks, reducing the scope to
13074 headlines matching this string."
13075 (require 'org-agenda)
13076 (let* ((re (concat "^"
13077 (if start-level
13078 ;; Get the correct level to match
13079 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13080 org-outline-regexp)
13081 " *\\(\\<\\("
13082 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13083 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13084 (props (list 'face 'default
13085 'done-face 'org-agenda-done
13086 'undone-face 'default
13087 'mouse-face 'highlight
13088 'org-not-done-regexp org-not-done-regexp
13089 'org-todo-regexp org-todo-regexp
13090 'org-complex-heading-regexp org-complex-heading-regexp
13091 'help-echo
13092 (format "mouse-2 or RET jump to org file %s"
13093 (abbreviate-file-name
13094 (or (buffer-file-name (buffer-base-buffer))
13095 (buffer-name (buffer-base-buffer)))))))
13096 (case-fold-search nil)
13097 (org-map-continue-from nil)
13098 lspos tags tags-list
13099 (tags-alist (list (cons 0 org-file-tags)))
13100 (llast 0) rtn rtn1 level category i txt
13101 todo marker entry priority)
13102 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13103 (setq action (list 'lambda nil action)))
13104 (save-excursion
13105 (goto-char (point-min))
13106 (when (eq action 'sparse-tree)
13107 (org-overview)
13108 (org-remove-occur-highlights))
13109 (while (re-search-forward re nil t)
13110 (setq org-map-continue-from nil)
13111 (catch :skip
13112 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13113 tags (if (match-end 4) (org-match-string-no-properties 4)))
13114 (goto-char (setq lspos (match-beginning 0)))
13115 (setq level (org-reduced-level (funcall outline-level))
13116 category (org-get-category))
13117 (setq i llast llast level)
13118 ;; remove tag lists from same and sublevels
13119 (while (>= i level)
13120 (when (setq entry (assoc i tags-alist))
13121 (setq tags-alist (delete entry tags-alist)))
13122 (setq i (1- i)))
13123 ;; add the next tags
13124 (when tags
13125 (setq tags (org-split-string tags ":")
13126 tags-alist
13127 (cons (cons level tags) tags-alist)))
13128 ;; compile tags for current headline
13129 (setq tags-list
13130 (if org-use-tag-inheritance
13131 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13132 tags)
13133 org-scanner-tags tags-list)
13134 (when org-use-tag-inheritance
13135 (setcdr (car tags-alist)
13136 (mapcar (lambda (x)
13137 (setq x (copy-sequence x))
13138 (org-add-prop-inherited x))
13139 (cdar tags-alist))))
13140 (when (and tags org-use-tag-inheritance
13141 (or (not (eq t org-use-tag-inheritance))
13142 org-tags-exclude-from-inheritance))
13143 ;; selective inheritance, remove uninherited ones
13144 (setcdr (car tags-alist)
13145 (org-remove-uninherited-tags (cdar tags-alist))))
13146 (when (and
13148 ;; eval matcher only when the todo condition is OK
13149 (and (or (not todo-only) (member todo org-not-done-keywords))
13150 (let ((case-fold-search t) (org-trust-scanner-tags t))
13151 (eval matcher)))
13153 ;; Call the skipper, but return t if it does not skip,
13154 ;; so that the `and' form continues evaluating
13155 (progn
13156 (unless (eq action 'sparse-tree) (org-agenda-skip))
13159 ;; Check if timestamps are deselecting this entry
13160 (or (not todo-only)
13161 (and (member todo org-not-done-keywords)
13162 (or (not org-agenda-tags-todo-honor-ignore-options)
13163 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13165 ;; select this headline
13166 (cond
13167 ((eq action 'sparse-tree)
13168 (and org-highlight-sparse-tree-matches
13169 (org-get-heading) (match-end 0)
13170 (org-highlight-new-match
13171 (match-beginning 1) (match-end 1)))
13172 (org-show-context 'tags-tree))
13173 ((eq action 'agenda)
13174 (setq txt (org-agenda-format-item
13176 (concat
13177 (if (eq org-tags-match-list-sublevels 'indented)
13178 (make-string (1- level) ?.) "")
13179 (org-get-heading))
13180 category
13181 tags-list)
13182 priority (org-get-priority txt))
13183 (goto-char lspos)
13184 (setq marker (org-agenda-new-marker))
13185 (org-add-props txt props
13186 'org-marker marker 'org-hd-marker marker 'org-category category
13187 'todo-state todo
13188 'priority priority 'type "tagsmatch")
13189 (push txt rtn))
13190 ((functionp action)
13191 (setq org-map-continue-from nil)
13192 (save-excursion
13193 (setq rtn1 (funcall action))
13194 (push rtn1 rtn)))
13195 (t (error "Invalid action")))
13197 ;; if we are to skip sublevels, jump to end of subtree
13198 (unless org-tags-match-list-sublevels
13199 (org-end-of-subtree t)
13200 (backward-char 1))))
13201 ;; Get the correct position from where to continue
13202 (if org-map-continue-from
13203 (goto-char org-map-continue-from)
13204 (and (= (point) lspos) (end-of-line 1)))))
13205 (when (and (eq action 'sparse-tree)
13206 (not org-sparse-tree-open-archived-trees))
13207 (org-hide-archived-subtrees (point-min) (point-max)))
13208 (nreverse rtn)))
13210 (defun org-remove-uninherited-tags (tags)
13211 "Remove all tags that are not inherited from the list TAGS."
13212 (cond
13213 ((eq org-use-tag-inheritance t)
13214 (if org-tags-exclude-from-inheritance
13215 (org-delete-all org-tags-exclude-from-inheritance tags)
13216 tags))
13217 ((not org-use-tag-inheritance) nil)
13218 ((stringp org-use-tag-inheritance)
13219 (delq nil (mapcar
13220 (lambda (x)
13221 (if (and (string-match org-use-tag-inheritance x)
13222 (not (member x org-tags-exclude-from-inheritance)))
13223 x nil))
13224 tags)))
13225 ((listp org-use-tag-inheritance)
13226 (delq nil (mapcar
13227 (lambda (x)
13228 (if (member x org-use-tag-inheritance) x nil))
13229 tags)))))
13231 (defun org-match-sparse-tree (&optional todo-only match)
13232 "Create a sparse tree according to tags string MATCH.
13233 MATCH can contain positive and negative selection of tags, like
13234 \"+WORK+URGENT-WITHBOSS\".
13235 If optional argument TODO-ONLY is non-nil, only select lines that are
13236 also TODO lines."
13237 (interactive "P")
13238 (org-agenda-prepare-buffers (list (current-buffer)))
13239 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13241 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13243 (defvar org-cached-props nil)
13244 (defun org-cached-entry-get (pom property)
13245 (if (or (eq t org-use-property-inheritance)
13246 (and (stringp org-use-property-inheritance)
13247 (string-match org-use-property-inheritance property))
13248 (and (listp org-use-property-inheritance)
13249 (member property org-use-property-inheritance)))
13250 ;; Caching is not possible, check it directly
13251 (org-entry-get pom property 'inherit)
13252 ;; Get all properties, so that we can do complicated checks easily
13253 (cdr (assoc property (or org-cached-props
13254 (setq org-cached-props
13255 (org-entry-properties pom)))))))
13257 (defun org-global-tags-completion-table (&optional files)
13258 "Return the list of all tags in all agenda buffer/files.
13259 Optional FILES argument is a list of files which can be used
13260 instead of the agenda files."
13261 (save-excursion
13262 (org-uniquify
13263 (delq nil
13264 (apply 'append
13265 (mapcar
13266 (lambda (file)
13267 (set-buffer (find-file-noselect file))
13268 (append (org-get-buffer-tags)
13269 (mapcar (lambda (x) (if (stringp (car-safe x))
13270 (list (car-safe x)) nil))
13271 org-tag-alist)))
13272 (if (and files (car files))
13273 files
13274 (org-agenda-files))))))))
13276 (defun org-make-tags-matcher (match)
13277 "Create the TAGS/TODO matcher form for the selection string MATCH.
13279 The variable `todo-only' is scoped dynamically into this function.
13280 It will be set to t if the matcher restricts matching to TODO entries,
13281 otherwise will not be touched.
13283 Returns a cons of the selection string MATCH and the constructed
13284 lisp form implementing the matcher. The matcher is to be evaluated
13285 at an Org entry, with point on the headline, and returns t if the
13286 entry matches the selection string MATCH. The returned lisp form
13287 references two variables with information about the entry, which
13288 must be bound around the form's evaluation: todo, the TODO keyword
13289 at the entry (or nil of none); and tags-list, the list of all tags
13290 at the entry including inherited ones. Additionally, the category
13291 of the entry (if any) must be specified as the text property
13292 'org-category on the headline.
13294 See also `org-scan-tags'.
13296 (declare (special todo-only))
13297 (unless (boundp 'todo-only)
13298 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13299 (unless match
13300 ;; Get a new match request, with completion
13301 (let ((org-last-tags-completion-table
13302 (org-global-tags-completion-table)))
13303 (setq match (org-completing-read-no-i
13304 "Match: " 'org-tags-completion-function nil nil nil
13305 'org-tags-history))))
13307 ;; Parse the string and create a lisp form
13308 (let ((match0 match)
13309 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13310 minus tag mm
13311 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13312 orterms term orlist re-p str-p level-p level-op time-p
13313 prop-p pn pv po gv rest)
13314 (if (string-match "/+" match)
13315 ;; match contains also a todo-matching request
13316 (progn
13317 (setq tagsmatch (substring match 0 (match-beginning 0))
13318 todomatch (substring match (match-end 0)))
13319 (if (string-match "^!" todomatch)
13320 (setq todo-only t todomatch (substring todomatch 1)))
13321 (if (string-match "^\\s-*$" todomatch)
13322 (setq todomatch nil)))
13323 ;; only matching tags
13324 (setq tagsmatch match todomatch nil))
13326 ;; Make the tags matcher
13327 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13328 (setq tagsmatcher t)
13329 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13330 (while (setq term (pop orterms))
13331 (while (and (equal (substring term -1) "\\") orterms)
13332 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13333 (while (string-match re term)
13334 (setq rest (substring term (match-end 0))
13335 minus (and (match-end 1)
13336 (equal (match-string 1 term) "-"))
13337 tag (save-match-data (replace-regexp-in-string
13338 "\\\\-" "-"
13339 (match-string 2 term)))
13340 re-p (equal (string-to-char tag) ?{)
13341 level-p (match-end 4)
13342 prop-p (match-end 5)
13343 mm (cond
13344 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13345 (level-p
13346 (setq level-op (org-op-to-function (match-string 3 term)))
13347 `(,level-op level ,(string-to-number
13348 (match-string 4 term))))
13349 (prop-p
13350 (setq pn (match-string 5 term)
13351 po (match-string 6 term)
13352 pv (match-string 7 term)
13353 re-p (equal (string-to-char pv) ?{)
13354 str-p (equal (string-to-char pv) ?\")
13355 time-p (save-match-data
13356 (string-match "^\"[[<].*[]>]\"$" pv))
13357 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13358 (if time-p (setq pv (org-matcher-time pv)))
13359 (setq po (org-op-to-function po (if time-p 'time str-p)))
13360 (cond
13361 ((equal pn "CATEGORY")
13362 (setq gv '(get-text-property (point) 'org-category)))
13363 ((equal pn "TODO")
13364 (setq gv 'todo))
13366 (setq gv `(org-cached-entry-get nil ,pn))))
13367 (if re-p
13368 (if (eq po 'org<>)
13369 `(not (string-match ,pv (or ,gv "")))
13370 `(string-match ,pv (or ,gv "")))
13371 (if str-p
13372 `(,po (or ,gv "") ,pv)
13373 `(,po (string-to-number (or ,gv ""))
13374 ,(string-to-number pv) ))))
13375 (t `(member ,tag tags-list)))
13376 mm (if minus (list 'not mm) mm)
13377 term rest)
13378 (push mm tagsmatcher))
13379 (push (if (> (length tagsmatcher) 1)
13380 (cons 'and tagsmatcher)
13381 (car tagsmatcher))
13382 orlist)
13383 (setq tagsmatcher nil))
13384 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13385 (setq tagsmatcher
13386 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13387 ;; Make the todo matcher
13388 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13389 (setq todomatcher t)
13390 (setq orterms (org-split-string todomatch "|") orlist nil)
13391 (while (setq term (pop orterms))
13392 (while (string-match re term)
13393 (setq minus (and (match-end 1)
13394 (equal (match-string 1 term) "-"))
13395 kwd (match-string 2 term)
13396 re-p (equal (string-to-char kwd) ?{)
13397 term (substring term (match-end 0))
13398 mm (if re-p
13399 `(string-match ,(substring kwd 1 -1) todo)
13400 (list 'equal 'todo kwd))
13401 mm (if minus (list 'not mm) mm))
13402 (push mm todomatcher))
13403 (push (if (> (length todomatcher) 1)
13404 (cons 'and todomatcher)
13405 (car todomatcher))
13406 orlist)
13407 (setq todomatcher nil))
13408 (setq todomatcher (if (> (length orlist) 1)
13409 (cons 'or orlist) (car orlist))))
13411 ;; Return the string and lisp forms of the matcher
13412 (setq matcher (if todomatcher
13413 (list 'and tagsmatcher todomatcher)
13414 tagsmatcher))
13415 (when todo-only
13416 (setq matcher (list 'and '(member todo org-not-done-keywords)
13417 matcher)))
13418 (cons match0 matcher)))
13420 (defun org-op-to-function (op &optional stringp)
13421 "Turn an operator into the appropriate function."
13422 (setq op
13423 (cond
13424 ((equal op "<" ) '(< string< org-time<))
13425 ((equal op ">" ) '(> org-string> org-time>))
13426 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13427 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13428 ((member op '("=" "==")) '(= string= org-time=))
13429 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13430 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13432 (defun org<> (a b) (not (= a b)))
13433 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13434 (defun org-string>= (a b) (not (string< a b)))
13435 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13436 (defun org-string<> (a b) (not (string= a b)))
13437 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13438 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13439 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13440 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13441 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13442 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13443 (defun org-2ft (s)
13444 "Convert S to a floating point time.
13445 If S is already a number, just return it. If it is a string, parse
13446 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13447 (cond
13448 ((numberp s) s)
13449 ((stringp s)
13450 (condition-case nil
13451 (float-time (apply 'encode-time (org-parse-time-string s)))
13452 (error 0.)))
13453 (t 0.)))
13455 (defun org-time-today ()
13456 "Time in seconds today at 0:00.
13457 Returns the float number of seconds since the beginning of the
13458 epoch to the beginning of today (00:00)."
13459 (float-time (apply 'encode-time
13460 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13462 (defun org-matcher-time (s)
13463 "Interpret a time comparison value."
13464 (save-match-data
13465 (cond
13466 ((string= s "<now>") (float-time))
13467 ((string= s "<today>") (org-time-today))
13468 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13469 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13470 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13471 (+ (org-time-today)
13472 (* (string-to-number (match-string 1 s))
13473 (cdr (assoc (match-string 2 s)
13474 '(("d" . 86400.0) ("w" . 604800.0)
13475 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13476 (t (org-2ft s)))))
13478 (defun org-match-any-p (re list)
13479 "Does re match any element of list?"
13480 (setq list (mapcar (lambda (x) (string-match re x)) list))
13481 (delq nil list))
13483 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13484 (defvar org-tags-overlay (make-overlay 1 1))
13485 (org-detach-overlay org-tags-overlay)
13487 (defun org-get-local-tags-at (&optional pos)
13488 "Get a list of tags defined in the current headline."
13489 (org-get-tags-at pos 'local))
13491 (defun org-get-local-tags ()
13492 "Get a list of tags defined in the current headline."
13493 (org-get-tags-at nil 'local))
13495 (defun org-get-tags-at (&optional pos local)
13496 "Get a list of all headline tags applicable at POS.
13497 POS defaults to point. If tags are inherited, the list contains
13498 the targets in the same sequence as the headlines appear, i.e.
13499 the tags of the current headline come last.
13500 When LOCAL is non-nil, only return tags from the current headline,
13501 ignore inherited ones."
13502 (interactive)
13503 (if (and org-trust-scanner-tags
13504 (or (not pos) (equal pos (point)))
13505 (not local))
13506 org-scanner-tags
13507 (let (tags ltags lastpos parent)
13508 (save-excursion
13509 (save-restriction
13510 (widen)
13511 (goto-char (or pos (point)))
13512 (save-match-data
13513 (catch 'done
13514 (condition-case nil
13515 (progn
13516 (org-back-to-heading t)
13517 (while (not (equal lastpos (point)))
13518 (setq lastpos (point))
13519 (when (looking-at
13520 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13521 (setq ltags (org-split-string
13522 (org-match-string-no-properties 1) ":"))
13523 (when parent
13524 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13525 (setq tags (append
13526 (if parent
13527 (org-remove-uninherited-tags ltags)
13528 ltags)
13529 tags)))
13530 (or org-use-tag-inheritance (throw 'done t))
13531 (if local (throw 'done t))
13532 (or (org-up-heading-safe) (error nil))
13533 (setq parent t)))
13534 (error nil)))))
13535 (if local
13536 tags
13537 (reverse (delete-dups
13538 (reverse (append
13539 (org-remove-uninherited-tags
13540 org-file-tags) tags)))))))))
13542 (defun org-add-prop-inherited (s)
13543 (add-text-properties 0 (length s) '(inherited t) s)
13546 (defun org-toggle-tag (tag &optional onoff)
13547 "Toggle the tag TAG for the current line.
13548 If ONOFF is `on' or `off', don't toggle but set to this state."
13549 (let (res current)
13550 (save-excursion
13551 (org-back-to-heading t)
13552 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13553 (point-at-eol) t)
13554 (progn
13555 (setq current (match-string 1))
13556 (replace-match ""))
13557 (setq current ""))
13558 (setq current (nreverse (org-split-string current ":")))
13559 (cond
13560 ((eq onoff 'on)
13561 (setq res t)
13562 (or (member tag current) (push tag current)))
13563 ((eq onoff 'off)
13564 (or (not (member tag current)) (setq current (delete tag current))))
13565 (t (if (member tag current)
13566 (setq current (delete tag current))
13567 (setq res t)
13568 (push tag current))))
13569 (end-of-line 1)
13570 (if current
13571 (progn
13572 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13573 (org-set-tags nil t))
13574 (delete-horizontal-space))
13575 (run-hooks 'org-after-tags-change-hook))
13576 res))
13578 (defun org-align-tags-here (to-col)
13579 ;; Assumes that this is a headline
13580 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13581 (beginning-of-line 1)
13582 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13583 (< pos (match-beginning 2)))
13584 (progn
13585 (setq tags-l (- (match-end 2) (match-beginning 2)))
13586 (goto-char (match-beginning 1))
13587 (insert " ")
13588 (delete-region (point) (1+ (match-beginning 2)))
13589 (setq ncol (max (current-column)
13590 (1+ col)
13591 (if (> to-col 0)
13592 to-col
13593 (- (abs to-col) tags-l))))
13594 (setq p (point))
13595 (insert (make-string (- ncol (current-column)) ?\ ))
13596 (setq ncol (current-column))
13597 (when indent-tabs-mode (tabify p (point-at-eol)))
13598 (org-move-to-column (min ncol col) t))
13599 (goto-char pos))))
13601 (defun org-set-tags-command (&optional arg just-align)
13602 "Call the set-tags command for the current entry."
13603 (interactive "P")
13604 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13605 (org-set-tags arg just-align)
13606 (save-excursion
13607 (unless (and (org-region-active-p)
13608 org-loop-over-headlines-in-active-region)
13609 (org-back-to-heading t))
13610 (org-set-tags arg just-align))))
13612 (defun org-set-tags-to (data)
13613 "Set the tags of the current entry to DATA, replacing the current tags.
13614 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13615 If DATA is nil or the empty string, any tags will be removed."
13616 (interactive "sTags: ")
13617 (setq data
13618 (cond
13619 ((eq data nil) "")
13620 ((equal data "") "")
13621 ((stringp data)
13622 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13623 ":"))
13624 ((listp data)
13625 (concat ":" (mapconcat 'identity data ":") ":"))))
13626 (when data
13627 (save-excursion
13628 (org-back-to-heading t)
13629 (when (looking-at org-complex-heading-regexp)
13630 (if (match-end 5)
13631 (progn
13632 (goto-char (match-beginning 5))
13633 (insert data)
13634 (delete-region (point) (point-at-eol))
13635 (org-set-tags nil 'align))
13636 (goto-char (point-at-eol))
13637 (insert " " data)
13638 (org-set-tags nil 'align)))
13639 (beginning-of-line 1)
13640 (if (looking-at ".*?\\([ \t]+\\)$")
13641 (delete-region (match-beginning 1) (match-end 1))))))
13643 (defun org-align-all-tags ()
13644 "Align the tags i all headings."
13645 (interactive)
13646 (save-excursion
13647 (or (ignore-errors (org-back-to-heading t))
13648 (outline-next-heading))
13649 (if (org-at-heading-p)
13650 (org-set-tags t)
13651 (message "No headings"))))
13653 (defvar org-indent-indentation-per-level)
13654 (defun org-set-tags (&optional arg just-align)
13655 "Set the tags for the current headline.
13656 With prefix ARG, realign all tags in headings in the current buffer."
13657 (interactive "P")
13658 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13659 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13660 'region-start-level 'region))
13661 org-loop-over-headlines-in-active-region)
13662 (org-map-entries
13663 ;; We don't use ARG and JUST-ALIGN here these args are not
13664 ;; useful when looping over headlines
13665 `(org-set-tags)
13666 org-loop-over-headlines-in-active-region
13667 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13668 (let* ((re org-outline-regexp-bol)
13669 (current (unless arg (org-get-tags-string)))
13670 (col (current-column))
13671 (org-setting-tags t)
13672 table current-tags inherited-tags ; computed below when needed
13673 tags p0 c0 c1 rpl di tc level)
13674 (if arg
13675 (save-excursion
13676 (goto-char (point-min))
13677 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13678 (while (re-search-forward re nil t)
13679 (org-set-tags nil t)
13680 (end-of-line 1)))
13681 (message "All tags realigned to column %d" org-tags-column))
13682 (if just-align
13683 (setq tags current)
13684 ;; Get a new set of tags from the user
13685 (save-excursion
13686 (setq table (append org-tag-persistent-alist
13687 (or org-tag-alist (org-get-buffer-tags))
13688 (and
13689 org-complete-tags-always-offer-all-agenda-tags
13690 (org-global-tags-completion-table
13691 (org-agenda-files))))
13692 org-last-tags-completion-table table
13693 current-tags (org-split-string current ":")
13694 inherited-tags (nreverse
13695 (nthcdr (length current-tags)
13696 (nreverse (org-get-tags-at))))
13697 tags
13698 (if (or (eq t org-use-fast-tag-selection)
13699 (and org-use-fast-tag-selection
13700 (delq nil (mapcar 'cdr table))))
13701 (org-fast-tag-selection
13702 current-tags inherited-tags table
13703 (if org-fast-tag-selection-include-todo
13704 org-todo-key-alist))
13705 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13706 (org-trim
13707 (org-icompleting-read "Tags: "
13708 'org-tags-completion-function
13709 nil nil current 'org-tags-history))))))
13710 (while (string-match "[-+&]+" tags)
13711 ;; No boolean logic, just a list
13712 (setq tags (replace-match ":" t t tags))))
13714 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13716 (if org-tags-sort-function
13717 (setq tags (mapconcat 'identity
13718 (sort (org-split-string
13719 tags (org-re "[^[:alnum:]_@#%]+"))
13720 org-tags-sort-function) ":")))
13722 (if (string-match "\\`[\t ]*\\'" tags)
13723 (setq tags "")
13724 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13725 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13727 ;; Insert new tags at the correct column
13728 (beginning-of-line 1)
13729 (setq level (or (and (looking-at org-outline-regexp)
13730 (- (match-end 0) (point) 1))
13732 (cond
13733 ((and (equal current "") (equal tags "")))
13734 ((re-search-forward
13735 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13736 (point-at-eol) t)
13737 (if (equal tags "")
13738 (setq rpl "")
13739 (goto-char (match-beginning 0))
13740 (setq c0 (current-column)
13741 ;; compute offset for the case of org-indent-mode active
13742 di (if org-indent-mode
13743 (* (1- org-indent-indentation-per-level) (1- level))
13745 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13746 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13747 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13748 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13749 (replace-match rpl t t)
13750 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13751 tags)
13752 (t (error "Tags alignment failed")))
13753 (org-move-to-column col)
13754 (unless just-align
13755 (run-hooks 'org-after-tags-change-hook))))))
13757 (defun org-change-tag-in-region (beg end tag off)
13758 "Add or remove TAG for each entry in the region.
13759 This works in the agenda, and also in an org-mode buffer."
13760 (interactive
13761 (list (region-beginning) (region-end)
13762 (let ((org-last-tags-completion-table
13763 (if (derived-mode-p 'org-mode)
13764 (org-get-buffer-tags)
13765 (org-global-tags-completion-table))))
13766 (org-icompleting-read
13767 "Tag: " 'org-tags-completion-function nil nil nil
13768 'org-tags-history))
13769 (progn
13770 (message "[s]et or [r]emove? ")
13771 (equal (read-char-exclusive) ?r))))
13772 (if (fboundp 'deactivate-mark) (deactivate-mark))
13773 (let ((agendap (equal major-mode 'org-agenda-mode))
13774 l1 l2 m buf pos newhead (cnt 0))
13775 (goto-char end)
13776 (setq l2 (1- (org-current-line)))
13777 (goto-char beg)
13778 (setq l1 (org-current-line))
13779 (loop for l from l1 to l2 do
13780 (org-goto-line l)
13781 (setq m (get-text-property (point) 'org-hd-marker))
13782 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13783 (and agendap m))
13784 (setq buf (if agendap (marker-buffer m) (current-buffer))
13785 pos (if agendap m (point)))
13786 (with-current-buffer buf
13787 (save-excursion
13788 (save-restriction
13789 (goto-char pos)
13790 (setq cnt (1+ cnt))
13791 (org-toggle-tag tag (if off 'off 'on))
13792 (setq newhead (org-get-heading)))))
13793 (and agendap (org-agenda-change-all-lines newhead m))))
13794 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13796 (defun org-tags-completion-function (string predicate &optional flag)
13797 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13798 (confirm (lambda (x) (stringp (car x)))))
13799 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13800 (setq s1 (match-string 1 string)
13801 s2 (match-string 2 string))
13802 (setq s1 "" s2 string))
13803 (cond
13804 ((eq flag nil)
13805 ;; try completion
13806 (setq rtn (try-completion s2 ctable confirm))
13807 (if (stringp rtn)
13808 (setq rtn
13809 (concat s1 s2 (substring rtn (length s2))
13810 (if (and org-add-colon-after-tag-completion
13811 (assoc rtn ctable))
13812 ":" ""))))
13813 rtn)
13814 ((eq flag t)
13815 ;; all-completions
13816 (all-completions s2 ctable confirm)
13818 ((eq flag 'lambda)
13819 ;; exact match?
13820 (assoc s2 ctable)))
13823 (defun org-fast-tag-insert (kwd tags face &optional end)
13824 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13825 (insert (format "%-12s" (concat kwd ":"))
13826 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13827 (or end "")))
13829 (defun org-fast-tag-show-exit (flag)
13830 (save-excursion
13831 (org-goto-line 3)
13832 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13833 (replace-match ""))
13834 (when flag
13835 (end-of-line 1)
13836 (org-move-to-column (- (window-width) 19) t)
13837 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13839 (defun org-set-current-tags-overlay (current prefix)
13840 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13841 (if (featurep 'xemacs)
13842 (org-overlay-display org-tags-overlay (concat prefix s)
13843 'secondary-selection)
13844 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13845 (org-overlay-display org-tags-overlay (concat prefix s)))))
13847 (defvar org-last-tag-selection-key nil)
13848 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13849 "Fast tag selection with single keys.
13850 CURRENT is the current list of tags in the headline, INHERITED is the
13851 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13852 possibly with grouping information. TODO-TABLE is a similar table with
13853 TODO keywords, should these have keys assigned to them.
13854 If the keys are nil, a-z are automatically assigned.
13855 Returns the new tags string, or nil to not change the current settings."
13856 (let* ((fulltable (append table todo-table))
13857 (maxlen (apply 'max (mapcar
13858 (lambda (x)
13859 (if (stringp (car x)) (string-width (car x)) 0))
13860 fulltable)))
13861 (buf (current-buffer))
13862 (expert (eq org-fast-tag-selection-single-key 'expert))
13863 (buffer-tags nil)
13864 (fwidth (+ maxlen 3 1 3))
13865 (ncol (/ (- (window-width) 4) fwidth))
13866 (i-face 'org-done)
13867 (c-face 'org-todo)
13868 tg cnt e c char c1 c2 ntable tbl rtn
13869 ov-start ov-end ov-prefix
13870 (exit-after-next org-fast-tag-selection-single-key)
13871 (done-keywords org-done-keywords)
13872 groups ingroup)
13873 (save-excursion
13874 (beginning-of-line 1)
13875 (if (looking-at
13876 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13877 (setq ov-start (match-beginning 1)
13878 ov-end (match-end 1)
13879 ov-prefix "")
13880 (setq ov-start (1- (point-at-eol))
13881 ov-end (1+ ov-start))
13882 (skip-chars-forward "^\n\r")
13883 (setq ov-prefix
13884 (concat
13885 (buffer-substring (1- (point)) (point))
13886 (if (> (current-column) org-tags-column)
13888 (make-string (- org-tags-column (current-column)) ?\ ))))))
13889 (move-overlay org-tags-overlay ov-start ov-end)
13890 (save-window-excursion
13891 (if expert
13892 (set-buffer (get-buffer-create " *Org tags*"))
13893 (delete-other-windows)
13894 (split-window-vertically)
13895 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13896 (erase-buffer)
13897 (org-set-local 'org-done-keywords done-keywords)
13898 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13899 (org-fast-tag-insert "Current" current c-face "\n\n")
13900 (org-fast-tag-show-exit exit-after-next)
13901 (org-set-current-tags-overlay current ov-prefix)
13902 (setq tbl fulltable char ?a cnt 0)
13903 (while (setq e (pop tbl))
13904 (cond
13905 ((equal (car e) :startgroup)
13906 (push '() groups) (setq ingroup t)
13907 (when (not (= cnt 0))
13908 (setq cnt 0)
13909 (insert "\n"))
13910 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13911 ((equal (car e) :endgroup)
13912 (setq ingroup nil cnt 0)
13913 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13914 ((equal e '(:newline))
13915 (when (not (= cnt 0))
13916 (setq cnt 0)
13917 (insert "\n")
13918 (setq e (car tbl))
13919 (while (equal (car tbl) '(:newline))
13920 (insert "\n")
13921 (setq tbl (cdr tbl)))))
13923 (setq tg (copy-sequence (car e)) c2 nil)
13924 (if (cdr e)
13925 (setq c (cdr e))
13926 ;; automatically assign a character.
13927 (setq c1 (string-to-char
13928 (downcase (substring
13929 tg (if (= (string-to-char tg) ?@) 1 0)))))
13930 (if (or (rassoc c1 ntable) (rassoc c1 table))
13931 (while (or (rassoc char ntable) (rassoc char table))
13932 (setq char (1+ char)))
13933 (setq c2 c1))
13934 (setq c (or c2 char)))
13935 (if ingroup (push tg (car groups)))
13936 (setq tg (org-add-props tg nil 'face
13937 (cond
13938 ((not (assoc tg table))
13939 (org-get-todo-face tg))
13940 ((member tg current) c-face)
13941 ((member tg inherited) i-face))))
13942 (if (and (= cnt 0) (not ingroup)) (insert " "))
13943 (insert "[" c "] " tg (make-string
13944 (- fwidth 4 (length tg)) ?\ ))
13945 (push (cons tg c) ntable)
13946 (when (= (setq cnt (1+ cnt)) ncol)
13947 (insert "\n")
13948 (if ingroup (insert " "))
13949 (setq cnt 0)))))
13950 (setq ntable (nreverse ntable))
13951 (insert "\n")
13952 (goto-char (point-min))
13953 (if (not expert) (org-fit-window-to-buffer))
13954 (setq rtn
13955 (catch 'exit
13956 (while t
13957 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13958 (if (not groups) "no " "")
13959 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13960 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13961 (setq org-last-tag-selection-key c)
13962 (cond
13963 ((= c ?\r) (throw 'exit t))
13964 ((= c ?!)
13965 (setq groups (not groups))
13966 (goto-char (point-min))
13967 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13968 ((= c ?\C-c)
13969 (if (not expert)
13970 (org-fast-tag-show-exit
13971 (setq exit-after-next (not exit-after-next)))
13972 (setq expert nil)
13973 (delete-other-windows)
13974 (set-window-buffer (split-window-vertically) " *Org tags*")
13975 (org-switch-to-buffer-other-window " *Org tags*")
13976 (org-fit-window-to-buffer)))
13977 ((or (= c ?\C-g)
13978 (and (= c ?q) (not (rassoc c ntable))))
13979 (org-detach-overlay org-tags-overlay)
13980 (setq quit-flag t))
13981 ((= c ?\ )
13982 (setq current nil)
13983 (if exit-after-next (setq exit-after-next 'now)))
13984 ((= c ?\t)
13985 (condition-case nil
13986 (setq tg (org-icompleting-read
13987 "Tag: "
13988 (or buffer-tags
13989 (with-current-buffer buf
13990 (org-get-buffer-tags)))))
13991 (quit (setq tg "")))
13992 (when (string-match "\\S-" tg)
13993 (add-to-list 'buffer-tags (list tg))
13994 (if (member tg current)
13995 (setq current (delete tg current))
13996 (push tg current)))
13997 (if exit-after-next (setq exit-after-next 'now)))
13998 ((setq e (rassoc c todo-table) tg (car e))
13999 (with-current-buffer buf
14000 (save-excursion (org-todo tg)))
14001 (if exit-after-next (setq exit-after-next 'now)))
14002 ((setq e (rassoc c ntable) tg (car e))
14003 (if (member tg current)
14004 (setq current (delete tg current))
14005 (loop for g in groups do
14006 (if (member tg g)
14007 (mapc (lambda (x)
14008 (setq current (delete x current)))
14009 g)))
14010 (push tg current))
14011 (if exit-after-next (setq exit-after-next 'now))))
14013 ;; Create a sorted list
14014 (setq current
14015 (sort current
14016 (lambda (a b)
14017 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14018 (if (eq exit-after-next 'now) (throw 'exit t))
14019 (goto-char (point-min))
14020 (beginning-of-line 2)
14021 (delete-region (point) (point-at-eol))
14022 (org-fast-tag-insert "Current" current c-face)
14023 (org-set-current-tags-overlay current ov-prefix)
14024 (while (re-search-forward
14025 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14026 (setq tg (match-string 1))
14027 (add-text-properties
14028 (match-beginning 1) (match-end 1)
14029 (list 'face
14030 (cond
14031 ((member tg current) c-face)
14032 ((member tg inherited) i-face)
14033 (t (get-text-property (match-beginning 1) 'face))))))
14034 (goto-char (point-min)))))
14035 (org-detach-overlay org-tags-overlay)
14036 (if rtn
14037 (mapconcat 'identity current ":")
14038 nil))))
14040 (defun org-get-tags-string ()
14041 "Get the TAGS string in the current headline."
14042 (unless (org-at-heading-p t)
14043 (error "Not on a heading"))
14044 (save-excursion
14045 (beginning-of-line 1)
14046 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14047 (org-match-string-no-properties 1)
14048 "")))
14050 (defun org-get-tags ()
14051 "Get the list of tags specified in the current headline."
14052 (org-split-string (org-get-tags-string) ":"))
14054 (defun org-get-buffer-tags ()
14055 "Get a table of all tags used in the buffer, for completion."
14056 (let (tags)
14057 (save-excursion
14058 (goto-char (point-min))
14059 (while (re-search-forward
14060 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14061 (when (equal (char-after (point-at-bol 0)) ?*)
14062 (mapc (lambda (x) (add-to-list 'tags x))
14063 (org-split-string (org-match-string-no-properties 1) ":")))))
14064 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14065 (mapcar 'list tags)))
14067 ;;;; The mapping API
14069 (defun org-map-entries (func &optional match scope &rest skip)
14070 "Call FUNC at each headline selected by MATCH in SCOPE.
14072 FUNC is a function or a lisp form. The function will be called without
14073 arguments, with the cursor positioned at the beginning of the headline.
14074 The return values of all calls to the function will be collected and
14075 returned as a list.
14077 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14078 does not need to preserve point. After evaluation, the cursor will be
14079 moved to the end of the line (presumably of the headline of the
14080 processed entry) and search continues from there. Under some
14081 circumstances, this may not produce the wanted results. For example,
14082 if you have removed (e.g. archived) the current (sub)tree it could
14083 mean that the next entry will be skipped entirely. In such cases, you
14084 can specify the position from where search should continue by making
14085 FUNC set the variable `org-map-continue-from' to the desired buffer
14086 position.
14088 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14089 Only headlines that are matched by this query will be considered during
14090 the iteration. When MATCH is nil or t, all headlines will be
14091 visited by the iteration.
14093 SCOPE determines the scope of this command. It can be any of:
14095 nil The current buffer, respecting the restriction if any
14096 tree The subtree started with the entry at point
14097 region The entries within the active region, if any
14098 region-start-level
14099 The entries within the active region, but only those at
14100 the same level than the first one.
14101 file The current buffer, without restriction
14102 file-with-archives
14103 The current buffer, and any archives associated with it
14104 agenda All agenda files
14105 agenda-with-archives
14106 All agenda files with any archive files associated with them
14107 \(file1 file2 ...)
14108 If this is a list, all files in the list will be scanned
14110 The remaining args are treated as settings for the skipping facilities of
14111 the scanner. The following items can be given here:
14113 archive skip trees with the archive tag
14114 comment skip trees with the COMMENT keyword
14115 function or Emacs Lisp form:
14116 will be used as value for `org-agenda-skip-function', so
14117 whenever the function returns a position, FUNC will not be
14118 called for that entry and search will continue from the
14119 position returned
14121 If your function needs to retrieve the tags including inherited tags
14122 at the *current* entry, you can use the value of the variable
14123 `org-scanner-tags' which will be much faster than getting the value
14124 with `org-get-tags-at'. If your function gets properties with
14125 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14126 to t around the call to `org-entry-properties' to get the same speedup.
14127 Note that if your function moves around to retrieve tags and properties at
14128 a *different* entry, you cannot use these techniques."
14129 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14130 (not (org-region-active-p)))
14131 (let* ((org-agenda-archives-mode nil) ; just to make sure
14132 (org-agenda-skip-archived-trees (memq 'archive skip))
14133 (org-agenda-skip-comment-trees (memq 'comment skip))
14134 (org-agenda-skip-function
14135 (car (org-delete-all '(comment archive) skip)))
14136 (org-tags-match-list-sublevels t)
14137 (start-level (eq scope 'region-start-level))
14138 matcher file res
14139 org-todo-keywords-for-agenda
14140 org-done-keywords-for-agenda
14141 org-todo-keyword-alist-for-agenda
14142 org-drawers-for-agenda
14143 org-tag-alist-for-agenda
14144 todo-only)
14146 (cond
14147 ((eq match t) (setq matcher t))
14148 ((eq match nil) (setq matcher t))
14149 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14151 (save-excursion
14152 (save-restriction
14153 (cond ((eq scope 'tree)
14154 (org-back-to-heading t)
14155 (org-narrow-to-subtree)
14156 (setq scope nil))
14157 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14158 (org-region-active-p))
14159 ;; If needed, set start-level to a string like "2"
14160 (when start-level
14161 (save-excursion
14162 (goto-char (region-beginning))
14163 (unless (org-at-heading-p) (outline-next-heading))
14164 (setq start-level (org-current-level))))
14165 (narrow-to-region (region-beginning)
14166 (save-excursion
14167 (goto-char (region-end))
14168 (unless (and (bolp) (org-at-heading-p))
14169 (outline-next-heading))
14170 (point)))
14171 (setq scope nil)))
14173 (if (not scope)
14174 (progn
14175 (org-agenda-prepare-buffers
14176 (list (buffer-file-name (current-buffer))))
14177 (setq res (org-scan-tags func matcher todo-only start-level)))
14178 ;; Get the right scope
14179 (cond
14180 ((and scope (listp scope) (symbolp (car scope)))
14181 (setq scope (eval scope)))
14182 ((eq scope 'agenda)
14183 (setq scope (org-agenda-files t)))
14184 ((eq scope 'agenda-with-archives)
14185 (setq scope (org-agenda-files t))
14186 (setq scope (org-add-archive-files scope)))
14187 ((eq scope 'file)
14188 (setq scope (list (buffer-file-name))))
14189 ((eq scope 'file-with-archives)
14190 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14191 (org-agenda-prepare-buffers scope)
14192 (while (setq file (pop scope))
14193 (with-current-buffer (org-find-base-buffer-visiting file)
14194 (save-excursion
14195 (save-restriction
14196 (widen)
14197 (goto-char (point-min))
14198 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14199 res)))
14201 ;;;; Properties
14203 ;;; Setting and retrieving properties
14205 (defconst org-special-properties
14206 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14207 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14208 "The special properties valid in Org-mode.
14210 These are properties that are not defined in the property drawer,
14211 but in some other way.")
14213 (defconst org-default-properties
14214 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14215 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14216 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14217 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14218 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14219 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14220 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14221 "Some properties that are used by Org-mode for various purposes.
14222 Being in this list makes sure that they are offered for completion.")
14224 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14225 "Regular expression matching the first line of a property drawer.")
14227 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14228 "Regular expression matching the last line of a property drawer.")
14230 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14231 "Regular expression matching the first line of a property drawer.")
14233 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14234 "Regular expression matching the first line of a property drawer.")
14236 (defconst org-property-drawer-re
14237 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14238 org-property-end-re "\\)\n?")
14239 "Matches an entire property drawer.")
14241 (defconst org-clock-drawer-re
14242 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14243 org-property-end-re "\\)\n?")
14244 "Matches an entire clock drawer.")
14246 (defsubst org-re-property (property)
14247 "Return a regexp matching a PROPERTY line.
14248 Match group 1 will be set to the value."
14249 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14251 (defsubst org-re-property-keyword (property)
14252 "Return a regexp matching a PROPERTY line, possibly with no
14253 value for the property."
14254 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14256 (defun org-property-action ()
14257 "Do an action on properties."
14258 (interactive)
14259 (let (c)
14260 (org-at-property-p)
14261 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14262 (setq c (read-char-exclusive))
14263 (cond
14264 ((equal c ?s)
14265 (call-interactively 'org-set-property))
14266 ((equal c ?d)
14267 (call-interactively 'org-delete-property))
14268 ((equal c ?D)
14269 (call-interactively 'org-delete-property-globally))
14270 ((equal c ?c)
14271 (call-interactively 'org-compute-property-at-point))
14272 (t (error "No such property action %c" c)))))
14274 (defun org-inc-effort ()
14275 "Increment the value of the effort property in the current entry."
14276 (interactive)
14277 (org-set-effort nil t))
14279 (defun org-set-effort (&optional value increment)
14280 "Set the effort property of the current entry.
14281 With numerical prefix arg, use the nth allowed value, 0 stands for the
14282 10th allowed value.
14284 When INCREMENT is non-nil, set the property to the next allowed value."
14285 (interactive "P")
14286 (if (equal value 0) (setq value 10))
14287 (let* ((completion-ignore-case t)
14288 (prop org-effort-property)
14289 (cur (org-entry-get nil prop))
14290 (allowed (org-property-get-allowed-values nil prop 'table))
14291 (existing (mapcar 'list (org-property-values prop)))
14293 (val (cond
14294 ((stringp value) value)
14295 ((and allowed (integerp value))
14296 (or (car (nth (1- value) allowed))
14297 (car (org-last allowed))))
14298 ((and allowed increment)
14299 (or (caadr (member (list cur) allowed))
14300 (error "Allowed effort values are not set")))
14301 (allowed
14302 (message "Select 1-9,0, [RET%s]: %s"
14303 (if cur (concat "=" cur) "")
14304 (mapconcat 'car allowed " "))
14305 (setq rpl (read-char-exclusive))
14306 (if (equal rpl ?\r)
14308 (setq rpl (- rpl ?0))
14309 (if (equal rpl 0) (setq rpl 10))
14310 (if (and (> rpl 0) (<= rpl (length allowed)))
14311 (car (nth (1- rpl) allowed))
14312 (org-completing-read "Effort: " allowed nil))))
14314 (let (org-completion-use-ido org-completion-use-iswitchb)
14315 (org-completing-read
14316 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14317 (concat "[" cur "]") "")
14318 ": ")
14319 existing nil nil "" nil cur))))))
14320 (unless (equal (org-entry-get nil prop) val)
14321 (org-entry-put nil prop val))
14322 (save-excursion
14323 (org-back-to-heading t)
14324 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14325 (message "%s is now %s" prop val)))
14327 (defun org-at-property-p ()
14328 "Is cursor inside a property drawer?"
14329 (save-excursion
14330 (beginning-of-line 1)
14331 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14332 (save-match-data ;; Used by calling procedures
14333 (let ((p (point))
14334 (range (unless (org-before-first-heading-p)
14335 (org-get-property-block))))
14336 (and range (<= (car range) p) (< p (cdr range))))))))
14338 (defun org-get-property-block (&optional beg end force)
14339 "Return the (beg . end) range of the body of the property drawer.
14340 BEG and END are the beginning and end of the current subtree, or of
14341 the part before the first headline. If they are not given, they will
14342 be found. If the drawer does not exist and FORCE is non-nil, create
14343 the drawer."
14344 (catch 'exit
14345 (save-excursion
14346 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14347 (progn (org-back-to-heading t) (point))))
14348 (end (or end (and (not (outline-next-heading)) (point-max))
14349 (point))))
14350 (goto-char beg)
14351 (if (re-search-forward org-property-start-re end t)
14352 (setq beg (1+ (match-end 0)))
14353 (if force
14354 (save-excursion
14355 (org-insert-property-drawer)
14356 (setq end (progn (outline-next-heading) (point))))
14357 (throw 'exit nil))
14358 (goto-char beg)
14359 (if (re-search-forward org-property-start-re end t)
14360 (setq beg (1+ (match-end 0)))))
14361 (if (re-search-forward org-property-end-re end t)
14362 (setq end (match-beginning 0))
14363 (or force (throw 'exit nil))
14364 (goto-char beg)
14365 (setq end beg)
14366 (org-indent-line)
14367 (insert ":END:\n"))
14368 (cons beg end)))))
14370 (defun org-entry-properties (&optional pom which specific)
14371 "Get all properties of the entry at point-or-marker POM.
14372 This includes the TODO keyword, the tags, time strings for deadline,
14373 scheduled, and clocking, and any additional properties defined in the
14374 entry. The return value is an alist, keys may occur multiple times
14375 if the property key was used several times.
14376 POM may also be nil, in which case the current entry is used.
14377 If WHICH is nil or `all', get all properties. If WHICH is
14378 `special' or `standard', only get that subclass. If WHICH
14379 is a string only get exactly this property. SPECIFIC can be a string, the
14380 specific property we are interested in. Specifying it can speed
14381 things up because then unnecessary parsing is avoided."
14382 (setq which (or which 'all))
14383 (org-with-point-at pom
14384 (let ((clockstr (substring org-clock-string 0 -1))
14385 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14386 (case-fold-search nil)
14387 beg end range props sum-props key key1 value string clocksum clocksumt)
14388 (save-excursion
14389 (when (condition-case nil
14390 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14391 (error nil))
14392 (setq beg (point))
14393 (setq sum-props (get-text-property (point) 'org-summaries))
14394 (setq clocksum (get-text-property (point) :org-clock-minutes)
14395 clocksumt (get-text-property (point) :org-clock-minutes-today))
14396 (outline-next-heading)
14397 (setq end (point))
14398 (when (memq which '(all special))
14399 ;; Get the special properties, like TODO and tags
14400 (goto-char beg)
14401 (when (and (or (not specific) (string= specific "TODO"))
14402 (looking-at org-todo-line-regexp) (match-end 2))
14403 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14404 (when (and (or (not specific) (string= specific "PRIORITY"))
14405 (looking-at org-priority-regexp))
14406 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14407 (when (or (not specific) (string= specific "FILE"))
14408 (push (cons "FILE" buffer-file-name) props))
14409 (when (and (or (not specific) (string= specific "TAGS"))
14410 (setq value (org-get-tags-string))
14411 (string-match "\\S-" value))
14412 (push (cons "TAGS" value) props))
14413 (when (and (or (not specific) (string= specific "ALLTAGS"))
14414 (setq value (org-get-tags-at)))
14415 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14416 ":"))
14417 props))
14418 (when (or (not specific) (string= specific "BLOCKED"))
14419 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14420 (when (or (not specific)
14421 (member specific
14422 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14423 "TIMESTAMP" "TIMESTAMP_IA")))
14424 (catch 'match
14425 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14426 (setq key (if (match-end 1)
14427 (substring (org-match-string-no-properties 1)
14428 0 -1))
14429 string (if (equal key clockstr)
14430 (org-trim
14431 (buffer-substring-no-properties
14432 (match-beginning 3) (goto-char
14433 (point-at-eol))))
14434 (substring (org-match-string-no-properties 3)
14435 1 -1)))
14436 ;; Get the correct property name from the key. This is
14437 ;; necessary if the user has configured time keywords.
14438 (setq key1 (concat key ":"))
14439 (cond
14440 ((not key)
14441 (setq key
14442 (if (= (char-after (match-beginning 3)) ?\[)
14443 "TIMESTAMP_IA" "TIMESTAMP")))
14444 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14445 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14446 ((equal key1 org-closed-string) (setq key "CLOSED"))
14447 ((equal key1 org-clock-string) (setq key "CLOCK")))
14448 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14449 (progn
14450 (push (cons key string) props)
14451 ;; no need to search further if match is found
14452 (throw 'match t))
14453 (when (or (equal key "CLOCK") (not (assoc key props)))
14454 (push (cons key string) props)))))))
14456 (when (memq which '(all standard))
14457 ;; Get the standard properties, like :PROP: ...
14458 (setq range (org-get-property-block beg end))
14459 (when range
14460 (goto-char (car range))
14461 (while (re-search-forward
14462 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14463 (cdr range) t)
14464 (setq key (org-match-string-no-properties 1)
14465 value (org-trim (or (org-match-string-no-properties 2) "")))
14466 (unless (member key excluded)
14467 (push (cons key (or value "")) props)))))
14468 (if clocksum
14469 (push (cons "CLOCKSUM"
14470 (org-columns-number-to-string (/ (float clocksum) 60.)
14471 'add_times))
14472 props))
14473 (if clocksumt
14474 (push (cons "CLOCKSUM_T"
14475 (org-columns-number-to-string (/ (float clocksumt) 60.)
14476 'add_times))
14477 props))
14478 (unless (assoc "CATEGORY" props)
14479 (push (cons "CATEGORY" (org-get-category)) props))
14480 (append sum-props (nreverse props)))))))
14482 (defun org-entry-get (pom property &optional inherit literal-nil)
14483 "Get value of PROPERTY for entry or content at point-or-marker POM.
14484 If INHERIT is non-nil and the entry does not have the property,
14485 then also check higher levels of the hierarchy.
14486 If INHERIT is the symbol `selective', use inheritance only if the setting
14487 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14488 If the property is present but empty, the return value is the empty string.
14489 If the property is not present at all, nil is returned.
14491 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14492 do not interpret it as the list atom nil. This is used for inheritance
14493 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14494 (org-with-point-at pom
14495 (if (and inherit (if (eq inherit 'selective)
14496 (org-property-inherit-p property)
14498 (org-entry-get-with-inheritance property literal-nil)
14499 (if (member property org-special-properties)
14500 ;; We need a special property. Use `org-entry-properties' to
14501 ;; retrieve it, but specify the wanted property
14502 (cdr (assoc property (org-entry-properties nil 'special property)))
14503 (let ((range (org-get-property-block)))
14504 (when (and range (not (eq (car range) (cdr range))))
14505 (let* ((props (list (or (assoc property org-file-properties)
14506 (assoc property org-global-properties)
14507 (assoc property org-global-properties-fixed))))
14508 (ap (lambda (key)
14509 (when (re-search-forward
14510 (org-re-property key) (cdr range) t)
14511 (setq props
14512 (org-update-property-plist
14514 (if (match-end 1)
14515 (org-match-string-no-properties 1) "")
14516 props)))))
14517 val)
14518 (goto-char (car range))
14519 (funcall ap property)
14520 (goto-char (car range))
14521 (while (funcall ap (concat property "+")))
14522 (setq val (cdr (assoc property props)))
14523 (when val (if literal-nil val (org-not-nil val))))))))))
14525 (defun org-property-or-variable-value (var &optional inherit)
14526 "Check if there is a property fixing the value of VAR.
14527 If yes, return this value. If not, return the current value of the variable."
14528 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14529 (if (and prop (stringp prop) (string-match "\\S-" prop))
14530 (read prop)
14531 (symbol-value var))))
14533 (defun org-entry-delete (pom property)
14534 "Delete the property PROPERTY from entry at point-or-marker POM."
14535 (org-with-point-at pom
14536 (if (member property org-special-properties)
14537 nil ; cannot delete these properties.
14538 (let ((range (org-get-property-block)))
14539 (if (and range
14540 (goto-char (car range))
14541 (re-search-forward
14542 (org-re-property property)
14543 (cdr range) t))
14544 (progn
14545 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14547 nil)))))
14549 ;; Multi-values properties are properties that contain multiple values
14550 ;; These values are assumed to be single words, separated by whitespace.
14551 (defun org-entry-add-to-multivalued-property (pom property value)
14552 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14553 (let* ((old (org-entry-get pom property))
14554 (values (and old (org-split-string old "[ \t]"))))
14555 (setq value (org-entry-protect-space value))
14556 (unless (member value values)
14557 (setq values (cons value values))
14558 (org-entry-put pom property
14559 (mapconcat 'identity values " ")))))
14561 (defun org-entry-remove-from-multivalued-property (pom property value)
14562 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14563 (let* ((old (org-entry-get pom property))
14564 (values (and old (org-split-string old "[ \t]"))))
14565 (setq value (org-entry-protect-space value))
14566 (when (member value values)
14567 (setq values (delete value values))
14568 (org-entry-put pom property
14569 (mapconcat 'identity values " ")))))
14571 (defun org-entry-member-in-multivalued-property (pom property value)
14572 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14573 (let* ((old (org-entry-get pom property))
14574 (values (and old (org-split-string old "[ \t]"))))
14575 (setq value (org-entry-protect-space value))
14576 (member value values)))
14578 (defun org-entry-get-multivalued-property (pom property)
14579 "Return a list of values in a multivalued property."
14580 (let* ((value (org-entry-get pom property))
14581 (values (and value (org-split-string value "[ \t]"))))
14582 (mapcar 'org-entry-restore-space values)))
14584 (defun org-entry-put-multivalued-property (pom property &rest values)
14585 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14586 VALUES should be a list of strings. Spaces will be protected."
14587 (org-entry-put pom property
14588 (mapconcat 'org-entry-protect-space values " "))
14589 (let* ((value (org-entry-get pom property))
14590 (values (and value (org-split-string value "[ \t]"))))
14591 (mapcar 'org-entry-restore-space values)))
14593 (defun org-entry-protect-space (s)
14594 "Protect spaces and newline in string S."
14595 (while (string-match " " s)
14596 (setq s (replace-match "%20" t t s)))
14597 (while (string-match "\n" s)
14598 (setq s (replace-match "%0A" t t s)))
14601 (defun org-entry-restore-space (s)
14602 "Restore spaces and newline in string S."
14603 (while (string-match "%20" s)
14604 (setq s (replace-match " " t t s)))
14605 (while (string-match "%0A" s)
14606 (setq s (replace-match "\n" t t s)))
14609 (defvar org-entry-property-inherited-from (make-marker)
14610 "Marker pointing to the entry from where a property was inherited.
14611 Each call to `org-entry-get-with-inheritance' will set this marker to the
14612 location of the entry where the inheritance search matched. If there was
14613 no match, the marker will point nowhere.
14614 Note that also `org-entry-get' calls this function, if the INHERIT flag
14615 is set.")
14617 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14618 "Get PROPERTY of entry or content at point, search higher levels if needed.
14619 The search will stop at the first ancestor which has the property defined.
14620 If the value found is \"nil\", return nil to show that the property
14621 should be considered as undefined (this is the meaning of nil here).
14622 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14623 (move-marker org-entry-property-inherited-from nil)
14624 (let (tmp)
14625 (save-excursion
14626 (save-restriction
14627 (widen)
14628 (catch 'ex
14629 (while t
14630 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14631 (or (ignore-errors (org-back-to-heading t))
14632 (goto-char (point-min)))
14633 (move-marker org-entry-property-inherited-from (point))
14634 (throw 'ex tmp))
14635 (or (ignore-errors (org-up-heading-safe))
14636 (throw 'ex nil))))))
14637 (setq tmp (or tmp
14638 (cdr (assoc property org-file-properties))
14639 (cdr (assoc property org-global-properties))
14640 (cdr (assoc property org-global-properties-fixed))))
14641 (if literal-nil tmp (org-not-nil tmp))))
14643 (defvar org-property-changed-functions nil
14644 "Hook called when the value of a property has changed.
14645 Each hook function should accept two arguments, the name of the property
14646 and the new value.")
14648 (defun org-entry-put (pom property value)
14649 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14650 (org-with-point-at pom
14651 (org-back-to-heading t)
14652 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14653 range)
14654 (cond
14655 ((equal property "TODO")
14656 (when (and (stringp value) (string-match "\\S-" value)
14657 (not (member value org-todo-keywords-1)))
14658 (error "\"%s\" is not a valid TODO state" value))
14659 (if (or (not value)
14660 (not (string-match "\\S-" value)))
14661 (setq value 'none))
14662 (org-todo value)
14663 (org-set-tags nil 'align))
14664 ((equal property "PRIORITY")
14665 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14666 (string-to-char value) ?\ ))
14667 (org-set-tags nil 'align))
14668 ((equal property "SCHEDULED")
14669 (if (re-search-forward org-scheduled-time-regexp end t)
14670 (cond
14671 ((eq value 'earlier) (org-timestamp-change -1 'day))
14672 ((eq value 'later) (org-timestamp-change 1 'day))
14673 (t (call-interactively 'org-schedule)))
14674 (call-interactively 'org-schedule)))
14675 ((equal property "DEADLINE")
14676 (if (re-search-forward org-deadline-time-regexp end t)
14677 (cond
14678 ((eq value 'earlier) (org-timestamp-change -1 'day))
14679 ((eq value 'later) (org-timestamp-change 1 'day))
14680 (t (call-interactively 'org-deadline)))
14681 (call-interactively 'org-deadline)))
14682 ((member property org-special-properties)
14683 (error "The %s property can not yet be set with `org-entry-put'"
14684 property))
14685 (t ; a non-special property
14686 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14687 (setq range (org-get-property-block beg end 'force))
14688 (goto-char (car range))
14689 (if (re-search-forward
14690 (org-re-property-keyword property) (cdr range) t)
14691 (progn
14692 (delete-region (match-beginning 0) (match-end 0))
14693 (goto-char (match-beginning 0)))
14694 (goto-char (cdr range))
14695 (insert "\n")
14696 (backward-char 1)
14697 (org-indent-line))
14698 (insert ":" property ":")
14699 (and value (insert " " value))
14700 (org-indent-line)))))
14701 (run-hook-with-args 'org-property-changed-functions property value)))
14703 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14704 "Get all property keys in the current buffer.
14705 With INCLUDE-SPECIALS, also list the special properties that reflect things
14706 like tags and TODO state.
14707 With INCLUDE-DEFAULTS, also include properties that has special meaning
14708 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14709 and others.
14710 With INCLUDE-COLUMNS, also include property names given in COLUMN
14711 formats in the current buffer."
14712 (let (rtn range cfmt s p)
14713 (save-excursion
14714 (save-restriction
14715 (widen)
14716 (goto-char (point-min))
14717 (while (re-search-forward org-property-start-re nil t)
14718 (setq range (org-get-property-block))
14719 (goto-char (car range))
14720 (while (re-search-forward
14721 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14722 (cdr range) t)
14723 (add-to-list 'rtn (org-match-string-no-properties 1)))
14724 (outline-next-heading))))
14726 (when include-specials
14727 (setq rtn (append org-special-properties rtn)))
14729 (when include-defaults
14730 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14731 (add-to-list 'rtn org-effort-property))
14733 (when include-columns
14734 (save-excursion
14735 (save-restriction
14736 (widen)
14737 (goto-char (point-min))
14738 (while (re-search-forward
14739 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14740 nil t)
14741 (setq cfmt (match-string 2) s 0)
14742 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14743 cfmt s)
14744 (setq s (match-end 0)
14745 p (match-string 1 cfmt))
14746 (unless (or (equal p "ITEM")
14747 (member p org-special-properties))
14748 (add-to-list 'rtn (match-string 1 cfmt))))))))
14750 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14752 (defun org-property-values (key)
14753 "Return a list of all values of property KEY in the current buffer."
14754 (save-excursion
14755 (save-restriction
14756 (widen)
14757 (goto-char (point-min))
14758 (let ((re (org-re-property key))
14759 values)
14760 (while (re-search-forward re nil t)
14761 (add-to-list 'values (org-trim (match-string 1))))
14762 (delete "" values)))))
14764 (defun org-insert-property-drawer ()
14765 "Insert a property drawer into the current entry."
14766 (org-back-to-heading t)
14767 (looking-at org-outline-regexp)
14768 (let ((indent (if org-adapt-indentation
14769 (- (match-end 0) (match-beginning 0))
14771 (beg (point))
14772 (re (concat "^[ \t]*" org-keyword-time-regexp))
14773 end hiddenp)
14774 (outline-next-heading)
14775 (setq end (point))
14776 (goto-char beg)
14777 (while (re-search-forward re end t))
14778 (setq hiddenp (outline-invisible-p))
14779 (end-of-line 1)
14780 (and (equal (char-after) ?\n) (forward-char 1))
14781 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14782 (if (member (match-string 1) '("CLOCK:" ":END:"))
14783 ;; just skip this line
14784 (beginning-of-line 2)
14785 ;; Drawer start, find the end
14786 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14787 (beginning-of-line 1)))
14788 (org-skip-over-state-notes)
14789 (skip-chars-backward " \t\n\r")
14790 (if (eq (char-before) ?*) (forward-char 1))
14791 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14792 (beginning-of-line 0)
14793 (org-indent-to-column indent)
14794 (beginning-of-line 2)
14795 (org-indent-to-column indent)
14796 (beginning-of-line 0)
14797 (if hiddenp
14798 (save-excursion
14799 (org-back-to-heading t)
14800 (hide-entry))
14801 (org-flag-drawer t))))
14803 (defun org-insert-drawer (&optional arg drawer)
14804 "Insert a drawer at point.
14806 Optional argument DRAWER, when non-nil, is a string representing
14807 drawer's name. Otherwise, the user is prompted for a name.
14809 If a region is active, insert the drawer around that region
14810 instead.
14812 Point is left between drawer's boundaries."
14813 (interactive "P")
14814 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14815 "LOGBOOK"))
14816 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14817 ;; internally by Org. They are meant to be inserted
14818 ;; automatically.
14819 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14820 ;; Remove system drawers from list. Note: For some reason,
14821 ;; `org-completing-read' ignores the predicate while
14822 ;; `completing-read' handles it fine.
14823 (drawer (if arg "PROPERTIES"
14824 (or drawer
14825 (completing-read
14826 "Drawer: " org-drawers
14827 (lambda (d) (not (member d system-drawers))))))))
14828 (cond
14829 ;; With C-u, fall back on `org-insert-property-drawer'
14830 (arg (org-insert-property-drawer))
14831 ;; With an active region, insert a drawer at point.
14832 ((not (org-region-active-p))
14833 (progn
14834 (unless (bolp) (insert "\n"))
14835 (insert (format ":%s:\n\n:END:\n" drawer))
14836 (forward-line -2)))
14837 ;; Otherwise, insert the drawer at point
14839 (let ((rbeg (region-beginning))
14840 (rend (copy-marker (region-end))))
14841 (unwind-protect
14842 (progn
14843 (goto-char rbeg)
14844 (beginning-of-line)
14845 (when (save-excursion
14846 (re-search-forward org-outline-regexp-bol rend t))
14847 (error "Drawers cannot contain headlines"))
14848 ;; Position point at the beginning of the first
14849 ;; non-blank line in region. Insert drawer's opening
14850 ;; there, then indent it.
14851 (org-skip-whitespace)
14852 (beginning-of-line)
14853 (insert ":" drawer ":\n")
14854 (forward-line -1)
14855 (indent-for-tab-command)
14856 ;; Move point to the beginning of the first blank line
14857 ;; after the last non-blank line in region. Insert
14858 ;; drawer's closing, then indent it.
14859 (goto-char rend)
14860 (skip-chars-backward " \r\t\n")
14861 (insert "\n:END:")
14862 (deactivate-mark t)
14863 (indent-for-tab-command)
14864 (unless (eolp) (insert "\n")))
14865 ;; Clear marker, whatever the outcome of insertion is.
14866 (set-marker rend nil)))))))
14868 (defvar org-property-set-functions-alist nil
14869 "Property set function alist.
14870 Each entry should have the following format:
14872 (PROPERTY . READ-FUNCTION)
14874 The read function will be called with the same argument as
14875 `org-completing-read'.")
14877 (defun org-set-property-function (property)
14878 "Get the function that should be used to set PROPERTY.
14879 This is computed according to `org-property-set-functions-alist'."
14880 (or (cdr (assoc property org-property-set-functions-alist))
14881 'org-completing-read))
14883 (defun org-read-property-value (property)
14884 "Read PROPERTY value from user."
14885 (let* ((completion-ignore-case t)
14886 (allowed (org-property-get-allowed-values nil property 'table))
14887 (cur (org-entry-get nil property))
14888 (prompt (concat property " value"
14889 (if (and cur (string-match "\\S-" cur))
14890 (concat " [" cur "]") "") ": "))
14891 (set-function (org-set-property-function property))
14892 (val (if allowed
14893 (funcall set-function prompt allowed nil
14894 (not (get-text-property 0 'org-unrestricted
14895 (caar allowed))))
14896 (let (org-completion-use-ido org-completion-use-iswitchb)
14897 (funcall set-function prompt
14898 (mapcar 'list (org-property-values property))
14899 nil nil "" nil cur)))))
14900 (if (equal val "")
14902 val)))
14904 (defvar org-last-set-property nil)
14905 (defun org-read-property-name ()
14906 "Read a property name."
14907 (let* ((completion-ignore-case t)
14908 (keys (org-buffer-property-keys nil t t))
14909 (default-prop (or (save-excursion
14910 (save-match-data
14911 (beginning-of-line)
14912 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14913 (null (string= (match-string 1) "END"))
14914 (match-string 1))))
14915 org-last-set-property))
14916 (property (org-icompleting-read
14917 (concat "Property"
14918 (if default-prop (concat " [" default-prop "]") "")
14919 ": ")
14920 (mapcar 'list keys)
14921 nil nil nil nil
14922 default-prop
14924 (if (member property keys)
14925 property
14926 (or (cdr (assoc (downcase property)
14927 (mapcar (lambda (x) (cons (downcase x) x))
14928 keys)))
14929 property))))
14931 (defun org-set-property (property value)
14932 "In the current entry, set PROPERTY to VALUE.
14933 When called interactively, this will prompt for a property name, offering
14934 completion on existing and default properties. And then it will prompt
14935 for a value, offering completion either on allowed values (via an inherited
14936 xxx_ALL property) or on existing values in other instances of this property
14937 in the current file."
14938 (interactive (list nil nil))
14939 (let* ((property (or property (org-read-property-name)))
14940 (value (or value (org-read-property-value property)))
14941 (fn (cdr (assoc property org-properties-postprocess-alist))))
14942 (setq org-last-set-property property)
14943 ;; Possibly postprocess the inserted value:
14944 (when fn (setq value (funcall fn value)))
14945 (unless (equal (org-entry-get nil property) value)
14946 (org-entry-put nil property value))))
14948 (defun org-delete-property (property)
14949 "In the current entry, delete PROPERTY."
14950 (interactive
14951 (let* ((completion-ignore-case t)
14952 (prop (org-icompleting-read "Property: "
14953 (org-entry-properties nil 'standard))))
14954 (list prop)))
14955 (message "Property %s %s" property
14956 (if (org-entry-delete nil property)
14957 "deleted"
14958 "was not present in the entry")))
14960 (defun org-delete-property-globally (property)
14961 "Remove PROPERTY globally, from all entries."
14962 (interactive
14963 (let* ((completion-ignore-case t)
14964 (prop (org-icompleting-read
14965 "Globally remove property: "
14966 (mapcar 'list (org-buffer-property-keys)))))
14967 (list prop)))
14968 (save-excursion
14969 (save-restriction
14970 (widen)
14971 (goto-char (point-min))
14972 (let ((cnt 0))
14973 (while (re-search-forward
14974 (org-re-property property)
14975 nil t)
14976 (setq cnt (1+ cnt))
14977 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14978 (message "Property \"%s\" removed from %d entries" property cnt)))))
14980 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14982 (defun org-compute-property-at-point ()
14983 "Compute the property at point.
14984 This looks for an enclosing column format, extracts the operator and
14985 then applies it to the property in the column format's scope."
14986 (interactive)
14987 (unless (org-at-property-p)
14988 (error "Not at a property"))
14989 (let ((prop (org-match-string-no-properties 2)))
14990 (org-columns-get-format-and-top-level)
14991 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14992 (error "No operator defined for property %s" prop))
14993 (org-columns-compute prop)))
14995 (defvar org-property-allowed-value-functions nil
14996 "Hook for functions supplying allowed values for a specific property.
14997 The functions must take a single argument, the name of the property, and
14998 return a flat list of allowed values. If \":ETC\" is one of
14999 the values, this means that these values are intended as defaults for
15000 completion, but that other values should be allowed too.
15001 The functions must return nil if they are not responsible for this
15002 property.")
15004 (defun org-property-get-allowed-values (pom property &optional table)
15005 "Get allowed values for the property PROPERTY.
15006 When TABLE is non-nil, return an alist that can directly be used for
15007 completion."
15008 (let (vals)
15009 (cond
15010 ((equal property "TODO")
15011 (setq vals (org-with-point-at pom
15012 (append org-todo-keywords-1 '("")))))
15013 ((equal property "PRIORITY")
15014 (let ((n org-lowest-priority))
15015 (while (>= n org-highest-priority)
15016 (push (char-to-string n) vals)
15017 (setq n (1- n)))))
15018 ((member property org-special-properties))
15019 ((setq vals (run-hook-with-args-until-success
15020 'org-property-allowed-value-functions property)))
15022 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15023 (when (and vals (string-match "\\S-" vals))
15024 (setq vals (car (read-from-string (concat "(" vals ")"))))
15025 (setq vals (mapcar (lambda (x)
15026 (cond ((stringp x) x)
15027 ((numberp x) (number-to-string x))
15028 ((symbolp x) (symbol-name x))
15029 (t "???")))
15030 vals)))))
15031 (when (member ":ETC" vals)
15032 (setq vals (remove ":ETC" vals))
15033 (org-add-props (car vals) '(org-unrestricted t)))
15034 (if table (mapcar 'list vals) vals)))
15036 (defun org-property-previous-allowed-value (&optional previous)
15037 "Switch to the next allowed value for this property."
15038 (interactive)
15039 (org-property-next-allowed-value t))
15041 (defun org-property-next-allowed-value (&optional previous)
15042 "Switch to the next allowed value for this property."
15043 (interactive)
15044 (unless (org-at-property-p)
15045 (error "Not at a property"))
15046 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15047 (key (match-string 2))
15048 (value (match-string 3))
15049 (allowed (or (org-property-get-allowed-values (point) key)
15050 (and (member value '("[ ]" "[-]" "[X]"))
15051 '("[ ]" "[X]"))))
15052 nval)
15053 (unless allowed
15054 (error "Allowed values for this property have not been defined"))
15055 (if previous (setq allowed (reverse allowed)))
15056 (if (member value allowed)
15057 (setq nval (car (cdr (member value allowed)))))
15058 (setq nval (or nval (car allowed)))
15059 (if (equal nval value)
15060 (error "Only one allowed value for this property"))
15061 (org-at-property-p)
15062 (replace-match (concat " :" key ": " nval) t t)
15063 (org-indent-line)
15064 (beginning-of-line 1)
15065 (skip-chars-forward " \t")
15066 (when (equal prop org-effort-property)
15067 (save-excursion
15068 (org-back-to-heading t)
15069 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15070 (run-hook-with-args 'org-property-changed-functions key nval)))
15072 (defun org-find-olp (path &optional this-buffer)
15073 "Return a marker pointing to the entry at outline path OLP.
15074 If anything goes wrong, throw an error.
15075 You can wrap this call to catch the error like this:
15077 (condition-case msg
15078 (org-mobile-locate-entry (match-string 4))
15079 (error (nth 1 msg)))
15081 The return value will then be either a string with the error message,
15082 or a marker if everything is OK.
15084 If THIS-BUFFER is set, the outline path does not contain a file,
15085 only headings."
15086 (let* ((file (if this-buffer buffer-file-name (pop path)))
15087 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15088 (level 1)
15089 (lmin 1)
15090 (lmax 1)
15091 limit re end found pos heading cnt flevel)
15092 (unless buffer (error "File not found :%s" file))
15093 (with-current-buffer buffer
15094 (save-excursion
15095 (save-restriction
15096 (widen)
15097 (setq limit (point-max))
15098 (goto-char (point-min))
15099 (while (setq heading (pop path))
15100 (setq re (format org-complex-heading-regexp-format
15101 (regexp-quote heading)))
15102 (setq cnt 0 pos (point))
15103 (while (re-search-forward re end t)
15104 (setq level (- (match-end 1) (match-beginning 1)))
15105 (if (and (>= level lmin) (<= level lmax))
15106 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15107 (when (= cnt 0) (error "Heading not found on level %d: %s"
15108 lmax heading))
15109 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15110 lmax heading))
15111 (goto-char found)
15112 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15113 (setq end (save-excursion (org-end-of-subtree t t))))
15114 (when (org-at-heading-p)
15115 (point-marker)))))))
15117 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15118 "Find node HEADING in BUFFER.
15119 Return a marker to the heading if it was found, or nil if not.
15120 If POS-ONLY is set, return just the position instead of a marker.
15122 The heading text must match exact, but it may have a TODO keyword,
15123 a priority cookie and tags in the standard locations."
15124 (with-current-buffer (or buffer (current-buffer))
15125 (save-excursion
15126 (save-restriction
15127 (widen)
15128 (goto-char (point-min))
15129 (let (case-fold-search)
15130 (if (re-search-forward
15131 (format org-complex-heading-regexp-format
15132 (regexp-quote heading)) nil t)
15133 (if pos-only
15134 (match-beginning 0)
15135 (move-marker (make-marker) (match-beginning 0)))))))))
15137 (defun org-find-exact-heading-in-directory (heading &optional dir)
15138 "Find Org node headline HEADING in all .org files in directory DIR.
15139 When the target headline is found, return a marker to this location."
15140 (let ((files (directory-files (or dir default-directory)
15141 nil "\\`[^.#].*\\.org\\'"))
15142 file visiting m buffer)
15143 (catch 'found
15144 (while (setq file (pop files))
15145 (message "trying %s" file)
15146 (setq visiting (org-find-base-buffer-visiting file))
15147 (setq buffer (or visiting (find-file-noselect file)))
15148 (setq m (org-find-exact-headline-in-buffer
15149 heading buffer))
15150 (when (and (not m) (not visiting)) (kill-buffer buffer))
15151 (and m (throw 'found m))))))
15153 (defun org-find-entry-with-id (ident)
15154 "Locate the entry that contains the ID property with exact value IDENT.
15155 IDENT can be a string, a symbol or a number, this function will search for
15156 the string representation of it.
15157 Return the position where this entry starts, or nil if there is no such entry."
15158 (interactive "sID: ")
15159 (let ((id (cond
15160 ((stringp ident) ident)
15161 ((symbol-name ident) (symbol-name ident))
15162 ((numberp ident) (number-to-string ident))
15163 (t (error "IDENT %s must be a string, symbol or number" ident))))
15164 (case-fold-search nil))
15165 (save-excursion
15166 (save-restriction
15167 (widen)
15168 (goto-char (point-min))
15169 (when (re-search-forward
15170 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15171 nil t)
15172 (org-back-to-heading t)
15173 (point))))))
15175 ;;;; Timestamps
15177 (defvar org-last-changed-timestamp nil)
15178 (defvar org-last-inserted-timestamp nil
15179 "The last time stamp inserted with `org-insert-time-stamp'.")
15180 (defvar org-time-was-given) ; dynamically scoped parameter
15181 (defvar org-end-time-was-given) ; dynamically scoped parameter
15182 (defvar org-ts-what) ; dynamically scoped parameter
15184 (defun org-time-stamp (arg &optional inactive)
15185 "Prompt for a date/time and insert a time stamp.
15186 If the user specifies a time like HH:MM or if this command is
15187 called with at least one prefix argument, the time stamp contains
15188 the date and the time. Otherwise, only the date is be included.
15190 All parts of a date not specified by the user is filled in from
15191 the current date/time. So if you just press return without
15192 typing anything, the time stamp will represent the current
15193 date/time.
15195 If there is already a timestamp at the cursor, it will be
15196 modified.
15198 With two universal prefix arguments, insert an active timestamp
15199 with the current time without prompting the user."
15200 (interactive "P")
15201 (let* ((ts nil)
15202 (default-time
15203 ;; Default time is either today, or, when entering a range,
15204 ;; the range start.
15205 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15206 (save-excursion
15207 (re-search-backward
15208 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15209 (- (point) 20) t)))
15210 (apply 'encode-time (org-parse-time-string (match-string 1)))
15211 (current-time)))
15212 (default-input (and ts (org-get-compact-tod ts)))
15213 (repeater (save-excursion
15214 (save-match-data
15215 (beginning-of-line)
15216 (when (re-search-forward
15217 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15218 (save-excursion (progn (end-of-line) (point))) t)
15219 (match-string 0)))))
15220 org-time-was-given org-end-time-was-given time)
15221 (cond
15222 ((and (org-at-timestamp-p t)
15223 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15224 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15225 (insert "--")
15226 (setq time (let ((this-command this-command))
15227 (org-read-date arg 'totime nil nil
15228 default-time default-input inactive)))
15229 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15230 ((org-at-timestamp-p t)
15231 (setq time (let ((this-command this-command))
15232 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15233 (when (org-at-timestamp-p t) ; just to get the match data
15234 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15235 (replace-match "")
15236 (setq org-last-changed-timestamp
15237 (org-insert-time-stamp
15238 time (or org-time-was-given arg)
15239 inactive nil nil (list org-end-time-was-given)))
15240 (when repeater (goto-char (1- (point))) (insert " " repeater)
15241 (setq org-last-changed-timestamp
15242 (concat (substring org-last-inserted-timestamp 0 -1)
15243 " " repeater ">"))))
15244 (message "Timestamp updated"))
15245 ((equal arg '(16))
15246 (org-insert-time-stamp (current-time) t))
15248 (setq time (let ((this-command this-command))
15249 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15250 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15251 nil nil (list org-end-time-was-given))))))
15253 ;; FIXME: can we use this for something else, like computing time differences?
15254 (defun org-get-compact-tod (s)
15255 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15256 (let* ((t1 (match-string 1 s))
15257 (h1 (string-to-number (match-string 2 s)))
15258 (m1 (string-to-number (match-string 3 s)))
15259 (t2 (and (match-end 4) (match-string 5 s)))
15260 (h2 (and t2 (string-to-number (match-string 6 s))))
15261 (m2 (and t2 (string-to-number (match-string 7 s))))
15262 dh dm)
15263 (if (not t2)
15265 (setq dh (- h2 h1) dm (- m2 m1))
15266 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15267 (concat t1 "+" (number-to-string dh)
15268 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15270 (defun org-time-stamp-inactive (&optional arg)
15271 "Insert an inactive time stamp.
15272 An inactive time stamp is enclosed in square brackets instead of angle
15273 brackets. It is inactive in the sense that it does not trigger agenda entries,
15274 does not link to the calendar and cannot be changed with the S-cursor keys.
15275 So these are more for recording a certain time/date."
15276 (interactive "P")
15277 (org-time-stamp arg 'inactive))
15279 (defvar org-date-ovl (make-overlay 1 1))
15280 (overlay-put org-date-ovl 'face 'org-date-selected)
15281 (org-detach-overlay org-date-ovl)
15283 (defvar org-ans1) ; dynamically scoped parameter
15284 (defvar org-ans2) ; dynamically scoped parameter
15286 (defvar org-plain-time-of-day-regexp) ; defined below
15288 (defvar org-overriding-default-time nil) ; dynamically scoped
15289 (defvar org-read-date-overlay nil)
15290 (defvar org-dcst nil) ; dynamically scoped
15291 (defvar org-read-date-history nil)
15292 (defvar org-read-date-final-answer nil)
15293 (defvar org-read-date-analyze-futurep nil)
15294 (defvar org-read-date-analyze-forced-year nil)
15295 (defvar org-read-date-inactive)
15297 (defun org-read-date (&optional org-with-time to-time from-string prompt
15298 default-time default-input inactive)
15299 "Read a date, possibly a time, and make things smooth for the user.
15300 The prompt will suggest to enter an ISO date, but you can also enter anything
15301 which will at least partially be understood by `parse-time-string'.
15302 Unrecognized parts of the date will default to the current day, month, year,
15303 hour and minute. If this command is called to replace a timestamp at point,
15304 or to enter the second timestamp of a range, the default time is taken
15305 from the existing stamp. Furthermore, the command prefers the future,
15306 so if you are giving a date where the year is not given, and the day-month
15307 combination is already past in the current year, it will assume you
15308 mean next year. For details, see the manual. A few examples:
15310 3-2-5 --> 2003-02-05
15311 feb 15 --> currentyear-02-15
15312 2/15 --> currentyear-02-15
15313 sep 12 9 --> 2009-09-12
15314 12:45 --> today 12:45
15315 22 sept 0:34 --> currentyear-09-22 0:34
15316 12 --> currentyear-currentmonth-12
15317 Fri --> nearest Friday (today or later)
15318 etc.
15320 Furthermore you can specify a relative date by giving, as the *first* thing
15321 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15322 change in days weeks, months, years.
15323 With a single plus or minus, the date is relative to today. With a double
15324 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15325 +4d --> four days from today
15326 +4 --> same as above
15327 +2w --> two weeks from today
15328 ++5 --> five days from default date
15330 The function understands only English month and weekday abbreviations.
15332 While prompting, a calendar is popped up - you can also select the
15333 date with the mouse (button 1). The calendar shows a period of three
15334 months. To scroll it to other months, use the keys `>' and `<'.
15335 If you don't like the calendar, turn it off with
15336 \(setq org-read-date-popup-calendar nil)
15338 With optional argument TO-TIME, the date will immediately be converted
15339 to an internal time.
15340 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15341 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15342 still enter a time, and this function will inform the calling routine
15343 about this change. The calling routine may then choose to change the
15344 format used to insert the time stamp into the buffer to include the time.
15345 With optional argument FROM-STRING, read from this string instead from
15346 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15347 the time/date that is used for everything that is not specified by the
15348 user."
15349 (require 'parse-time)
15350 (let* ((org-time-stamp-rounding-minutes
15351 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15352 (org-dcst org-display-custom-times)
15353 (ct (org-current-time))
15354 (org-def (or org-overriding-default-time default-time ct))
15355 (org-defdecode (decode-time org-def))
15356 (dummy (progn
15357 (when (< (nth 2 org-defdecode) org-extend-today-until)
15358 (setcar (nthcdr 2 org-defdecode) -1)
15359 (setcar (nthcdr 1 org-defdecode) 59)
15360 (setq org-def (apply 'encode-time org-defdecode)
15361 org-defdecode (decode-time org-def)))))
15362 (mouse-autoselect-window nil) ; Don't let the mouse jump
15363 (calendar-frame-setup nil)
15364 (calendar-setup nil)
15365 (calendar-move-hook nil)
15366 (calendar-view-diary-initially-flag nil)
15367 (calendar-view-holidays-initially-flag nil)
15368 (timestr (format-time-string
15369 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15370 (prompt (concat (if prompt (concat prompt " ") "")
15371 (format "Date+time [%s]: " timestr)))
15372 ans (org-ans0 "") org-ans1 org-ans2 final)
15374 (cond
15375 (from-string (setq ans from-string))
15376 (org-read-date-popup-calendar
15377 (save-excursion
15378 (save-window-excursion
15379 (calendar)
15380 (org-eval-in-calendar '(setq cursor-type nil) t)
15381 (unwind-protect
15382 (progn
15383 (calendar-forward-day (- (time-to-days org-def)
15384 (calendar-absolute-from-gregorian
15385 (calendar-current-date))))
15386 (org-eval-in-calendar nil t)
15387 (let* ((old-map (current-local-map))
15388 (map (copy-keymap calendar-mode-map))
15389 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15390 (org-defkey map (kbd "RET") 'org-calendar-select)
15391 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15392 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15393 (org-defkey minibuffer-local-map [(meta shift left)]
15394 (lambda () (interactive)
15395 (org-eval-in-calendar '(calendar-backward-month 1))))
15396 (org-defkey minibuffer-local-map [(meta shift right)]
15397 (lambda () (interactive)
15398 (org-eval-in-calendar '(calendar-forward-month 1))))
15399 (org-defkey minibuffer-local-map [(meta shift up)]
15400 (lambda () (interactive)
15401 (org-eval-in-calendar '(calendar-backward-year 1))))
15402 (org-defkey minibuffer-local-map [(meta shift down)]
15403 (lambda () (interactive)
15404 (org-eval-in-calendar '(calendar-forward-year 1))))
15405 (org-defkey minibuffer-local-map [?\e (shift left)]
15406 (lambda () (interactive)
15407 (org-eval-in-calendar '(calendar-backward-month 1))))
15408 (org-defkey minibuffer-local-map [?\e (shift right)]
15409 (lambda () (interactive)
15410 (org-eval-in-calendar '(calendar-forward-month 1))))
15411 (org-defkey minibuffer-local-map [?\e (shift up)]
15412 (lambda () (interactive)
15413 (org-eval-in-calendar '(calendar-backward-year 1))))
15414 (org-defkey minibuffer-local-map [?\e (shift down)]
15415 (lambda () (interactive)
15416 (org-eval-in-calendar '(calendar-forward-year 1))))
15417 (org-defkey minibuffer-local-map [(shift up)]
15418 (lambda () (interactive)
15419 (org-eval-in-calendar '(calendar-backward-week 1))))
15420 (org-defkey minibuffer-local-map [(shift down)]
15421 (lambda () (interactive)
15422 (org-eval-in-calendar '(calendar-forward-week 1))))
15423 (org-defkey minibuffer-local-map [(shift left)]
15424 (lambda () (interactive)
15425 (org-eval-in-calendar '(calendar-backward-day 1))))
15426 (org-defkey minibuffer-local-map [(shift right)]
15427 (lambda () (interactive)
15428 (org-eval-in-calendar '(calendar-forward-day 1))))
15429 (org-defkey minibuffer-local-map ">"
15430 (lambda () (interactive)
15431 (org-eval-in-calendar '(scroll-calendar-left 1))))
15432 (org-defkey minibuffer-local-map "<"
15433 (lambda () (interactive)
15434 (org-eval-in-calendar '(scroll-calendar-right 1))))
15435 (org-defkey minibuffer-local-map "\C-v"
15436 (lambda () (interactive)
15437 (org-eval-in-calendar
15438 '(calendar-scroll-left-three-months 1))))
15439 (org-defkey minibuffer-local-map "\M-v"
15440 (lambda () (interactive)
15441 (org-eval-in-calendar
15442 '(calendar-scroll-right-three-months 1))))
15443 (run-hooks 'org-read-date-minibuffer-setup-hook)
15444 (unwind-protect
15445 (progn
15446 (use-local-map map)
15447 (setq org-read-date-inactive inactive)
15448 (add-hook 'post-command-hook 'org-read-date-display)
15449 (setq org-ans0 (read-string prompt default-input
15450 'org-read-date-history nil))
15451 ;; org-ans0: from prompt
15452 ;; org-ans1: from mouse click
15453 ;; org-ans2: from calendar motion
15454 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15455 (remove-hook 'post-command-hook 'org-read-date-display)
15456 (use-local-map old-map)
15457 (when org-read-date-overlay
15458 (delete-overlay org-read-date-overlay)
15459 (setq org-read-date-overlay nil)))))
15460 (bury-buffer "*Calendar*")))))
15462 (t ; Naked prompt only
15463 (unwind-protect
15464 (setq ans (read-string prompt default-input
15465 'org-read-date-history timestr))
15466 (when org-read-date-overlay
15467 (delete-overlay org-read-date-overlay)
15468 (setq org-read-date-overlay nil)))))
15470 (setq final (org-read-date-analyze ans org-def org-defdecode))
15472 (when org-read-date-analyze-forced-year
15473 (message "Year was forced into %s"
15474 (if org-read-date-force-compatible-dates
15475 "compatible range (1970-2037)"
15476 "range representable on this machine"))
15477 (ding))
15479 ;; One round trip to get rid of 34th of August and stuff like that....
15480 (setq final (decode-time (apply 'encode-time final)))
15482 (setq org-read-date-final-answer ans)
15484 (if to-time
15485 (apply 'encode-time final)
15486 (if (and (boundp 'org-time-was-given) org-time-was-given)
15487 (format "%04d-%02d-%02d %02d:%02d"
15488 (nth 5 final) (nth 4 final) (nth 3 final)
15489 (nth 2 final) (nth 1 final))
15490 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15492 (defvar org-def)
15493 (defvar org-defdecode)
15494 (defvar org-with-time)
15495 (defun org-read-date-display ()
15496 "Display the current date prompt interpretation in the minibuffer."
15497 (when org-read-date-display-live
15498 (when org-read-date-overlay
15499 (delete-overlay org-read-date-overlay))
15500 (when (minibufferp (current-buffer))
15501 (save-excursion
15502 (end-of-line 1)
15503 (while (not (equal (buffer-substring
15504 (max (point-min) (- (point) 4)) (point))
15505 " "))
15506 (insert " ")))
15507 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15508 " " (or org-ans1 org-ans2)))
15509 (org-end-time-was-given nil)
15510 (f (org-read-date-analyze ans org-def org-defdecode))
15511 (fmts (if org-dcst
15512 org-time-stamp-custom-formats
15513 org-time-stamp-formats))
15514 (fmt (if (or org-with-time
15515 (and (boundp 'org-time-was-given) org-time-was-given))
15516 (cdr fmts)
15517 (car fmts)))
15518 (txt (format-time-string fmt (apply 'encode-time f)))
15519 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15520 (txt (concat "=> " txt)))
15521 (when (and org-end-time-was-given
15522 (string-match org-plain-time-of-day-regexp txt))
15523 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15524 org-end-time-was-given
15525 (substring txt (match-end 0)))))
15526 (when org-read-date-analyze-futurep
15527 (setq txt (concat txt " (=>F)")))
15528 (setq org-read-date-overlay
15529 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15530 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15532 (defun org-read-date-analyze (ans org-def org-defdecode)
15533 "Analyze the combined answer of the date prompt."
15534 ;; FIXME: cleanup and comment
15535 (let ((nowdecode (decode-time (current-time)))
15536 delta deltan deltaw deltadef year month day
15537 hour minute second wday pm h2 m2 tl wday1
15538 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15539 (setq org-read-date-analyze-futurep nil
15540 org-read-date-analyze-forced-year nil)
15541 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15542 (setq ans "+0"))
15544 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15545 (setq ans (replace-match "" t t ans)
15546 deltan (car delta)
15547 deltaw (nth 1 delta)
15548 deltadef (nth 2 delta)))
15550 ;; Check if there is an iso week date in there. If yes, store the
15551 ;; info and postpone interpreting it until the rest of the parsing
15552 ;; is done.
15553 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15554 (setq iso-year (if (match-end 1)
15555 (org-small-year-to-year
15556 (string-to-number (match-string 1 ans))))
15557 iso-weekday (if (match-end 3)
15558 (string-to-number (match-string 3 ans)))
15559 iso-week (string-to-number (match-string 2 ans)))
15560 (setq ans (replace-match "" t t ans)))
15562 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15563 (when (string-match
15564 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15565 (setq year (if (match-end 2)
15566 (string-to-number (match-string 2 ans))
15567 (progn (setq kill-year t)
15568 (string-to-number (format-time-string "%Y"))))
15569 month (string-to-number (match-string 3 ans))
15570 day (string-to-number (match-string 4 ans)))
15571 (if (< year 100) (setq year (+ 2000 year)))
15572 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15573 t nil ans)))
15575 ;; Help matching dotted european dates
15576 (when (string-match
15577 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15578 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15579 (setq kill-year t)
15580 (string-to-number (format-time-string "%Y")))
15581 day (string-to-number (match-string 1 ans))
15582 month (string-to-number (match-string 2 ans))
15583 ans (replace-match (format "%04d-%02d-%02d" year month day)
15584 t nil ans)))
15586 ;; Help matching american dates, like 5/30 or 5/30/7
15587 (when (string-match
15588 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15589 (setq year (if (match-end 4)
15590 (string-to-number (match-string 4 ans))
15591 (progn (setq kill-year t)
15592 (string-to-number (format-time-string "%Y"))))
15593 month (string-to-number (match-string 1 ans))
15594 day (string-to-number (match-string 2 ans)))
15595 (if (< year 100) (setq year (+ 2000 year)))
15596 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15597 t nil ans)))
15598 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15599 ;; If there is a time with am/pm, and *no* time without it, we convert
15600 ;; so that matching will be successful.
15601 (loop for i from 1 to 2 do ; twice, for end time as well
15602 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15603 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15604 (setq hour (string-to-number (match-string 1 ans))
15605 minute (if (match-end 3)
15606 (string-to-number (match-string 3 ans))
15608 pm (equal ?p
15609 (string-to-char (downcase (match-string 4 ans)))))
15610 (if (and (= hour 12) (not pm))
15611 (setq hour 0)
15612 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15613 (setq ans (replace-match (format "%02d:%02d" hour minute)
15614 t t ans))))
15616 ;; Check if a time range is given as a duration
15617 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15618 (setq hour (string-to-number (match-string 1 ans))
15619 h2 (+ hour (string-to-number (match-string 3 ans)))
15620 minute (string-to-number (match-string 2 ans))
15621 m2 (+ minute (if (match-end 5) (string-to-number
15622 (match-string 5 ans))0)))
15623 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15624 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15625 t t ans)))
15627 ;; Check if there is a time range
15628 (when (boundp 'org-end-time-was-given)
15629 (setq org-time-was-given nil)
15630 (when (and (string-match org-plain-time-of-day-regexp ans)
15631 (match-end 8))
15632 (setq org-end-time-was-given (match-string 8 ans))
15633 (setq ans (concat (substring ans 0 (match-beginning 7))
15634 (substring ans (match-end 7))))))
15636 (setq tl (parse-time-string ans)
15637 day (or (nth 3 tl) (nth 3 org-defdecode))
15638 month (or (nth 4 tl)
15639 (if (and org-read-date-prefer-future
15640 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15641 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15642 (nth 4 org-defdecode)))
15643 year (or (and (not kill-year) (nth 5 tl))
15644 (if (and org-read-date-prefer-future
15645 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15646 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15647 (nth 5 org-defdecode)))
15648 hour (or (nth 2 tl) (nth 2 org-defdecode))
15649 minute (or (nth 1 tl) (nth 1 org-defdecode))
15650 second (or (nth 0 tl) 0)
15651 wday (nth 6 tl))
15653 (when (and (eq org-read-date-prefer-future 'time)
15654 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15655 (equal day (nth 3 nowdecode))
15656 (equal month (nth 4 nowdecode))
15657 (equal year (nth 5 nowdecode))
15658 (nth 2 tl)
15659 (or (< (nth 2 tl) (nth 2 nowdecode))
15660 (and (= (nth 2 tl) (nth 2 nowdecode))
15661 (nth 1 tl)
15662 (< (nth 1 tl) (nth 1 nowdecode)))))
15663 (setq day (1+ day)
15664 futurep t))
15666 ;; Special date definitions below
15667 (cond
15668 (iso-week
15669 ;; There was an iso week
15670 (require 'cal-iso)
15671 (setq futurep nil)
15672 (setq year (or iso-year year)
15673 day (or iso-weekday wday 1)
15674 wday nil ; to make sure that the trigger below does not match
15675 iso-date (calendar-gregorian-from-absolute
15676 (calendar-absolute-from-iso
15677 (list iso-week day year))))
15678 ; FIXME: Should we also push ISO weeks into the future?
15679 ; (when (and org-read-date-prefer-future
15680 ; (not iso-year)
15681 ; (< (calendar-absolute-from-gregorian iso-date)
15682 ; (time-to-days (current-time))))
15683 ; (setq year (1+ year)
15684 ; iso-date (calendar-gregorian-from-absolute
15685 ; (calendar-absolute-from-iso
15686 ; (list iso-week day year)))))
15687 (setq month (car iso-date)
15688 year (nth 2 iso-date)
15689 day (nth 1 iso-date)))
15690 (deltan
15691 (setq futurep nil)
15692 (unless deltadef
15693 (let ((now (decode-time (current-time))))
15694 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15695 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15696 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15697 ((equal deltaw "m") (setq month (+ month deltan)))
15698 ((equal deltaw "y") (setq year (+ year deltan)))))
15699 ((and wday (not (nth 3 tl)))
15700 ;; Weekday was given, but no day, so pick that day in the week
15701 ;; on or after the derived date.
15702 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15703 (unless (equal wday wday1)
15704 (setq day (+ day (% (- wday wday1 -7) 7))))))
15705 (if (and (boundp 'org-time-was-given)
15706 (nth 2 tl))
15707 (setq org-time-was-given t))
15708 (if (< year 100) (setq year (+ 2000 year)))
15709 ;; Check of the date is representable
15710 (if org-read-date-force-compatible-dates
15711 (progn
15712 (if (< year 1970)
15713 (setq year 1970 org-read-date-analyze-forced-year t))
15714 (if (> year 2037)
15715 (setq year 2037 org-read-date-analyze-forced-year t)))
15716 (condition-case nil
15717 (ignore (encode-time second minute hour day month year))
15718 (error
15719 (setq year (nth 5 org-defdecode))
15720 (setq org-read-date-analyze-forced-year t))))
15721 (setq org-read-date-analyze-futurep futurep)
15722 (list second minute hour day month year)))
15724 (defvar parse-time-weekdays)
15725 (defun org-read-date-get-relative (s today default)
15726 "Check string S for special relative date string.
15727 TODAY and DEFAULT are internal times, for today and for a default.
15728 Return shift list (N what def-flag)
15729 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15730 N is the number of WHATs to shift.
15731 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15732 the DEFAULT date rather than TODAY."
15733 (require 'parse-time)
15734 (when (and
15735 (string-match
15736 (concat
15737 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15738 "\\([0-9]+\\)?"
15739 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15740 "\\([ \t]\\|$\\)") s)
15741 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15742 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15743 (string-to-char (substring (match-string 1 s) -1))
15744 ?+))
15745 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15746 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15747 (what (if (match-end 3) (match-string 3 s) "d"))
15748 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15749 (date (if rel default today))
15750 (wday (nth 6 (decode-time date)))
15751 delta)
15752 (if wday1
15753 (progn
15754 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15755 (if (= dir ?-) (setq delta (- delta 7)))
15756 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15757 (list delta "d" rel))
15758 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15760 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15761 "Turn a user-specified date into the internal representation.
15762 The internal representation needed by the calendar is (month day year).
15763 This is a wrapper to handle the brain-dead convention in calendar that
15764 user function argument order change dependent on argument order."
15765 (if (boundp 'calendar-date-style)
15766 (cond
15767 ((eq calendar-date-style 'american)
15768 (list arg1 arg2 arg3))
15769 ((eq calendar-date-style 'european)
15770 (list arg2 arg1 arg3))
15771 ((eq calendar-date-style 'iso)
15772 (list arg2 arg3 arg1)))
15773 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15774 (if (org-bound-and-true-p european-calendar-style)
15775 (list arg2 arg1 arg3)
15776 (list arg1 arg2 arg3)))))
15778 (defun org-eval-in-calendar (form &optional keepdate)
15779 "Eval FORM in the calendar window and return to current window.
15780 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15781 otherwise stick to the current value of `org-ans2'."
15782 (let ((sf (selected-frame))
15783 (sw (selected-window)))
15784 (select-window (get-buffer-window "*Calendar*" t))
15785 (eval form)
15786 (when (and (not keepdate) (calendar-cursor-to-date))
15787 (let* ((date (calendar-cursor-to-date))
15788 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15789 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15790 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15791 (select-window sw)
15792 (org-select-frame-set-input-focus sf)))
15794 (defun org-calendar-select ()
15795 "Return to `org-read-date' with the date currently selected.
15796 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15797 (interactive)
15798 (when (calendar-cursor-to-date)
15799 (let* ((date (calendar-cursor-to-date))
15800 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15801 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15802 (if (active-minibuffer-window) (exit-minibuffer))))
15804 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15805 "Insert a date stamp for the date given by the internal TIME.
15806 WITH-HM means use the stamp format that includes the time of the day.
15807 INACTIVE means use square brackets instead of angular ones, so that the
15808 stamp will not contribute to the agenda.
15809 PRE and POST are optional strings to be inserted before and after the
15810 stamp.
15811 The command returns the inserted time stamp."
15812 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15813 stamp)
15814 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15815 (insert-before-markers (or pre ""))
15816 (when (listp extra)
15817 (setq extra (car extra))
15818 (if (and (stringp extra)
15819 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15820 (setq extra (format "-%02d:%02d"
15821 (string-to-number (match-string 1 extra))
15822 (string-to-number (match-string 2 extra))))
15823 (setq extra nil)))
15824 (when extra
15825 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15826 (insert-before-markers (setq stamp (format-time-string fmt time)))
15827 (insert-before-markers (or post ""))
15828 (setq org-last-inserted-timestamp stamp)))
15830 (defun org-toggle-time-stamp-overlays ()
15831 "Toggle the use of custom time stamp formats."
15832 (interactive)
15833 (setq org-display-custom-times (not org-display-custom-times))
15834 (unless org-display-custom-times
15835 (let ((p (point-min)) (bmp (buffer-modified-p)))
15836 (while (setq p (next-single-property-change p 'display))
15837 (if (and (get-text-property p 'display)
15838 (eq (get-text-property p 'face) 'org-date))
15839 (remove-text-properties
15840 p (setq p (next-single-property-change p 'display))
15841 '(display t))))
15842 (set-buffer-modified-p bmp)))
15843 (if (featurep 'xemacs)
15844 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15845 (org-restart-font-lock)
15846 (setq org-table-may-need-update t)
15847 (if org-display-custom-times
15848 (message "Time stamps are overlaid with custom format")
15849 (message "Time stamp overlays removed")))
15851 (defun org-display-custom-time (beg end)
15852 "Overlay modified time stamp format over timestamp between BEG and END."
15853 (let* ((ts (buffer-substring beg end))
15854 t1 w1 with-hm tf time str w2 (off 0))
15855 (save-match-data
15856 (setq t1 (org-parse-time-string ts t))
15857 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15858 (setq off (- (match-end 0) (match-beginning 0)))))
15859 (setq end (- end off))
15860 (setq w1 (- end beg)
15861 with-hm (and (nth 1 t1) (nth 2 t1))
15862 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15863 time (org-fix-decoded-time t1)
15864 str (org-add-props
15865 (format-time-string
15866 (substring tf 1 -1) (apply 'encode-time time))
15867 nil 'mouse-face 'highlight)
15868 w2 (length str))
15869 (if (not (= w2 w1))
15870 (add-text-properties (1+ beg) (+ 2 beg)
15871 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15872 (if (featurep 'xemacs)
15873 (progn
15874 (put-text-property beg end 'invisible t)
15875 (put-text-property beg end 'end-glyph (make-glyph str)))
15876 (put-text-property beg end 'display str))))
15878 (defun org-translate-time (string)
15879 "Translate all timestamps in STRING to custom format.
15880 But do this only if the variable `org-display-custom-times' is set."
15881 (when org-display-custom-times
15882 (save-match-data
15883 (let* ((start 0)
15884 (re org-ts-regexp-both)
15885 t1 with-hm inactive tf time str beg end)
15886 (while (setq start (string-match re string start))
15887 (setq beg (match-beginning 0)
15888 end (match-end 0)
15889 t1 (save-match-data
15890 (org-parse-time-string (substring string beg end) t))
15891 with-hm (and (nth 1 t1) (nth 2 t1))
15892 inactive (equal (substring string beg (1+ beg)) "[")
15893 tf (funcall (if with-hm 'cdr 'car)
15894 org-time-stamp-custom-formats)
15895 time (org-fix-decoded-time t1)
15896 str (format-time-string
15897 (concat
15898 (if inactive "[" "<") (substring tf 1 -1)
15899 (if inactive "]" ">"))
15900 (apply 'encode-time time))
15901 string (replace-match str t t string)
15902 start (+ start (length str)))))))
15903 string)
15905 (defun org-fix-decoded-time (time)
15906 "Set 0 instead of nil for the first 6 elements of time.
15907 Don't touch the rest."
15908 (let ((n 0))
15909 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15911 (defun org-days-to-time (timestamp-string)
15912 "Difference between TIMESTAMP-STRING and now in days."
15913 (- (time-to-days (org-time-string-to-time timestamp-string))
15914 (time-to-days (current-time))))
15916 (defun org-deadline-close (timestamp-string &optional ndays)
15917 "Is the time in TIMESTAMP-STRING close to the current date?"
15918 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15919 (and (< (org-days-to-time timestamp-string) ndays)
15920 (not (org-entry-is-done-p))))
15922 (defun org-get-wdays (ts)
15923 "Get the deadline lead time appropriate for timestring TS."
15924 (cond
15925 ((<= org-deadline-warning-days 0)
15926 ;; 0 or negative, enforce this value no matter what
15927 (- org-deadline-warning-days))
15928 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15929 ;; lead time is specified.
15930 (floor (* (string-to-number (match-string 1 ts))
15931 (cdr (assoc (match-string 2 ts)
15932 '(("d" . 1) ("w" . 7)
15933 ("m" . 30.4) ("y" . 365.25)
15934 ("h" . 0.041667)))))))
15935 ;; go for the default.
15936 (t org-deadline-warning-days)))
15938 (defun org-calendar-select-mouse (ev)
15939 "Return to `org-read-date' with the date currently selected.
15940 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15941 (interactive "e")
15942 (mouse-set-point ev)
15943 (when (calendar-cursor-to-date)
15944 (let* ((date (calendar-cursor-to-date))
15945 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15946 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15947 (if (active-minibuffer-window) (exit-minibuffer))))
15949 (defun org-check-deadlines (ndays)
15950 "Check if there are any deadlines due or past due.
15951 A deadline is considered due if it happens within `org-deadline-warning-days'
15952 days from today's date. If the deadline appears in an entry marked DONE,
15953 it is not shown. The prefix arg NDAYS can be used to test that many
15954 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15955 (interactive "P")
15956 (let* ((org-warn-days
15957 (cond
15958 ((equal ndays '(4)) 100000)
15959 (ndays (prefix-numeric-value ndays))
15960 (t (abs org-deadline-warning-days))))
15961 (case-fold-search nil)
15962 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15963 (callback
15964 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15966 (message "%d deadlines past-due or due within %d days"
15967 (org-occur regexp nil callback)
15968 org-warn-days)))
15970 (defsubst org-re-timestamp (type)
15971 "Return a regexp for timestamp TYPE.
15972 Allowed values for TYPE are:
15974 all: all timestamps
15975 active: only active timestamps (<...>)
15976 inactive: only inactive timestamps ([...])
15977 scheduled: only scheduled timestamps
15978 deadline: only deadline timestamps
15980 When TYPE is nil, fall back on returning a regexp that matches
15981 both scheduled and deadline timestamps."
15982 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15983 ((eq type 'active) org-ts-regexp)
15984 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15985 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15986 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15987 ((eq type 'scheduled-or-deadline)
15988 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15990 (defun org-check-before-date (date)
15991 "Check if there are deadlines or scheduled entries before DATE."
15992 (interactive (list (org-read-date)))
15993 (let ((case-fold-search nil)
15994 (regexp (org-re-timestamp org-ts-type))
15995 (callback
15996 (lambda () (time-less-p
15997 (org-time-string-to-time (match-string 1))
15998 (org-time-string-to-time date)))))
15999 (message "%d entries before %s"
16000 (org-occur regexp nil callback) date)))
16002 (defun org-check-after-date (date)
16003 "Check if there are deadlines or scheduled entries after DATE."
16004 (interactive (list (org-read-date)))
16005 (let ((case-fold-search nil)
16006 (regexp (org-re-timestamp org-ts-type))
16007 (callback
16008 (lambda () (not
16009 (time-less-p
16010 (org-time-string-to-time (match-string 1))
16011 (org-time-string-to-time date))))))
16012 (message "%d entries after %s"
16013 (org-occur regexp nil callback) date)))
16015 (defun org-check-dates-range (start-date end-date)
16016 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16017 (interactive (list (org-read-date nil nil nil "Range starts")
16018 (org-read-date nil nil nil "Range end")))
16019 (let ((case-fold-search nil)
16020 (regexp (org-re-timestamp org-ts-type))
16021 (callback
16022 (lambda ()
16023 (let ((match (match-string 1)))
16024 (and
16025 (not (time-less-p
16026 (org-time-string-to-time match)
16027 (org-time-string-to-time start-date)))
16028 (time-less-p
16029 (org-time-string-to-time match)
16030 (org-time-string-to-time end-date)))))))
16031 (message "%d entries between %s and %s"
16032 (org-occur regexp nil callback) start-date end-date)))
16034 (defun org-evaluate-time-range (&optional to-buffer)
16035 "Evaluate a time range by computing the difference between start and end.
16036 Normally the result is just printed in the echo area, but with prefix arg
16037 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16038 If the time range is actually in a table, the result is inserted into the
16039 next column.
16040 For time difference computation, a year is assumed to be exactly 365
16041 days in order to avoid rounding problems."
16042 (interactive "P")
16044 (org-clock-update-time-maybe)
16045 (save-excursion
16046 (unless (org-at-date-range-p t)
16047 (goto-char (point-at-bol))
16048 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16049 (if (not (org-at-date-range-p t))
16050 (error "Not at a time-stamp range, and none found in current line")))
16051 (let* ((ts1 (match-string 1))
16052 (ts2 (match-string 2))
16053 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16054 (match-end (match-end 0))
16055 (time1 (org-time-string-to-time ts1))
16056 (time2 (org-time-string-to-time ts2))
16057 (t1 (org-float-time time1))
16058 (t2 (org-float-time time2))
16059 (diff (abs (- t2 t1)))
16060 (negative (< (- t2 t1) 0))
16061 ;; (ys (floor (* 365 24 60 60)))
16062 (ds (* 24 60 60))
16063 (hs (* 60 60))
16064 (fy "%dy %dd %02d:%02d")
16065 (fy1 "%dy %dd")
16066 (fd "%dd %02d:%02d")
16067 (fd1 "%dd")
16068 (fh "%02d:%02d")
16069 y d h m align)
16070 (if havetime
16071 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16073 d (floor (/ diff ds)) diff (mod diff ds)
16074 h (floor (/ diff hs)) diff (mod diff hs)
16075 m (floor (/ diff 60)))
16076 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16078 d (floor (+ (/ diff ds) 0.5))
16079 h 0 m 0))
16080 (if (not to-buffer)
16081 (message "%s" (org-make-tdiff-string y d h m))
16082 (if (org-at-table-p)
16083 (progn
16084 (goto-char match-end)
16085 (setq align t)
16086 (and (looking-at " *|") (goto-char (match-end 0))))
16087 (goto-char match-end))
16088 (if (looking-at
16089 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16090 (replace-match ""))
16091 (if negative (insert " -"))
16092 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16093 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16094 (insert " " (format fh h m))))
16095 (if align (org-table-align))
16096 (message "Time difference inserted")))))
16098 (defun org-make-tdiff-string (y d h m)
16099 (let ((fmt "")
16100 (l nil))
16101 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16102 l (push y l)))
16103 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16104 l (push d l)))
16105 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16106 l (push h l)))
16107 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16108 l (push m l)))
16109 (apply 'format fmt (nreverse l))))
16111 (defun org-time-string-to-time (s &optional buffer pos)
16112 "Convert a timestamp string into internal time."
16113 (condition-case errdata
16114 (apply 'encode-time (org-parse-time-string s))
16115 (error (error "Bad timestamp `%s'%s\nError was: %s"
16116 s (if (not (and buffer pos))
16118 (format " at %d in buffer `%s'" pos buffer))
16119 (cdr errdata)))))
16121 (defun org-time-string-to-seconds (s)
16122 "Convert a timestamp string to a number of seconds."
16123 (org-float-time (org-time-string-to-time s)))
16125 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16126 "Convert a time stamp to an absolute day number.
16127 If there is a specifier for a cyclic time stamp, get the closest date to
16128 DAYNR.
16129 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16130 The variable date is bound by the calendar when this is called."
16131 (cond
16132 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16133 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16134 daynr
16135 (+ daynr 1000)))
16136 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16137 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16138 (time-to-days (current-time))) (match-string 0 s)
16139 prefer show-all))
16140 (t (time-to-days
16141 (condition-case errdata
16142 (apply 'encode-time (org-parse-time-string s))
16143 (error (error "Bad timestamp `%s'%s\nError was: %s"
16144 s (if (not (and buffer pos))
16146 (format " at %d in buffer `%s'" pos buffer))
16147 (cdr errdata))))))))
16149 (defun org-days-to-iso-week (days)
16150 "Return the iso week number."
16151 (require 'cal-iso)
16152 (car (calendar-iso-from-absolute days)))
16154 (defun org-small-year-to-year (year)
16155 "Convert 2-digit years into 4-digit years.
16156 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16157 The year 2000 cannot be abbreviated. Any year larger than 99
16158 is returned unchanged."
16159 (if (< year 38)
16160 (setq year (+ 2000 year))
16161 (if (< year 100)
16162 (setq year (+ 1900 year))))
16163 year)
16165 (defun org-time-from-absolute (d)
16166 "Return the time corresponding to date D.
16167 D may be an absolute day number, or a calendar-type list (month day year)."
16168 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16169 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16171 (defun org-calendar-holiday ()
16172 "List of holidays, for Diary display in Org-mode."
16173 (require 'holidays)
16174 (let ((hl (funcall
16175 (if (fboundp 'calendar-check-holidays)
16176 'calendar-check-holidays 'check-calendar-holidays) date)))
16177 (if hl (mapconcat 'identity hl "; "))))
16179 (defun org-diary-sexp-entry (sexp entry date)
16180 "Process a SEXP diary ENTRY for DATE."
16181 (require 'diary-lib)
16182 (let ((result (if calendar-debug-sexp
16183 (let ((stack-trace-on-error t))
16184 (eval (car (read-from-string sexp))))
16185 (condition-case nil
16186 (eval (car (read-from-string sexp)))
16187 (error
16188 (beep)
16189 (message "Bad sexp at line %d in %s: %s"
16190 (org-current-line)
16191 (buffer-file-name) sexp)
16192 (sleep-for 2))))))
16193 (cond ((stringp result) (split-string result "; "))
16194 ((and (consp result)
16195 (not (consp (cdr result)))
16196 (stringp (cdr result))) (cdr result))
16197 ((and (consp result)
16198 (stringp (car result))) result)
16199 (result entry))))
16201 (defun org-diary-to-ical-string (frombuf)
16202 "Get iCalendar entries from diary entries in buffer FROMBUF.
16203 This uses the icalendar.el library."
16204 (let* ((tmpdir (if (featurep 'xemacs)
16205 (temp-directory)
16206 temporary-file-directory))
16207 (tmpfile (make-temp-name
16208 (expand-file-name "orgics" tmpdir)))
16209 buf rtn b e)
16210 (with-current-buffer frombuf
16211 (icalendar-export-region (point-min) (point-max) tmpfile)
16212 (setq buf (find-buffer-visiting tmpfile))
16213 (set-buffer buf)
16214 (goto-char (point-min))
16215 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16216 (setq b (match-beginning 0)))
16217 (goto-char (point-max))
16218 (if (re-search-backward "^END:VEVENT" nil t)
16219 (setq e (match-end 0)))
16220 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16221 (kill-buffer buf)
16222 (delete-file tmpfile)
16223 rtn))
16225 (defun org-closest-date (start current change prefer show-all)
16226 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16227 When PREFER is `past', return a date that is either CURRENT or past.
16228 When PREFER is `future', return a date that is either CURRENT or future.
16229 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16230 ;; Make the proper lists from the dates
16231 (catch 'exit
16232 (let ((a1 '(("h" . hour)
16233 ("d" . day)
16234 ("w" . week)
16235 ("m" . month)
16236 ("y" . year)))
16237 (shour (nth 2 (org-parse-time-string start)))
16238 dn dw sday cday n1 n2 n0
16239 d m y y1 y2 date1 date2 nmonths nm ny m2)
16241 (setq start (org-date-to-gregorian start)
16242 current (org-date-to-gregorian
16243 (if show-all
16244 current
16245 (time-to-days (current-time))))
16246 sday (calendar-absolute-from-gregorian start)
16247 cday (calendar-absolute-from-gregorian current))
16249 (if (<= cday sday) (throw 'exit sday))
16251 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16252 (setq dn (string-to-number (match-string 1 change))
16253 dw (cdr (assoc (match-string 2 change) a1)))
16254 (error "Invalid change specifier: %s" change))
16255 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16256 (cond
16257 ((eq dw 'hour)
16258 (let ((missing-hours
16259 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16260 dn)))
16261 (setq n1 (if (zerop missing-hours) cday
16262 (- cday (1+ (floor (/ missing-hours 24)))))
16263 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16264 ((eq dw 'day)
16265 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16266 n2 (+ n1 dn)))
16267 ((eq dw 'year)
16268 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16269 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16270 (setq date1 (list m d y1)
16271 n1 (calendar-absolute-from-gregorian date1)
16272 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16273 n2 (calendar-absolute-from-gregorian date2)))
16274 ((eq dw 'month)
16275 ;; approx number of month between the two dates
16276 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16277 ;; How often does dn fit in there?
16278 (setq d (nth 1 start) m (car start) y (nth 2 start)
16279 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16280 m (+ m nm)
16281 ny (floor (/ m 12))
16282 y (+ y ny)
16283 m (- m (* ny 12)))
16284 (while (> m 12) (setq m (- m 12) y (1+ y)))
16285 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16286 (setq m2 (+ m dn) y2 y)
16287 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16288 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16289 (while (<= n2 cday)
16290 (setq n1 n2 m m2 y y2)
16291 (setq m2 (+ m dn) y2 y)
16292 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16293 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16294 ;; Make sure n1 is the earlier date
16295 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16296 (if show-all
16297 (cond
16298 ((eq prefer 'past) (if (= cday n2) n2 n1))
16299 ((eq prefer 'future) (if (= cday n1) n1 n2))
16300 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16301 (cond
16302 ((eq prefer 'past) (if (= cday n2) n2 n1))
16303 ((eq prefer 'future) (if (= cday n1) n1 n2))
16304 (t (if (= cday n1) n1 n2)))))))
16306 (defun org-date-to-gregorian (date)
16307 "Turn any specification of DATE into a Gregorian date for the calendar."
16308 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16309 ((and (listp date) (= (length date) 3)) date)
16310 ((stringp date)
16311 (setq date (org-parse-time-string date))
16312 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16313 ((listp date)
16314 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16316 (defun org-parse-time-string (s &optional nodefault)
16317 "Parse the standard Org-mode time string.
16318 This should be a lot faster than the normal `parse-time-string'.
16319 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16320 hour and minute fields will be nil if not given."
16321 (if (string-match org-ts-regexp0 s)
16322 (list 0
16323 (if (or (match-beginning 8) (not nodefault))
16324 (string-to-number (or (match-string 8 s) "0")))
16325 (if (or (match-beginning 7) (not nodefault))
16326 (string-to-number (or (match-string 7 s) "0")))
16327 (string-to-number (match-string 4 s))
16328 (string-to-number (match-string 3 s))
16329 (string-to-number (match-string 2 s))
16330 nil nil nil)
16331 (error "Not a standard Org-mode time string: %s" s)))
16333 (defun org-timestamp-up (&optional arg)
16334 "Increase the date item at the cursor by one.
16335 If the cursor is on the year, change the year. If it is on the month,
16336 the day or the time, change that.
16337 With prefix ARG, change by that many units."
16338 (interactive "p")
16339 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16341 (defun org-timestamp-down (&optional arg)
16342 "Decrease the date item at the cursor by one.
16343 If the cursor is on the year, change the year. If it is on the month,
16344 the day or the time, change that.
16345 With prefix ARG, change by that many units."
16346 (interactive "p")
16347 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16349 (defun org-timestamp-up-day (&optional arg)
16350 "Increase the date in the time stamp by one day.
16351 With prefix ARG, change that many days."
16352 (interactive "p")
16353 (if (and (not (org-at-timestamp-p t))
16354 (org-at-heading-p))
16355 (org-todo 'up)
16356 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16358 (defun org-timestamp-down-day (&optional arg)
16359 "Decrease the date in the time stamp by one day.
16360 With prefix ARG, change that many days."
16361 (interactive "p")
16362 (if (and (not (org-at-timestamp-p t))
16363 (org-at-heading-p))
16364 (org-todo 'down)
16365 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16367 (defun org-at-timestamp-p (&optional inactive-ok)
16368 "Determine if the cursor is in or at a timestamp."
16369 (interactive)
16370 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16371 (pos (point))
16372 (ans (or (looking-at tsr)
16373 (save-excursion
16374 (skip-chars-backward "^[<\n\r\t")
16375 (if (> (point) (point-min)) (backward-char 1))
16376 (and (looking-at tsr)
16377 (> (- (match-end 0) pos) -1))))))
16378 (and ans
16379 (boundp 'org-ts-what)
16380 (setq org-ts-what
16381 (cond
16382 ((= pos (match-beginning 0)) 'bracket)
16383 ;; Point is considered to be "on the bracket" whether
16384 ;; it's really on it or right after it.
16385 ((= pos (1- (match-end 0))) 'bracket)
16386 ((= pos (match-end 0)) 'after)
16387 ((org-pos-in-match-range pos 2) 'year)
16388 ((org-pos-in-match-range pos 3) 'month)
16389 ((org-pos-in-match-range pos 7) 'hour)
16390 ((org-pos-in-match-range pos 8) 'minute)
16391 ((or (org-pos-in-match-range pos 4)
16392 (org-pos-in-match-range pos 5)) 'day)
16393 ((and (> pos (or (match-end 8) (match-end 5)))
16394 (< pos (match-end 0)))
16395 (- pos (or (match-end 8) (match-end 5))))
16396 (t 'day))))
16397 ans))
16399 (defun org-toggle-timestamp-type ()
16400 "Toggle the type (<active> or [inactive]) of a time stamp."
16401 (interactive)
16402 (when (org-at-timestamp-p t)
16403 (let ((beg (match-beginning 0)) (end (match-end 0))
16404 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16405 (save-excursion
16406 (goto-char beg)
16407 (while (re-search-forward "[][<>]" end t)
16408 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16409 t t)))
16410 (message "Timestamp is now %sactive"
16411 (if (equal (char-after beg) ?<) "" "in")))))
16413 (defun org-at-clock-log-p nil
16414 "Is the cursor on the clock log line?"
16415 (save-excursion
16416 (move-beginning-of-line 1)
16417 (looking-at "^[ \t]*CLOCK:")))
16419 (defvar org-clock-history) ; defined in org-clock.el
16420 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16421 (defun org-timestamp-change (n &optional what updown)
16422 "Change the date in the time stamp at point.
16423 The date will be changed by N times WHAT. WHAT can be `day', `month',
16424 `year', `minute', `second'. If WHAT is not given, the cursor position
16425 in the timestamp determines what will be changed."
16426 (let ((origin (point)) origin-cat
16427 with-hm inactive
16428 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16429 org-ts-what
16430 extra rem
16431 ts time time0 fixnext clrgx)
16432 (if (not (org-at-timestamp-p t))
16433 (error "Not at a timestamp"))
16434 (if (and (not what) (eq org-ts-what 'bracket))
16435 (org-toggle-timestamp-type)
16436 ;; Point isn't on brackets. Remember the part of the time-stamp
16437 ;; the point was in. Indeed, size of time-stamps may change,
16438 ;; but point must be kept in the same category nonetheless.
16439 (setq origin-cat org-ts-what)
16440 (if (and (not what) (not (eq org-ts-what 'day))
16441 org-display-custom-times
16442 (get-text-property (point) 'display)
16443 (not (get-text-property (1- (point)) 'display)))
16444 (setq org-ts-what 'day))
16445 (setq org-ts-what (or what org-ts-what)
16446 inactive (= (char-after (match-beginning 0)) ?\[)
16447 ts (match-string 0))
16448 (replace-match "")
16449 (if (string-match
16450 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16452 (setq extra (match-string 1 ts)))
16453 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16454 (setq with-hm t))
16455 (setq time0 (org-parse-time-string ts))
16456 (when (and updown
16457 (eq org-ts-what 'minute)
16458 (not current-prefix-arg))
16459 ;; This looks like s-up and s-down. Change by one rounding step.
16460 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16461 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16462 (setcar (cdr time0) (+ (nth 1 time0)
16463 (if (> n 0) (- rem) (- dm rem))))))
16464 (setq time
16465 (encode-time (or (car time0) 0)
16466 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16467 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16468 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16469 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16470 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16471 (nthcdr 6 time0)))
16472 (when (and (member org-ts-what '(hour minute))
16473 extra
16474 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16475 (setq extra (org-modify-ts-extra
16476 extra
16477 (if (eq org-ts-what 'hour) 2 5)
16478 n dm)))
16479 (when (integerp org-ts-what)
16480 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16481 (if (eq what 'calendar)
16482 (let ((cal-date (org-get-date-from-calendar)))
16483 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16484 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16485 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16486 (setcar time0 (or (car time0) 0))
16487 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16488 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16489 (setq time (apply 'encode-time time0))))
16490 ;; Insert the new time-stamp, and ensure point stays in the same
16491 ;; category as before (i.e. not after the last position in that
16492 ;; category).
16493 (let ((pos (point)))
16494 ;; Stay before inserted string. `save-excursion' is of no use.
16495 (setq org-last-changed-timestamp
16496 (org-insert-time-stamp time with-hm inactive nil nil extra))
16497 (goto-char pos))
16498 (save-match-data
16499 (looking-at org-ts-regexp3)
16500 (goto-char (cond
16501 ;; `day' category ends before `hour' if any, or at
16502 ;; the end of the day name.
16503 ((eq origin-cat 'day)
16504 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16505 ((eq origin-cat 'hour) (min (match-end 7) origin))
16506 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16507 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16508 ;; `year' and `month' have both fixed size: point
16509 ;; couldn't have moved into another part.
16510 (t origin))))
16511 ;; Update clock if on a CLOCK line.
16512 (org-clock-update-time-maybe)
16513 ;; Maybe adjust the closest clock in `org-clock-history'
16514 (when org-clock-adjust-closest
16515 (if (not (and (org-at-clock-log-p)
16516 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16517 org-clock-history))))))
16518 (message "No clock to adjust")
16519 (cond ((save-excursion ; fix previous clock?
16520 (re-search-backward org-ts-regexp0 nil t)
16521 (org-looking-back (concat org-clock-string " \\[")))
16522 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16523 ((save-excursion ; fix next clock?
16524 (re-search-backward org-ts-regexp0 nil t)
16525 (looking-at (concat org-ts-regexp0 "\\] =>")))
16526 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16527 (save-window-excursion
16528 ;; Find closest clock to point, adjust the previous/next one in history
16529 (let* ((p (save-excursion (org-back-to-heading t)))
16530 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16531 (clfixnth
16532 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16533 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16534 (if (not clfixpos)
16535 (message "No clock to adjust")
16536 (save-excursion
16537 (org-goto-marker-or-bmk clfixpos)
16538 (org-show-subtree)
16539 (when (re-search-forward clrgx nil t)
16540 (goto-char (match-beginning 1))
16541 (let (org-clock-adjust-closest)
16542 (org-timestamp-change n org-ts-what updown))
16543 (message "Clock adjusted in %s for heading: %s"
16544 (file-name-nondirectory (buffer-file-name))
16545 (org-get-heading t t)))))))))
16546 ;; Try to recenter the calendar window, if any.
16547 (if (and org-calendar-follow-timestamp-change
16548 (get-buffer-window "*Calendar*" t)
16549 (memq org-ts-what '(day month year)))
16550 (org-recenter-calendar (time-to-days time))))))
16552 (defun org-modify-ts-extra (s pos n dm)
16553 "Change the different parts of the lead-time and repeat fields in timestamp."
16554 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16555 ng h m new rem)
16556 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16557 (cond
16558 ((or (org-pos-in-match-range pos 2)
16559 (org-pos-in-match-range pos 3))
16560 (setq m (string-to-number (match-string 3 s))
16561 h (string-to-number (match-string 2 s)))
16562 (if (org-pos-in-match-range pos 2)
16563 (setq h (+ h n))
16564 (setq n (* dm (org-no-warnings (signum n))))
16565 (when (not (= 0 (setq rem (% m dm))))
16566 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16567 (setq m (+ m n)))
16568 (if (< m 0) (setq m (+ m 60) h (1- h)))
16569 (if (> m 59) (setq m (- m 60) h (1+ h)))
16570 (setq h (min 24 (max 0 h)))
16571 (setq ng 1 new (format "-%02d:%02d" h m)))
16572 ((org-pos-in-match-range pos 6)
16573 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16574 ((org-pos-in-match-range pos 5)
16575 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16577 ((org-pos-in-match-range pos 9)
16578 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16579 ((org-pos-in-match-range pos 8)
16580 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16582 (when ng
16583 (setq s (concat
16584 (substring s 0 (match-beginning ng))
16586 (substring s (match-end ng))))))
16589 (defun org-recenter-calendar (date)
16590 "If the calendar is visible, recenter it to DATE."
16591 (let ((cwin (get-buffer-window "*Calendar*" t)))
16592 (when cwin
16593 (let ((calendar-move-hook nil))
16594 (with-selected-window cwin
16595 (calendar-goto-date (if (listp date) date
16596 (calendar-gregorian-from-absolute date))))))))
16598 (defun org-goto-calendar (&optional arg)
16599 "Go to the Emacs calendar at the current date.
16600 If there is a time stamp in the current line, go to that date.
16601 A prefix ARG can be used to force the current date."
16602 (interactive "P")
16603 (let ((tsr org-ts-regexp) diff
16604 (calendar-move-hook nil)
16605 (calendar-view-holidays-initially-flag nil)
16606 (calendar-view-diary-initially-flag nil))
16607 (if (or (org-at-timestamp-p)
16608 (save-excursion
16609 (beginning-of-line 1)
16610 (looking-at (concat ".*" tsr))))
16611 (let ((d1 (time-to-days (current-time)))
16612 (d2 (time-to-days
16613 (org-time-string-to-time (match-string 1)))))
16614 (setq diff (- d2 d1))))
16615 (calendar)
16616 (calendar-goto-today)
16617 (if (and diff (not arg)) (calendar-forward-day diff))))
16619 (defun org-get-date-from-calendar ()
16620 "Return a list (month day year) of date at point in calendar."
16621 (with-current-buffer "*Calendar*"
16622 (save-match-data
16623 (calendar-cursor-to-date))))
16625 (defun org-date-from-calendar ()
16626 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16627 If there is already a time stamp at the cursor position, update it."
16628 (interactive)
16629 (if (org-at-timestamp-p t)
16630 (org-timestamp-change 0 'calendar)
16631 (let ((cal-date (org-get-date-from-calendar)))
16632 (org-insert-time-stamp
16633 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16635 (defun org-minutes-to-hh:mm-string (m)
16636 "Compute H:MM from a number of minutes."
16637 (let ((h (/ m 60)))
16638 (setq m (- m (* 60 h)))
16639 (format org-time-clocksum-format h m)))
16641 (defun org-hh:mm-string-to-minutes (s)
16642 "Convert a string H:MM to a number of minutes.
16643 If the string is just a number, interpret it as minutes.
16644 In fact, the first hh:mm or number in the string will be taken,
16645 there can be extra stuff in the string.
16646 If no number is found, the return value is 0."
16647 (cond
16648 ((integerp s) s)
16649 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16650 (+ (* (string-to-number (match-string 1 s)) 60)
16651 (string-to-number (match-string 2 s))))
16652 ((string-match "\\([0-9]+\\)" s)
16653 (string-to-number (match-string 1 s)))
16654 (t 0)))
16656 (defcustom org-effort-durations
16657 `(("h" . 60)
16658 ("d" . ,(* 60 8))
16659 ("w" . ,(* 60 8 5))
16660 ("m" . ,(* 60 8 5 4))
16661 ("y" . ,(* 60 8 5 40)))
16662 "Conversion factor to minutes for an effort modifier.
16664 Each entry has the form (MODIFIER . MINUTES).
16666 In an effort string, a number followed by MODIFIER is multiplied
16667 by the specified number of MINUTES to obtain an effort in
16668 minutes.
16670 For example, if the value of this variable is ((\"hours\" . 60)), then an
16671 effort string \"2hours\" is equivalent to 120 minutes."
16672 :group 'org-agenda
16673 :version "24.1"
16674 :type '(alist :key-type (string :tag "Modifier")
16675 :value-type (number :tag "Minutes")))
16677 (defcustom org-agenda-inhibit-startup t
16678 "Inhibit startup when preparing agenda buffers.
16679 When this variable is `t' (the default), the initialization of
16680 the Org agenda buffers is inhibited: e.g. the visibility state
16681 is not set, the tables are not re-aligned, etc."
16682 :type 'boolean
16683 :version "24.3"
16684 :group 'org-agenda)
16686 (defun org-duration-string-to-minutes (s &optional output-to-string)
16687 "Convert a duration string S to minutes.
16689 A bare number is interpreted as minutes, modifiers can be set by
16690 customizing `org-effort-durations' (which see).
16692 Entries containing a colon are interpreted as H:MM by
16693 `org-hh:mm-string-to-minutes'."
16694 (let ((result 0)
16695 (re (concat "\\([0-9.]+\\) *\\("
16696 (regexp-opt (mapcar 'car org-effort-durations))
16697 "\\)")))
16698 (while (string-match re s)
16699 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16700 (string-to-number (match-string 1 s))))
16701 (setq s (replace-match "" nil t s)))
16702 (setq result (floor result))
16703 (incf result (org-hh:mm-string-to-minutes s))
16704 (if output-to-string (number-to-string result) result)))
16706 ;;;; Files
16708 (defun org-save-all-org-buffers ()
16709 "Save all Org-mode buffers without user confirmation."
16710 (interactive)
16711 (message "Saving all Org-mode buffers...")
16712 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16713 (when (featurep 'org-id) (org-id-locations-save))
16714 (message "Saving all Org-mode buffers... done"))
16716 (defun org-revert-all-org-buffers ()
16717 "Revert all Org-mode buffers.
16718 Prompt for confirmation when there are unsaved changes.
16719 Be sure you know what you are doing before letting this function
16720 overwrite your changes.
16722 This function is useful in a setup where one tracks org files
16723 with a version control system, to revert on one machine after pulling
16724 changes from another. I believe the procedure must be like this:
16726 1. M-x org-save-all-org-buffers
16727 2. Pull changes from the other machine, resolve conflicts
16728 3. M-x org-revert-all-org-buffers"
16729 (interactive)
16730 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16731 (error "Abort"))
16732 (save-excursion
16733 (save-window-excursion
16734 (mapc
16735 (lambda (b)
16736 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16737 (with-current-buffer b buffer-file-name))
16738 (org-pop-to-buffer-same-window b)
16739 (revert-buffer t 'no-confirm)))
16740 (buffer-list))
16741 (when (and (featurep 'org-id) org-id-track-globally)
16742 (org-id-locations-load)))))
16744 ;;;; Agenda files
16746 ;;;###autoload
16747 (defun org-switchb (&optional arg)
16748 "Switch between Org buffers.
16749 With one prefix argument, restrict available buffers to files.
16750 With two prefix arguments, restrict available buffers to agenda files.
16752 Defaults to `iswitchb' for buffer name completion.
16753 Set `org-completion-use-ido' to make it use ido instead."
16754 (interactive "P")
16755 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16756 ((equal arg '(16)) (org-buffer-list 'agenda))
16757 (t (org-buffer-list))))
16758 (org-completion-use-iswitchb org-completion-use-iswitchb)
16759 (org-completion-use-ido org-completion-use-ido))
16760 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16761 (setq org-completion-use-iswitchb t))
16762 (org-pop-to-buffer-same-window
16763 (org-icompleting-read "Org buffer: "
16764 (mapcar 'list (mapcar 'buffer-name blist))
16765 nil t))))
16767 ;;; Define some older names previously used for this functionality
16768 ;;;###autoload
16769 (defalias 'org-ido-switchb 'org-switchb)
16770 ;;;###autoload
16771 (defalias 'org-iswitchb 'org-switchb)
16773 (defun org-buffer-list (&optional predicate exclude-tmp)
16774 "Return a list of Org buffers.
16775 PREDICATE can be `export', `files' or `agenda'.
16777 export restrict the list to Export buffers.
16778 files restrict the list to buffers visiting Org files.
16779 agenda restrict the list to buffers visiting agenda files.
16781 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16782 (let* ((bfn nil)
16783 (agenda-files (and (eq predicate 'agenda)
16784 (mapcar 'file-truename (org-agenda-files t))))
16785 (filter
16786 (cond
16787 ((eq predicate 'files)
16788 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16789 ((eq predicate 'export)
16790 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16791 ((eq predicate 'agenda)
16792 (lambda (b)
16793 (with-current-buffer b
16794 (and (derived-mode-p 'org-mode)
16795 (setq bfn (buffer-file-name b))
16796 (member (file-truename bfn) agenda-files)))))
16797 (t (lambda (b) (with-current-buffer b
16798 (or (derived-mode-p 'org-mode)
16799 (string-match "\*Org .*Export"
16800 (buffer-name b)))))))))
16801 (delq nil
16802 (mapcar
16803 (lambda(b)
16804 (if (and (funcall filter b)
16805 (or (not exclude-tmp)
16806 (not (string-match "tmp" (buffer-name b)))))
16808 nil))
16809 (buffer-list)))))
16811 (defun org-agenda-files (&optional unrestricted archives)
16812 "Get the list of agenda files.
16813 Optional UNRESTRICTED means return the full list even if a restriction
16814 is currently in place.
16815 When ARCHIVES is t, include all archive files that are really being
16816 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16817 `org-agenda-archives-mode' is t."
16818 (let ((files
16819 (cond
16820 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16821 ((stringp org-agenda-files) (org-read-agenda-file-list))
16822 ((listp org-agenda-files) org-agenda-files)
16823 (t (error "Invalid value of `org-agenda-files'")))))
16824 (setq files (apply 'append
16825 (mapcar (lambda (f)
16826 (if (file-directory-p f)
16827 (directory-files
16828 f t org-agenda-file-regexp)
16829 (list f)))
16830 files)))
16831 (when org-agenda-skip-unavailable-files
16832 (setq files (delq nil
16833 (mapcar (function
16834 (lambda (file)
16835 (and (file-readable-p file) file)))
16836 files))))
16837 (when (or (eq archives t)
16838 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16839 (setq files (org-add-archive-files files)))
16840 files))
16842 (defun org-agenda-file-p (&optional file)
16843 "Return non-nil, if FILE is an agenda file.
16844 If FILE is omitted, use the file associated with the current
16845 buffer."
16846 (member (or file (buffer-file-name))
16847 (org-agenda-files t)))
16849 (defun org-edit-agenda-file-list ()
16850 "Edit the list of agenda files.
16851 Depending on setup, this either uses customize to edit the variable
16852 `org-agenda-files', or it visits the file that is holding the list. In the
16853 latter case, the buffer is set up in a way that saving it automatically kills
16854 the buffer and restores the previous window configuration."
16855 (interactive)
16856 (if (stringp org-agenda-files)
16857 (let ((cw (current-window-configuration)))
16858 (find-file org-agenda-files)
16859 (org-set-local 'org-window-configuration cw)
16860 (org-add-hook 'after-save-hook
16861 (lambda ()
16862 (set-window-configuration
16863 (prog1 org-window-configuration
16864 (kill-buffer (current-buffer))))
16865 (org-install-agenda-files-menu)
16866 (message "New agenda file list installed"))
16867 nil 'local)
16868 (message "%s" (substitute-command-keys
16869 "Edit list and finish with \\[save-buffer]")))
16870 (customize-variable 'org-agenda-files)))
16872 (defun org-store-new-agenda-file-list (list)
16873 "Set new value for the agenda file list and save it correctly."
16874 (if (stringp org-agenda-files)
16875 (let ((fe (org-read-agenda-file-list t)) b u)
16876 (while (setq b (find-buffer-visiting org-agenda-files))
16877 (kill-buffer b))
16878 (with-temp-file org-agenda-files
16879 (insert
16880 (mapconcat
16881 (lambda (f) ;; Keep un-expanded entries.
16882 (if (setq u (assoc f fe))
16883 (cdr u)
16885 list "\n")
16886 "\n")))
16887 (let ((org-mode-hook nil) (org-inhibit-startup t)
16888 (org-insert-mode-line-in-empty-file nil))
16889 (setq org-agenda-files list)
16890 (customize-save-variable 'org-agenda-files org-agenda-files))))
16892 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16893 "Read the list of agenda files from a file.
16894 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16895 filenames, used by `org-store-new-agenda-file-list' to write back
16896 un-expanded file names."
16897 (when (file-directory-p org-agenda-files)
16898 (error "`org-agenda-files' cannot be a single directory"))
16899 (when (stringp org-agenda-files)
16900 (with-temp-buffer
16901 (insert-file-contents org-agenda-files)
16902 (mapcar
16903 (lambda (f)
16904 (let ((e (expand-file-name (substitute-in-file-name f)
16905 org-directory)))
16906 (if pair-with-expansion
16907 (cons e f)
16908 e)))
16909 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16911 ;;;###autoload
16912 (defun org-cycle-agenda-files ()
16913 "Cycle through the files in `org-agenda-files'.
16914 If the current buffer visits an agenda file, find the next one in the list.
16915 If the current buffer does not, find the first agenda file."
16916 (interactive)
16917 (let* ((fs (org-agenda-files t))
16918 (files (append fs (list (car fs))))
16919 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16920 file)
16921 (unless files (error "No agenda files"))
16922 (catch 'exit
16923 (while (setq file (pop files))
16924 (if (equal (file-truename file) tcf)
16925 (when (car files)
16926 (find-file (car files))
16927 (throw 'exit t))))
16928 (find-file (car fs)))
16929 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16931 (defun org-agenda-file-to-front (&optional to-end)
16932 "Move/add the current file to the top of the agenda file list.
16933 If the file is not present in the list, it is added to the front. If it is
16934 present, it is moved there. With optional argument TO-END, add/move to the
16935 end of the list."
16936 (interactive "P")
16937 (let ((org-agenda-skip-unavailable-files nil)
16938 (file-alist (mapcar (lambda (x)
16939 (cons (file-truename x) x))
16940 (org-agenda-files t)))
16941 (ctf (file-truename
16942 (or buffer-file-name
16943 (error "Please save the current buffer to a file"))))
16944 x had)
16945 (setq x (assoc ctf file-alist) had x)
16947 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16948 (if to-end
16949 (setq file-alist (append (delq x file-alist) (list x)))
16950 (setq file-alist (cons x (delq x file-alist))))
16951 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16952 (org-install-agenda-files-menu)
16953 (message "File %s to %s of agenda file list"
16954 (if had "moved" "added") (if to-end "end" "front"))))
16956 (defun org-remove-file (&optional file)
16957 "Remove current file from the list of files in variable `org-agenda-files'.
16958 These are the files which are being checked for agenda entries.
16959 Optional argument FILE means use this file instead of the current."
16960 (interactive)
16961 (let* ((org-agenda-skip-unavailable-files nil)
16962 (file (or file buffer-file-name
16963 (error "Current buffer does not visit a file")))
16964 (true-file (file-truename file))
16965 (afile (abbreviate-file-name file))
16966 (files (delq nil (mapcar
16967 (lambda (x)
16968 (if (equal true-file
16969 (file-truename x))
16970 nil x))
16971 (org-agenda-files t)))))
16972 (if (not (= (length files) (length (org-agenda-files t))))
16973 (progn
16974 (org-store-new-agenda-file-list files)
16975 (org-install-agenda-files-menu)
16976 (message "Removed file: %s" afile))
16977 (message "File was not in list: %s (not removed)" afile))))
16979 (defun org-file-menu-entry (file)
16980 (vector file (list 'find-file file) t))
16982 (defun org-check-agenda-file (file)
16983 "Make sure FILE exists. If not, ask user what to do."
16984 (when (not (file-exists-p file))
16985 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16986 (abbreviate-file-name file))
16987 (let ((r (downcase (read-char-exclusive))))
16988 (cond
16989 ((equal r ?r)
16990 (org-remove-file file)
16991 (throw 'nextfile t))
16992 (t (error "Abort"))))))
16994 (defun org-get-agenda-file-buffer (file)
16995 "Get a buffer visiting FILE. If the buffer needs to be created, add
16996 it to the list of buffers which might be released later."
16997 (let ((buf (org-find-base-buffer-visiting file)))
16998 (if buf
16999 buf ; just return it
17000 ;; Make a new buffer and remember it
17001 (setq buf (find-file-noselect file))
17002 (if buf (push buf org-agenda-new-buffers))
17003 buf)))
17005 (defun org-release-buffers (blist)
17006 "Release all buffers in list, asking the user for confirmation when needed.
17007 When a buffer is unmodified, it is just killed. When modified, it is saved
17008 \(if the user agrees) and then killed."
17009 (let (buf file)
17010 (while (setq buf (pop blist))
17011 (setq file (buffer-file-name buf))
17012 (when (and (buffer-modified-p buf)
17013 file
17014 (y-or-n-p (format "Save file %s? " file)))
17015 (with-current-buffer buf (save-buffer)))
17016 (kill-buffer buf))))
17018 (defun org-agenda-prepare-buffers (files)
17019 "Create buffers for all agenda files, protect archived trees and comments."
17020 (interactive)
17021 (let ((pa '(:org-archived t))
17022 (pc '(:org-comment t))
17023 (pall '(:org-archived t :org-comment t))
17024 (inhibit-read-only t)
17025 (org-inhibit-startup org-agenda-inhibit-startup)
17026 (rea (concat ":" org-archive-tag ":"))
17027 bmp file re)
17028 (save-excursion
17029 (save-restriction
17030 (while (setq file (pop files))
17031 (catch 'nextfile
17032 (if (bufferp file)
17033 (set-buffer file)
17034 (org-check-agenda-file file)
17035 (set-buffer (org-get-agenda-file-buffer file)))
17036 (widen)
17037 (setq bmp (buffer-modified-p))
17038 (org-refresh-category-properties)
17039 (org-refresh-properties org-effort-property 'org-effort)
17040 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17041 (setq org-todo-keywords-for-agenda
17042 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17043 (setq org-done-keywords-for-agenda
17044 (append org-done-keywords-for-agenda org-done-keywords))
17045 (setq org-todo-keyword-alist-for-agenda
17046 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17047 (setq org-drawers-for-agenda
17048 (append org-drawers-for-agenda org-drawers))
17049 (setq org-tag-alist-for-agenda
17050 (append org-tag-alist-for-agenda org-tag-alist))
17052 (save-excursion
17053 (remove-text-properties (point-min) (point-max) pall)
17054 (when org-agenda-skip-archived-trees
17055 (goto-char (point-min))
17056 (while (re-search-forward rea nil t)
17057 (if (org-at-heading-p t)
17058 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17059 (goto-char (point-min))
17060 (setq re (format org-heading-keyword-regexp-format
17061 org-comment-string))
17062 (while (re-search-forward re nil t)
17063 (add-text-properties
17064 (match-beginning 0) (org-end-of-subtree t) pc)))
17065 (set-buffer-modified-p bmp)))))
17066 (setq org-todo-keywords-for-agenda
17067 (org-uniquify org-todo-keywords-for-agenda))
17068 (setq org-todo-keyword-alist-for-agenda
17069 (org-uniquify org-todo-keyword-alist-for-agenda)
17070 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17072 ;;;; Embedded LaTeX
17074 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17075 "Keymap for the minor `org-cdlatex-mode'.")
17077 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17078 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17079 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17080 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17081 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17083 (defvar org-cdlatex-texmathp-advice-is-done nil
17084 "Flag remembering if we have applied the advice to texmathp already.")
17086 (define-minor-mode org-cdlatex-mode
17087 "Toggle the minor `org-cdlatex-mode'.
17088 This mode supports entering LaTeX environment and math in LaTeX fragments
17089 in Org-mode.
17090 \\{org-cdlatex-mode-map}"
17091 nil " OCDL" nil
17092 (when org-cdlatex-mode
17093 (require 'cdlatex)
17094 (run-hooks 'cdlatex-mode-hook)
17095 (cdlatex-compute-tables))
17096 (unless org-cdlatex-texmathp-advice-is-done
17097 (setq org-cdlatex-texmathp-advice-is-done t)
17098 (defadvice texmathp (around org-math-always-on activate)
17099 "Always return t in org-mode buffers.
17100 This is because we want to insert math symbols without dollars even outside
17101 the LaTeX math segments. If Orgmode thinks that point is actually inside
17102 an embedded LaTeX fragment, let texmathp do its job.
17103 \\[org-cdlatex-mode-map]"
17104 (interactive)
17105 (let (p)
17106 (cond
17107 ((not (derived-mode-p 'org-mode)) ad-do-it)
17108 ((eq this-command 'cdlatex-math-symbol)
17109 (setq ad-return-value t
17110 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17112 (let ((p (org-inside-LaTeX-fragment-p)))
17113 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17114 (setq ad-return-value t
17115 texmathp-why '("Org-mode embedded math" . 0))
17116 (if p ad-do-it)))))))))
17118 (defun turn-on-org-cdlatex ()
17119 "Unconditionally turn on `org-cdlatex-mode'."
17120 (org-cdlatex-mode 1))
17122 (defun org-inside-LaTeX-fragment-p ()
17123 "Test if point is inside a LaTeX fragment.
17124 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17125 sequence appearing also before point.
17126 Even though the matchers for math are configurable, this function assumes
17127 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17128 delimiters are skipped when they have been removed by customization.
17129 The return value is nil, or a cons cell with the delimiter and the
17130 position of this delimiter.
17132 This function does a reasonably good job, but can locally be fooled by
17133 for example currency specifications. For example it will assume being in
17134 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17135 fragments that are properly closed, but during editing, we have to live
17136 with the uncertainty caused by missing closing delimiters. This function
17137 looks only before point, not after."
17138 (catch 'exit
17139 (let ((pos (point))
17140 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17141 (lim (progn
17142 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17143 (point)))
17144 dd-on str (start 0) m re)
17145 (goto-char pos)
17146 (when dodollar
17147 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17148 re (nth 1 (assoc "$" org-latex-regexps)))
17149 (while (string-match re str start)
17150 (cond
17151 ((= (match-end 0) (length str))
17152 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17153 ((= (match-end 0) (- (length str) 5))
17154 (throw 'exit nil))
17155 (t (setq start (match-end 0))))))
17156 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17157 (goto-char pos)
17158 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17159 (and (match-beginning 2) (throw 'exit nil))
17160 ;; count $$
17161 (while (re-search-backward "\\$\\$" lim t)
17162 (setq dd-on (not dd-on)))
17163 (goto-char pos)
17164 (if dd-on (cons "$$" m))))))
17166 (defun org-inside-latex-macro-p ()
17167 "Is point inside a LaTeX macro or its arguments?"
17168 (save-match-data
17169 (org-in-regexp
17170 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17172 (defun org-try-cdlatex-tab ()
17173 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17174 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17175 - inside a LaTeX fragment, or
17176 - after the first word in a line, where an abbreviation expansion could
17177 insert a LaTeX environment."
17178 (when org-cdlatex-mode
17179 (cond
17180 ;; Before any word on the line: No expansion possible.
17181 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17182 ;; Just after first word on the line: Expand it. Make sure it
17183 ;; cannot happen on headlines, though.
17184 ((save-excursion
17185 (skip-chars-backward "a-zA-Z0-9*")
17186 (skip-chars-backward " \t")
17187 (and (bolp) (not (org-at-heading-p))))
17188 (cdlatex-tab) t)
17189 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17191 (defun org-cdlatex-underscore-caret (&optional arg)
17192 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17193 Revert to the normal definition outside of these fragments."
17194 (interactive "P")
17195 (if (org-inside-LaTeX-fragment-p)
17196 (call-interactively 'cdlatex-sub-superscript)
17197 (let (org-cdlatex-mode)
17198 (call-interactively (key-binding (vector last-input-event))))))
17200 (defun org-cdlatex-math-modify (&optional arg)
17201 "Execute `cdlatex-math-modify' in LaTeX fragments.
17202 Revert to the normal definition outside of these fragments."
17203 (interactive "P")
17204 (if (org-inside-LaTeX-fragment-p)
17205 (call-interactively 'cdlatex-math-modify)
17206 (let (org-cdlatex-mode)
17207 (call-interactively (key-binding (vector last-input-event))))))
17209 (defvar org-latex-fragment-image-overlays nil
17210 "List of overlays carrying the images of latex fragments.")
17211 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17213 (defun org-remove-latex-fragment-image-overlays ()
17214 "Remove all overlays with LaTeX fragment images in current buffer."
17215 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17216 (setq org-latex-fragment-image-overlays nil))
17218 (defun org-preview-latex-fragment (&optional subtree)
17219 "Preview the LaTeX fragment at point, or all locally or globally.
17220 If the cursor is in a LaTeX fragment, create the image and overlay
17221 it over the source code. If there is no fragment at point, display
17222 all fragments in the current text, from one headline to the next. With
17223 prefix SUBTREE, display all fragments in the current subtree. With a
17224 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17225 the cursor is before the first headline,
17226 display all fragments in the buffer.
17227 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17228 (interactive "P")
17229 (unless buffer-file-name
17230 (error "Can't preview LaTeX fragment in a non-file buffer"))
17231 (org-remove-latex-fragment-image-overlays)
17232 (save-excursion
17233 (save-restriction
17234 (let (beg end at msg)
17235 (cond
17236 ((or (equal subtree '(16))
17237 (not (save-excursion
17238 (re-search-backward org-outline-regexp-bol nil t))))
17239 (setq beg (point-min) end (point-max)
17240 msg "Creating images for buffer...%s"))
17241 ((equal subtree '(4))
17242 (org-back-to-heading)
17243 (setq beg (point) end (org-end-of-subtree t)
17244 msg "Creating images for subtree...%s"))
17246 (if (setq at (org-inside-LaTeX-fragment-p))
17247 (goto-char (max (point-min) (- (cdr at) 2)))
17248 (org-back-to-heading))
17249 (setq beg (point) end (progn (outline-next-heading) (point))
17250 msg (if at "Creating image...%s"
17251 "Creating images for entry...%s"))))
17252 (message msg "")
17253 (narrow-to-region beg end)
17254 (goto-char beg)
17255 (org-format-latex
17256 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17257 (file-name-nondirectory
17258 buffer-file-name)))
17259 default-directory 'overlays msg at 'forbuffer
17260 org-latex-create-formula-image-program)
17261 (message msg "done. Use `C-c C-c' to remove images.")))))
17263 (defvar org-latex-regexps
17264 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17265 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17266 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17267 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17268 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17269 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17270 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17271 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17272 "Regular expressions for matching embedded LaTeX.")
17274 (defvar org-export-have-math nil) ;; dynamic scoping
17275 (defun org-format-latex (prefix &optional dir overlays msg at
17276 forbuffer processing-type)
17277 "Replace LaTeX fragments with links to an image, and produce images.
17278 Some of the options can be changed using the variable
17279 `org-format-latex-options'."
17280 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17281 (let* ((prefixnodir (file-name-nondirectory prefix))
17282 (absprefix (expand-file-name prefix dir))
17283 (todir (file-name-directory absprefix))
17284 (opt org-format-latex-options)
17285 (matchers (plist-get opt :matchers))
17286 (re-list org-latex-regexps)
17287 (org-format-latex-header-extra
17288 (plist-get (org-infile-export-plist) :latex-header-extra))
17289 (cnt 0) txt hash link beg end re e checkdir
17290 executables-checked string
17291 m n block-type block linkfile movefile ov)
17292 ;; Check the different regular expressions
17293 (while (setq e (pop re-list))
17294 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17295 block (if block-type "\n\n" ""))
17296 (when (member m matchers)
17297 (goto-char (point-min))
17298 (while (re-search-forward re nil t)
17299 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17300 (not (get-text-property (match-beginning n)
17301 'org-protected))
17302 (or (not overlays)
17303 (not (eq (get-char-property (match-beginning n)
17304 'org-overlay-type)
17305 'org-latex-overlay))))
17306 (setq org-export-have-math t)
17307 (cond
17308 ((eq processing-type 'verbatim)
17309 ;; Leave the text verbatim, just protect it
17310 (add-text-properties (match-beginning n) (match-end n)
17311 '(org-protected t)))
17312 ((eq processing-type 'mathjax)
17313 ;; Prepare for MathJax processing
17314 (setq string (match-string n))
17315 (if (member m '("$" "$1"))
17316 (save-excursion
17317 (delete-region (match-beginning n) (match-end n))
17318 (goto-char (match-beginning n))
17319 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17320 "\\)")
17321 '(org-protected t))))
17322 (add-text-properties (match-beginning n) (match-end n)
17323 '(org-protected t))))
17324 ((or (eq processing-type 'dvipng)
17325 (eq processing-type 'imagemagick))
17326 ;; Process to an image
17327 (setq txt (match-string n)
17328 beg (match-beginning n) end (match-end n)
17329 cnt (1+ cnt))
17330 (let (print-length print-level) ; make sure full list is printed
17331 (setq hash (sha1 (prin1-to-string
17332 (list org-format-latex-header
17333 org-format-latex-header-extra
17334 org-export-latex-default-packages-alist
17335 org-export-latex-packages-alist
17336 org-format-latex-options
17337 forbuffer txt)))
17338 linkfile (format "%s_%s.png" prefix hash)
17339 movefile (format "%s_%s.png" absprefix hash)))
17340 (setq link (concat block "[[file:" linkfile "]]" block))
17341 (if msg (message msg cnt))
17342 (goto-char beg)
17343 (unless checkdir ; make sure the directory exists
17344 (setq checkdir t)
17345 (or (file-directory-p todir) (make-directory todir t)))
17346 (cond
17347 ((eq processing-type 'dvipng)
17348 (unless executables-checked
17349 (org-check-external-command
17350 "latex" "needed to convert LaTeX fragments to images")
17351 (org-check-external-command
17352 "dvipng" "needed to convert LaTeX fragments to images")
17353 (setq executables-checked t))
17354 (unless (file-exists-p movefile)
17355 (org-create-formula-image-with-dvipng
17356 txt movefile opt forbuffer)))
17357 ((eq processing-type 'imagemagick)
17358 (unless executables-checked
17359 (org-check-external-command
17360 "convert" "you need to install imagemagick")
17361 (setq executables-checked t))
17362 (unless (file-exists-p movefile)
17363 (org-create-formula-image-with-imagemagick
17364 txt movefile opt forbuffer))))
17365 (if overlays
17366 (progn
17367 (mapc (lambda (o)
17368 (if (eq (overlay-get o 'org-overlay-type)
17369 'org-latex-overlay)
17370 (delete-overlay o)))
17371 (overlays-in beg end))
17372 (setq ov (make-overlay beg end))
17373 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17374 (if (featurep 'xemacs)
17375 (progn
17376 (overlay-put ov 'invisible t)
17377 (overlay-put
17378 ov 'end-glyph
17379 (make-glyph (vector 'png :file movefile))))
17380 (overlay-put
17381 ov 'display
17382 (list 'image :type 'png :file movefile :ascent 'center)))
17383 (push ov org-latex-fragment-image-overlays)
17384 (goto-char end))
17385 (delete-region beg end)
17386 (insert (org-add-props link
17387 (list 'org-latex-src
17388 (replace-regexp-in-string
17389 "\"" "" txt)
17390 'org-latex-src-embed-type
17391 (if block-type 'paragraph 'character))))))
17392 ((eq processing-type 'mathml)
17393 ;; Process to MathML
17394 (unless executables-checked
17395 (unless (save-match-data (org-format-latex-mathml-available-p))
17396 (error "LaTeX to MathML converter not configured"))
17397 (setq executables-checked t))
17398 (setq txt (match-string n)
17399 beg (match-beginning n) end (match-end n)
17400 cnt (1+ cnt))
17401 (if msg (message msg cnt))
17402 (goto-char beg)
17403 (delete-region beg end)
17404 (insert (org-format-latex-as-mathml
17405 txt block-type prefix dir)))
17407 (error "Unknown conversion type %s for latex fragments"
17408 processing-type)))))))))
17410 (defun org-create-math-formula (latex-frag &optional mathml-file)
17411 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17412 Use `org-latex-to-mathml-convert-command'. If the conversion is
17413 sucessful, return the portion between \"<math...> </math>\"
17414 elements otherwise return nil. When MATHML-FILE is specified,
17415 write the results in to that file. When invoked as an
17416 interactive command, prompt for LATEX-FRAG, with initial value
17417 set to the current active region and echo the results for user
17418 inspection."
17419 (interactive (list (let ((frag (when (org-region-active-p)
17420 (buffer-substring-no-properties
17421 (region-beginning) (region-end)))))
17422 (read-string "LaTeX Fragment: " frag nil frag))))
17423 (unless latex-frag (error "Invalid latex-frag"))
17424 (let* ((tmp-in-file (file-relative-name
17425 (make-temp-name (expand-file-name "ltxmathml-in"))))
17426 (ignore (write-region latex-frag nil tmp-in-file))
17427 (tmp-out-file (file-relative-name
17428 (make-temp-name (expand-file-name "ltxmathml-out"))))
17429 (cmd (format-spec
17430 org-latex-to-mathml-convert-command
17431 `((?j . ,(shell-quote-argument
17432 (expand-file-name org-latex-to-mathml-jar-file)))
17433 (?I . ,(shell-quote-argument tmp-in-file))
17434 (?o . ,(shell-quote-argument tmp-out-file)))))
17435 mathml shell-command-output)
17436 (when (org-called-interactively-p 'any)
17437 (unless (org-format-latex-mathml-available-p)
17438 (error "LaTeX to MathML converter not configured")))
17439 (message "Running %s" cmd)
17440 (setq shell-command-output (shell-command-to-string cmd))
17441 (setq mathml
17442 (when (file-readable-p tmp-out-file)
17443 (with-current-buffer (find-file-noselect tmp-out-file t)
17444 (goto-char (point-min))
17445 (when (re-search-forward
17446 (concat
17447 (regexp-quote
17448 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17449 "\\(.\\|\n\\)*"
17450 (regexp-quote "</math>")) nil t)
17451 (prog1 (match-string 0) (kill-buffer))))))
17452 (cond
17453 (mathml
17454 (setq mathml
17455 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17456 (when mathml-file
17457 (write-region mathml nil mathml-file))
17458 (when (org-called-interactively-p 'any)
17459 (message mathml)))
17460 ((message "LaTeX to MathML conversion failed")
17461 (message shell-command-output)))
17462 (delete-file tmp-in-file)
17463 (when (file-exists-p tmp-out-file)
17464 (delete-file tmp-out-file))
17465 mathml))
17467 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17468 prefix &optional dir)
17469 "Use `org-create-math-formula' but check local cache first."
17470 (let* ((absprefix (expand-file-name prefix dir))
17471 (print-length nil) (print-level nil)
17472 (formula-id (concat
17473 "formula-"
17474 (sha1
17475 (prin1-to-string
17476 (list latex-frag
17477 org-latex-to-mathml-convert-command)))))
17478 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17479 (formula-cache-dir (file-name-directory formula-cache)))
17481 (unless (file-directory-p formula-cache-dir)
17482 (make-directory formula-cache-dir t))
17484 (unless (file-exists-p formula-cache)
17485 (org-create-math-formula latex-frag formula-cache))
17487 (if (file-exists-p formula-cache)
17488 ;; Successful conversion. Return the link to MathML file.
17489 (org-add-props
17490 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17491 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17492 'org-latex-src-embed-type (if latex-frag-type
17493 'paragraph 'character)))
17494 ;; Failed conversion. Return the LaTeX fragment verbatim
17495 (add-text-properties
17496 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17497 latex-frag)))
17499 ;; This function borrows from Ganesh Swami's latex2png.el
17500 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17501 "This calls dvipng."
17502 (require 'org-latex)
17503 (let* ((tmpdir (if (featurep 'xemacs)
17504 (temp-directory)
17505 temporary-file-directory))
17506 (texfilebase (make-temp-name
17507 (expand-file-name "orgtex" tmpdir)))
17508 (texfile (concat texfilebase ".tex"))
17509 (dvifile (concat texfilebase ".dvi"))
17510 (pngfile (concat texfilebase ".png"))
17511 (fnh (if (featurep 'xemacs)
17512 (font-height (face-font 'default))
17513 (face-attribute 'default :height nil)))
17514 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17515 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17516 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17517 "Black"))
17518 (bg (or (plist-get options (if buffer :background :html-background))
17519 "Transparent")))
17520 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17521 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17522 (with-temp-file texfile
17523 (insert (org-splice-latex-header
17524 org-format-latex-header
17525 org-export-latex-default-packages-alist
17526 org-export-latex-packages-alist t
17527 org-format-latex-header-extra))
17528 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17529 (require 'org-latex)
17530 (org-export-latex-fix-inputenc))
17531 (let ((dir default-directory))
17532 (condition-case nil
17533 (progn
17534 (cd tmpdir)
17535 (call-process "latex" nil nil nil texfile))
17536 (error nil))
17537 (cd dir))
17538 (if (not (file-exists-p dvifile))
17539 (progn (message "Failed to create dvi file from %s" texfile) nil)
17540 (condition-case nil
17541 (if (featurep 'xemacs)
17542 (call-process "dvipng" nil nil nil
17543 "-fg" fg "-bg" bg
17544 "-T" "tight"
17545 "-o" pngfile
17546 dvifile)
17547 (call-process "dvipng" nil nil nil
17548 "-fg" fg "-bg" bg
17549 "-D" dpi
17550 ;;"-x" scale "-y" scale
17551 "-T" "tight"
17552 "-o" pngfile
17553 dvifile))
17554 (error nil))
17555 (if (not (file-exists-p pngfile))
17556 (if org-format-latex-signal-error
17557 (error "Failed to create png file from %s" texfile)
17558 (message "Failed to create png file from %s" texfile)
17559 nil)
17560 ;; Use the requested file name and clean up
17561 (copy-file pngfile tofile 'replace)
17562 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17563 (if (file-exists-p (concat texfilebase e))
17564 (delete-file (concat texfilebase e))))
17565 pngfile))))
17567 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17568 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17569 "This calls convert, which is included into imagemagick."
17570 (require 'org-latex)
17571 (let* ((tmpdir (if (featurep 'xemacs)
17572 (temp-directory)
17573 temporary-file-directory))
17574 (texfilebase (make-temp-name
17575 (expand-file-name "orgtex" tmpdir)))
17576 (texfile (concat texfilebase ".tex"))
17577 (pdffile (concat texfilebase ".pdf"))
17578 (pngfile (concat texfilebase ".png"))
17579 (fnh (if (featurep 'xemacs)
17580 (font-height (face-font 'default))
17581 (face-attribute 'default :height nil)))
17582 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17583 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17584 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17585 "black"))
17586 (bg (or (plist-get options (if buffer :background :html-background))
17587 "white")))
17588 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17589 (setq fg (org-latex-color-format fg)))
17590 (if (eq bg 'default) (setq bg (org-latex-color :background))
17591 (setq bg (org-latex-color-format
17592 (if (string= bg "Transparent")(setq bg "white")))))
17593 (with-temp-file texfile
17594 (insert (org-splice-latex-header
17595 org-format-latex-header
17596 org-export-latex-default-packages-alist
17597 org-export-latex-packages-alist t
17598 org-format-latex-header-extra))
17599 (insert "\n\\begin{document}\n"
17600 "\\definecolor{fg}{rgb}{" fg "}\n"
17601 "\\definecolor{bg}{rgb}{" bg "}\n"
17602 "\n\\pagecolor{bg}\n"
17603 "\n{\\color{fg}\n"
17604 string
17605 "\n}\n"
17606 "\n\\end{document}\n" )
17607 (require 'org-latex)
17608 (org-export-latex-fix-inputenc))
17609 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17610 (condition-case nil
17611 (progn
17612 (cd tmpdir)
17613 (setq cmds org-latex-to-pdf-process)
17614 (while cmds
17615 (setq latex-frags-cmds (pop cmds))
17616 (if (listp latex-frags-cmds)
17617 (setq cmds nil)
17618 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17619 (while latex-frags-cmds
17620 (setq cmd (pop latex-frags-cmds))
17621 (while (string-match "%b" cmd)
17622 (setq cmd (replace-match
17623 (save-match-data
17624 (shell-quote-argument texfile))
17625 t t cmd)))
17626 (while (string-match "%f" cmd)
17627 (setq cmd (replace-match
17628 (save-match-data
17629 (shell-quote-argument (file-name-nondirectory texfile)))
17630 t t cmd)))
17631 (while (string-match "%o" cmd)
17632 (setq cmd (replace-match
17633 (save-match-data
17634 (shell-quote-argument (file-name-directory texfile)))
17635 t t cmd)))
17636 (setq cmd (split-string cmd))
17637 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17638 (error nil))
17639 (cd dir))
17640 (if (not (file-exists-p pdffile))
17641 (progn (message "Failed to create pdf file from %s" texfile) nil)
17642 (condition-case nil
17643 (if (featurep 'xemacs)
17644 (call-process "convert" nil nil nil
17645 "-density" "96"
17646 "-trim"
17647 "-antialias"
17648 pdffile
17649 "-quality" "100"
17650 ;; "-sharpen" "0x1.0"
17651 pngfile)
17652 (call-process "convert" nil nil nil
17653 "-density" dpi
17654 "-trim"
17655 "-antialias"
17656 pdffile
17657 "-quality" "100"
17658 ; "-sharpen" "0x1.0"
17659 pngfile))
17660 (error nil))
17661 (if (not (file-exists-p pngfile))
17662 (if org-format-latex-signal-error
17663 (error "Failed to create png file from %s" texfile)
17664 (message "Failed to create png file from %s" texfile)
17665 nil)
17666 ;; Use the requested file name and clean up
17667 (copy-file pngfile tofile 'replace)
17668 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17669 (if (file-exists-p (concat texfilebase e))
17670 (delete-file (concat texfilebase e))))
17671 pngfile))))
17673 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17674 "Fill a LaTeX header template TPL.
17675 In the template, the following place holders will be recognized:
17677 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17678 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17679 [PACKAGES] \\usepackage statements for PKG
17680 [NO-PACKAGES] do not include PKG
17681 [EXTRA] the string EXTRA
17682 [NO-EXTRA] do not include EXTRA
17684 For backward compatibility, if both the positive and the negative place
17685 holder is missing, the positive one (without the \"NO-\") will be
17686 assumed to be present at the end of the template.
17687 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17688 EXTRA is a string.
17689 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17690 (let (rpl (end ""))
17691 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17692 (setq rpl (if (or (match-end 1) (not def-pkg))
17693 "" (org-latex-packages-to-string def-pkg snippets-p t))
17694 tpl (replace-match rpl t t tpl))
17695 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17697 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17698 (setq rpl (if (or (match-end 1) (not pkg))
17699 "" (org-latex-packages-to-string pkg snippets-p t))
17700 tpl (replace-match rpl t t tpl))
17701 (if pkg (setq end
17702 (concat end "\n"
17703 (org-latex-packages-to-string pkg snippets-p)))))
17705 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17706 (setq rpl (if (or (match-end 1) (not extra))
17707 "" (concat extra "\n"))
17708 tpl (replace-match rpl t t tpl))
17709 (if (and extra (string-match "\\S-" extra))
17710 (setq end (concat end "\n" extra))))
17712 (if (string-match "\\S-" end)
17713 (concat tpl "\n" end)
17714 tpl)))
17716 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17717 "Turn an alist of packages into a string with the \\usepackage macros."
17718 (setq pkg (mapconcat (lambda(p)
17719 (cond
17720 ((stringp p) p)
17721 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17722 (format "%% Package %s omitted" (cadr p)))
17723 ((equal "" (car p))
17724 (format "\\usepackage{%s}" (cadr p)))
17726 (format "\\usepackage[%s]{%s}"
17727 (car p) (cadr p)))))
17729 "\n"))
17730 (if newline (concat pkg "\n") pkg))
17732 (defun org-dvipng-color (attr)
17733 "Return a RGB color specification for dvipng."
17734 (apply 'format "rgb %s %s %s"
17735 (mapcar 'org-normalize-color
17736 (if (featurep 'xemacs)
17737 (color-rgb-components
17738 (face-property 'default
17739 (cond ((eq attr :foreground) 'foreground)
17740 ((eq attr :background) 'background))))
17741 (color-values (face-attribute 'default attr nil))))))
17743 (defun org-latex-color (attr)
17744 "Return a RGB color for the LaTeX color package."
17745 (apply 'format "%s,%s,%s"
17746 (mapcar 'org-normalize-color
17747 (if (featurep 'xemacs)
17748 (color-rgb-components
17749 (face-property 'default
17750 (cond ((eq attr :foreground) 'foreground)
17751 ((eq attr :background) 'background))))
17752 (color-values (face-attribute 'default attr nil))))))
17754 (defun org-latex-color-format (color-name)
17755 "Convert COLOR-NAME to a RGB color value."
17756 (apply 'format "%s,%s,%s"
17757 (mapcar 'org-normalize-color
17758 (color-values color-name))))
17760 (defun org-normalize-color (value)
17761 "Return string to be used as color value for an RGB component."
17762 (format "%g" (/ value 65535.0)))
17764 ;; Image display
17767 (defvar org-inline-image-overlays nil)
17768 (make-variable-buffer-local 'org-inline-image-overlays)
17770 (defun org-toggle-inline-images (&optional include-linked)
17771 "Toggle the display of inline images.
17772 INCLUDE-LINKED is passed to `org-display-inline-images'."
17773 (interactive "P")
17774 (if org-inline-image-overlays
17775 (progn
17776 (org-remove-inline-images)
17777 (message "Inline image display turned off"))
17778 (org-display-inline-images include-linked)
17779 (if org-inline-image-overlays
17780 (message "%d images displayed inline"
17781 (length org-inline-image-overlays))
17782 (message "No images to display inline"))))
17784 (defun org-redisplay-inline-images ()
17785 "Refresh the display of inline images."
17786 (interactive)
17787 (if (not org-inline-image-overlays)
17788 (org-toggle-inline-images)
17789 (org-toggle-inline-images)
17790 (org-toggle-inline-images)))
17792 (defun org-display-inline-images (&optional include-linked refresh beg end)
17793 "Display inline images.
17794 Normally only links without a description part are inlined, because this
17795 is how it will work for export. When INCLUDE-LINKED is set, also links
17796 with a description part will be inlined. This can be nice for a quick
17797 look at those images, but it does not reflect what exported files will look
17798 like.
17799 When REFRESH is set, refresh existing images between BEG and END.
17800 This will create new image displays only if necessary.
17801 BEG and END default to the buffer boundaries."
17802 (interactive "P")
17803 (unless refresh
17804 (org-remove-inline-images)
17805 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17806 (save-excursion
17807 (save-restriction
17808 (widen)
17809 (setq beg (or beg (point-min)) end (or end (point-max)))
17810 (goto-char beg)
17811 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17812 (substring (org-image-file-name-regexp) 0 -2)
17813 "\\)\\]" (if include-linked "" "\\]")))
17814 old file ov img)
17815 (while (re-search-forward re end t)
17816 (setq old (get-char-property-and-overlay (match-beginning 1)
17817 'org-image-overlay))
17818 (setq file (expand-file-name
17819 (concat (or (match-string 3) "") (match-string 4))))
17820 (when (file-exists-p file)
17821 (if (and (car-safe old) refresh)
17822 (image-refresh (overlay-get (cdr old) 'display))
17823 (setq img (save-match-data (create-image file)))
17824 (when img
17825 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17826 (overlay-put ov 'display img)
17827 (overlay-put ov 'face 'default)
17828 (overlay-put ov 'org-image-overlay t)
17829 (overlay-put ov 'modification-hooks
17830 (list 'org-display-inline-remove-overlay))
17831 (push ov org-inline-image-overlays)))))))))
17833 (define-obsolete-function-alias
17834 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17836 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17837 "Remove inline-display overlay if a corresponding region is modified."
17838 (let ((inhibit-modification-hooks t))
17839 (when (and ov after)
17840 (delete ov org-inline-image-overlays)
17841 (delete-overlay ov))))
17843 (defun org-remove-inline-images ()
17844 "Remove inline display of images."
17845 (interactive)
17846 (mapc 'delete-overlay org-inline-image-overlays)
17847 (setq org-inline-image-overlays nil))
17849 ;;;; Key bindings
17851 ;; Outline functions from `outline-mode-prefix-map'
17852 ;; that can be remapped in Org:
17853 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17854 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17855 (define-key org-mode-map [remap outline-forward-same-level]
17856 'org-forward-heading-same-level)
17857 (define-key org-mode-map [remap outline-backward-same-level]
17858 'org-backward-heading-same-level)
17859 (define-key org-mode-map [remap show-branches]
17860 'org-kill-note-or-show-branches)
17861 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17862 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17863 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17865 ;; Outline functions from `outline-mode-prefix-map' that can not
17866 ;; be remapped in Org:
17868 ;; - the column "key binding" shows whether the Outline function is still
17869 ;; available in Org mode on the same key that it has been bound to in
17870 ;; Outline mode:
17871 ;; - "overridden": key used for a different functionality in Org mode
17872 ;; - else: key still bound to the same Outline function in Org mode
17874 ;; | Outline function | key binding | Org replacement |
17875 ;; |------------------------------------+-------------+-----------------------|
17876 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17877 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17878 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17879 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17880 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17881 ;; | `show-entry' | overridden | no replacement |
17882 ;; | `show-children' | `C-c C-i' | visibility cycling |
17883 ;; | `show-branches' | `C-c C-k' | still same function |
17884 ;; | `show-subtree' | overridden | visibility cycling |
17885 ;; | `show-all' | overridden | no replacement |
17886 ;; | `hide-subtree' | overridden | visibility cycling |
17887 ;; | `hide-body' | overridden | no replacement |
17888 ;; | `hide-entry' | overridden | visibility cycling |
17889 ;; | `hide-leaves' | overridden | no replacement |
17890 ;; | `hide-sublevels' | overridden | no replacement |
17891 ;; | `hide-other' | overridden | no replacement |
17893 ;; Make `C-c C-x' a prefix key
17894 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17896 ;; TAB key with modifiers
17897 (org-defkey org-mode-map "\C-i" 'org-cycle)
17898 (org-defkey org-mode-map [(tab)] 'org-cycle)
17899 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17900 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17901 ;; The following line is necessary under Suse GNU/Linux
17902 (unless (featurep 'xemacs)
17903 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17904 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17905 (define-key org-mode-map [backtab] 'org-shifttab)
17907 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17908 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17909 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17911 ;; Cursor keys with modifiers
17912 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17913 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17914 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17915 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17917 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17918 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17919 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17920 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17922 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17923 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17924 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17925 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17927 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17928 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17929 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17930 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17932 ;; Babel keys
17933 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17934 (mapc (lambda (pair)
17935 (define-key org-babel-map (car pair) (cdr pair)))
17936 org-babel-key-bindings)
17938 ;;; Extra keys for tty access.
17939 ;; We only set them when really needed because otherwise the
17940 ;; menus don't show the simple keys
17942 (when (or org-use-extra-keys
17943 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17944 (not window-system))
17945 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17946 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17947 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17948 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17949 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17950 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17951 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17952 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17953 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17954 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17955 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17956 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17957 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17958 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17959 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17960 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17961 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17962 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17963 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17964 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17965 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17966 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17967 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17968 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17969 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17970 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17971 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17972 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17974 ;; All the other keys
17976 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17977 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17978 (if (boundp 'narrow-map)
17979 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17980 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17981 (if (boundp 'narrow-map)
17982 (org-defkey narrow-map "b" 'org-narrow-to-block)
17983 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17984 (if (boundp 'narrow-map)
17985 (org-defkey narrow-map "e" 'org-narrow-to-element)
17986 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17987 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17988 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17989 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17990 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17991 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17992 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17993 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17994 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17995 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17996 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17997 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17998 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17999 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18000 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18001 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18002 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18003 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18004 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18005 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18006 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18007 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18008 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18009 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18010 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18011 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18012 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18013 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18014 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18015 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18016 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18017 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18018 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18019 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18020 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18021 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18022 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18023 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18024 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18025 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18026 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18027 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18028 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18029 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18030 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18031 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18032 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18033 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18034 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18035 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18036 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18037 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18038 (org-defkey org-mode-map "\C-c^" 'org-sort)
18039 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18040 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18041 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18042 (org-defkey org-mode-map "\C-m" 'org-return)
18043 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18044 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18045 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18046 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18047 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18048 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18049 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18050 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18051 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18052 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18053 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18054 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18055 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18056 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18057 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18058 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18059 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18060 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18061 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18062 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18063 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18064 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18065 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18067 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18068 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18069 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18071 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18072 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18073 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18074 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18075 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18076 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18077 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18078 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18079 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18080 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18081 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18082 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18083 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18084 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18085 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18086 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18087 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18088 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18089 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18090 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18091 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18092 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18094 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18095 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18096 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18097 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18098 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18100 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18102 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18104 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18105 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18107 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18110 (when (featurep 'xemacs)
18111 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18114 (defconst org-speed-commands-default
18116 ("Outline Navigation")
18117 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18118 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18119 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18120 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18121 ("u" . (org-speed-move-safe 'outline-up-heading))
18122 ("j" . org-goto)
18123 ("g" . (org-refile t))
18124 ("Outline Visibility")
18125 ("c" . org-cycle)
18126 ("C" . org-shifttab)
18127 (" " . org-display-outline-path)
18128 ("=" . org-columns)
18129 ("Outline Structure Editing")
18130 ("U" . org-shiftmetaup)
18131 ("D" . org-shiftmetadown)
18132 ("r" . org-metaright)
18133 ("l" . org-metaleft)
18134 ("R" . org-shiftmetaright)
18135 ("L" . org-shiftmetaleft)
18136 ("i" . (progn (forward-char 1) (call-interactively
18137 'org-insert-heading-respect-content)))
18138 ("^" . org-sort)
18139 ("w" . org-refile)
18140 ("a" . org-archive-subtree-default-with-confirmation)
18141 ("." . org-mark-subtree)
18142 ("#" . org-toggle-comment)
18143 ("Clock Commands")
18144 ("I" . org-clock-in)
18145 ("O" . org-clock-out)
18146 ("Meta Data Editing")
18147 ("t" . org-todo)
18148 ("," . (org-priority))
18149 ("0" . (org-priority ?\ ))
18150 ("1" . (org-priority ?A))
18151 ("2" . (org-priority ?B))
18152 ("3" . (org-priority ?C))
18153 (":" . org-set-tags-command)
18154 ("e" . org-set-effort)
18155 ("E" . org-inc-effort)
18156 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18157 (org-entry-put (point) "APPT_WARNTIME" m)))
18158 ("Agenda Views etc")
18159 ("v" . org-agenda)
18160 ("/" . org-sparse-tree)
18161 ("Misc")
18162 ("o" . org-open-at-point)
18163 ("?" . org-speed-command-help)
18164 ("<" . (org-agenda-set-restriction-lock 'subtree))
18165 (">" . (org-agenda-remove-restriction-lock))
18167 "The default speed commands.")
18169 (defun org-print-speed-command (e)
18170 (if (> (length (car e)) 1)
18171 (progn
18172 (princ "\n")
18173 (princ (car e))
18174 (princ "\n")
18175 (princ (make-string (length (car e)) ?-))
18176 (princ "\n"))
18177 (princ (car e))
18178 (princ " ")
18179 (if (symbolp (cdr e))
18180 (princ (symbol-name (cdr e)))
18181 (prin1 (cdr e)))
18182 (princ "\n")))
18184 (defun org-speed-command-help ()
18185 "Show the available speed commands."
18186 (interactive)
18187 (if (not org-use-speed-commands)
18188 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18189 (with-output-to-temp-buffer "*Help*"
18190 (princ "User-defined Speed commands\n===========================\n")
18191 (mapc 'org-print-speed-command org-speed-commands-user)
18192 (princ "\n")
18193 (princ "Built-in Speed commands\n=======================\n")
18194 (mapc 'org-print-speed-command org-speed-commands-default))
18195 (with-current-buffer "*Help*"
18196 (setq truncate-lines t))))
18198 (defun org-speed-move-safe (cmd)
18199 "Execute CMD, but make sure that the cursor always ends up in a headline.
18200 If not, return to the original position and throw an error."
18201 (interactive)
18202 (let ((pos (point)))
18203 (call-interactively cmd)
18204 (unless (and (bolp) (org-at-heading-p))
18205 (goto-char pos)
18206 (error "Boundary reached while executing %s" cmd))))
18208 (defvar org-self-insert-command-undo-counter 0)
18210 (defvar org-table-auto-blank-field) ; defined in org-table.el
18211 (defvar org-speed-command nil)
18213 (define-obsolete-function-alias
18214 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18216 (defun org-speed-command-activate (keys)
18217 "Hook for activating single-letter speed commands.
18218 `org-speed-commands-default' specifies a minimal command set.
18219 Use `org-speed-commands-user' for further customization."
18220 (when (or (and (bolp) (looking-at org-outline-regexp))
18221 (and (functionp org-use-speed-commands)
18222 (funcall org-use-speed-commands)))
18223 (cdr (assoc keys (append org-speed-commands-user
18224 org-speed-commands-default)))))
18226 (define-obsolete-function-alias
18227 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18229 (defun org-babel-speed-command-activate (keys)
18230 "Hook for activating single-letter code block commands."
18231 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18232 (cdr (assoc keys org-babel-key-bindings))))
18234 (defcustom org-speed-command-hook
18235 '(org-speed-command-default-hook org-babel-speed-command-hook)
18236 "Hook for activating speed commands at strategic locations.
18237 Hook functions are called in sequence until a valid handler is
18238 found.
18240 Each hook takes a single argument, a user-pressed command key
18241 which is also a `self-insert-command' from the global map.
18243 Within the hook, examine the cursor position and the command key
18244 and return nil or a valid handler as appropriate. Handler could
18245 be one of an interactive command, a function, or a form.
18247 Set `org-use-speed-commands' to non-nil value to enable this
18248 hook. The default setting is `org-speed-command-activate'."
18249 :group 'org-structure
18250 :version "24.1"
18251 :type 'hook)
18253 (defun org-self-insert-command (N)
18254 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18255 If the cursor is in a table looking at whitespace, the whitespace is
18256 overwritten, and the table is not marked as requiring realignment."
18257 (interactive "p")
18258 (org-check-before-invisible-edit 'insert)
18259 (cond
18260 ((and org-use-speed-commands
18261 (setq org-speed-command
18262 (run-hook-with-args-until-success
18263 'org-speed-command-hook (this-command-keys))))
18264 (cond
18265 ((commandp org-speed-command)
18266 (setq this-command org-speed-command)
18267 (call-interactively org-speed-command))
18268 ((functionp org-speed-command)
18269 (funcall org-speed-command))
18270 ((and org-speed-command (listp org-speed-command))
18271 (eval org-speed-command))
18272 (t (let (org-use-speed-commands)
18273 (call-interactively 'org-self-insert-command)))))
18274 ((and
18275 (org-table-p)
18276 (progn
18277 ;; check if we blank the field, and if that triggers align
18278 (and (featurep 'org-table) org-table-auto-blank-field
18279 (member last-command
18280 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18281 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18282 ;; got extra space, this field does not determine column width
18283 (let (org-table-may-need-update) (org-table-blank-field))
18284 ;; no extra space, this field may determine column width
18285 (org-table-blank-field)))
18287 (eq N 1)
18288 (looking-at "[^|\n]* |"))
18289 (let (org-table-may-need-update)
18290 (goto-char (1- (match-end 0)))
18291 (backward-delete-char 1)
18292 (goto-char (match-beginning 0))
18293 (self-insert-command N)))
18295 (setq org-table-may-need-update t)
18296 (self-insert-command N)
18297 (org-fix-tags-on-the-fly)
18298 (if org-self-insert-cluster-for-undo
18299 (if (not (eq last-command 'org-self-insert-command))
18300 (setq org-self-insert-command-undo-counter 1)
18301 (if (>= org-self-insert-command-undo-counter 20)
18302 (setq org-self-insert-command-undo-counter 1)
18303 (and (> org-self-insert-command-undo-counter 0)
18304 buffer-undo-list (listp buffer-undo-list)
18305 (not (cadr buffer-undo-list)) ; remove nil entry
18306 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18307 (setq org-self-insert-command-undo-counter
18308 (1+ org-self-insert-command-undo-counter))))))))
18310 (defun org-check-before-invisible-edit (kind)
18311 "Check is editing if kind KIND would be dangerous with invisible text around.
18312 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18313 ;; First, try to get out of here as quickly as possible, to reduce overhead
18314 (if (and org-catch-invisible-edits
18315 (or (not (boundp 'visible-mode)) (not visible-mode))
18316 (or (get-char-property (point) 'invisible)
18317 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18318 ;; OK, we need to take a closer look
18319 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18320 (invisible-before-point (if (bobp) nil (get-char-property
18321 (1- (point)) 'invisible)))
18322 (border-and-ok-direction
18324 ;; Check if we are acting predictably before invisible text
18325 (and invisible-at-point (not invisible-before-point)
18326 (memq kind '(insert delete-backward)))
18327 ;; Check if we are acting predictably after invisible text
18328 ;; This works not well, and I have turned it off. It seems
18329 ;; better to always show and stop after invisible text.
18330 ;; (and (not invisible-at-point) invisible-before-point
18331 ;; (memq kind '(insert delete)))
18333 (when (or (memq invisible-at-point '(outline org-hide-block t))
18334 (memq invisible-before-point '(outline org-hide-block t)))
18335 (if (eq org-catch-invisible-edits 'error)
18336 (error "Editing in invisible areas is prohibited - make visible first"))
18337 (if (and org-custom-properties-overlays
18338 (y-or-n-p "Display invisible properties in this buffer? "))
18339 (org-toggle-custom-properties-visibility)
18340 ;; Make the area visible
18341 (save-excursion
18342 (if invisible-before-point
18343 (goto-char (previous-single-char-property-change
18344 (point) 'invisible)))
18345 (org-cycle))
18346 (cond
18347 ((eq org-catch-invisible-edits 'show)
18348 ;; That's it, we do the edit after showing
18349 (message
18350 "Unfolding invisible region around point before editing")
18351 (sit-for 1))
18352 ((and (eq org-catch-invisible-edits 'smart)
18353 border-and-ok-direction)
18354 (message "Unfolding invisible region around point before editing"))
18356 ;; Don't do the edit, make the user repeat it in full visibility
18357 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18359 (defun org-fix-tags-on-the-fly ()
18360 (when (and (equal (char-after (point-at-bol)) ?*)
18361 (org-at-heading-p))
18362 (org-align-tags-here org-tags-column)))
18364 (defun org-delete-backward-char (N)
18365 "Like `delete-backward-char', insert whitespace at field end in tables.
18366 When deleting backwards, in tables this function will insert whitespace in
18367 front of the next \"|\" separator, to keep the table aligned. The table will
18368 still be marked for re-alignment if the field did fill the entire column,
18369 because, in this case the deletion might narrow the column."
18370 (interactive "p")
18371 (save-match-data
18372 (org-check-before-invisible-edit 'delete-backward)
18373 (if (and (org-table-p)
18374 (eq N 1)
18375 (string-match "|" (buffer-substring (point-at-bol) (point)))
18376 (looking-at ".*?|"))
18377 (let ((pos (point))
18378 (noalign (looking-at "[^|\n\r]* |"))
18379 (c org-table-may-need-update))
18380 (backward-delete-char N)
18381 (if (not overwrite-mode)
18382 (progn
18383 (skip-chars-forward "^|")
18384 (insert " ")
18385 (goto-char (1- pos))))
18386 ;; noalign: if there were two spaces at the end, this field
18387 ;; does not determine the width of the column.
18388 (if noalign (setq org-table-may-need-update c)))
18389 (backward-delete-char N)
18390 (org-fix-tags-on-the-fly))))
18392 (defun org-delete-char (N)
18393 "Like `delete-char', but insert whitespace at field end in tables.
18394 When deleting characters, in tables this function will insert whitespace in
18395 front of the next \"|\" separator, to keep the table aligned. The table will
18396 still be marked for re-alignment if the field did fill the entire column,
18397 because, in this case the deletion might narrow the column."
18398 (interactive "p")
18399 (save-match-data
18400 (org-check-before-invisible-edit 'delete)
18401 (if (and (org-table-p)
18402 (not (bolp))
18403 (not (= (char-after) ?|))
18404 (eq N 1))
18405 (if (looking-at ".*?|")
18406 (let ((pos (point))
18407 (noalign (looking-at "[^|\n\r]* |"))
18408 (c org-table-may-need-update))
18409 (replace-match (concat
18410 (substring (match-string 0) 1 -1)
18411 " |"))
18412 (goto-char pos)
18413 ;; noalign: if there were two spaces at the end, this field
18414 ;; does not determine the width of the column.
18415 (if noalign (setq org-table-may-need-update c)))
18416 (delete-char N))
18417 (delete-char N)
18418 (org-fix-tags-on-the-fly))))
18420 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18421 (put 'org-self-insert-command 'delete-selection t)
18422 (put 'orgtbl-self-insert-command 'delete-selection t)
18423 (put 'org-delete-char 'delete-selection 'supersede)
18424 (put 'org-delete-backward-char 'delete-selection 'supersede)
18425 (put 'org-yank 'delete-selection 'yank)
18427 ;; Make `flyspell-mode' delay after some commands
18428 (put 'org-self-insert-command 'flyspell-delayed t)
18429 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18430 (put 'org-delete-char 'flyspell-delayed t)
18431 (put 'org-delete-backward-char 'flyspell-delayed t)
18433 ;; Make pabbrev-mode expand after org-mode commands
18434 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18435 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18437 ;; How to do this: Measure non-white length of current string
18438 ;; If equal to column width, we should realign.
18440 (defun org-remap (map &rest commands)
18441 "In MAP, remap the functions given in COMMANDS.
18442 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18443 (let (new old)
18444 (while commands
18445 (setq old (pop commands) new (pop commands))
18446 (if (fboundp 'command-remapping)
18447 (org-defkey map (vector 'remap old) new)
18448 (substitute-key-definition old new map global-map)))))
18450 (when (eq org-enable-table-editor 'optimized)
18451 ;; If the user wants maximum table support, we need to hijack
18452 ;; some standard editing functions
18453 (org-remap org-mode-map
18454 'self-insert-command 'org-self-insert-command
18455 'delete-char 'org-delete-char
18456 'delete-backward-char 'org-delete-backward-char)
18457 (org-defkey org-mode-map "|" 'org-force-self-insert))
18459 (defvar org-ctrl-c-ctrl-c-hook nil
18460 "Hook for functions attaching themselves to `C-c C-c'.
18462 This can be used to add additional functionality to the C-c C-c
18463 key which executes context-dependent commands. This hook is run
18464 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18465 run after the last test.
18467 Each function will be called with no arguments. The function
18468 must check if the context is appropriate for it to act. If yes,
18469 it should do its thing and then return a non-nil value. If the
18470 context is wrong, just do nothing and return nil.")
18472 (defvar org-ctrl-c-ctrl-c-final-hook nil
18473 "Hook for functions attaching themselves to `C-c C-c'.
18475 This can be used to add additional functionality to the C-c C-c
18476 key which executes context-dependent commands. This hook is run
18477 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18478 before the first test.
18480 Each function will be called with no arguments. The function
18481 must check if the context is appropriate for it to act. If yes,
18482 it should do its thing and then return a non-nil value. If the
18483 context is wrong, just do nothing and return nil.")
18485 (defvar org-tab-first-hook nil
18486 "Hook for functions to attach themselves to TAB.
18487 See `org-ctrl-c-ctrl-c-hook' for more information.
18488 This hook runs as the first action when TAB is pressed, even before
18489 `org-cycle' messes around with the `outline-regexp' to cater for
18490 inline tasks and plain list item folding.
18491 If any function in this hook returns t, any other actions that
18492 would have been caused by TAB (such as table field motion or visibility
18493 cycling) will not occur.")
18495 (defvar org-tab-after-check-for-table-hook nil
18496 "Hook for functions to attach themselves to TAB.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.
18498 This hook runs after it has been established that the cursor is not in a
18499 table, but before checking if the cursor is in a headline or if global cycling
18500 should be done.
18501 If any function in this hook returns t, not other actions like visibility
18502 cycling will be done.")
18504 (defvar org-tab-after-check-for-cycling-hook nil
18505 "Hook for functions to attach themselves to TAB.
18506 See `org-ctrl-c-ctrl-c-hook' for more information.
18507 This hook runs after it has been established that not table field motion and
18508 not visibility should be done because of current context. This is probably
18509 the place where a package like yasnippets can hook in.")
18511 (defvar org-tab-before-tab-emulation-hook nil
18512 "Hook for functions to attach themselves to TAB.
18513 See `org-ctrl-c-ctrl-c-hook' for more information.
18514 This hook runs after every other options for TAB have been exhausted, but
18515 before indentation and \t insertion takes place.")
18517 (defvar org-metaleft-hook nil
18518 "Hook for functions attaching themselves to `M-left'.
18519 See `org-ctrl-c-ctrl-c-hook' for more information.")
18520 (defvar org-metaright-hook nil
18521 "Hook for functions attaching themselves to `M-right'.
18522 See `org-ctrl-c-ctrl-c-hook' for more information.")
18523 (defvar org-metaup-hook nil
18524 "Hook for functions attaching themselves to `M-up'.
18525 See `org-ctrl-c-ctrl-c-hook' for more information.")
18526 (defvar org-metadown-hook nil
18527 "Hook for functions attaching themselves to `M-down'.
18528 See `org-ctrl-c-ctrl-c-hook' for more information.")
18529 (defvar org-shiftmetaleft-hook nil
18530 "Hook for functions attaching themselves to `M-S-left'.
18531 See `org-ctrl-c-ctrl-c-hook' for more information.")
18532 (defvar org-shiftmetaright-hook nil
18533 "Hook for functions attaching themselves to `M-S-right'.
18534 See `org-ctrl-c-ctrl-c-hook' for more information.")
18535 (defvar org-shiftmetaup-hook nil
18536 "Hook for functions attaching themselves to `M-S-up'.
18537 See `org-ctrl-c-ctrl-c-hook' for more information.")
18538 (defvar org-shiftmetadown-hook nil
18539 "Hook for functions attaching themselves to `M-S-down'.
18540 See `org-ctrl-c-ctrl-c-hook' for more information.")
18541 (defvar org-metareturn-hook nil
18542 "Hook for functions attaching themselves to `M-RET'.
18543 See `org-ctrl-c-ctrl-c-hook' for more information.")
18544 (defvar org-shiftup-hook nil
18545 "Hook for functions attaching themselves to `S-up'.
18546 See `org-ctrl-c-ctrl-c-hook' for more information.")
18547 (defvar org-shiftup-final-hook nil
18548 "Hook for functions attaching themselves to `S-up'.
18549 This one runs after all other options except shift-select have been excluded.
18550 See `org-ctrl-c-ctrl-c-hook' for more information.")
18551 (defvar org-shiftdown-hook nil
18552 "Hook for functions attaching themselves to `S-down'.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.")
18554 (defvar org-shiftdown-final-hook nil
18555 "Hook for functions attaching themselves to `S-down'.
18556 This one runs after all other options except shift-select have been excluded.
18557 See `org-ctrl-c-ctrl-c-hook' for more information.")
18558 (defvar org-shiftleft-hook nil
18559 "Hook for functions attaching themselves to `S-left'.
18560 See `org-ctrl-c-ctrl-c-hook' for more information.")
18561 (defvar org-shiftleft-final-hook nil
18562 "Hook for functions attaching themselves to `S-left'.
18563 This one runs after all other options except shift-select have been excluded.
18564 See `org-ctrl-c-ctrl-c-hook' for more information.")
18565 (defvar org-shiftright-hook nil
18566 "Hook for functions attaching themselves to `S-right'.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.")
18568 (defvar org-shiftright-final-hook nil
18569 "Hook for functions attaching themselves to `S-right'.
18570 This one runs after all other options except shift-select have been excluded.
18571 See `org-ctrl-c-ctrl-c-hook' for more information.")
18573 (defun org-modifier-cursor-error ()
18574 "Throw an error, a modified cursor command was applied in wrong context."
18575 (error "This command is active in special context like tables, headlines or items"))
18577 (defun org-shiftselect-error ()
18578 "Throw an error because Shift-Cursor command was applied in wrong context."
18579 (if (and (boundp 'shift-select-mode) shift-select-mode)
18580 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18581 (error "This command works only in special context like headlines or timestamps")))
18583 (defun org-call-for-shift-select (cmd)
18584 (let ((this-command-keys-shift-translated t))
18585 (call-interactively cmd)))
18587 (defun org-shifttab (&optional arg)
18588 "Global visibility cycling or move to previous table field.
18589 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18590 on context.
18591 See the individual commands for more information."
18592 (interactive "P")
18593 (cond
18594 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18595 ((integerp arg)
18596 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18597 (message "Content view to level: %d" arg)
18598 (org-content (prefix-numeric-value arg2))
18599 (setq org-cycle-global-status 'overview)))
18600 (t (call-interactively 'org-global-cycle))))
18602 (defun org-shiftmetaleft ()
18603 "Promote subtree or delete table column.
18604 Calls `org-promote-subtree', `org-outdent-item-tree', or
18605 `org-table-delete-column', depending on context. See the
18606 individual commands for more information."
18607 (interactive)
18608 (cond
18609 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18610 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18611 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18612 ((if (not (org-region-active-p)) (org-at-item-p)
18613 (save-excursion (goto-char (region-beginning))
18614 (org-at-item-p)))
18615 (call-interactively 'org-outdent-item-tree))
18616 (t (org-modifier-cursor-error))))
18618 (defun org-shiftmetaright ()
18619 "Demote subtree or insert table column.
18620 Calls `org-demote-subtree', `org-indent-item-tree', or
18621 `org-table-insert-column', depending on context. See the
18622 individual commands for more information."
18623 (interactive)
18624 (cond
18625 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18626 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18627 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18628 ((if (not (org-region-active-p)) (org-at-item-p)
18629 (save-excursion (goto-char (region-beginning))
18630 (org-at-item-p)))
18631 (call-interactively 'org-indent-item-tree))
18632 (t (org-modifier-cursor-error))))
18634 (defun org-shiftmetaup (&optional arg)
18635 "Move subtree up or kill table row.
18636 Calls `org-move-subtree-up' or `org-table-kill-row' or
18637 `org-move-item-up' or `org-timestamp-up', depending on context.
18638 See the individual commands for more information."
18639 (interactive "P")
18640 (cond
18641 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18642 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18643 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18644 ((org-at-item-p) (call-interactively 'org-move-item-up))
18645 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18646 (call-interactively 'org-timestamp-up)))
18647 (t (org-modifier-cursor-error))))
18649 (defun org-shiftmetadown (&optional arg)
18650 "Move subtree down or insert table row.
18651 Calls `org-move-subtree-down' or `org-table-insert-row' or
18652 `org-move-item-down' or `org-timestamp-up', depending on context.
18653 See the individual commands for more information."
18654 (interactive "P")
18655 (cond
18656 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18657 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18658 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18659 ((org-at-item-p) (call-interactively 'org-move-item-down))
18660 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18661 (call-interactively 'org-timestamp-down)))
18662 (t (org-modifier-cursor-error))))
18664 (defsubst org-hidden-tree-error ()
18665 (error
18666 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18668 (defun org-metaleft (&optional arg)
18669 "Promote heading or move table column to left.
18670 Calls `org-do-promote' or `org-table-move-column', depending on context.
18671 With no specific context, calls the Emacs default `backward-word'.
18672 See the individual commands for more information."
18673 (interactive "P")
18674 (cond
18675 ((run-hook-with-args-until-success 'org-metaleft-hook))
18676 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18677 ((org-with-limited-levels
18678 (or (org-at-heading-p)
18679 (and (org-region-active-p)
18680 (save-excursion
18681 (goto-char (region-beginning))
18682 (org-at-heading-p)))))
18683 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18684 (call-interactively 'org-do-promote))
18685 ;; At an inline task.
18686 ((org-at-heading-p)
18687 (call-interactively 'org-inlinetask-promote))
18688 ((or (org-at-item-p)
18689 (and (org-region-active-p)
18690 (save-excursion
18691 (goto-char (region-beginning))
18692 (org-at-item-p))))
18693 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18694 (call-interactively 'org-outdent-item))
18695 (t (call-interactively 'backward-word))))
18697 (defun org-metaright (&optional arg)
18698 "Demote a subtree, a list item or move table column to right.
18699 In front of a drawer or a block keyword, indent it correctly.
18700 With no specific context, calls the Emacs default `forward-word'.
18701 See the individual commands for more information."
18702 (interactive "P")
18703 (cond
18704 ((run-hook-with-args-until-success 'org-metaright-hook))
18705 ((org-at-table-p) (call-interactively 'org-table-move-column))
18706 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18707 ((org-at-block-p) (call-interactively 'org-indent-block))
18708 ((org-with-limited-levels
18709 (or (org-at-heading-p)
18710 (and (org-region-active-p)
18711 (save-excursion
18712 (goto-char (region-beginning))
18713 (org-at-heading-p)))))
18714 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18715 (call-interactively 'org-do-demote))
18716 ;; At an inline task.
18717 ((org-at-heading-p)
18718 (call-interactively 'org-inlinetask-demote))
18719 ((or (org-at-item-p)
18720 (and (org-region-active-p)
18721 (save-excursion
18722 (goto-char (region-beginning))
18723 (org-at-item-p))))
18724 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18725 (call-interactively 'org-indent-item))
18726 (t (call-interactively 'forward-word))))
18728 (defun org-check-for-hidden (what)
18729 "Check if there are hidden headlines/items in the current visual line.
18730 WHAT can be either `headlines' or `items'. If the current line is
18731 an outline or item heading and it has a folded subtree below it,
18732 this function returns t, nil otherwise."
18733 (let ((re (cond
18734 ((eq what 'headlines) org-outline-regexp-bol)
18735 ((eq what 'items) (org-item-beginning-re))
18736 (t (error "This should not happen"))))
18737 beg end)
18738 (save-excursion
18739 (catch 'exit
18740 (unless (org-region-active-p)
18741 (setq beg (point-at-bol))
18742 (beginning-of-line 2)
18743 (while (and (not (eobp)) ;; this is like `next-line'
18744 (get-char-property (1- (point)) 'invisible))
18745 (beginning-of-line 2))
18746 (setq end (point))
18747 (goto-char beg)
18748 (goto-char (point-at-eol))
18749 (setq end (max end (point)))
18750 (while (re-search-forward re end t)
18751 (if (get-char-property (match-beginning 0) 'invisible)
18752 (throw 'exit t))))
18753 nil))))
18755 (org-autoload "org-element" '(org-element-at-point org-element-type))
18757 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18758 (declare-function org-element-type "org-element" (element))
18759 (declare-function org-element-contents "org-element" (element))
18760 (declare-function org-element-property "org-element" (property element))
18761 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18762 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18763 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18764 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18765 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18767 (defun org-metaup (&optional arg)
18768 "Move subtree up or move table row up.
18769 Calls `org-move-subtree-up' or `org-table-move-row' or
18770 `org-move-item-up', depending on context. See the individual commands
18771 for more information."
18772 (interactive "P")
18773 (cond
18774 ((run-hook-with-args-until-success 'org-metaup-hook))
18775 ((org-region-active-p)
18776 (let* ((a (min (region-beginning) (region-end)))
18777 (b (1- (max (region-beginning) (region-end))))
18778 (c (save-excursion (goto-char a)
18779 (move-beginning-of-line 0)))
18780 (d (save-excursion (goto-char a)
18781 (move-end-of-line 0) (point))))
18782 (transpose-regions a b c d)
18783 (goto-char c)))
18784 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18785 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18786 ((org-at-item-p) (call-interactively 'org-move-item-up))
18787 (t (org-drag-element-backward))))
18789 (defun org-metadown (&optional arg)
18790 "Move subtree down or move table row down.
18791 Calls `org-move-subtree-down' or `org-table-move-row' or
18792 `org-move-item-down', depending on context. See the individual
18793 commands for more information."
18794 (interactive "P")
18795 (cond
18796 ((run-hook-with-args-until-success 'org-metadown-hook))
18797 ((org-region-active-p)
18798 (let* ((a (min (region-beginning) (region-end)))
18799 (b (max (region-beginning) (region-end)))
18800 (c (save-excursion (goto-char b)
18801 (move-beginning-of-line 1)))
18802 (d (save-excursion (goto-char b)
18803 (move-end-of-line 1) (1+ (point)))))
18804 (transpose-regions a b c d)
18805 (goto-char d)))
18806 ((org-at-table-p) (call-interactively 'org-table-move-row))
18807 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18808 ((org-at-item-p) (call-interactively 'org-move-item-down))
18809 (t (org-drag-element-forward))))
18811 (defun org-shiftup (&optional arg)
18812 "Increase item in timestamp or increase priority of current headline.
18813 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18814 depending on context. See the individual commands for more information."
18815 (interactive "P")
18816 (cond
18817 ((run-hook-with-args-until-success 'org-shiftup-hook))
18818 ((and org-support-shift-select (org-region-active-p))
18819 (org-call-for-shift-select 'previous-line))
18820 ((org-at-timestamp-p t)
18821 (call-interactively (if org-edit-timestamp-down-means-later
18822 'org-timestamp-down 'org-timestamp-up)))
18823 ((and (not (eq org-support-shift-select 'always))
18824 org-enable-priority-commands
18825 (org-at-heading-p))
18826 (call-interactively 'org-priority-up))
18827 ((and (not org-support-shift-select) (org-at-item-p))
18828 (call-interactively 'org-previous-item))
18829 ((org-clocktable-try-shift 'up arg))
18830 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18831 (org-support-shift-select
18832 (org-call-for-shift-select 'previous-line))
18833 (t (org-shiftselect-error))))
18835 (defun org-shiftdown (&optional arg)
18836 "Decrease item in timestamp or decrease priority of current headline.
18837 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18838 depending on context. See the individual commands for more information."
18839 (interactive "P")
18840 (cond
18841 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18842 ((and org-support-shift-select (org-region-active-p))
18843 (org-call-for-shift-select 'next-line))
18844 ((org-at-timestamp-p t)
18845 (call-interactively (if org-edit-timestamp-down-means-later
18846 'org-timestamp-up 'org-timestamp-down)))
18847 ((and (not (eq org-support-shift-select 'always))
18848 org-enable-priority-commands
18849 (org-at-heading-p))
18850 (call-interactively 'org-priority-down))
18851 ((and (not org-support-shift-select) (org-at-item-p))
18852 (call-interactively 'org-next-item))
18853 ((org-clocktable-try-shift 'down arg))
18854 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18855 (org-support-shift-select
18856 (org-call-for-shift-select 'next-line))
18857 (t (org-shiftselect-error))))
18859 (defun org-shiftright (&optional arg)
18860 "Cycle the thing at point or in the current line, depending on context.
18861 Depending on context, this does one of the following:
18863 - switch a timestamp at point one day into the future
18864 - on a headline, switch to the next TODO keyword.
18865 - on an item, switch entire list to the next bullet type
18866 - on a property line, switch to the next allowed value
18867 - on a clocktable definition line, move time block into the future"
18868 (interactive "P")
18869 (cond
18870 ((run-hook-with-args-until-success 'org-shiftright-hook))
18871 ((and org-support-shift-select (org-region-active-p))
18872 (org-call-for-shift-select 'forward-char))
18873 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18874 ((and (not (eq org-support-shift-select 'always))
18875 (org-at-heading-p))
18876 (let ((org-inhibit-logging
18877 (not org-treat-S-cursor-todo-selection-as-state-change))
18878 (org-inhibit-blocking
18879 (not org-treat-S-cursor-todo-selection-as-state-change)))
18880 (org-call-with-arg 'org-todo 'right)))
18881 ((or (and org-support-shift-select
18882 (not (eq org-support-shift-select 'always))
18883 (org-at-item-bullet-p))
18884 (and (not org-support-shift-select) (org-at-item-p)))
18885 (org-call-with-arg 'org-cycle-list-bullet nil))
18886 ((and (not (eq org-support-shift-select 'always))
18887 (org-at-property-p))
18888 (call-interactively 'org-property-next-allowed-value))
18889 ((org-clocktable-try-shift 'right arg))
18890 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18891 (org-support-shift-select
18892 (org-call-for-shift-select 'forward-char))
18893 (t (org-shiftselect-error))))
18895 (defun org-shiftleft (&optional arg)
18896 "Cycle the thing at point or in the current line, depending on context.
18897 Depending on context, this does one of the following:
18899 - switch a timestamp at point one day into the past
18900 - on a headline, switch to the previous TODO keyword.
18901 - on an item, switch entire list to the previous bullet type
18902 - on a property line, switch to the previous allowed value
18903 - on a clocktable definition line, move time block into the past"
18904 (interactive "P")
18905 (cond
18906 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18907 ((and org-support-shift-select (org-region-active-p))
18908 (org-call-for-shift-select 'backward-char))
18909 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18910 ((and (not (eq org-support-shift-select 'always))
18911 (org-at-heading-p))
18912 (let ((org-inhibit-logging
18913 (not org-treat-S-cursor-todo-selection-as-state-change))
18914 (org-inhibit-blocking
18915 (not org-treat-S-cursor-todo-selection-as-state-change)))
18916 (org-call-with-arg 'org-todo 'left)))
18917 ((or (and org-support-shift-select
18918 (not (eq org-support-shift-select 'always))
18919 (org-at-item-bullet-p))
18920 (and (not org-support-shift-select) (org-at-item-p)))
18921 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18922 ((and (not (eq org-support-shift-select 'always))
18923 (org-at-property-p))
18924 (call-interactively 'org-property-previous-allowed-value))
18925 ((org-clocktable-try-shift 'left arg))
18926 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18927 (org-support-shift-select
18928 (org-call-for-shift-select 'backward-char))
18929 (t (org-shiftselect-error))))
18931 (defun org-shiftcontrolright ()
18932 "Switch to next TODO set."
18933 (interactive)
18934 (cond
18935 ((and org-support-shift-select (org-region-active-p))
18936 (org-call-for-shift-select 'forward-word))
18937 ((and (not (eq org-support-shift-select 'always))
18938 (org-at-heading-p))
18939 (org-call-with-arg 'org-todo 'nextset))
18940 (org-support-shift-select
18941 (org-call-for-shift-select 'forward-word))
18942 (t (org-shiftselect-error))))
18944 (defun org-shiftcontrolleft ()
18945 "Switch to previous TODO set."
18946 (interactive)
18947 (cond
18948 ((and org-support-shift-select (org-region-active-p))
18949 (org-call-for-shift-select 'backward-word))
18950 ((and (not (eq org-support-shift-select 'always))
18951 (org-at-heading-p))
18952 (org-call-with-arg 'org-todo 'previousset))
18953 (org-support-shift-select
18954 (org-call-for-shift-select 'backward-word))
18955 (t (org-shiftselect-error))))
18957 (defun org-shiftcontrolup ()
18958 "Change timestamps synchronously up in CLOCK log lines."
18959 (interactive)
18960 (cond ((and (not org-support-shift-select)
18961 (org-at-clock-log-p)
18962 (org-at-timestamp-p t))
18963 (org-clock-timestamps-up))
18964 (t (org-shiftselect-error))))
18966 (defun org-shiftcontroldown ()
18967 "Change timestamps synchronously down in CLOCK log lines."
18968 (interactive)
18969 (cond ((and (not org-support-shift-select)
18970 (org-at-clock-log-p)
18971 (org-at-timestamp-p t))
18972 (org-clock-timestamps-down))
18973 (t (org-shiftselect-error))))
18975 (defun org-ctrl-c-ret ()
18976 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18977 (interactive)
18978 (cond
18979 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18980 (t (call-interactively 'org-insert-heading))))
18982 (defun org-find-visible ()
18983 (let ((s (point)))
18984 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18985 (get-char-property s 'invisible)))
18987 (defun org-find-invisible ()
18988 (let ((s (point)))
18989 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18990 (not (get-char-property s 'invisible))))
18993 (defun org-copy-visible (beg end)
18994 "Copy the visible parts of the region."
18995 (interactive "r")
18996 (let (snippets s)
18997 (save-excursion
18998 (save-restriction
18999 (narrow-to-region beg end)
19000 (setq s (goto-char (point-min)))
19001 (while (not (= (point) (point-max)))
19002 (goto-char (org-find-invisible))
19003 (push (buffer-substring s (point)) snippets)
19004 (setq s (goto-char (org-find-visible))))))
19005 (kill-new (apply 'concat (nreverse snippets)))))
19007 (defun org-copy-special ()
19008 "Copy region in table or copy current subtree.
19009 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19010 See the individual commands for more information."
19011 (interactive)
19012 (call-interactively
19013 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19015 (defun org-cut-special ()
19016 "Cut region in table or cut current subtree.
19017 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19018 See the individual commands for more information."
19019 (interactive)
19020 (call-interactively
19021 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19023 (defun org-paste-special (arg)
19024 "Paste rectangular region into table, or past subtree relative to level.
19025 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19026 See the individual commands for more information."
19027 (interactive "P")
19028 (if (org-at-table-p)
19029 (org-table-paste-rectangle)
19030 (org-paste-subtree arg)))
19032 (defsubst org-in-fixed-width-region-p ()
19033 "Is point in a fixed-width region?"
19034 (save-match-data
19035 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19037 (defun org-edit-special (&optional arg)
19038 "Call a special editor for the stuff at point.
19039 When at a table, call the formula editor with `org-table-edit-formulas'.
19040 When in a source code block, call `org-edit-src-code'.
19041 When in a fixed-width region, call `org-edit-fixed-width-region'.
19042 When in an #+include line, visit the included file.
19043 On a link, call `ffap' to visit the link at point.
19044 Otherwise, return a user error."
19045 (interactive)
19046 ;; possibly prep session before editing source
19047 (when (and (org-in-src-block-p) arg)
19048 (let* ((info (org-babel-get-src-block-info))
19049 (lang (nth 0 info))
19050 (params (nth 2 info))
19051 (session (cdr (assoc :session params))))
19052 (when (and info session) ;; we are in a source-code block with a session
19053 (funcall
19054 (intern (concat "org-babel-prep-session:" lang)) session params))))
19055 (cond ;; proceed with `org-edit-special'
19056 ((save-excursion
19057 (beginning-of-line 1)
19058 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19059 (find-file (org-trim (match-string 1))))
19060 ((org-at-table.el-p) (org-edit-src-code))
19061 ((or (org-at-table-p)
19062 (save-excursion
19063 (beginning-of-line 1)
19064 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19065 (call-interactively 'org-table-edit-formulas))
19066 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19067 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19068 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19069 (t (user-error "No special environment to edit here"))))
19071 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19072 (defun org-ctrl-c-ctrl-c (&optional arg)
19073 "Set tags in headline, or update according to changed information at point.
19075 This command does many different things, depending on context:
19077 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19078 this is what we do.
19080 - If the cursor is on a statistics cookie, update it.
19082 - If the cursor is in a headline, prompt for tags and insert them
19083 into the current line, aligned to `org-tags-column'. When called
19084 with prefix arg, realign all tags in the current buffer.
19086 - If the cursor is in one of the special #+KEYWORD lines, this
19087 triggers scanning the buffer for these lines and updating the
19088 information.
19090 - If the cursor is inside a table, realign the table. This command
19091 works even if the automatic table editor has been turned off.
19093 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19094 the entire table.
19096 - If the cursor is at a footnote reference or definition, jump to
19097 the corresponding definition or references, respectively.
19099 - If the cursor is a the beginning of a dynamic block, update it.
19101 - If the current buffer is a capture buffer, close note and file it.
19103 - If the cursor is on a <<<target>>>, update radio targets and
19104 corresponding links in this buffer.
19106 - If the cursor is on a numbered item in a plain list, renumber the
19107 ordered list.
19109 - If the cursor is on a checkbox, toggle it.
19111 - If the cursor is on a code block, evaluate it. The variable
19112 `org-confirm-babel-evaluate' can be used to control prompting
19113 before code block evaluation, by default every code block
19114 evaluation requires confirmation. Code block evaluation can be
19115 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19116 (interactive "P")
19117 (let ((org-enable-table-editor t))
19118 (cond
19119 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19120 org-occur-highlights
19121 org-latex-fragment-image-overlays)
19122 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19123 (org-remove-occur-highlights)
19124 (org-remove-latex-fragment-image-overlays)
19125 (message "Temporary highlights/overlays removed from current buffer"))
19126 ((and (local-variable-p 'org-finish-function (current-buffer))
19127 (fboundp org-finish-function))
19128 (funcall org-finish-function))
19129 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19130 ((org-in-regexp org-ts-regexp-both)
19131 (org-timestamp-change 0 'day))
19132 ((or (looking-at org-property-start-re)
19133 (org-at-property-p))
19134 (call-interactively 'org-property-action))
19135 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19136 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19137 (or (org-at-heading-p) (org-at-item-p)))
19138 (call-interactively 'org-update-statistics-cookies))
19139 ((org-at-heading-p) (call-interactively 'org-set-tags))
19140 ((org-at-table.el-p)
19141 (message "Use C-c ' to edit table.el tables"))
19142 ((org-at-table-p)
19143 (org-table-maybe-eval-formula)
19144 (if arg
19145 (call-interactively 'org-table-recalculate)
19146 (org-table-maybe-recalculate-line))
19147 (call-interactively 'org-table-align)
19148 (orgtbl-send-table 'maybe))
19149 ((or (org-footnote-at-reference-p)
19150 (org-footnote-at-definition-p))
19151 (call-interactively 'org-footnote-action))
19152 ((org-at-item-checkbox-p)
19153 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19154 ;; list only if at top item.
19155 (let* ((cbox (match-string 1))
19156 (struct (org-list-struct))
19157 (old-struct (copy-tree struct))
19158 (parents (org-list-parents-alist struct))
19159 (orderedp (org-entry-get nil "ORDERED"))
19160 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19161 block-item)
19162 ;; Use a light version of `org-toggle-checkbox' to avoid
19163 ;; computing list structure twice.
19164 (let ((new-box (cond
19165 ((equal arg '(16)) "[-]")
19166 ((equal arg '(4)) nil)
19167 ((equal "[X]" cbox) "[ ]")
19168 (t "[X]"))))
19169 (if (and firstp arg)
19170 ;; If at first item of sub-list, remove check-box from
19171 ;; every item at the same level.
19172 (mapc
19173 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19174 (org-list-get-all-items
19175 (point-at-bol) struct (org-list-prevs-alist struct)))
19176 (org-list-set-checkbox (point-at-bol) struct new-box)))
19177 ;; Replicate `org-list-write-struct', while grabbing a return
19178 ;; value from `org-list-struct-fix-box'.
19179 (org-list-struct-fix-ind struct parents 2)
19180 (org-list-struct-fix-item-end struct)
19181 (let ((prevs (org-list-prevs-alist struct)))
19182 (org-list-struct-fix-bul struct prevs)
19183 (org-list-struct-fix-ind struct parents)
19184 (setq block-item
19185 (org-list-struct-fix-box struct parents prevs orderedp)))
19186 (if (equal struct old-struct)
19187 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19188 (org-list-struct-apply-struct struct old-struct)
19189 (org-update-checkbox-count-maybe))
19190 (when block-item
19191 (message
19192 "Checkboxes were removed due to unchecked box at line %d"
19193 (org-current-line block-item)))
19194 (when firstp (org-list-send-list 'maybe))))
19195 ((org-at-item-p)
19196 ;; Cursor at an item: repair list. Do checkbox related actions
19197 ;; only if function was called with an argument. Send list only
19198 ;; if at top item.
19199 (let* ((struct (org-list-struct))
19200 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19201 old-struct)
19202 (when arg
19203 (setq old-struct (copy-tree struct))
19204 (if firstp
19205 ;; If at first item of sub-list, add check-box to every
19206 ;; item at the same level.
19207 (mapc
19208 (lambda (pos)
19209 (unless (org-list-get-checkbox pos struct)
19210 (org-list-set-checkbox pos struct "[ ]")))
19211 (org-list-get-all-items
19212 (point-at-bol) struct (org-list-prevs-alist struct)))
19213 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19214 (org-list-write-struct
19215 struct (org-list-parents-alist struct) old-struct)
19216 (when arg (org-update-checkbox-count-maybe))
19217 (when firstp (org-list-send-list 'maybe))))
19218 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19219 ;; Dynamic block
19220 (beginning-of-line 1)
19221 (save-excursion (org-update-dblock)))
19222 ((save-excursion
19223 (let ((case-fold-search t))
19224 (beginning-of-line 1)
19225 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19226 (cond
19227 ((or (equal (match-string 1) "TBLFM")
19228 (equal (match-string 1) "tblfm"))
19229 ;; Recalculate the table before this line
19230 (save-excursion
19231 (beginning-of-line 1)
19232 (skip-chars-backward " \r\n\t")
19233 (if (org-at-table-p)
19234 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19236 (let ((org-inhibit-startup-visibility-stuff t)
19237 (org-startup-align-all-tables nil))
19238 (when (boundp 'org-table-coordinate-overlays)
19239 (mapc 'delete-overlay org-table-coordinate-overlays)
19240 (setq org-table-coordinate-overlays nil))
19241 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19242 (message "Local setup has been refreshed"))))
19243 ((org-clock-update-time-maybe))
19245 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19246 (error "C-c C-c can do nothing useful at this location"))))))
19248 (defun org-mode-restart ()
19249 "Restart Org-mode, to scan again for special lines.
19250 Also updates the keyword regular expressions."
19251 (interactive)
19252 (org-mode)
19253 (message "Org-mode restarted"))
19255 (defun org-kill-note-or-show-branches ()
19256 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19257 (interactive)
19258 (if (not org-finish-function)
19259 (progn
19260 (hide-subtree)
19261 (call-interactively 'show-branches))
19262 (let ((org-note-abort t))
19263 (funcall org-finish-function))))
19265 (defun org-return (&optional indent)
19266 "Goto next table row or insert a newline.
19267 Calls `org-table-next-row' or `newline', depending on context.
19268 See the individual commands for more information."
19269 (interactive)
19270 (let (org-ts-what)
19271 (cond
19272 ((or (bobp) (org-in-src-block-p))
19273 (if indent (newline-and-indent) (newline)))
19274 ((org-at-table-p)
19275 (org-table-justify-field-maybe)
19276 (call-interactively 'org-table-next-row))
19277 ;; when `newline-and-indent' is called within a list, make sure
19278 ;; text moved stays inside the item.
19279 ((and (org-in-item-p) indent)
19280 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19281 (progn
19282 (save-match-data (newline))
19283 (org-indent-line-to (length (match-string 0))))
19284 (let ((ind (org-get-indentation)))
19285 (newline)
19286 (if (org-looking-back org-list-end-re)
19287 (org-indent-line)
19288 (org-indent-line-to ind)))))
19289 ((and org-return-follows-link
19290 (org-at-timestamp-p t)
19291 (not (eq org-ts-what 'after)))
19292 (org-follow-timestamp-link))
19293 ((and org-return-follows-link
19294 (let ((tprop (get-text-property (point) 'face)))
19295 (or (eq tprop 'org-link)
19296 (and (listp tprop) (memq 'org-link tprop)))))
19297 (call-interactively 'org-open-at-point))
19298 ((and (org-at-heading-p)
19299 (looking-at
19300 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19301 (org-show-entry)
19302 (end-of-line 1)
19303 (newline))
19304 (t (if indent (newline-and-indent) (newline))))))
19306 (defun org-return-indent ()
19307 "Goto next table row or insert a newline and indent.
19308 Calls `org-table-next-row' or `newline-and-indent', depending on
19309 context. See the individual commands for more information."
19310 (interactive)
19311 (org-return t))
19313 (defun org-ctrl-c-star ()
19314 "Compute table, or change heading status of lines.
19315 Calls `org-table-recalculate' or `org-toggle-heading',
19316 depending on context."
19317 (interactive)
19318 (cond
19319 ((org-at-table-p)
19320 (call-interactively 'org-table-recalculate))
19322 ;; Convert all lines in region to list items
19323 (call-interactively 'org-toggle-heading))))
19325 (defun org-ctrl-c-minus ()
19326 "Insert separator line in table or modify bullet status of line.
19327 Also turns a plain line or a region of lines into list items.
19328 Calls `org-table-insert-hline', `org-toggle-item', or
19329 `org-cycle-list-bullet', depending on context."
19330 (interactive)
19331 (cond
19332 ((org-at-table-p)
19333 (call-interactively 'org-table-insert-hline))
19334 ((org-region-active-p)
19335 (call-interactively 'org-toggle-item))
19336 ((org-in-item-p)
19337 (call-interactively 'org-cycle-list-bullet))
19339 (call-interactively 'org-toggle-item))))
19341 (defun org-toggle-item (arg)
19342 "Convert headings or normal lines to items, items to normal lines.
19343 If there is no active region, only the current line is considered.
19345 If the first non blank line in the region is an headline, convert
19346 all headlines to items, shifting text accordingly.
19348 If it is an item, convert all items to normal lines.
19350 If it is normal text, change region into an item. With a prefix
19351 argument ARG, change each line in region into an item."
19352 (interactive "P")
19353 (let ((shift-text
19354 (function
19355 ;; Shift text in current section to IND, from point to END.
19356 ;; The function leaves point to END line.
19357 (lambda (ind end)
19358 (let ((min-i 1000) (end (copy-marker end)))
19359 ;; First determine the minimum indentation (MIN-I) of
19360 ;; the text.
19361 (save-excursion
19362 (catch 'exit
19363 (while (< (point) end)
19364 (let ((i (org-get-indentation)))
19365 (cond
19366 ;; Skip blank lines and inline tasks.
19367 ((looking-at "^[ \t]*$"))
19368 ((looking-at org-outline-regexp-bol))
19369 ;; We can't find less than 0 indentation.
19370 ((zerop i) (throw 'exit (setq min-i 0)))
19371 ((< i min-i) (setq min-i i))))
19372 (forward-line))))
19373 ;; Then indent each line so that a line indented to
19374 ;; MIN-I becomes indented to IND. Ignore blank lines
19375 ;; and inline tasks in the process.
19376 (let ((delta (- ind min-i)))
19377 (while (< (point) end)
19378 (unless (or (looking-at "^[ \t]*$")
19379 (looking-at org-outline-regexp-bol))
19380 (org-indent-line-to (+ (org-get-indentation) delta)))
19381 (forward-line)))))))
19382 (skip-blanks
19383 (function
19384 ;; Return beginning of first non-blank line, starting from
19385 ;; line at POS.
19386 (lambda (pos)
19387 (save-excursion
19388 (goto-char pos)
19389 (skip-chars-forward " \r\t\n")
19390 (point-at-bol)))))
19391 beg end)
19392 ;; Determine boundaries of changes.
19393 (if (org-region-active-p)
19394 (setq beg (funcall skip-blanks (region-beginning))
19395 end (copy-marker (region-end)))
19396 (setq beg (funcall skip-blanks (point-at-bol))
19397 end (copy-marker (point-at-eol))))
19398 ;; Depending on the starting line, choose an action on the text
19399 ;; between BEG and END.
19400 (org-with-limited-levels
19401 (save-excursion
19402 (goto-char beg)
19403 (cond
19404 ;; Case 1. Start at an item: de-itemize. Note that it only
19405 ;; happens when a region is active: `org-ctrl-c-minus'
19406 ;; would call `org-cycle-list-bullet' otherwise.
19407 ((org-at-item-p)
19408 (while (< (point) end)
19409 (when (org-at-item-p)
19410 (skip-chars-forward " \t")
19411 (delete-region (point) (match-end 0)))
19412 (forward-line)))
19413 ;; Case 2. Start at an heading: convert to items.
19414 ((org-at-heading-p)
19415 (let* ((bul (org-list-bullet-string "-"))
19416 (bul-len (length bul))
19417 ;; Indentation of the first heading. It should be
19418 ;; relative to the indentation of its parent, if any.
19419 (start-ind (save-excursion
19420 (cond
19421 ((not org-adapt-indentation) 0)
19422 ((not (outline-previous-heading)) 0)
19423 (t (length (match-string 0))))))
19424 ;; Level of first heading. Further headings will be
19425 ;; compared to it to determine hierarchy in the list.
19426 (ref-level (org-reduced-level (org-outline-level))))
19427 (while (< (point) end)
19428 (let* ((level (org-reduced-level (org-outline-level)))
19429 (delta (max 0 (- level ref-level))))
19430 ;; If current headline is less indented than the first
19431 ;; one, set it as reference, in order to preserve
19432 ;; subtrees.
19433 (when (< level ref-level) (setq ref-level level))
19434 (replace-match bul t t)
19435 (org-indent-line-to (+ start-ind (* delta bul-len)))
19436 ;; Ensure all text down to END (or SECTION-END) belongs
19437 ;; to the newly created item.
19438 (let ((section-end (save-excursion
19439 (or (outline-next-heading) (point)))))
19440 (forward-line)
19441 (funcall shift-text
19442 (+ start-ind (* (1+ delta) bul-len))
19443 (min end section-end)))))))
19444 ;; Case 3. Normal line with ARG: turn each non-item line into
19445 ;; an item.
19446 (arg
19447 (while (< (point) end)
19448 (unless (or (org-at-heading-p) (org-at-item-p))
19449 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19450 (replace-match
19451 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19452 (forward-line)))
19453 ;; Case 4. Normal line without ARG: make the first line of
19454 ;; region an item, and shift indentation of others
19455 ;; lines to set them as item's body.
19456 (t (let* ((bul (org-list-bullet-string "-"))
19457 (bul-len (length bul))
19458 (ref-ind (org-get-indentation)))
19459 (skip-chars-forward " \t")
19460 (insert bul)
19461 (forward-line)
19462 (while (< (point) end)
19463 ;; Ensure that lines less indented than first one
19464 ;; still get included in item body.
19465 (funcall shift-text
19466 (+ ref-ind bul-len)
19467 (min end (save-excursion (or (outline-next-heading)
19468 (point)))))
19469 (forward-line)))))))))
19471 (defun org-toggle-heading (&optional nstars)
19472 "Convert headings to normal text, or items or text to headings.
19473 If there is no active region, only the current line is considered.
19475 With a \\[universal-argument] prefix, convert the whole list at
19476 point into heading.
19478 In a region:
19480 - If the first non blank line is an headline, remove the stars
19481 from all headlines in the region.
19483 - If it is a normal line turn each and every normal line (i.e. not an
19484 heading or an item) in the region into a heading.
19486 - If it is a plain list item, turn all plain list items into headings.
19488 When converting a line into a heading, the number of stars is chosen
19489 such that the lines become children of the current entry. However,
19490 when a prefix argument is given, its value determines the number of
19491 stars to add."
19492 (interactive "P")
19493 (let ((skip-blanks
19494 (function
19495 ;; Return beginning of first non-blank line, starting from
19496 ;; line at POS.
19497 (lambda (pos)
19498 (save-excursion
19499 (goto-char pos)
19500 (while (org-at-comment-p) (forward-line))
19501 (skip-chars-forward " \r\t\n")
19502 (point-at-bol)))))
19503 beg end toggled)
19504 ;; Determine boundaries of changes. If a universal prefix has
19505 ;; been given, put the list in a region. If region ends at a bol,
19506 ;; do not consider the last line to be in the region.
19508 (when (and current-prefix-arg (org-at-item-p))
19509 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19510 (org-mark-element))
19512 (if (org-region-active-p)
19513 (setq beg (funcall skip-blanks (region-beginning))
19514 end (copy-marker (save-excursion
19515 (goto-char (region-end))
19516 (if (bolp) (point) (point-at-eol)))))
19517 (setq beg (funcall skip-blanks (point-at-bol))
19518 end (copy-marker (point-at-eol))))
19519 ;; Ensure inline tasks don't count as headings.
19520 (org-with-limited-levels
19521 (save-excursion
19522 (goto-char beg)
19523 (cond
19524 ;; Case 1. Started at an heading: de-star headings.
19525 ((org-at-heading-p)
19526 (while (< (point) end)
19527 (when (org-at-heading-p t)
19528 (looking-at org-outline-regexp) (replace-match "")
19529 (setq toggled t))
19530 (forward-line)))
19531 ;; Case 2. Started at an item: change items into headlines.
19532 ;; One star will be added by `org-list-to-subtree'.
19533 ((org-at-item-p)
19534 (let* ((stars (make-string
19535 (if nstars
19536 ;; subtract the star that will be added again by
19537 ;; `org-list-to-subtree'
19538 (1- (prefix-numeric-value current-prefix-arg))
19539 (or (org-current-level) 0))
19540 ?*))
19541 (add-stars
19542 (cond (nstars "") ; stars from prefix only
19543 ((equal stars "") "") ; before first heading
19544 (org-odd-levels-only "*") ; inside heading, odd
19545 (t "")))) ; inside heading, oddeven
19546 (while (< (point) end)
19547 (when (org-at-item-p)
19548 ;; Pay attention to cases when region ends before list.
19549 (let* ((struct (org-list-struct))
19550 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19551 (save-restriction
19552 (narrow-to-region (point) list-end)
19553 (insert
19554 (org-list-to-subtree
19555 (org-list-parse-list t)
19556 '(:istart (concat stars add-stars (funcall get-stars depth))
19557 :icount (concat stars add-stars (funcall get-stars depth)))))))
19558 (setq toggled t))
19559 (forward-line))))
19560 ;; Case 3. Started at normal text: make every line an heading,
19561 ;; skipping headlines and items.
19562 (t (let* ((stars (make-string
19563 (if nstars
19564 (prefix-numeric-value current-prefix-arg)
19565 (or (org-current-level) 0))
19566 ?*))
19567 (add-stars
19568 (cond (nstars "") ; stars from prefix only
19569 ((equal stars "") "*") ; before first heading
19570 (org-odd-levels-only "**") ; inside heading, odd
19571 (t "*"))) ; inside heading, oddeven
19572 (rpl (concat stars add-stars " ")))
19573 (while (< (point) end)
19574 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19575 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19576 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19577 (forward-line)))))))
19578 (unless toggled (message "Cannot toggle heading from here"))))
19580 (defun org-meta-return (&optional arg)
19581 "Insert a new heading or wrap a region in a table.
19582 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19583 See the individual commands for more information."
19584 (interactive "P")
19585 (cond
19586 ((run-hook-with-args-until-success 'org-metareturn-hook))
19587 ((or (org-at-drawer-p) (org-at-property-p))
19588 (newline-and-indent))
19589 ((org-at-table-p)
19590 (call-interactively 'org-table-wrap-region))
19591 (t (call-interactively 'org-insert-heading))))
19593 ;;; Menu entries
19595 (defsubst org-in-subtree-not-table-p ()
19596 "Are we in a subtree and not in a table?"
19597 (and (not (org-before-first-heading-p))
19598 (not (org-at-table-p))))
19600 ;; Define the Org-mode menus
19601 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19602 '("Tbl"
19603 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19604 ["Next Field" org-cycle (org-at-table-p)]
19605 ["Previous Field" org-shifttab (org-at-table-p)]
19606 ["Next Row" org-return (org-at-table-p)]
19607 "--"
19608 ["Blank Field" org-table-blank-field (org-at-table-p)]
19609 ["Edit Field" org-table-edit-field (org-at-table-p)]
19610 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19611 "--"
19612 ("Column"
19613 ["Move Column Left" org-metaleft (org-at-table-p)]
19614 ["Move Column Right" org-metaright (org-at-table-p)]
19615 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19616 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19617 ("Row"
19618 ["Move Row Up" org-metaup (org-at-table-p)]
19619 ["Move Row Down" org-metadown (org-at-table-p)]
19620 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19621 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19622 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19623 "--"
19624 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19625 ("Rectangle"
19626 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19627 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19628 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19629 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19630 "--"
19631 ("Calculate"
19632 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19633 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19634 ["Edit Formulas" org-edit-special (org-at-table-p)]
19635 "--"
19636 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19637 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19638 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19639 "--"
19640 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19641 "--"
19642 ["Sum Column/Rectangle" org-table-sum
19643 (or (org-at-table-p) (org-region-active-p))]
19644 ["Which Column?" org-table-current-column (org-at-table-p)])
19645 ["Debug Formulas"
19646 org-table-toggle-formula-debugger
19647 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19648 ["Show Col/Row Numbers"
19649 org-table-toggle-coordinate-overlays
19650 :style toggle
19651 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19652 "--"
19653 ["Create" org-table-create (and (not (org-at-table-p))
19654 org-enable-table-editor)]
19655 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19656 ["Import from File" org-table-import (not (org-at-table-p))]
19657 ["Export to File" org-table-export (org-at-table-p)]
19658 "--"
19659 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19661 (easy-menu-define org-org-menu org-mode-map "Org menu"
19662 '("Org"
19663 ("Show/Hide"
19664 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19665 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19666 ["Sparse Tree..." org-sparse-tree t]
19667 ["Reveal Context" org-reveal t]
19668 ["Show All" show-all t]
19669 "--"
19670 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19671 "--"
19672 ["New Heading" org-insert-heading t]
19673 ("Navigate Headings"
19674 ["Up" outline-up-heading t]
19675 ["Next" outline-next-visible-heading t]
19676 ["Previous" outline-previous-visible-heading t]
19677 ["Next Same Level" outline-forward-same-level t]
19678 ["Previous Same Level" outline-backward-same-level t]
19679 "--"
19680 ["Jump" org-goto t])
19681 ("Edit Structure"
19682 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19683 "--"
19684 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19685 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19686 "--"
19687 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19688 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19689 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19690 "--"
19691 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19692 "--"
19693 ["Copy visible text" org-copy-visible t]
19694 "--"
19695 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19696 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19697 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19698 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19699 "--"
19700 ["Sort Region/Children" org-sort t]
19701 "--"
19702 ["Convert to odd levels" org-convert-to-odd-levels t]
19703 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19704 ("Editing"
19705 ["Emphasis..." org-emphasize t]
19706 ["Edit Source Example" org-edit-special t]
19707 "--"
19708 ["Footnote new/jump" org-footnote-action t]
19709 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19710 ("Archive"
19711 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19712 "--"
19713 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19714 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19715 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19717 "--"
19718 ("Hyperlinks"
19719 ["Store Link (Global)" org-store-link t]
19720 ["Find existing link to here" org-occur-link-in-agenda-files t]
19721 ["Insert Link" org-insert-link t]
19722 ["Follow Link" org-open-at-point t]
19723 "--"
19724 ["Next link" org-next-link t]
19725 ["Previous link" org-previous-link t]
19726 "--"
19727 ["Descriptive Links"
19728 org-toggle-link-display
19729 :style radio
19730 :selected org-descriptive-links
19732 ["Literal Links"
19733 org-toggle-link-display
19734 :style radio
19735 :selected (not org-descriptive-links)])
19736 "--"
19737 ("TODO Lists"
19738 ["TODO/DONE/-" org-todo t]
19739 ("Select keyword"
19740 ["Next keyword" org-shiftright (org-at-heading-p)]
19741 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19742 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19743 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19744 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19745 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19746 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19747 "--"
19748 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19749 :selected org-enforce-todo-dependencies :style toggle :active t]
19750 "Settings for tree at point"
19751 ["Do Children sequentially" org-toggle-ordered-property :style radio
19752 :selected (org-entry-get nil "ORDERED")
19753 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19754 ["Do Children parallel" org-toggle-ordered-property :style radio
19755 :selected (not (org-entry-get nil "ORDERED"))
19756 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19757 "--"
19758 ["Set Priority" org-priority t]
19759 ["Priority Up" org-shiftup t]
19760 ["Priority Down" org-shiftdown t]
19761 "--"
19762 ["Get news from all feeds" org-feed-update-all t]
19763 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19764 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19765 ("TAGS and Properties"
19766 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19767 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19768 "--"
19769 ["Set property" org-set-property (not (org-before-first-heading-p))]
19770 ["Column view of properties" org-columns t]
19771 ["Insert Column View DBlock" org-insert-columns-dblock t])
19772 ("Dates and Scheduling"
19773 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19774 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19775 ("Change Date"
19776 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19777 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19778 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19779 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19780 ["Compute Time Range" org-evaluate-time-range t]
19781 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19782 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19783 "--"
19784 ["Custom time format" org-toggle-time-stamp-overlays
19785 :style radio :selected org-display-custom-times]
19786 "--"
19787 ["Goto Calendar" org-goto-calendar t]
19788 ["Date from Calendar" org-date-from-calendar t]
19789 "--"
19790 ["Start/Restart Timer" org-timer-start t]
19791 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19792 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19793 ["Insert Timer String" org-timer t]
19794 ["Insert Timer Item" org-timer-item t])
19795 ("Logging work"
19796 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19797 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19798 ["Clock out" org-clock-out t]
19799 ["Clock cancel" org-clock-cancel t]
19800 "--"
19801 ["Mark as default task" org-clock-mark-default-task t]
19802 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19803 ["Goto running clock" org-clock-goto t]
19804 "--"
19805 ["Display times" org-clock-display t]
19806 ["Create clock table" org-clock-report t]
19807 "--"
19808 ["Record DONE time"
19809 (progn (setq org-log-done (not org-log-done))
19810 (message "Switching to %s will %s record a timestamp"
19811 (car org-done-keywords)
19812 (if org-log-done "automatically" "not")))
19813 :style toggle :selected org-log-done])
19814 "--"
19815 ["Agenda Command..." org-agenda t]
19816 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19817 ("File List for Agenda")
19818 ("Special views current file"
19819 ["TODO Tree" org-show-todo-tree t]
19820 ["Check Deadlines" org-check-deadlines t]
19821 ["Timeline" org-timeline t]
19822 ["Tags/Property tree" org-match-sparse-tree t])
19823 "--"
19824 ["Export/Publish..." org-export t]
19825 ("LaTeX"
19826 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19827 :selected org-cdlatex-mode]
19828 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19829 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19830 ["Modify math symbol" org-cdlatex-math-modify
19831 (org-inside-LaTeX-fragment-p)]
19832 ["Insert citation" org-reftex-citation t]
19833 "--"
19834 ["Template for BEAMER" (progn (require 'org-beamer)
19835 (org-insert-beamer-options-template)) t])
19836 "--"
19837 ("MobileOrg"
19838 ["Push Files and Views" org-mobile-push t]
19839 ["Get Captured and Flagged" org-mobile-pull t]
19840 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19841 "--"
19842 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19843 "--"
19844 ("Documentation"
19845 ["Show Version" org-version t]
19846 ["Info Documentation" org-info t])
19847 ("Customize"
19848 ["Browse Org Group" org-customize t]
19849 "--"
19850 ["Expand This Menu" org-create-customize-menu
19851 (fboundp 'customize-menu-create)])
19852 ["Send bug report" org-submit-bug-report t]
19853 "--"
19854 ("Refresh/Reload"
19855 ["Refresh setup current buffer" org-mode-restart t]
19856 ["Reload Org (after update)" org-reload t]
19857 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
19860 (defun org-info (&optional node)
19861 "Read documentation for Org-mode in the info system.
19862 With optional NODE, go directly to that node."
19863 (interactive)
19864 (info (format "(org)%s" (or node ""))))
19866 ;;;###autoload
19867 (defun org-submit-bug-report ()
19868 "Submit a bug report on Org-mode via mail.
19870 Don't hesitate to report any problems or inaccurate documentation.
19872 If you don't have setup sending mail from (X)Emacs, please copy the
19873 output buffer into your mail program, as it gives us important
19874 information about your Org-mode version and configuration."
19875 (interactive)
19876 (require 'reporter)
19877 (org-load-modules-maybe)
19878 (org-require-autoloaded-modules)
19879 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19880 (reporter-submit-bug-report
19881 "emacs-orgmode@gnu.org"
19882 (org-version nil 'full)
19883 (let (list)
19884 (save-window-excursion
19885 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19886 (delete-other-windows)
19887 (erase-buffer)
19888 (insert "You are about to submit a bug report to the Org-mode mailing list.
19890 We would like to add your full Org-mode and Outline configuration to the
19891 bug report. This greatly simplifies the work of the maintainer and
19892 other experts on the mailing list.
19894 HOWEVER, some variables you have customized may contain private
19895 information. The names of customers, colleagues, or friends, might
19896 appear in the form of file names, tags, todo states, or search strings.
19897 If you answer yes to the prompt, you might want to check and remove
19898 such private information before sending the email.")
19899 (add-text-properties (point-min) (point-max) '(face org-warning))
19900 (when (yes-or-no-p "Include your Org-mode configuration ")
19901 (mapatoms
19902 (lambda (v)
19903 (and (boundp v)
19904 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19905 (or (and (symbol-value v)
19906 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19907 (and
19908 (get v 'custom-type) (get v 'standard-value)
19909 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19910 (push v list)))))
19911 (kill-buffer (get-buffer "*Warn about privacy*"))
19912 list))
19913 nil nil
19914 "Remember to cover the basics, that is, what you expected to happen and
19915 what in fact did happen. You don't know how to make a good report? See
19917 http://orgmode.org/manual/Feedback.html#Feedback
19919 Your bug report will be posted to the Org-mode mailing list.
19920 ------------------------------------------------------------------------")
19921 (save-excursion
19922 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19923 (replace-match "\\1Bug: \\3 [\\2]")))))
19926 (defun org-install-agenda-files-menu ()
19927 (let ((bl (buffer-list)))
19928 (save-excursion
19929 (while bl
19930 (set-buffer (pop bl))
19931 (if (derived-mode-p 'org-mode) (setq bl nil)))
19932 (when (derived-mode-p 'org-mode)
19933 (easy-menu-change
19934 '("Org") "File List for Agenda"
19935 (append
19936 (list
19937 ["Edit File List" (org-edit-agenda-file-list) t]
19938 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19939 ["Remove Current File from List" org-remove-file t]
19940 ["Cycle through agenda files" org-cycle-agenda-files t]
19941 ["Occur in all agenda files" org-occur-in-agenda-files t]
19942 "--")
19943 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19945 ;;;; Documentation
19947 (defun org-require-autoloaded-modules ()
19948 (interactive)
19949 (mapc 'require
19950 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19951 org-docbook org-exp org-html org-icalendar
19952 org-id org-latex
19953 org-publish org-remember org-table
19954 org-timer org-xoxo)))
19956 ;;;###autoload
19957 (defun org-reload (&optional uncompiled)
19958 "Reload all org lisp files.
19959 With prefix arg UNCOMPILED, load the uncompiled versions."
19960 (interactive "P")
19961 (require 'find-func)
19962 (let* ((file-re "^org\\(-.*\\)?\\.el")
19963 (dir-org (file-name-directory (org-find-library-dir "org")))
19964 (dir-org-contrib (ignore-errors
19965 (file-name-directory
19966 (org-find-library-dir "org-contribdir"))))
19967 (babel-files
19968 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19969 (append (list nil "comint" "eval" "exp" "keys"
19970 "lob" "ref" "table" "tangle")
19971 (delq nil
19972 (mapcar
19973 (lambda (lang)
19974 (when (cdr lang) (symbol-name (car lang))))
19975 org-babel-load-languages)))))
19976 (files
19977 (append babel-files
19978 (and dir-org-contrib
19979 (directory-files dir-org-contrib t file-re))
19980 (directory-files dir-org t file-re)))
19981 (remove-re (concat (if (featurep 'xemacs)
19982 "org-colview" "org-colview-xemacs")
19983 "\\'")))
19984 (setq files (mapcar 'file-name-sans-extension files))
19985 (setq files (mapcar
19986 (lambda (x) (if (string-match remove-re x) nil x))
19987 files))
19988 (setq files (delq nil files))
19989 (mapc
19990 (lambda (f)
19991 (when (featurep (intern (file-name-nondirectory f)))
19992 (if (and (not uncompiled)
19993 (file-exists-p (concat f ".elc")))
19994 (load (concat f ".elc") nil nil 'nosuffix)
19995 (load (concat f ".el") nil nil 'nosuffix))))
19996 files)
19997 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19998 (org-version nil 'full 'message))
20000 ;;;###autoload
20001 (defun org-customize ()
20002 "Call the customize function with org as argument."
20003 (interactive)
20004 (org-load-modules-maybe)
20005 (org-require-autoloaded-modules)
20006 (customize-browse 'org))
20008 (defun org-create-customize-menu ()
20009 "Create a full customization menu for Org-mode, insert it into the menu."
20010 (interactive)
20011 (org-load-modules-maybe)
20012 (org-require-autoloaded-modules)
20013 (if (fboundp 'customize-menu-create)
20014 (progn
20015 (easy-menu-change
20016 '("Org") "Customize"
20017 `(["Browse Org group" org-customize t]
20018 "--"
20019 ,(customize-menu-create 'org)
20020 ["Set" Custom-set t]
20021 ["Save" Custom-save t]
20022 ["Reset to Current" Custom-reset-current t]
20023 ["Reset to Saved" Custom-reset-saved t]
20024 ["Reset to Standard Settings" Custom-reset-standard t]))
20025 (message "\"Org\"-menu now contains full customization menu"))
20026 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20028 ;;;; Miscellaneous stuff
20030 ;;; Generally useful functions
20032 (defun org-get-at-bol (property)
20033 "Get text property PROPERTY at beginning of line."
20034 (get-text-property (point-at-bol) property))
20036 (defun org-find-text-property-in-string (prop s)
20037 "Return the first non-nil value of property PROP in string S."
20038 (or (get-text-property 0 prop s)
20039 (get-text-property (or (next-single-property-change 0 prop s) 0)
20040 prop s)))
20042 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20043 "Display the given MESSAGE as a warning."
20044 (if (fboundp 'display-warning)
20045 (display-warning 'org message
20046 (if (featurep 'xemacs) 'warning :warning))
20047 (let ((buf (get-buffer-create "*Org warnings*")))
20048 (with-current-buffer buf
20049 (goto-char (point-max))
20050 (insert "Warning (Org): " message)
20051 (unless (bolp)
20052 (newline)))
20053 (display-buffer buf)
20054 (sit-for 0))))
20056 (defun org-eval (form)
20057 "Eval FORM and return result."
20058 (condition-case error
20059 (eval form)
20060 (error (format "%%![Error: %s]" error))))
20062 (defun org-in-clocktable-p ()
20063 "Check if the cursor is in a clocktable."
20064 (let ((pos (point)) start)
20065 (save-excursion
20066 (end-of-line 1)
20067 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20068 (setq start (match-beginning 0))
20069 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20070 (>= (match-end 0) pos)
20071 start))))
20073 (defun org-in-commented-line ()
20074 "Is point in a line starting with `#'?"
20075 (equal (char-after (point-at-bol)) ?#))
20077 (defun org-in-indented-comment-line ()
20078 "Is point in a line starting with `#' after some white space?"
20079 (save-excursion
20080 (save-match-data
20081 (goto-char (point-at-bol))
20082 (looking-at "[ \t]*#"))))
20084 (defun org-in-verbatim-emphasis ()
20085 (save-match-data
20086 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20088 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20089 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20090 (if (and marker (marker-buffer marker)
20091 (buffer-live-p (marker-buffer marker)))
20092 (progn
20093 (org-pop-to-buffer-same-window (marker-buffer marker))
20094 (if (or (> marker (point-max)) (< marker (point-min)))
20095 (widen))
20096 (goto-char marker)
20097 (org-show-context 'org-goto))
20098 (if bookmark
20099 (bookmark-jump bookmark)
20100 (error "Cannot find location"))))
20102 (defun org-quote-csv-field (s)
20103 "Quote field for inclusion in CSV material."
20104 (if (string-match "[\",]" s)
20105 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20108 (defun org-force-self-insert (N)
20109 "Needed to enforce self-insert under remapping."
20110 (interactive "p")
20111 (self-insert-command N))
20113 (defun org-string-width (s)
20114 "Compute width of string, ignoring invisible characters.
20115 This ignores character with invisibility property `org-link', and also
20116 characters with property `org-cwidth', because these will become invisible
20117 upon the next fontification round."
20118 (let (b l)
20119 (when (or (eq t buffer-invisibility-spec)
20120 (assq 'org-link buffer-invisibility-spec))
20121 (while (setq b (text-property-any 0 (length s)
20122 'invisible 'org-link s))
20123 (setq s (concat (substring s 0 b)
20124 (substring s (or (next-single-property-change
20125 b 'invisible s) (length s)))))))
20126 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20127 (setq s (concat (substring s 0 b)
20128 (substring s (or (next-single-property-change
20129 b 'org-cwidth s) (length s))))))
20130 (setq l (string-width s) b -1)
20131 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20132 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20135 (defun org-shorten-string (s maxlength)
20136 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20137 If the string is shorter or has length MAXLENGTH, just return the
20138 original string. If it is longer, the functions finds a space in the
20139 string, breaks this string off at that locations and adds three dots
20140 as ellipsis. Including the ellipsis, the string will not be longer
20141 than MAXLENGTH. If finding a good breaking point in the string does
20142 not work, the string is just chopped off in the middle of a word
20143 if necessary."
20144 (if (<= (length s) maxlength)
20146 (let* ((n (max (- maxlength 4) 1))
20147 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20148 (if (string-match re s)
20149 (concat (match-string 1 s) "...")
20150 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20152 (defun org-get-indentation (&optional line)
20153 "Get the indentation of the current line, interpreting tabs.
20154 When LINE is given, assume it represents a line and compute its indentation."
20155 (if line
20156 (if (string-match "^ *" (org-remove-tabs line))
20157 (match-end 0))
20158 (save-excursion
20159 (beginning-of-line 1)
20160 (skip-chars-forward " \t")
20161 (current-column))))
20163 (defun org-get-string-indentation (s)
20164 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20165 (let ((n -1) (i 0) (w tab-width) c)
20166 (catch 'exit
20167 (while (< (setq n (1+ n)) (length s))
20168 (setq c (aref s n))
20169 (cond ((= c ?\ ) (setq i (1+ i)))
20170 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20171 (t (throw 'exit t)))))
20174 (defun org-remove-tabs (s &optional width)
20175 "Replace tabulators in S with spaces.
20176 Assumes that s is a single line, starting in column 0."
20177 (setq width (or width tab-width))
20178 (while (string-match "\t" s)
20179 (setq s (replace-match
20180 (make-string
20181 (- (* width (/ (+ (match-beginning 0) width) width))
20182 (match-beginning 0)) ?\ )
20183 t t s)))
20186 (defun org-fix-indentation (line ind)
20187 "Fix indentation in LINE.
20188 IND is a cons cell with target and minimum indentation.
20189 If the current indentation in LINE is smaller than the minimum,
20190 leave it alone. If it is larger than ind, set it to the target."
20191 (let* ((l (org-remove-tabs line))
20192 (i (org-get-indentation l))
20193 (i1 (car ind)) (i2 (cdr ind)))
20194 (if (>= i i2) (setq l (substring line i2)))
20195 (if (> i1 0)
20196 (concat (make-string i1 ?\ ) l)
20197 l)))
20199 (defun org-remove-indentation (code &optional n)
20200 "Remove the maximum common indentation from the lines in CODE.
20201 N may optionally be the number of spaces to remove."
20202 (with-temp-buffer
20203 (insert code)
20204 (org-do-remove-indentation n)
20205 (buffer-string)))
20207 (defun org-do-remove-indentation (&optional n)
20208 "Remove the maximum common indentation from the buffer."
20209 (untabify (point-min) (point-max))
20210 (let ((min 10000) re)
20211 (if n
20212 (setq min n)
20213 (goto-char (point-min))
20214 (while (re-search-forward "^ *[^ \n]" nil t)
20215 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20216 (unless (or (= min 0) (= min 10000))
20217 (setq re (format "^ \\{%d\\}" min))
20218 (goto-char (point-min))
20219 (while (re-search-forward re nil t)
20220 (replace-match "")
20221 (end-of-line 1))
20222 min)))
20224 (defun org-fill-template (template alist)
20225 "Find each %key of ALIST in TEMPLATE and replace it."
20226 (let ((case-fold-search nil)
20227 entry key value)
20228 (setq alist (sort (copy-sequence alist)
20229 (lambda (a b) (< (length (car a)) (length (car b))))))
20230 (while (setq entry (pop alist))
20231 (setq template
20232 (replace-regexp-in-string
20233 (concat "%" (regexp-quote (car entry)))
20234 (or (cdr entry) "") template t t)))
20235 template))
20237 (defun org-base-buffer (buffer)
20238 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20239 (if (not buffer)
20240 buffer
20241 (or (buffer-base-buffer buffer)
20242 buffer)))
20244 (defun org-trim (s)
20245 "Remove whitespace at beginning and end of string."
20246 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20247 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20250 (defun org-wrap (string &optional width lines)
20251 "Wrap string to either a number of lines, or a width in characters.
20252 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20253 that costs. If there is a word longer than WIDTH, the text is actually
20254 wrapped to the length of that word.
20255 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20256 many lines, whatever width that takes.
20257 The return value is a list of lines, without newlines at the end."
20258 (let* ((words (org-split-string string "[ \t\n]+"))
20259 (maxword (apply 'max (mapcar 'org-string-width words)))
20260 w ll)
20261 (cond (width
20262 (org-do-wrap words (max maxword width)))
20263 (lines
20264 (setq w maxword)
20265 (setq ll (org-do-wrap words maxword))
20266 (if (<= (length ll) lines)
20268 (setq ll words)
20269 (while (> (length ll) lines)
20270 (setq w (1+ w))
20271 (setq ll (org-do-wrap words w)))
20272 ll))
20273 (t (error "Cannot wrap this")))))
20275 (defun org-do-wrap (words width)
20276 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20277 (let (lines line)
20278 (while words
20279 (setq line (pop words))
20280 (while (and words (< (+ (length line) (length (car words))) width))
20281 (setq line (concat line " " (pop words))))
20282 (setq lines (push line lines)))
20283 (nreverse lines)))
20285 (defun org-split-string (string &optional separators)
20286 "Splits STRING into substrings at SEPARATORS.
20287 No empty strings are returned if there are matches at the beginning
20288 and end of string."
20289 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20290 (start 0)
20291 notfirst
20292 (list nil))
20293 (while (and (string-match rexp string
20294 (if (and notfirst
20295 (= start (match-beginning 0))
20296 (< start (length string)))
20297 (1+ start) start))
20298 (< (match-beginning 0) (length string)))
20299 (setq notfirst t)
20300 (or (eq (match-beginning 0) 0)
20301 (and (eq (match-beginning 0) (match-end 0))
20302 (eq (match-beginning 0) start))
20303 (setq list
20304 (cons (substring string start (match-beginning 0))
20305 list)))
20306 (setq start (match-end 0)))
20307 (or (eq start (length string))
20308 (setq list
20309 (cons (substring string start)
20310 list)))
20311 (nreverse list)))
20313 (defun org-quote-vert (s)
20314 "Replace \"|\" with \"\\vert\"."
20315 (while (string-match "|" s)
20316 (setq s (replace-match "\\vert" t t s)))
20319 (defun org-uuidgen-p (s)
20320 "Is S an ID created by UUIDGEN?"
20321 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20323 (defun org-in-src-block-p (&optional inside)
20324 "Whether point is in a code source block.
20325 When INSIDE is non-nil, don't consider we are within a src block
20326 when point is at #+BEGIN_SRC or #+END_SRC."
20327 (let ((case-fold-search t) ov)
20328 (or (and (setq ov (overlays-at (point)))
20329 (memq 'org-block-background
20330 (overlay-properties (car ov))))
20331 (and (not inside)
20332 (save-match-data
20333 (save-excursion
20334 (beginning-of-line)
20335 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20337 (defun org-context ()
20338 "Return a list of contexts of the current cursor position.
20339 If several contexts apply, all are returned.
20340 Each context entry is a list with a symbol naming the context, and
20341 two positions indicating start and end of the context. Possible
20342 contexts are:
20344 :headline anywhere in a headline
20345 :headline-stars on the leading stars in a headline
20346 :todo-keyword on a TODO keyword (including DONE) in a headline
20347 :tags on the TAGS in a headline
20348 :priority on the priority cookie in a headline
20349 :item on the first line of a plain list item
20350 :item-bullet on the bullet/number of a plain list item
20351 :checkbox on the checkbox in a plain list item
20352 :table in an org-mode table
20353 :table-special on a special filed in a table
20354 :table-table in a table.el table
20355 :clocktable in a clocktable
20356 :src-block in a source block
20357 :link on a hyperlink
20358 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20359 :target on a <<target>>
20360 :radio-target on a <<<radio-target>>>
20361 :latex-fragment on a LaTeX fragment
20362 :latex-preview on a LaTeX fragment with overlaid preview image
20364 This function expects the position to be visible because it uses font-lock
20365 faces as a help to recognize the following contexts: :table-special, :link,
20366 and :keyword."
20367 (let* ((f (get-text-property (point) 'face))
20368 (faces (if (listp f) f (list f)))
20369 (case-fold-search t)
20370 (p (point)) clist o)
20371 ;; First the large context
20372 (cond
20373 ((org-at-heading-p t)
20374 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20375 (when (progn
20376 (beginning-of-line 1)
20377 (looking-at org-todo-line-tags-regexp))
20378 (push (org-point-in-group p 1 :headline-stars) clist)
20379 (push (org-point-in-group p 2 :todo-keyword) clist)
20380 (push (org-point-in-group p 4 :tags) clist))
20381 (goto-char p)
20382 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20383 (if (looking-at "\\[#[A-Z0-9]\\]")
20384 (push (org-point-in-group p 0 :priority) clist)))
20386 ((org-at-item-p)
20387 (push (org-point-in-group p 2 :item-bullet) clist)
20388 (push (list :item (point-at-bol)
20389 (save-excursion (org-end-of-item) (point)))
20390 clist)
20391 (and (org-at-item-checkbox-p)
20392 (push (org-point-in-group p 0 :checkbox) clist)))
20394 ((org-at-table-p)
20395 (push (list :table (org-table-begin) (org-table-end)) clist)
20396 (if (memq 'org-formula faces)
20397 (push (list :table-special
20398 (previous-single-property-change p 'face)
20399 (next-single-property-change p 'face)) clist)))
20400 ((org-at-table-p 'any)
20401 (push (list :table-table) clist)))
20402 (goto-char p)
20404 (let ((case-fold-search t))
20405 ;; New the "medium" contexts: clocktables, source blocks
20406 (cond ((org-in-clocktable-p)
20407 (push (list :clocktable
20408 (and (or (looking-at "#\\+BEGIN: clocktable")
20409 (search-backward "#+BEGIN: clocktable" nil t))
20410 (match-beginning 0))
20411 (and (re-search-forward "#\\+END:?" nil t)
20412 (match-end 0))) clist))
20413 ((org-in-src-block-p)
20414 (push (list :src-block
20415 (and (or (looking-at "#\\+BEGIN_SRC")
20416 (search-backward "#+BEGIN_SRC" nil t))
20417 (match-beginning 0))
20418 (and (search-forward "#+END_SRC" nil t)
20419 (match-beginning 0))) clist))))
20420 (goto-char p)
20422 ;; Now the small context
20423 (cond
20424 ((org-at-timestamp-p)
20425 (push (org-point-in-group p 0 :timestamp) clist))
20426 ((memq 'org-link faces)
20427 (push (list :link
20428 (previous-single-property-change p 'face)
20429 (next-single-property-change p 'face)) clist))
20430 ((memq 'org-special-keyword faces)
20431 (push (list :keyword
20432 (previous-single-property-change p 'face)
20433 (next-single-property-change p 'face)) clist))
20434 ((org-at-target-p)
20435 (push (org-point-in-group p 0 :target) clist)
20436 (goto-char (1- (match-beginning 0)))
20437 (if (looking-at org-radio-target-regexp)
20438 (push (org-point-in-group p 0 :radio-target) clist))
20439 (goto-char p))
20440 ((setq o (car (delq nil
20441 (mapcar
20442 (lambda (x)
20443 (if (memq x org-latex-fragment-image-overlays) x))
20444 (overlays-at (point))))))
20445 (push (list :latex-fragment
20446 (overlay-start o) (overlay-end o)) clist)
20447 (push (list :latex-preview
20448 (overlay-start o) (overlay-end o)) clist))
20449 ((org-inside-LaTeX-fragment-p)
20450 ;; FIXME: positions wrong.
20451 (push (list :latex-fragment (point) (point)) clist)))
20453 (setq clist (nreverse (delq nil clist)))
20454 clist))
20456 ;; FIXME: Compare with at-regexp-p Do we need both?
20457 (defun org-in-regexp (re &optional nlines visually)
20458 "Check if point is inside a match of regexp.
20459 Normally only the current line is checked, but you can include NLINES extra
20460 lines both before and after point into the search.
20461 If VISUALLY is set, require that the cursor is not after the match but
20462 really on, so that the block visually is on the match."
20463 (catch 'exit
20464 (let ((pos (point))
20465 (eol (point-at-eol (+ 1 (or nlines 0))))
20466 (inc (if visually 1 0)))
20467 (save-excursion
20468 (beginning-of-line (- 1 (or nlines 0)))
20469 (while (re-search-forward re eol t)
20470 (if (and (<= (match-beginning 0) pos)
20471 (>= (+ inc (match-end 0)) pos))
20472 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20474 (defun org-at-regexp-p (regexp)
20475 "Is point inside a match of REGEXP in the current line?"
20476 (catch 'exit
20477 (save-excursion
20478 (let ((pos (point)) (end (point-at-eol)))
20479 (beginning-of-line 1)
20480 (while (re-search-forward regexp end t)
20481 (if (and (<= (match-beginning 0) pos)
20482 (>= (match-end 0) pos))
20483 (throw 'exit t)))
20484 nil))))
20486 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20487 "Non-nil when point is between matches of START-RE and END-RE.
20489 Also return a non-nil value when point is on one of the matches.
20491 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20492 buffer positions. Default values are the positions of headlines
20493 surrounding the point.
20495 The functions returns a cons cell whose car (resp. cdr) is the
20496 position before START-RE (resp. after END-RE)."
20497 (save-match-data
20498 (let ((pos (point))
20499 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20500 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20501 beg end)
20502 (save-excursion
20503 ;; Point is on a block when on START-RE or if START-RE can be
20504 ;; found before it...
20505 (and (or (org-at-regexp-p start-re)
20506 (re-search-backward start-re limit-up t))
20507 (setq beg (match-beginning 0))
20508 ;; ... and END-RE after it...
20509 (goto-char (match-end 0))
20510 (re-search-forward end-re limit-down t)
20511 (> (setq end (match-end 0)) pos)
20512 ;; ... without another START-RE in-between.
20513 (goto-char (match-beginning 0))
20514 (not (re-search-backward start-re (1+ beg) t))
20515 ;; Return value.
20516 (cons beg end))))))
20518 (defun org-in-block-p (names)
20519 "Non-nil when point belongs to a block whose name belongs to NAMES.
20521 NAMES is a list of strings containing names of blocks.
20523 Return first block name matched, or nil. Beware that in case of
20524 nested blocks, the returned name may not belong to the closest
20525 block from point."
20526 (save-match-data
20527 (catch 'exit
20528 (let ((case-fold-search t)
20529 (lim-up (save-excursion (outline-previous-heading)))
20530 (lim-down (save-excursion (outline-next-heading))))
20531 (mapc (lambda (name)
20532 (let ((n (regexp-quote name)))
20533 (when (org-between-regexps-p
20534 (concat "^[ \t]*#\\+begin_" n)
20535 (concat "^[ \t]*#\\+end_" n)
20536 lim-up lim-down)
20537 (throw 'exit n))))
20538 names))
20539 nil)))
20541 (defun org-occur-in-agenda-files (regexp &optional nlines)
20542 "Call `multi-occur' with buffers for all agenda files."
20543 (interactive "sOrg-files matching: \np")
20544 (let* ((files (org-agenda-files))
20545 (tnames (mapcar 'file-truename files))
20546 (extra org-agenda-text-search-extra-files)
20548 (when (eq (car extra) 'agenda-archives)
20549 (setq extra (cdr extra))
20550 (setq files (org-add-archive-files files)))
20551 (while (setq f (pop extra))
20552 (unless (member (file-truename f) tnames)
20553 (add-to-list 'files f 'append)
20554 (add-to-list 'tnames (file-truename f) 'append)))
20555 (multi-occur
20556 (mapcar (lambda (x)
20557 (with-current-buffer
20558 (or (get-file-buffer x) (find-file-noselect x))
20559 (widen)
20560 (current-buffer)))
20561 files)
20562 regexp)))
20564 (if (boundp 'occur-mode-find-occurrence-hook)
20565 ;; Emacs 23
20566 (add-hook 'occur-mode-find-occurrence-hook
20567 (lambda ()
20568 (when (derived-mode-p 'org-mode)
20569 (org-reveal))))
20570 ;; Emacs 22
20571 (defadvice occur-mode-goto-occurrence
20572 (after org-occur-reveal activate)
20573 (and (derived-mode-p 'org-mode) (org-reveal)))
20574 (defadvice occur-mode-goto-occurrence-other-window
20575 (after org-occur-reveal activate)
20576 (and (derived-mode-p 'org-mode) (org-reveal)))
20577 (defadvice occur-mode-display-occurrence
20578 (after org-occur-reveal activate)
20579 (when (derived-mode-p 'org-mode)
20580 (let ((pos (occur-mode-find-occurrence)))
20581 (with-current-buffer (marker-buffer pos)
20582 (save-excursion
20583 (goto-char pos)
20584 (org-reveal)))))))
20586 (defun org-occur-link-in-agenda-files ()
20587 "Create a link and search for it in the agendas.
20588 The link is not stored in `org-stored-links', it is just created
20589 for the search purpose."
20590 (interactive)
20591 (let ((link (condition-case nil
20592 (org-store-link nil)
20593 (error "Unable to create a link to here"))))
20594 (org-occur-in-agenda-files (regexp-quote link))))
20596 (defun org-uniquify (list)
20597 "Remove duplicate elements from LIST."
20598 (let (res)
20599 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20600 res))
20602 (defun org-delete-all (elts list)
20603 "Remove all elements in ELTS from LIST."
20604 (while elts
20605 (setq list (delete (pop elts) list)))
20606 list)
20608 (defun org-count (cl-item cl-seq)
20609 "Count the number of occurrences of ITEM in SEQ.
20610 Taken from `count' in cl-seq.el with all keyword arguments removed."
20611 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20612 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20613 (while (< cl-start cl-end)
20614 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20615 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20616 (setq cl-start (1+ cl-start)))
20617 cl-count))
20619 (defun org-remove-if (predicate seq)
20620 "Remove everything from SEQ that fulfills PREDICATE."
20621 (let (res e)
20622 (while seq
20623 (setq e (pop seq))
20624 (if (not (funcall predicate e)) (push e res)))
20625 (nreverse res)))
20627 (defun org-remove-if-not (predicate seq)
20628 "Remove everything from SEQ that does not fulfill PREDICATE."
20629 (let (res e)
20630 (while seq
20631 (setq e (pop seq))
20632 (if (funcall predicate e) (push e res)))
20633 (nreverse res)))
20635 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20636 "Reduce two-argument FUNCTION across SEQ.
20637 Taken from `reduce' in cl-seq.el with all keyword arguments but
20638 \":initial-value\" removed."
20639 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20640 (cadr (memq :initial-value cl-keys)))
20641 (cl-seq (pop cl-seq))
20642 (t (funcall cl-func)))))
20643 (while cl-seq
20644 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20645 cl-accum))
20647 (defun org-back-over-empty-lines ()
20648 "Move backwards over whitespace, to the beginning of the first empty line.
20649 Returns the number of empty lines passed."
20650 (let ((pos (point)))
20651 (if (cdr (assoc 'heading org-blank-before-new-entry))
20652 (skip-chars-backward " \t\n\r")
20653 (unless (eobp)
20654 (forward-line -1)))
20655 (beginning-of-line 2)
20656 (goto-char (min (point) pos))
20657 (count-lines (point) pos)))
20659 (defun org-skip-whitespace ()
20660 (skip-chars-forward " \t\n\r"))
20662 (defun org-point-in-group (point group &optional context)
20663 "Check if POINT is in match-group GROUP.
20664 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20665 match. If the match group does not exist or point is not inside it,
20666 return nil."
20667 (and (match-beginning group)
20668 (>= point (match-beginning group))
20669 (<= point (match-end group))
20670 (if context
20671 (list context (match-beginning group) (match-end group))
20672 t)))
20674 (defun org-switch-to-buffer-other-window (&rest args)
20675 "Switch to buffer in a second window on the current frame.
20676 In particular, do not allow pop-up frames.
20677 Returns the newly created buffer."
20678 (org-no-popups
20679 (apply 'switch-to-buffer-other-window args)))
20681 (defun org-combine-plists (&rest plists)
20682 "Create a single property list from all plists in PLISTS.
20683 The process starts by copying the first list, and then setting properties
20684 from the other lists. Settings in the last list are the most significant
20685 ones and overrule settings in the other lists."
20686 (let ((rtn (copy-sequence (pop plists)))
20687 p v ls)
20688 (while plists
20689 (setq ls (pop plists))
20690 (while ls
20691 (setq p (pop ls) v (pop ls))
20692 (setq rtn (plist-put rtn p v))))
20693 rtn))
20695 (defun org-replace-escapes (string table)
20696 "Replace %-escapes in STRING with values in TABLE.
20697 TABLE is an association list with keys like \"%a\" and string values.
20698 The sequences in STRING may contain normal field width and padding information,
20699 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20700 so values can contain further %-escapes if they are define later in TABLE."
20701 (let ((tbl (copy-alist table))
20702 (case-fold-search nil)
20703 (pchg 0)
20704 e re rpl)
20705 (while (setq e (pop tbl))
20706 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20707 (when (and (cdr e) (string-match re (cdr e)))
20708 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20709 (safe "SREF"))
20710 (add-text-properties 0 3 (list 'sref sref) safe)
20711 (setcdr e (replace-match safe t t (cdr e)))))
20712 (while (string-match re string)
20713 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20714 (cdr e)))
20715 (setq string (replace-match rpl t t string))))
20716 (while (setq pchg (next-property-change pchg string))
20717 (let ((sref (get-text-property pchg 'sref string)))
20718 (when (and sref (string-match "SREF" string pchg))
20719 (setq string (replace-match sref t t string)))))
20720 string))
20722 (defun org-sublist (list start end)
20723 "Return a section of LIST, from START to END.
20724 Counting starts at 1."
20725 (let (rtn (c start))
20726 (setq list (nthcdr (1- start) list))
20727 (while (and list (<= c end))
20728 (push (pop list) rtn)
20729 (setq c (1+ c)))
20730 (nreverse rtn)))
20732 (defun org-find-base-buffer-visiting (file)
20733 "Like `find-buffer-visiting' but always return the base buffer and
20734 not an indirect buffer."
20735 (let ((buf (or (get-file-buffer file)
20736 (find-buffer-visiting file))))
20737 (if buf
20738 (or (buffer-base-buffer buf) buf)
20739 nil)))
20741 (defun org-image-file-name-regexp (&optional extensions)
20742 "Return regexp matching the file names of images.
20743 If EXTENSIONS is given, only match these."
20744 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20745 (image-file-name-regexp)
20746 (let ((image-file-name-extensions
20747 (or extensions
20748 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20749 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20750 (concat "\\."
20751 (regexp-opt (nconc (mapcar 'upcase
20752 image-file-name-extensions)
20753 image-file-name-extensions)
20755 "\\'"))))
20757 (defun org-file-image-p (file &optional extensions)
20758 "Return non-nil if FILE is an image."
20759 (save-match-data
20760 (string-match (org-image-file-name-regexp extensions) file)))
20762 (defun org-get-cursor-date ()
20763 "Return the date at cursor in as a time.
20764 This works in the calendar and in the agenda, anywhere else it just
20765 returns the current time."
20766 (let (date day defd)
20767 (cond
20768 ((eq major-mode 'calendar-mode)
20769 (setq date (calendar-cursor-to-date)
20770 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20771 ((eq major-mode 'org-agenda-mode)
20772 (setq day (get-text-property (point) 'day))
20773 (if day
20774 (setq date (calendar-gregorian-from-absolute day)
20775 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20776 (nth 2 date))))))
20777 (or defd (current-time))))
20779 (defun org-mark-subtree (&optional up)
20780 "Mark the current subtree.
20781 This puts point at the start of the current subtree, and mark at
20782 the end. If a numeric prefix UP is given, move up into the
20783 hierarchy of headlines by UP levels before marking the subtree."
20784 (interactive "P")
20785 (org-with-limited-levels
20786 (cond ((org-at-heading-p) (beginning-of-line))
20787 ((org-before-first-heading-p) (error "Not in a subtree"))
20788 (t (outline-previous-visible-heading 1))))
20789 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20790 (if (org-called-interactively-p 'any)
20791 (call-interactively 'org-mark-element)
20792 (org-mark-element)))
20794 ;;; Indentation
20796 (defun org-indent-line ()
20797 "Indent line depending on context."
20798 (interactive)
20799 (let* ((pos (point))
20800 (itemp (org-at-item-p))
20801 (case-fold-search t)
20802 (org-drawer-regexp (or org-drawer-regexp "\000"))
20803 (inline-task-p (and (featurep 'org-inlinetask)
20804 (org-inlinetask-in-task-p)))
20805 (inline-re (and inline-task-p
20806 (org-inlinetask-outline-regexp)))
20807 column)
20808 (if (and orgstruct-is-++ (eq pos (point)))
20809 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20810 (indent-according-to-mode))
20811 (beginning-of-line 1)
20812 (cond
20813 ;; Headings
20814 ((looking-at org-outline-regexp) (setq column 0))
20815 ;; Included files
20816 ((looking-at "#\\+include:") (setq column 0))
20817 ;; Footnote definition
20818 ((looking-at org-footnote-definition-re) (setq column 0))
20819 ;; Literal examples
20820 ((looking-at "[ \t]*:\\( \\|$\\)")
20821 (setq column (org-get-indentation))) ; do nothing
20822 ;; Lists
20823 ((ignore-errors (goto-char (org-in-item-p)))
20824 (setq column (if itemp
20825 (org-get-indentation)
20826 (org-list-item-body-column (point))))
20827 (goto-char pos))
20828 ;; Drawers
20829 ((and (looking-at "[ \t]*:END:")
20830 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20831 (save-excursion
20832 (goto-char (1- (match-beginning 1)))
20833 (setq column (current-column))))
20834 ;; Special blocks
20835 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20836 (save-excursion
20837 (re-search-backward
20838 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20839 (setq column (org-get-indentation (match-string 0))))
20840 ((and (not (looking-at "[ \t]*#\\+begin_"))
20841 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20842 (save-excursion
20843 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20844 (setq column
20845 (cond ((equal (downcase (match-string 1)) "src")
20846 ;; src blocks: let `org-edit-src-exit' handle them
20847 (org-get-indentation))
20848 ((equal (downcase (match-string 1)) "example")
20849 (max (org-get-indentation)
20850 (org-get-indentation (match-string 0))))
20852 (org-get-indentation (match-string 0))))))
20853 ;; This line has nothing special, look at the previous relevant
20854 ;; line to compute indentation
20856 (beginning-of-line 0)
20857 (while (and (not (bobp))
20858 (not (looking-at org-table-line-regexp))
20859 (not (looking-at org-drawer-regexp))
20860 ;; When point started in an inline task, do not move
20861 ;; above task starting line.
20862 (not (and inline-task-p (looking-at inline-re)))
20863 ;; Skip drawers, blocks, empty lines, verbatim,
20864 ;; comments, tables, footnotes definitions, lists,
20865 ;; inline tasks.
20866 (or (and (looking-at "[ \t]*:END:")
20867 (re-search-backward org-drawer-regexp nil t))
20868 (and (looking-at "[ \t]*#\\+end_")
20869 (re-search-backward "[ \t]*#\\+begin_"nil t))
20870 (looking-at "[ \t]*[\n:#|]")
20871 (looking-at org-footnote-definition-re)
20872 (and (ignore-errors (goto-char (org-in-item-p)))
20873 (goto-char
20874 (org-list-get-top-point (org-list-struct))))
20875 (and (not inline-task-p)
20876 (featurep 'org-inlinetask)
20877 (org-inlinetask-in-task-p)
20878 (or (org-inlinetask-goto-beginning) t))))
20879 (beginning-of-line 0))
20880 (cond
20881 ;; There was an heading above.
20882 ((looking-at "\\*+[ \t]+")
20883 (if (not org-adapt-indentation)
20884 (setq column 0)
20885 (goto-char (match-end 0))
20886 (setq column (current-column))))
20887 ;; A drawer had started and is unfinished
20888 ((looking-at org-drawer-regexp)
20889 (goto-char (1- (match-beginning 1)))
20890 (setq column (current-column)))
20891 ;; Else, nothing noticeable found: get indentation and go on.
20892 (t (setq column (org-get-indentation))))))
20893 ;; Now apply indentation and move cursor accordingly
20894 (goto-char pos)
20895 (if (<= (current-column) (current-indentation))
20896 (org-indent-line-to column)
20897 (save-excursion (org-indent-line-to column)))
20898 ;; Special polishing for properties, see `org-property-format'
20899 (setq column (current-column))
20900 (beginning-of-line 1)
20901 (if (looking-at
20902 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20903 (replace-match (concat (match-string 1)
20904 (format org-property-format
20905 (match-string 2) (match-string 3)))
20906 t t))
20907 (org-move-to-column column))))
20909 (defun org-indent-drawer ()
20910 "Indent the drawer at point."
20911 (interactive)
20912 (let ((p (point))
20913 (e (and (save-excursion (re-search-forward ":END:" nil t))
20914 (match-end 0)))
20915 (folded
20916 (save-excursion
20917 (end-of-line)
20918 (when (overlays-at (point))
20919 (member 'invisible (overlay-properties
20920 (car (overlays-at (point)))))))))
20921 (when folded (org-cycle))
20922 (indent-for-tab-command)
20923 (while (and (move-beginning-of-line 2) (< (point) e))
20924 (indent-for-tab-command))
20925 (goto-char p)
20926 (when folded (org-cycle)))
20927 (message "Drawer at point indented"))
20929 (defun org-indent-block ()
20930 "Indent the block at point."
20931 (interactive)
20932 (let ((p (point))
20933 (case-fold-search t)
20934 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20935 (match-end 0)))
20936 (folded
20937 (save-excursion
20938 (end-of-line)
20939 (when (overlays-at (point))
20940 (member 'invisible (overlay-properties
20941 (car (overlays-at (point)))))))))
20942 (when folded (org-cycle))
20943 (indent-for-tab-command)
20944 (while (and (move-beginning-of-line 2) (< (point) e))
20945 (indent-for-tab-command))
20946 (goto-char p)
20947 (when folded (org-cycle)))
20948 (message "Block at point indented"))
20950 (defun org-indent-region (start end)
20951 "Indent region."
20952 (interactive "r")
20953 (save-excursion
20954 (let ((line-end (org-current-line end)))
20955 (goto-char start)
20956 (while (< (org-current-line) line-end)
20957 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20958 (t (call-interactively 'org-indent-line)))
20959 (move-beginning-of-line 2)))))
20962 ;;; Filling
20964 ;; We use our own fill-paragraph and auto-fill functions.
20966 ;; `org-fill-paragraph' relies on adaptive filling and context
20967 ;; checking. Appropriate `fill-prefix' is computed with
20968 ;; `org-adaptive-fill-function'.
20970 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20971 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20972 ;; `org-adaptive-fill-function' value. Internally,
20973 ;; `org-comment-line-break-function' breaks the line.
20975 ;; `org-setup-filling' installs filling and auto-filling related
20976 ;; variables during `org-mode' initialization.
20978 (defun org-setup-filling ()
20979 (interactive)
20980 ;; Prevent auto-fill from inserting unwanted new items.
20981 (when (boundp 'fill-nobreak-predicate)
20982 (org-set-local
20983 'fill-nobreak-predicate
20984 (org-uniquify
20985 (append fill-nobreak-predicate
20986 '(org-fill-paragraph-separate-nobreak-p
20987 org-fill-line-break-nobreak-p
20988 org-fill-paragraph-with-timestamp-nobreak-p)))))
20989 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20990 (org-set-local 'auto-fill-inhibit-regexp nil)
20991 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20992 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20993 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20995 (defvar org-element-paragraph-separate) ; org-element.el
20996 (defun org-fill-paragraph-separate-nobreak-p ()
20997 "Non-nil when a line break at point would insert a new item."
20998 (looking-at (substring org-element-paragraph-separate 1)))
21000 (defun org-fill-line-break-nobreak-p ()
21001 "Non-nil when a line break at point would create an Org line break."
21002 (save-excursion
21003 (skip-chars-backward "[ \t]")
21004 (skip-chars-backward "\\\\")
21005 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21007 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21008 "Non-nil when a line break at point would insert a new item."
21009 (and (org-at-timestamp-p t)
21010 (not (looking-at org-ts-regexp-both))))
21012 (declare-function message-in-body-p "message" ())
21013 (defvar org-element--affiliated-re) ; From org-element.el
21014 (defvar orgtbl-line-start-regexp) ; From org-table.el
21015 (defun org-adaptive-fill-function ()
21016 "Compute a fill prefix for the current line.
21017 Return fill prefix, as a string, or nil if current line isn't
21018 meant to be filled."
21019 (let (prefix)
21020 (catch 'exit
21021 (when (derived-mode-p 'message-mode)
21022 (save-excursion
21023 (beginning-of-line)
21024 (cond ((or (not (message-in-body-p))
21025 (looking-at orgtbl-line-start-regexp))
21026 (throw 'exit nil))
21027 ((looking-at message-cite-prefix-regexp)
21028 (throw 'exit (match-string-no-properties 0)))
21029 ((looking-at org-outline-regexp)
21030 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21031 (org-with-wide-buffer
21032 (let* ((p (line-beginning-position))
21033 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21034 (type (org-element-type element))
21035 (post-affiliated
21036 (save-excursion
21037 (goto-char (org-element-property :begin element))
21038 (while (looking-at org-element--affiliated-re) (forward-line))
21039 (point))))
21040 (unless (< p post-affiliated)
21041 (case type
21042 (comment (looking-at "[ \t]*# ?") (match-string 0))
21043 (footnote-definition "")
21044 ((item plain-list)
21045 (make-string (org-list-item-body-column post-affiliated) ? ))
21046 (paragraph
21047 ;; Fill prefix is usually the same as the current line,
21048 ;; except if the paragraph is at the beginning of an item.
21049 (let ((parent (org-element-property :parent element)))
21050 (cond ((eq (org-element-type parent) 'item)
21051 (make-string (org-list-item-body-column
21052 (org-element-property :begin parent))
21053 ? ))
21054 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21055 (match-string 0))
21056 (t ""))))
21057 (comment-block
21058 ;; Only fill contents if P is within block boundaries.
21059 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21060 (forward-line)
21061 (point)))
21062 (cend (save-excursion
21063 (goto-char (org-element-property :end element))
21064 (skip-chars-backward " \r\t\n")
21065 (line-beginning-position))))
21066 (when (and (>= p cbeg) (< p cend))
21067 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21068 (match-string 0)
21069 "")))))))))))
21071 (declare-function message-goto-body "message" ())
21072 (defvar message-cite-prefix-regexp) ; From message.el
21073 (defvar org-element-all-objects) ; From org-element.el
21074 (defun org-fill-paragraph (&optional justify)
21075 "Fill element at point, when applicable.
21077 This function only applies to comment blocks, comments, example
21078 blocks and paragraphs. Also, as a special case, re-align table
21079 when point is at one.
21081 If JUSTIFY is non-nil (interactively, with prefix argument),
21082 justify as well. If `sentence-end-double-space' is non-nil, then
21083 period followed by one space does not end a sentence, so don't
21084 break a line there. The variable `fill-column' controls the
21085 width for filling.
21087 For convenience, when point is at a plain list, an item or
21088 a footnote definition, try to fill the first paragraph within."
21089 (interactive)
21090 (if (and (derived-mode-p 'message-mode)
21091 (or (not (message-in-body-p))
21092 (save-excursion (move-beginning-of-line 1)
21093 (looking-at message-cite-prefix-regexp))))
21094 ;; First ensure filling is correct in message-mode.
21095 (let ((fill-paragraph-function
21096 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21097 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21098 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21099 (paragraph-separate
21100 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21101 (fill-paragraph nil))
21102 (save-excursion
21103 ;; Move to end of line in order to get the first paragraph
21104 ;; within a plain list or a footnote definition.
21105 (end-of-line)
21106 (let ((element (org-element-at-point)))
21107 ;; First check if point is in a blank line at the beginning of
21108 ;; the buffer. In that case, ignore filling.
21109 (if (< (point) (org-element-property :begin element)) t
21110 (case (org-element-type element)
21111 ;; Use major mode filling function is src blocks.
21112 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21113 ;; Align Org tables, leave table.el tables as-is.
21114 (table-row (org-table-align) t)
21115 (table
21116 (when (eq (org-element-property :type element) 'org)
21117 (org-table-align))
21119 (paragraph
21120 ;; Paragraphs may contain `line-break' type objects.
21121 (let ((beg (max (point-min)
21122 (org-element-property :contents-begin element)))
21123 (end (min (point-max)
21124 (org-element-property :contents-end element))))
21125 ;; Do nothing if point is at an affiliated keyword.
21126 (if (< (point) beg) t
21127 (when (derived-mode-p 'message-mode)
21128 ;; In `message-mode', do not fill following
21129 ;; citation in current paragraph nor text before
21130 ;; message body.
21131 (let ((body-start (save-excursion (message-goto-body))))
21132 (when body-start (setq beg (max body-start beg))))
21133 (when (save-excursion
21134 (re-search-forward
21135 (concat "^" message-cite-prefix-regexp) end t))
21136 (setq end (match-beginning 0))))
21137 ;; Fill paragraph, taking line breaks into
21138 ;; consideration. For that, slice the paragraph
21139 ;; using line breaks as separators, and fill the
21140 ;; parts in reverse order to avoid messing with
21141 ;; markers.
21142 (save-excursion
21143 (goto-char end)
21144 (mapc
21145 (lambda (pos)
21146 (fill-region-as-paragraph pos (point) justify)
21147 (goto-char pos))
21148 ;; Find the list of ending positions for line
21149 ;; breaks in the current paragraph. Add paragraph
21150 ;; beginning to include first slice.
21151 (nreverse
21152 (cons
21154 (org-element-map
21155 (org-element--parse-objects
21156 beg end nil org-element-all-objects)
21157 'line-break
21158 (lambda (lb) (org-element-property :end lb)))))))
21159 t)))
21160 ;; Contents of `comment-block' type elements should be
21161 ;; filled as plain text, but only if point is within block
21162 ;; markers.
21163 (comment-block
21164 (let* ((case-fold-search t)
21165 (beg (save-excursion
21166 (goto-char (org-element-property :begin element))
21167 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21168 (forward-line)
21169 (point)))
21170 (end (save-excursion
21171 (goto-char (org-element-property :end element))
21172 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21173 (line-beginning-position))))
21174 (when (and (>= (point) beg) (< (point) end))
21175 (fill-region-as-paragraph
21176 (save-excursion
21177 (end-of-line)
21178 (re-search-backward "^[ \t]*$" beg 'move)
21179 (line-beginning-position))
21180 (save-excursion
21181 (beginning-of-line)
21182 (re-search-forward "^[ \t]*$" end 'move)
21183 (line-beginning-position))
21184 justify)))
21186 ;; Fill comments.
21187 (comment (fill-comment-paragraph justify))
21188 ;; Ignore every other element.
21189 (otherwise t)))))))
21191 (defun org-auto-fill-function ()
21192 "Auto-fill function."
21193 ;; Check if auto-filling is meaningful.
21194 (let ((fc (current-fill-column)))
21195 (when (and fc (> (current-column) fc))
21196 (let* ((fill-prefix (org-adaptive-fill-function))
21197 ;; Enforce empty fill prefix, if required. Otherwise, it
21198 ;; will be computed again.
21199 (adaptive-fill-mode (not (equal fill-prefix ""))))
21200 (when fill-prefix (do-auto-fill))))))
21202 (defun org-comment-line-break-function (&optional soft)
21203 "Break line at point and indent, continuing comment if within one.
21204 The inserted newline is marked hard if variable
21205 `use-hard-newlines' is true, unless optional argument SOFT is
21206 non-nil."
21207 (if soft (insert-and-inherit ?\n) (newline 1))
21208 (save-excursion (forward-char -1) (delete-horizontal-space))
21209 (delete-horizontal-space)
21210 (indent-to-left-margin)
21211 (insert-before-markers-and-inherit fill-prefix))
21214 ;;; Comments
21216 ;; Org comments syntax is quite complex. It requires the entire line
21217 ;; to be just a comment. Also, even with the right syntax at the
21218 ;; beginning of line, some some elements (i.e. verse-block or
21219 ;; example-block) don't accept comments. Usual Emacs comment commands
21220 ;; cannot cope with those requirements. Therefore, Org replaces them.
21222 ;; Org still relies on `comment-dwim', but cannot trust
21223 ;; `comment-only-p'. So, `comment-region-function' and
21224 ;; `uncomment-region-function' both point
21225 ;; to`org-comment-or-uncomment-region'. Eventually,
21226 ;; `org-insert-comment' takes care of insertion of comments at the
21227 ;; beginning of line.
21229 ;; `org-setup-comments-handling' install comments related variables
21230 ;; during `org-mode' initialization.
21232 (defun org-setup-comments-handling ()
21233 (interactive)
21234 (org-set-local 'comment-use-syntax nil)
21235 (org-set-local 'comment-start "# ")
21236 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21237 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21238 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21239 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21241 (defun org-insert-comment ()
21242 "Insert an empty comment above current line.
21243 If the line is empty, insert comment at its beginning."
21244 (beginning-of-line)
21245 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21246 (org-indent-line)
21247 (insert "# "))
21249 (defvar comment-empty-lines) ; From newcomment.el.
21250 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21251 "Comment or uncomment each non-blank line in the region.
21252 Uncomment each non-blank line between BEG and END if it only
21253 contains commented lines. Otherwise, comment them."
21254 (save-restriction
21255 ;; Restrict region
21256 (narrow-to-region (save-excursion (goto-char beg)
21257 (skip-chars-forward " \r\t\n" end)
21258 (line-beginning-position))
21259 (save-excursion (goto-char end)
21260 (skip-chars-backward " \r\t\n" beg)
21261 (line-end-position)))
21262 (let ((uncommentp
21263 ;; UNCOMMENTP is non-nil when every non blank line between
21264 ;; BEG and END is a comment.
21265 (save-excursion
21266 (goto-char (point-min))
21267 (while (and (not (eobp))
21268 (let ((element (org-element-at-point)))
21269 (and (eq (org-element-type element) 'comment)
21270 (goto-char (min (point-max)
21271 (org-element-property
21272 :end element)))))))
21273 (eobp))))
21274 (if uncommentp
21275 ;; Only blank lines and comments in region: uncomment it.
21276 (save-excursion
21277 (goto-char (point-min))
21278 (while (not (eobp))
21279 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21280 (replace-match "" nil nil nil 1))
21281 (forward-line)))
21282 ;; Comment each line in region.
21283 (let ((min-indent (point-max)))
21284 ;; First find the minimum indentation across all lines.
21285 (save-excursion
21286 (goto-char (point-min))
21287 (while (and (not (eobp)) (not (zerop min-indent)))
21288 (unless (looking-at "[ \t]*$")
21289 (setq min-indent (min min-indent (current-indentation))))
21290 (forward-line)))
21291 ;; Then loop over all lines.
21292 (save-excursion
21293 (goto-char (point-min))
21294 (while (not (eobp))
21295 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21296 (org-move-to-column min-indent t)
21297 (insert comment-start))
21298 (forward-line))))))))
21301 ;;; Other stuff.
21303 (defun org-toggle-fixed-width-section (arg)
21304 "Toggle the fixed-width export.
21305 If there is no active region, the QUOTE keyword at the current headline is
21306 inserted or removed. When present, it causes the text between this headline
21307 and the next to be exported as fixed-width text, and unmodified.
21308 If there is an active region, this command adds or removes a colon as the
21309 first character of this line. If the first character of a line is a colon,
21310 this line is also exported in fixed-width font."
21311 (interactive "P")
21312 (let* ((cc 0)
21313 (regionp (org-region-active-p))
21314 (beg (if regionp (region-beginning) (point)))
21315 (end (if regionp (region-end)))
21316 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21317 (case-fold-search nil)
21318 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21319 off)
21320 (if regionp
21321 (save-excursion
21322 (goto-char beg)
21323 (setq cc (current-column))
21324 (beginning-of-line 1)
21325 (setq off (looking-at re))
21326 (while (> nlines 0)
21327 (setq nlines (1- nlines))
21328 (beginning-of-line 1)
21329 (cond
21330 (arg
21331 (org-move-to-column cc t)
21332 (insert ": \n")
21333 (forward-line -1))
21334 ((and off (looking-at re))
21335 (replace-match "" t t nil 1))
21336 ((not off) (org-move-to-column cc t) (insert ": ")))
21337 (forward-line 1)))
21338 (save-excursion
21339 (org-back-to-heading)
21340 (cond
21341 ((looking-at (format org-heading-keyword-regexp-format
21342 org-quote-string))
21343 (goto-char (match-end 1))
21344 (looking-at (concat " +" org-quote-string))
21345 (replace-match "" t t)
21346 (when (eolp) (insert " ")))
21347 ((looking-at org-outline-regexp)
21348 (goto-char (match-end 0))
21349 (insert org-quote-string " ")))))))
21351 (defun org-reftex-citation ()
21352 "Use reftex-citation to insert a citation into the buffer.
21353 This looks for a line like
21355 #+BIBLIOGRAPHY: foo plain option:-d
21357 and derives from it that foo.bib is the bibliography file relevant
21358 for this document. It then installs the necessary environment for RefTeX
21359 to work in this buffer and calls `reftex-citation' to insert a citation
21360 into the buffer.
21362 Export of such citations to both LaTeX and HTML is handled by the contributed
21363 package org-exp-bibtex by Taru Karttunen."
21364 (interactive)
21365 (let ((reftex-docstruct-symbol 'rds)
21366 (reftex-cite-format "\\cite{%l}")
21367 rds bib)
21368 (save-excursion
21369 (save-restriction
21370 (widen)
21371 (let ((case-fold-search t)
21372 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21373 (if (not (save-excursion
21374 (or (re-search-forward re nil t)
21375 (re-search-backward re nil t))))
21376 (error "No bibliography defined in file")
21377 (setq bib (concat (match-string 1) ".bib")
21378 rds (list (list 'bib bib)))))))
21379 (call-interactively 'reftex-citation)))
21381 ;;;; Functions extending outline functionality
21383 (defun org-beginning-of-line (&optional arg)
21384 "Go to the beginning of the current line. If that is invisible, continue
21385 to a visible line beginning. This makes the function of C-a more intuitive.
21386 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21387 first attempt, and only move to after the tags when the cursor is already
21388 beyond the end of the headline."
21389 (interactive "P")
21390 (let ((pos (point))
21391 (special (if (consp org-special-ctrl-a/e)
21392 (car org-special-ctrl-a/e)
21393 org-special-ctrl-a/e))
21394 refpos)
21395 (if (org-bound-and-true-p visual-line-mode)
21396 (beginning-of-visual-line 1)
21397 (beginning-of-line 1))
21398 (if (and arg (fboundp 'move-beginning-of-line))
21399 (call-interactively 'move-beginning-of-line)
21400 (if (bobp)
21402 (backward-char 1)
21403 (if (org-truely-invisible-p)
21404 (while (and (not (bobp)) (org-truely-invisible-p))
21405 (backward-char 1)
21406 (beginning-of-line 1))
21407 (forward-char 1))))
21408 (when special
21409 (cond
21410 ((and (looking-at org-complex-heading-regexp)
21411 (= (char-after (match-end 1)) ?\ ))
21412 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21413 (point-at-eol)))
21414 (goto-char
21415 (if (eq special t)
21416 (cond ((> pos refpos) refpos)
21417 ((= pos (point)) refpos)
21418 (t (point)))
21419 (cond ((> pos (point)) (point))
21420 ((not (eq last-command this-command)) (point))
21421 (t refpos)))))
21422 ((org-at-item-p)
21423 ;; Being at an item and not looking at an the item means point
21424 ;; was previously moved to beginning of a visual line, which
21425 ;; doesn't contain the item. Therefore, do nothing special,
21426 ;; just stay here.
21427 (when (looking-at org-list-full-item-re)
21428 ;; Set special position at first white space character after
21429 ;; bullet, and check-box, if any.
21430 (let ((after-bullet
21431 (let ((box (match-end 3)))
21432 (if (not box) (match-end 1)
21433 (let ((after (char-after box)))
21434 (if (and after (= after ? )) (1+ box) box))))))
21435 ;; Special case: Move point to special position when
21436 ;; currently after it or at beginning of line.
21437 (if (eq special t)
21438 (when (or (> pos after-bullet) (= (point) pos))
21439 (goto-char after-bullet))
21440 ;; Reversed case: Move point to special position when
21441 ;; point was already at beginning of line and command is
21442 ;; repeated.
21443 (when (and (= (point) pos) (eq last-command this-command))
21444 (goto-char after-bullet))))))))
21445 (org-no-warnings
21446 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21448 (defun org-end-of-line (&optional arg)
21449 "Go to the end of the line.
21450 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21451 tags on the first attempt, and only move to after the tags when
21452 the cursor is already beyond the end of the headline."
21453 (interactive "P")
21454 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21455 org-special-ctrl-a/e))
21456 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21457 'end-of-visual-line)
21458 ((fboundp 'move-end-of-line) 'move-end-of-line)
21459 (t 'end-of-line))))
21460 (if (or (not special) arg) (call-interactively move-fun)
21461 (let* ((element (save-excursion (beginning-of-line)
21462 (org-element-at-point)))
21463 (type (org-element-type element)))
21464 (cond
21465 ((memq type '(headline inlinetask))
21466 (let ((pos (point)))
21467 (beginning-of-line 1)
21468 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21469 (if (eq special t)
21470 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21471 (goto-char (match-beginning 1))
21472 (goto-char (match-end 0)))
21473 (if (or (< pos (match-end 0))
21474 (not (eq this-command last-command)))
21475 (goto-char (match-end 0))
21476 (goto-char (match-beginning 1))))
21477 (call-interactively move-fun))))
21478 ((org-element-property :hiddenp element)
21479 ;; If element is hidden, `move-end-of-line' would put point
21480 ;; after it. Use `end-of-line' to stay on current line.
21481 (call-interactively 'end-of-line))
21482 (t (call-interactively move-fun)))))
21483 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21485 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21486 (define-key org-mode-map "\C-e" 'org-end-of-line)
21488 (defun org-backward-sentence (&optional arg)
21489 "Go to beginning of sentence, or beginning of table field.
21490 This will call `backward-sentence' or `org-table-beginning-of-field',
21491 depending on context."
21492 (interactive "P")
21493 (cond
21494 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21495 (t (call-interactively 'backward-sentence))))
21497 (defun org-forward-sentence (&optional arg)
21498 "Go to end of sentence, or end of table field.
21499 This will call `forward-sentence' or `org-table-end-of-field',
21500 depending on context."
21501 (interactive "P")
21502 (cond
21503 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21504 (t (call-interactively 'forward-sentence))))
21506 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21507 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21509 (defun org-kill-line (&optional arg)
21510 "Kill line, to tags or end of line."
21511 (interactive "P")
21512 (cond
21513 ((or (not org-special-ctrl-k)
21514 (bolp)
21515 (not (org-at-heading-p)))
21516 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21517 org-ctrl-k-protect-subtree)
21518 (if (or (eq org-ctrl-k-protect-subtree 'error)
21519 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21520 (error "C-k aborted - would kill hidden subtree")))
21521 (call-interactively
21522 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21523 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21524 (kill-region (point) (match-beginning 1))
21525 (org-set-tags nil t))
21526 (t (kill-region (point) (point-at-eol)))))
21528 (define-key org-mode-map "\C-k" 'org-kill-line)
21530 (defun org-yank (&optional arg)
21531 "Yank. If the kill is a subtree, treat it specially.
21532 This command will look at the current kill and check if is a single
21533 subtree, or a series of subtrees[1]. If it passes the test, and if the
21534 cursor is at the beginning of a line or after the stars of a currently
21535 empty headline, then the yank is handled specially. How exactly depends
21536 on the value of the following variables, both set by default.
21538 org-yank-folded-subtrees
21539 When set, the subtree(s) will be folded after insertion, but only
21540 if doing so would now swallow text after the yanked text.
21542 org-yank-adjusted-subtrees
21543 When set, the subtree will be promoted or demoted in order to
21544 fit into the local outline tree structure, which means that the level
21545 will be adjusted so that it becomes the smaller one of the two
21546 *visible* surrounding headings.
21548 Any prefix to this command will cause `yank' to be called directly with
21549 no special treatment. In particular, a simple \\[universal-argument] prefix \
21550 will just
21551 plainly yank the text as it is.
21553 \[1] The test checks if the first non-white line is a heading
21554 and if there are no other headings with fewer stars."
21555 (interactive "P")
21556 (org-yank-generic 'yank arg))
21558 (defun org-yank-generic (command arg)
21559 "Perform some yank-like command.
21561 This function implements the behavior described in the `org-yank'
21562 documentation. However, it has been generalized to work for any
21563 interactive command with similar behavior."
21565 ;; pretend to be command COMMAND
21566 (setq this-command command)
21568 (if arg
21569 (call-interactively command)
21571 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21572 (and (org-kill-is-subtree-p)
21573 (or (bolp)
21574 (and (looking-at "[ \t]*$")
21575 (string-match
21576 "\\`\\*+\\'"
21577 (buffer-substring (point-at-bol) (point)))))))
21578 swallowp)
21579 (cond
21580 ((and subtreep org-yank-folded-subtrees)
21581 (let ((beg (point))
21582 end)
21583 (if (and subtreep org-yank-adjusted-subtrees)
21584 (org-paste-subtree nil nil 'for-yank)
21585 (call-interactively command))
21587 (setq end (point))
21588 (goto-char beg)
21589 (when (and (bolp) subtreep
21590 (not (setq swallowp
21591 (org-yank-folding-would-swallow-text beg end))))
21592 (org-with-limited-levels
21593 (or (looking-at org-outline-regexp)
21594 (re-search-forward org-outline-regexp-bol end t))
21595 (while (and (< (point) end) (looking-at org-outline-regexp))
21596 (hide-subtree)
21597 (org-cycle-show-empty-lines 'folded)
21598 (condition-case nil
21599 (outline-forward-same-level 1)
21600 (error (goto-char end))))))
21601 (when swallowp
21602 (message
21603 "Inserted text not folded because that would swallow text"))
21605 (goto-char end)
21606 (skip-chars-forward " \t\n\r")
21607 (beginning-of-line 1)
21608 (push-mark beg 'nomsg)))
21609 ((and subtreep org-yank-adjusted-subtrees)
21610 (let ((beg (point-at-bol)))
21611 (org-paste-subtree nil nil 'for-yank)
21612 (push-mark beg 'nomsg)))
21614 (call-interactively command))))))
21616 (defun org-yank-folding-would-swallow-text (beg end)
21617 "Would hide-subtree at BEG swallow any text after END?"
21618 (let (level)
21619 (org-with-limited-levels
21620 (save-excursion
21621 (goto-char beg)
21622 (when (or (looking-at org-outline-regexp)
21623 (re-search-forward org-outline-regexp-bol end t))
21624 (setq level (org-outline-level)))
21625 (goto-char end)
21626 (skip-chars-forward " \t\r\n\v\f")
21627 (if (or (eobp)
21628 (and (bolp) (looking-at org-outline-regexp)
21629 (<= (org-outline-level) level)))
21630 nil ; Nothing would be swallowed
21631 t))))) ; something would swallow
21633 (define-key org-mode-map "\C-y" 'org-yank)
21635 (defun org-truely-invisible-p ()
21636 "Check if point is at a character currently not visible.
21637 This version does not only check the character property, but also
21638 `visible-mode'."
21639 ;; Early versions of noutline don't have `outline-invisible-p'.
21640 (if (org-bound-and-true-p visible-mode)
21642 (outline-invisible-p)))
21644 (defun org-invisible-p2 ()
21645 "Check if point is at a character currently not visible."
21646 (save-excursion
21647 (if (and (eolp) (not (bobp))) (backward-char 1))
21648 ;; Early versions of noutline don't have `outline-invisible-p'.
21649 (outline-invisible-p)))
21651 (defun org-back-to-heading (&optional invisible-ok)
21652 "Call `outline-back-to-heading', but provide a better error message."
21653 (condition-case nil
21654 (outline-back-to-heading invisible-ok)
21655 (error (error "Before first headline at position %d in buffer %s"
21656 (point) (current-buffer)))))
21658 (defun org-before-first-heading-p ()
21659 "Before first heading?"
21660 (save-excursion
21661 (end-of-line)
21662 (null (re-search-backward org-outline-regexp-bol nil t))))
21664 (defun org-at-heading-p (&optional ignored)
21665 (outline-on-heading-p t))
21666 ;; Compatibility alias with Org versions < 7.8.03
21667 (defalias 'org-on-heading-p 'org-at-heading-p)
21669 (defun org-at-comment-p nil
21670 "Is cursor in a line starting with a # character?"
21671 (save-excursion
21672 (beginning-of-line)
21673 (looking-at "^#")))
21675 (defun org-at-drawer-p nil
21676 "Is cursor at a drawer keyword?"
21677 (save-excursion
21678 (move-beginning-of-line 1)
21679 (looking-at org-drawer-regexp)))
21681 (defun org-at-block-p nil
21682 "Is cursor at a block keyword?"
21683 (save-excursion
21684 (move-beginning-of-line 1)
21685 (looking-at org-block-regexp)))
21687 (defun org-point-at-end-of-empty-headline ()
21688 "If point is at the end of an empty headline, return t, else nil.
21689 If the heading only contains a TODO keyword, it is still still considered
21690 empty."
21691 (and (looking-at "[ \t]*$")
21692 (when org-todo-line-regexp
21693 (save-excursion
21694 (beginning-of-line 1)
21695 (let ((case-fold-search nil))
21696 (looking-at org-todo-line-regexp)
21697 (string= (match-string 3) ""))))))
21699 (defun org-at-heading-or-item-p ()
21700 (or (org-at-heading-p) (org-at-item-p)))
21702 (defun org-at-target-p ()
21703 (or (org-in-regexp org-radio-target-regexp)
21704 (org-in-regexp org-target-regexp)))
21705 ;; Compatibility alias with Org versions < 7.8.03
21706 (defalias 'org-on-target-p 'org-at-target-p)
21708 (defun org-up-heading-all (arg)
21709 "Move to the heading line of which the present line is a subheading.
21710 This function considers both visible and invisible heading lines.
21711 With argument, move up ARG levels."
21712 (if (fboundp 'outline-up-heading-all)
21713 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21714 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21716 (defun org-up-heading-safe ()
21717 "Move to the heading line of which the present line is a subheading.
21718 This version will not throw an error. It will return the level of the
21719 headline found, or nil if no higher level is found.
21721 Also, this function will be a lot faster than `outline-up-heading',
21722 because it relies on stars being the outline starters. This can really
21723 make a significant difference in outlines with very many siblings."
21724 (let (start-level re)
21725 (org-back-to-heading t)
21726 (setq start-level (funcall outline-level))
21727 (if (equal start-level 1)
21729 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21730 (if (re-search-backward re nil t)
21731 (funcall outline-level)))))
21733 (defun org-first-sibling-p ()
21734 "Is this heading the first child of its parents?"
21735 (interactive)
21736 (let ((re org-outline-regexp-bol)
21737 level l)
21738 (unless (org-at-heading-p t)
21739 (error "Not at a heading"))
21740 (setq level (funcall outline-level))
21741 (save-excursion
21742 (if (not (re-search-backward re nil t))
21744 (setq l (funcall outline-level))
21745 (< l level)))))
21747 (defun org-goto-sibling (&optional previous)
21748 "Goto the next sibling, even if it is invisible.
21749 When PREVIOUS is set, go to the previous sibling instead. Returns t
21750 when a sibling was found. When none is found, return nil and don't
21751 move point."
21752 (let ((fun (if previous 're-search-backward 're-search-forward))
21753 (pos (point))
21754 (re org-outline-regexp-bol)
21755 level l)
21756 (when (condition-case nil (org-back-to-heading t) (error nil))
21757 (setq level (funcall outline-level))
21758 (catch 'exit
21759 (or previous (forward-char 1))
21760 (while (funcall fun re nil t)
21761 (setq l (funcall outline-level))
21762 (when (< l level) (goto-char pos) (throw 'exit nil))
21763 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21764 (goto-char pos)
21765 nil))))
21767 (defun org-show-siblings ()
21768 "Show all siblings of the current headline."
21769 (save-excursion
21770 (while (org-goto-sibling) (org-flag-heading nil)))
21771 (save-excursion
21772 (while (org-goto-sibling 'previous)
21773 (org-flag-heading nil))))
21775 (defun org-goto-first-child ()
21776 "Goto the first child, even if it is invisible.
21777 Return t when a child was found. Otherwise don't move point and
21778 return nil."
21779 (let (level (pos (point)) (re org-outline-regexp-bol))
21780 (when (condition-case nil (org-back-to-heading t) (error nil))
21781 (setq level (outline-level))
21782 (forward-char 1)
21783 (if (and (re-search-forward re nil t) (> (outline-level) level))
21784 (progn (goto-char (match-beginning 0)) t)
21785 (goto-char pos) nil))))
21787 (defun org-show-hidden-entry ()
21788 "Show an entry where even the heading is hidden."
21789 (save-excursion
21790 (org-show-entry)))
21792 (defun org-flag-heading (flag &optional entry)
21793 "Flag the current heading. FLAG non-nil means make invisible.
21794 When ENTRY is non-nil, show the entire entry."
21795 (save-excursion
21796 (org-back-to-heading t)
21797 ;; Check if we should show the entire entry
21798 (if entry
21799 (progn
21800 (org-show-entry)
21801 (save-excursion
21802 (and (outline-next-heading)
21803 (org-flag-heading nil))))
21804 (outline-flag-region (max (point-min) (1- (point)))
21805 (save-excursion (outline-end-of-heading) (point))
21806 flag))))
21808 (defun org-get-next-sibling ()
21809 "Move to next heading of the same level, and return point.
21810 If there is no such heading, return nil.
21811 This is like outline-next-sibling, but invisible headings are ok."
21812 (let ((level (funcall outline-level)))
21813 (outline-next-heading)
21814 (while (and (not (eobp)) (> (funcall outline-level) level))
21815 (outline-next-heading))
21816 (if (or (eobp) (< (funcall outline-level) level))
21818 (point))))
21820 (defun org-get-last-sibling ()
21821 "Move to previous heading of the same level, and return point.
21822 If there is no such heading, return nil."
21823 (let ((opoint (point))
21824 (level (funcall outline-level)))
21825 (outline-previous-heading)
21826 (when (and (/= (point) opoint) (outline-on-heading-p t))
21827 (while (and (> (funcall outline-level) level)
21828 (not (bobp)))
21829 (outline-previous-heading))
21830 (if (< (funcall outline-level) level)
21832 (point)))))
21834 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21835 "Goto to the end of a subtree."
21836 ;; This contains an exact copy of the original function, but it uses
21837 ;; `org-back-to-heading', to make it work also in invisible
21838 ;; trees. And is uses an invisible-ok argument.
21839 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21840 ;; Furthermore, when used inside Org, finding the end of a large subtree
21841 ;; with many children and grandchildren etc, this can be much faster
21842 ;; than the outline version.
21843 (org-back-to-heading invisible-ok)
21844 (let ((first t)
21845 (level (funcall outline-level)))
21846 (if (and (derived-mode-p 'org-mode) (< level 1000))
21847 ;; A true heading (not a plain list item), in Org-mode
21848 ;; This means we can easily find the end by looking
21849 ;; only for the right number of stars. Using a regexp to do
21850 ;; this is so much faster than using a Lisp loop.
21851 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21852 (forward-char 1)
21853 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21854 ;; something else, do it the slow way
21855 (while (and (not (eobp))
21856 (or first (> (funcall outline-level) level)))
21857 (setq first nil)
21858 (outline-next-heading)))
21859 (unless to-heading
21860 (if (memq (preceding-char) '(?\n ?\^M))
21861 (progn
21862 ;; Go to end of line before heading
21863 (forward-char -1)
21864 (if (memq (preceding-char) '(?\n ?\^M))
21865 ;; leave blank line before heading
21866 (forward-char -1))))))
21867 (point))
21869 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21870 "Use Org version in org-mode, for dramatic speed-up."
21871 (if (derived-mode-p 'org-mode)
21872 (progn
21873 (org-end-of-subtree nil t)
21874 (unless (eobp) (backward-char 1)))
21875 ad-do-it))
21877 (defun org-end-of-meta-data-and-drawers ()
21878 "Jump to the first text after meta data and drawers in the current entry.
21879 This will move over empty lines, lines with planning time stamps,
21880 clocking lines, and drawers."
21881 (org-back-to-heading t)
21882 (let ((end (save-excursion (outline-next-heading) (point)))
21883 (re (concat "\\(" org-drawer-regexp "\\)"
21884 "\\|" "[ \t]*" org-keyword-time-regexp)))
21885 (forward-line 1)
21886 (while (re-search-forward re end t)
21887 (if (not (match-end 1))
21888 ;; empty or planning line
21889 (forward-line 1)
21890 ;; a drawer, find the end
21891 (re-search-forward "^[ \t]*:END:" end 'move)
21892 (forward-line 1)))
21893 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21894 (point)))
21896 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21897 "Move forward to the arg'th subheading at same level as this one.
21898 Stop at the first and last subheadings of a superior heading.
21899 Normally this only looks at visible headings, but when INVISIBLE-OK is
21900 non-nil it will also look at invisible ones."
21901 (interactive "p")
21902 (org-back-to-heading invisible-ok)
21903 (org-at-heading-p)
21904 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21905 (re (format "^\\*\\{1,%d\\} " level))
21907 (forward-char 1)
21908 (while (> arg 0)
21909 (while (and (re-search-forward re nil 'move)
21910 (setq l (- (match-end 0) (match-beginning 0) 1))
21911 (= l level)
21912 (not invisible-ok)
21913 (progn (backward-char 1) (outline-invisible-p)))
21914 (if (< l level) (setq arg 1)))
21915 (setq arg (1- arg)))
21916 (beginning-of-line 1)))
21918 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21919 "Move backward to the arg'th subheading at same level as this one.
21920 Stop at the first and last subheadings of a superior heading."
21921 (interactive "p")
21922 (org-back-to-heading)
21923 (org-at-heading-p)
21924 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21925 (re (format "^\\*\\{1,%d\\} " level))
21927 (while (> arg 0)
21928 (while (and (re-search-backward re nil 'move)
21929 (setq l (- (match-end 0) (match-beginning 0) 1))
21930 (= l level)
21931 (not invisible-ok)
21932 (outline-invisible-p))
21933 (if (< l level) (setq arg 1)))
21934 (setq arg (1- arg)))))
21936 (defun org-forward-element ()
21937 "Move forward by one element.
21938 Move to the next element at the same level, when possible."
21939 (interactive)
21940 (cond ((eobp) (error "Cannot move further down"))
21941 ((org-with-limited-levels (org-at-heading-p))
21942 (let ((origin (point)))
21943 (org-forward-heading-same-level 1)
21944 (unless (org-with-limited-levels (org-at-heading-p))
21945 (goto-char origin)
21946 (error "Cannot move further down"))))
21948 (let* ((elem (org-element-at-point))
21949 (end (org-element-property :end elem))
21950 (parent (org-element-property :parent elem)))
21951 (if (and parent (= (org-element-property :contents-end parent) end))
21952 (goto-char (org-element-property :end parent))
21953 (goto-char end))))))
21955 (defun org-backward-element ()
21956 "Move backward by one element.
21957 Move to the previous element at the same level, when possible."
21958 (interactive)
21959 (cond ((bobp) (error "Cannot move further up"))
21960 ((org-with-limited-levels (org-at-heading-p))
21961 ;; At an headline, move to the previous one, if any, or stay
21962 ;; here.
21963 (let ((origin (point)))
21964 (org-backward-heading-same-level 1)
21965 (unless (org-with-limited-levels (org-at-heading-p))
21966 (goto-char origin)
21967 (error "Cannot move further up"))))
21969 (let* ((trail (org-element-at-point 'keep-trail))
21970 (elem (car trail))
21971 (prev-elem (nth 1 trail))
21972 (beg (org-element-property :begin elem)))
21973 (cond
21974 ;; Move to beginning of current element if point isn't
21975 ;; there already.
21976 ((/= (point) beg) (goto-char beg))
21977 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21978 ((org-before-first-heading-p) (goto-char (point-min)))
21979 (t (org-back-to-heading)))))))
21981 (defun org-up-element ()
21982 "Move to upper element."
21983 (interactive)
21984 (if (org-with-limited-levels (org-at-heading-p))
21985 (unless (org-up-heading-safe) (error "No surrounding element"))
21986 (let* ((elem (org-element-at-point))
21987 (parent (org-element-property :parent elem)))
21988 (if parent (goto-char (org-element-property :begin parent))
21989 (if (org-with-limited-levels (org-before-first-heading-p))
21990 (error "No surrounding element")
21991 (org-with-limited-levels (org-back-to-heading)))))))
21993 (defvar org-element-greater-elements)
21994 (defun org-down-element ()
21995 "Move to inner element."
21996 (interactive)
21997 (let ((element (org-element-at-point)))
21998 (cond
21999 ((memq (org-element-type element) '(plain-list table))
22000 (goto-char (org-element-property :contents-begin element))
22001 (forward-char))
22002 ((memq (org-element-type element) org-element-greater-elements)
22003 ;; If contents are hidden, first disclose them.
22004 (when (org-element-property :hiddenp element) (org-cycle))
22005 (goto-char (or (org-element-property :contents-begin element)
22006 (error "No content for this element"))))
22007 (t (error "No inner element")))))
22009 (defun org-drag-element-backward ()
22010 "Move backward element at point."
22011 (interactive)
22012 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22013 (let* ((trail (org-element-at-point 'keep-trail))
22014 (elem (car trail))
22015 (prev-elem (nth 1 trail)))
22016 ;; Error out if no previous element or previous element is
22017 ;; a parent of the current one.
22018 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22019 (error "Cannot drag element backward")
22020 (let ((pos (point)))
22021 (org-element-swap-A-B prev-elem elem)
22022 (goto-char (+ (org-element-property :begin prev-elem)
22023 (- pos (org-element-property :begin elem)))))))))
22025 (defun org-drag-element-forward ()
22026 "Move forward element at point."
22027 (interactive)
22028 (let* ((pos (point))
22029 (elem (org-element-at-point)))
22030 (when (= (point-max) (org-element-property :end elem))
22031 (error "Cannot drag element forward"))
22032 (goto-char (org-element-property :end elem))
22033 (let ((next-elem (org-element-at-point)))
22034 (when (or (org-element-nested-p elem next-elem)
22035 (and (eq (org-element-type next-elem) 'headline)
22036 (not (eq (org-element-type elem) 'headline))))
22037 (goto-char pos)
22038 (error "Cannot drag element forward"))
22039 ;; Compute new position of point: it's shifted by NEXT-ELEM
22040 ;; body's length (without final blanks) and by the length of
22041 ;; blanks between ELEM and NEXT-ELEM.
22042 (let ((size-next (- (save-excursion
22043 (goto-char (org-element-property :end next-elem))
22044 (skip-chars-backward " \r\t\n")
22045 (forward-line)
22046 ;; Small correction if buffer doesn't end
22047 ;; with a newline character.
22048 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22049 (org-element-property :begin next-elem)))
22050 (size-blank (- (org-element-property :end elem)
22051 (save-excursion
22052 (goto-char (org-element-property :end elem))
22053 (skip-chars-backward " \r\t\n")
22054 (forward-line)
22055 (point)))))
22056 (org-element-swap-A-B elem next-elem)
22057 (goto-char (+ pos size-next size-blank))))))
22059 (defun org-mark-element ()
22060 "Put point at beginning of this element, mark at end.
22062 Interactively, if this command is repeated or (in Transient Mark
22063 mode) if the mark is active, it marks the next element after the
22064 ones already marked."
22065 (interactive)
22066 (let (deactivate-mark)
22067 (if (and (org-called-interactively-p 'any)
22068 (or (and (eq last-command this-command) (mark t))
22069 (and transient-mark-mode mark-active)))
22070 (set-mark
22071 (save-excursion
22072 (goto-char (mark))
22073 (goto-char (org-element-property :end (org-element-at-point)))))
22074 (let ((element (org-element-at-point)))
22075 (end-of-line)
22076 (push-mark (org-element-property :end element) t t)
22077 (goto-char (org-element-property :begin element))))))
22079 (defun org-narrow-to-element ()
22080 "Narrow buffer to current element."
22081 (interactive)
22082 (let ((elem (org-element-at-point)))
22083 (cond
22084 ((eq (car elem) 'headline)
22085 (narrow-to-region
22086 (org-element-property :begin elem)
22087 (org-element-property :end elem)))
22088 ((memq (car elem) org-element-greater-elements)
22089 (narrow-to-region
22090 (org-element-property :contents-begin elem)
22091 (org-element-property :contents-end elem)))
22093 (narrow-to-region
22094 (org-element-property :begin elem)
22095 (org-element-property :end elem))))))
22097 (defun org-transpose-element ()
22098 "Transpose current and previous elements, keeping blank lines between.
22099 Point is moved after both elements."
22100 (interactive)
22101 (org-skip-whitespace)
22102 (let ((end (org-element-property :end (org-element-at-point))))
22103 (org-drag-element-backward)
22104 (goto-char end)))
22106 (defun org-unindent-buffer ()
22107 "Un-indent the visible part of the buffer.
22108 Relative indentation (between items, inside blocks, etc.) isn't
22109 modified."
22110 (interactive)
22111 (unless (eq major-mode 'org-mode)
22112 (error "Cannot un-indent a buffer not in Org mode"))
22113 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22114 unindent-tree ; For byte-compiler.
22115 (unindent-tree
22116 (function
22117 (lambda (contents)
22118 (mapc
22119 (lambda (element)
22120 (if (memq (org-element-type element) '(headline section))
22121 (funcall unindent-tree (org-element-contents element))
22122 (save-excursion
22123 (save-restriction
22124 (narrow-to-region
22125 (org-element-property :begin element)
22126 (org-element-property :end element))
22127 (org-do-remove-indentation)))))
22128 (reverse contents))))))
22129 (funcall unindent-tree (org-element-contents parse-tree))))
22131 (defun org-show-subtree ()
22132 "Show everything after this heading at deeper levels."
22133 (interactive)
22134 (outline-flag-region
22135 (point)
22136 (save-excursion
22137 (org-end-of-subtree t t))
22138 nil))
22140 (defun org-show-entry ()
22141 "Show the body directly following this heading.
22142 Show the heading too, if it is currently invisible."
22143 (interactive)
22144 (save-excursion
22145 (condition-case nil
22146 (progn
22147 (org-back-to-heading t)
22148 (outline-flag-region
22149 (max (point-min) (1- (point)))
22150 (save-excursion
22151 (if (re-search-forward
22152 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22153 (match-beginning 1)
22154 (point-max)))
22155 nil)
22156 (org-cycle-hide-drawers 'children))
22157 (error nil))))
22159 (defun org-make-options-regexp (kwds &optional extra)
22160 "Make a regular expression for keyword lines."
22161 (concat
22162 "^#\\+\\("
22163 (mapconcat 'regexp-quote kwds "\\|")
22164 (if extra (concat "\\|" extra))
22165 "\\):[ \t]*\\(.*\\)"))
22167 ;; Make isearch reveal the necessary context
22168 (defun org-isearch-end ()
22169 "Reveal context after isearch exits."
22170 (when isearch-success ; only if search was successful
22171 (if (featurep 'xemacs)
22172 ;; Under XEmacs, the hook is run in the correct place,
22173 ;; we directly show the context.
22174 (org-show-context 'isearch)
22175 ;; In Emacs the hook runs *before* restoring the overlays.
22176 ;; So we have to use a one-time post-command-hook to do this.
22177 ;; (Emacs 22 has a special variable, see function `org-mode')
22178 (unless (and (boundp 'isearch-mode-end-hook-quit)
22179 isearch-mode-end-hook-quit)
22180 ;; Only when the isearch was not quitted.
22181 (org-add-hook 'post-command-hook 'org-isearch-post-command
22182 'append 'local)))))
22184 (defun org-isearch-post-command ()
22185 "Remove self from hook, and show context."
22186 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22187 (org-show-context 'isearch))
22190 ;;;; Integration with and fixes for other packages
22192 ;;; Imenu support
22194 (defvar org-imenu-markers nil
22195 "All markers currently used by Imenu.")
22196 (make-variable-buffer-local 'org-imenu-markers)
22198 (defun org-imenu-new-marker (&optional pos)
22199 "Return a new marker for use by Imenu, and remember the marker."
22200 (let ((m (make-marker)))
22201 (move-marker m (or pos (point)))
22202 (push m org-imenu-markers)
22205 (defun org-imenu-get-tree ()
22206 "Produce the index for Imenu."
22207 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22208 (setq org-imenu-markers nil)
22209 (let* ((n org-imenu-depth)
22210 (re (concat "^" (org-get-limited-outline-regexp)))
22211 (subs (make-vector (1+ n) nil))
22212 (last-level 0)
22213 m level head)
22214 (save-excursion
22215 (save-restriction
22216 (widen)
22217 (goto-char (point-max))
22218 (while (re-search-backward re nil t)
22219 (setq level (org-reduced-level (funcall outline-level)))
22220 (when (and (<= level n)
22221 (looking-at org-complex-heading-regexp))
22222 (setq head (org-link-display-format
22223 (org-match-string-no-properties 4))
22224 m (org-imenu-new-marker))
22225 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22226 (if (>= level last-level)
22227 (push (cons head m) (aref subs level))
22228 (push (cons head (aref subs (1+ level))) (aref subs level))
22229 (loop for i from (1+ level) to n do (aset subs i nil)))
22230 (setq last-level level)))))
22231 (aref subs 1)))
22233 (eval-after-load "imenu"
22234 '(progn
22235 (add-hook 'imenu-after-jump-hook
22236 (lambda ()
22237 (if (derived-mode-p 'org-mode)
22238 (org-show-context 'org-goto))))))
22240 (defun org-link-display-format (link)
22241 "Replace a link with either the description, or the link target
22242 if no description is present"
22243 (save-match-data
22244 (if (string-match org-bracket-link-analytic-regexp link)
22245 (replace-match (if (match-end 5)
22246 (match-string 5 link)
22247 (concat (match-string 1 link)
22248 (match-string 3 link)))
22249 nil t link)
22250 link)))
22252 (defun org-toggle-link-display ()
22253 "Toggle the literal or descriptive display of links."
22254 (interactive)
22255 (if org-descriptive-links
22256 (progn (org-remove-from-invisibility-spec '(org-link))
22257 (org-restart-font-lock)
22258 (setq org-descriptive-links nil))
22259 (progn (add-to-invisibility-spec '(org-link))
22260 (org-restart-font-lock)
22261 (setq org-descriptive-links t))))
22263 ;; Speedbar support
22265 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22266 "Overlay marking the agenda restriction line in speedbar.")
22267 (overlay-put org-speedbar-restriction-lock-overlay
22268 'face 'org-agenda-restriction-lock)
22269 (overlay-put org-speedbar-restriction-lock-overlay
22270 'help-echo "Agendas are currently limited to this item.")
22271 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22273 (defun org-speedbar-set-agenda-restriction ()
22274 "Restrict future agenda commands to the location at point in speedbar.
22275 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22276 (interactive)
22277 (require 'org-agenda)
22278 (let (p m tp np dir txt)
22279 (cond
22280 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22281 'org-imenu t))
22282 (setq m (get-text-property p 'org-imenu-marker))
22283 (with-current-buffer (marker-buffer m)
22284 (goto-char m)
22285 (org-agenda-set-restriction-lock 'subtree)))
22286 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22287 'speedbar-function 'speedbar-find-file))
22288 (setq tp (previous-single-property-change
22289 (1+ p) 'speedbar-function)
22290 np (next-single-property-change
22291 tp 'speedbar-function)
22292 dir (speedbar-line-directory)
22293 txt (buffer-substring-no-properties (or tp (point-min))
22294 (or np (point-max))))
22295 (with-current-buffer (find-file-noselect
22296 (let ((default-directory dir))
22297 (expand-file-name txt)))
22298 (unless (derived-mode-p 'org-mode)
22299 (error "Cannot restrict to non-Org-mode file"))
22300 (org-agenda-set-restriction-lock 'file)))
22301 (t (error "Don't know how to restrict Org-mode's agenda")))
22302 (move-overlay org-speedbar-restriction-lock-overlay
22303 (point-at-bol) (point-at-eol))
22304 (setq current-prefix-arg nil)
22305 (org-agenda-maybe-redo)))
22307 (eval-after-load "speedbar"
22308 '(progn
22309 (speedbar-add-supported-extension ".org")
22310 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22311 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22312 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22313 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22314 (add-hook 'speedbar-visiting-tag-hook
22315 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22317 ;;; Fixes and Hacks for problems with other packages
22319 ;; Make flyspell not check words in links, to not mess up our keymap
22320 (defun org-mode-flyspell-verify ()
22321 "Don't let flyspell put overlays at active buttons, or on
22322 {todo,all-time,additional-option-like}-keywords."
22323 (let ((pos (max (1- (point)) (point-min)))
22324 (word (thing-at-point 'word)))
22325 (and (not (get-text-property pos 'keymap))
22326 (not (get-text-property pos 'org-no-flyspell))
22327 (not (member word org-todo-keywords-1))
22328 (not (member word org-all-time-keywords))
22329 (not (member word org-options-keywords))
22330 (not (member word (mapcar 'car org-startup-options)))
22331 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22333 (defun org-remove-flyspell-overlays-in (beg end)
22334 "Remove flyspell overlays in region."
22335 (and (org-bound-and-true-p flyspell-mode)
22336 (fboundp 'flyspell-delete-region-overlays)
22337 (flyspell-delete-region-overlays beg end))
22338 (add-text-properties beg end '(org-no-flyspell t)))
22340 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22341 (eval-after-load "bookmark"
22342 '(if (boundp 'bookmark-after-jump-hook)
22343 ;; We can use the hook
22344 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22345 ;; Hook not available, use advice
22346 (defadvice bookmark-jump (after org-make-visible activate)
22347 "Make the position visible."
22348 (org-bookmark-jump-unhide))))
22350 ;; Make sure saveplace shows the location if it was hidden
22351 (eval-after-load "saveplace"
22352 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22353 "Make the position visible."
22354 (org-bookmark-jump-unhide)))
22356 ;; Make sure ecb shows the location if it was hidden
22357 (eval-after-load "ecb"
22358 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22359 "Make hierarchy visible when jumping into location from ECB tree buffer."
22360 (if (derived-mode-p 'org-mode)
22361 (org-show-context))))
22363 (defun org-bookmark-jump-unhide ()
22364 "Unhide the current position, to show the bookmark location."
22365 (and (derived-mode-p 'org-mode)
22366 (or (outline-invisible-p)
22367 (save-excursion (goto-char (max (point-min) (1- (point))))
22368 (outline-invisible-p)))
22369 (org-show-context 'bookmark-jump)))
22371 ;; Make session.el ignore our circular variable
22372 (eval-after-load "session"
22373 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22375 ;;;; Experimental code
22377 (defun org-closed-in-range ()
22378 "Sparse tree of items closed in a certain time range.
22379 Still experimental, may disappear in the future."
22380 (interactive)
22381 ;; Get the time interval from the user.
22382 (let* ((time1 (org-float-time
22383 (org-read-date nil 'to-time nil "Starting date: ")))
22384 (time2 (org-float-time
22385 (org-read-date nil 'to-time nil "End date:")))
22386 ;; callback function
22387 (callback (lambda ()
22388 (let ((time
22389 (org-float-time
22390 (apply 'encode-time
22391 (org-parse-time-string
22392 (match-string 1))))))
22393 ;; check if time in interval
22394 (and (>= time time1) (<= time time2))))))
22395 ;; make tree, check each match with the callback
22396 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22398 ;;;; Finish up
22400 (provide 'org)
22402 (run-hooks 'org-load-hook)
22404 ;;; org.el ends here