org.el (org-mode): Set `paragraph-start'
[org-mode.git] / lisp / org.el
blob13fb44d146534e3e30c78db29c2ebd26bdd91acd
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 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
4902 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
4903 (when (and org-ellipsis
4904 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4905 (fboundp 'make-glyph-code))
4906 (unless org-display-table
4907 (setq org-display-table (make-display-table)))
4908 (set-display-table-slot
4909 org-display-table 4
4910 (vconcat (mapcar
4911 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4912 org-ellipsis)))
4913 (if (stringp org-ellipsis) org-ellipsis "..."))))
4914 (setq buffer-display-table org-display-table))
4915 (org-set-regexps-and-options)
4916 (when (and org-tag-faces (not org-tags-special-faces-re))
4917 ;; tag faces set outside customize.... force initialization.
4918 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4919 ;; Calc embedded
4920 (org-set-local 'calc-embedded-open-mode "# ")
4921 (modify-syntax-entry ?@ "w")
4922 (if org-startup-truncated (setq truncate-lines t))
4923 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
4924 (org-set-local 'font-lock-unfontify-region-function
4925 'org-unfontify-region)
4926 ;; Activate before-change-function
4927 (org-set-local 'org-table-may-need-update t)
4928 (org-add-hook 'before-change-functions 'org-before-change-function nil
4929 'local)
4930 ;; Check for running clock before killing a buffer
4931 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4932 ;; Indentation.
4933 (org-set-local 'indent-line-function 'org-indent-line)
4934 (org-set-local 'indent-region-function 'org-indent-region)
4935 ;; Initialize radio targets.
4936 (org-update-radio-target-regexp)
4937 ;; Filling and auto-filling.
4938 (org-setup-filling)
4939 ;; Comments.
4940 (org-setup-comments-handling)
4941 ;; Beginning/end of defun
4942 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4943 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4944 ;; Next error for sparse trees
4945 (org-set-local 'next-error-function 'org-occur-next-match)
4946 ;; Make sure dependence stuff works reliably, even for users who set it
4947 ;; too late :-(
4948 (if org-enforce-todo-dependencies
4949 (add-hook 'org-blocker-hook
4950 'org-block-todo-from-children-or-siblings-or-parent)
4951 (remove-hook 'org-blocker-hook
4952 'org-block-todo-from-children-or-siblings-or-parent))
4953 (if org-enforce-todo-checkbox-dependencies
4954 (add-hook 'org-blocker-hook
4955 'org-block-todo-from-checkboxes)
4956 (remove-hook 'org-blocker-hook
4957 'org-block-todo-from-checkboxes))
4959 ;; Align options lines
4960 (org-set-local
4961 'align-mode-rules-list
4962 '((org-in-buffer-settings
4963 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4964 (modes . '(org-mode)))))
4966 ;; Imenu
4967 (org-set-local 'imenu-create-index-function
4968 'org-imenu-get-tree)
4970 ;; Make isearch reveal context
4971 (if (or (featurep 'xemacs)
4972 (not (boundp 'outline-isearch-open-invisible-function)))
4973 ;; Emacs 21 and XEmacs make use of the hook
4974 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4975 ;; Emacs 22 deals with this through a special variable
4976 (org-set-local 'outline-isearch-open-invisible-function
4977 (lambda (&rest ignore) (org-show-context 'isearch)))
4978 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
4980 ;; Setup the pcomplete hooks
4981 (set (make-local-variable 'pcomplete-command-completion-function)
4982 'org-pcomplete-initial)
4983 (set (make-local-variable 'pcomplete-command-name-function)
4984 'org-command-at-point)
4985 (set (make-local-variable 'pcomplete-default-completion-function)
4986 'ignore)
4987 (set (make-local-variable 'pcomplete-parse-arguments-function)
4988 'org-parse-arguments)
4989 (set (make-local-variable 'pcomplete-termination-string) "")
4990 (when (>= emacs-major-version 23)
4991 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4993 ;; If empty file that did not turn on org-mode automatically, make it to.
4994 (if (and org-insert-mode-line-in-empty-file
4995 (org-called-interactively-p 'any)
4996 (= (point-min) (point-max)))
4997 (insert "# -*- mode: org -*-\n\n"))
4998 (unless org-inhibit-startup
4999 (and org-startup-with-beamer-mode (org-beamer-mode))
5000 (when org-startup-align-all-tables
5001 (let ((bmp (buffer-modified-p)))
5002 (org-table-map-tables 'org-table-align 'quietly)
5003 (set-buffer-modified-p bmp)))
5004 (when org-startup-with-inline-images
5005 (org-display-inline-images))
5006 (unless org-inhibit-startup-visibility-stuff
5007 (org-set-startup-visibility)))
5008 ;; Try to set org-hide correctly
5009 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5011 (when (fboundp 'abbrev-table-put)
5012 (abbrev-table-put org-mode-abbrev-table
5013 :parents (list text-mode-abbrev-table)))
5015 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5017 (defsubst org-fix-ellipsis-at-bol ()
5018 (save-excursion (goto-char (window-start)) (recenter 0)))
5020 (defun org-find-invisible-foreground ()
5021 (let ((candidates (remove
5022 "unspecified-bg"
5023 (nconc
5024 (list (face-background 'default)
5025 (face-background 'org-default))
5026 (mapcar
5027 (lambda (alist)
5028 (when (boundp alist)
5029 (cdr (assoc 'background-color (symbol-value alist)))))
5030 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5031 (list (face-foreground 'org-hide))))))
5032 (car (remove nil candidates))))
5034 (defun org-current-time ()
5035 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5036 (if (> (car org-time-stamp-rounding-minutes) 1)
5037 (let ((r (car org-time-stamp-rounding-minutes))
5038 (time (decode-time)))
5039 (apply 'encode-time
5040 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5041 (nthcdr 2 time))))
5042 (current-time)))
5044 (defun org-today ()
5045 "Return today date, considering `org-extend-today-until'."
5046 (time-to-days
5047 (time-subtract (current-time)
5048 (list 0 (* 3600 org-extend-today-until) 0))))
5050 ;;;; Font-Lock stuff, including the activators
5052 (defvar org-mouse-map (make-sparse-keymap))
5053 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5054 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5055 (when org-mouse-1-follows-link
5056 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5057 (when org-tab-follows-link
5058 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5059 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5061 (require 'font-lock)
5063 (defconst org-non-link-chars "]\t\n\r<>")
5064 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5065 "shell" "elisp" "doi" "message"))
5066 (defvar org-link-types-re nil
5067 "Matches a link that has a url-like prefix like \"http:\"")
5068 (defvar org-link-re-with-space nil
5069 "Matches a link with spaces, optional angular brackets around it.")
5070 (defvar org-link-re-with-space2 nil
5071 "Matches a link with spaces, optional angular brackets around it.")
5072 (defvar org-link-re-with-space3 nil
5073 "Matches a link with spaces, only for internal part in bracket links.")
5074 (defvar org-angle-link-re nil
5075 "Matches link with angular brackets, spaces are allowed.")
5076 (defvar org-plain-link-re nil
5077 "Matches plain link, without spaces.")
5078 (defvar org-bracket-link-regexp nil
5079 "Matches a link in double brackets.")
5080 (defvar org-bracket-link-analytic-regexp nil
5081 "Regular expression used to analyze links.
5082 Here is what the match groups contain after a match:
5083 1: http:
5084 2: http
5085 3: path
5086 4: [desc]
5087 5: desc")
5088 (defvar org-bracket-link-analytic-regexp++ nil
5089 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5090 (defvar org-any-link-re nil
5091 "Regular expression matching any link.")
5093 (defcustom org-match-sexp-depth 3
5094 "Number of stacked braces for sub/superscript matching.
5095 This has to be set before loading org.el to be effective."
5096 :group 'org-export-translation ; ??????????????????????????/
5097 :type 'integer)
5099 (defun org-create-multibrace-regexp (left right n)
5100 "Create a regular expression which will match a balanced sexp.
5101 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5102 as single character strings.
5103 The regexp returned will match the entire expression including the
5104 delimiters. It will also define a single group which contains the
5105 match except for the outermost delimiters. The maximum depth of
5106 stacked delimiters is N. Escaping delimiters is not possible."
5107 (let* ((nothing (concat "[^" left right "]*?"))
5108 (or "\\|")
5109 (re nothing)
5110 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5111 (while (> n 1)
5112 (setq n (1- n)
5113 re (concat re or next)
5114 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5115 (concat left "\\(" re "\\)" right)))
5117 (defvar org-match-substring-regexp
5118 (concat
5119 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5120 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5121 "\\|"
5122 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5123 "\\|"
5124 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5125 "The regular expression matching a sub- or superscript.")
5127 (defvar org-match-substring-with-braces-regexp
5128 (concat
5129 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5130 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5131 "\\)")
5132 "The regular expression matching a sub- or superscript, forcing braces.")
5134 (defun org-make-link-regexps ()
5135 "Update the link regular expressions.
5136 This should be called after the variable `org-link-types' has changed."
5137 (setq org-link-types-re
5138 (concat
5139 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5140 org-link-re-with-space
5141 (concat
5142 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5143 "\\([^" org-non-link-chars " ]"
5144 "[^" org-non-link-chars "]*"
5145 "[^" org-non-link-chars " ]\\)>?")
5146 org-link-re-with-space2
5147 (concat
5148 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5149 "\\([^" org-non-link-chars " ]"
5150 "[^\t\n\r]*"
5151 "[^" org-non-link-chars " ]\\)>?")
5152 org-link-re-with-space3
5153 (concat
5154 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5155 "\\([^" org-non-link-chars " ]"
5156 "[^\t\n\r]*\\)")
5157 org-angle-link-re
5158 (concat
5159 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5160 "\\([^" org-non-link-chars " ]"
5161 "[^" org-non-link-chars "]*"
5162 "\\)>")
5163 org-plain-link-re
5164 (concat
5165 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5166 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5167 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5168 org-bracket-link-regexp
5169 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5170 org-bracket-link-analytic-regexp
5171 (concat
5172 "\\[\\["
5173 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5174 "\\([^]]+\\)"
5175 "\\]"
5176 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5177 "\\]")
5178 org-bracket-link-analytic-regexp++
5179 (concat
5180 "\\[\\["
5181 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5182 "\\([^]]+\\)"
5183 "\\]"
5184 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5185 "\\]")
5186 org-any-link-re
5187 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5188 org-angle-link-re "\\)\\|\\("
5189 org-plain-link-re "\\)")))
5191 (org-make-link-regexps)
5193 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5194 "Regular expression for fast time stamp matching.")
5195 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5196 "Regular expression for fast time stamp matching.")
5197 (defconst org-ts-regexp0
5198 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5199 "Regular expression matching time strings for analysis.
5200 This one does not require the space after the date, so it can be used
5201 on a string that terminates immediately after the date.")
5202 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5203 "Regular expression matching time strings for analysis.")
5204 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5205 "Regular expression matching time stamps, with groups.")
5206 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5207 "Regular expression matching time stamps (also [..]), with groups.")
5208 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5209 "Regular expression matching a time stamp range.")
5210 (defconst org-tr-regexp-both
5211 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5212 "Regular expression matching a time stamp range.")
5213 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5214 org-ts-regexp "\\)?")
5215 "Regular expression matching a time stamp or time stamp range.")
5216 (defconst org-tsr-regexp-both
5217 (concat org-ts-regexp-both "\\(--?-?"
5218 org-ts-regexp-both "\\)?")
5219 "Regular expression matching a time stamp or time stamp range.
5220 The time stamps may be either active or inactive.")
5222 (defvar org-emph-face nil)
5224 (defun org-do-emphasis-faces (limit)
5225 "Run through the buffer and add overlays to emphasized strings."
5226 (let (rtn a)
5227 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5228 (if (not (= (char-after (match-beginning 3))
5229 (char-after (match-beginning 4))))
5230 (progn
5231 (setq rtn t)
5232 (setq a (assoc (match-string 3) org-emphasis-alist))
5233 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5234 'face
5235 (nth 1 a))
5236 (and (nth 4 a)
5237 (org-remove-flyspell-overlays-in
5238 (match-beginning 0) (match-end 0)))
5239 (add-text-properties (match-beginning 2) (match-end 2)
5240 '(font-lock-multiline t org-emphasis t))
5241 (when org-hide-emphasis-markers
5242 (add-text-properties (match-end 4) (match-beginning 5)
5243 '(invisible org-link))
5244 (add-text-properties (match-beginning 3) (match-end 3)
5245 '(invisible org-link)))))
5246 (backward-char 1))
5247 rtn))
5249 (defun org-emphasize (&optional char)
5250 "Insert or change an emphasis, i.e. a font like bold or italic.
5251 If there is an active region, change that region to a new emphasis.
5252 If there is no region, just insert the marker characters and position
5253 the cursor between them.
5254 CHAR should be either the marker character, or the first character of the
5255 HTML tag associated with that emphasis. If CHAR is a space, the means
5256 to remove the emphasis of the selected region.
5257 If char is not given (for example in an interactive call) it
5258 will be prompted for."
5259 (interactive)
5260 (let ((eal org-emphasis-alist) e det
5261 (erc org-emphasis-regexp-components)
5262 (prompt "")
5263 (string "") beg end move tag c s)
5264 (if (org-region-active-p)
5265 (setq beg (region-beginning) end (region-end)
5266 string (buffer-substring beg end))
5267 (setq move t))
5269 (while (setq e (pop eal))
5270 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5271 c (aref tag 0))
5272 (push (cons c (string-to-char (car e))) det)
5273 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5274 (substring tag 1)))))
5275 (setq det (nreverse det))
5276 (unless char
5277 (message "%s" (concat "Emphasis marker or tag:" prompt))
5278 (setq char (read-char-exclusive)))
5279 (setq char (or (cdr (assoc char det)) char))
5280 (if (equal char ?\ )
5281 (setq s "" move nil)
5282 (unless (assoc (char-to-string char) org-emphasis-alist)
5283 (error "No such emphasis marker: \"%c\"" char))
5284 (setq s (char-to-string char)))
5285 (while (and (> (length string) 1)
5286 (equal (substring string 0 1) (substring string -1))
5287 (assoc (substring string 0 1) org-emphasis-alist))
5288 (setq string (substring string 1 -1)))
5289 (setq string (concat s string s))
5290 (if beg (delete-region beg end))
5291 (unless (or (bolp)
5292 (string-match (concat "[" (nth 0 erc) "\n]")
5293 (char-to-string (char-before (point)))))
5294 (insert " "))
5295 (unless (or (eobp)
5296 (string-match (concat "[" (nth 1 erc) "\n]")
5297 (char-to-string (char-after (point)))))
5298 (insert " ") (backward-char 1))
5299 (insert string)
5300 (and move (backward-char 1))))
5302 (defconst org-nonsticky-props
5303 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5305 (defsubst org-rear-nonsticky-at (pos)
5306 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5308 (defun org-activate-plain-links (limit)
5309 "Run through the buffer and add overlays to links."
5310 (let (f)
5311 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5312 (not (org-in-src-block-p)))
5313 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5314 (setq f (get-text-property (match-beginning 0) 'face))
5315 (unless (or (org-in-src-block-p)
5316 (eq f 'org-tag)
5317 (and (listp f) (memq 'org-tag f)))
5318 (add-text-properties (match-beginning 0) (match-end 0)
5319 (list 'mouse-face 'highlight
5320 'face 'org-link
5321 'keymap org-mouse-map))
5322 (org-rear-nonsticky-at (match-end 0)))
5323 t)))
5325 (defun org-activate-code (limit)
5326 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5327 (progn
5328 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5329 (remove-text-properties (match-beginning 0) (match-end 0)
5330 '(display t invisible t intangible t))
5331 t)))
5333 (defcustom org-src-fontify-natively nil
5334 "When non-nil, fontify code in code blocks."
5335 :type 'boolean
5336 :version "24.1"
5337 :group 'org-appearance
5338 :group 'org-babel)
5340 (defcustom org-allow-promoting-top-level-subtree nil
5341 "When non-nil, allow promoting a top level subtree.
5342 The leading star of the top level headline will be replaced
5343 by a #."
5344 :type 'boolean
5345 :version "24.1"
5346 :group 'org-appearance)
5348 (defun org-fontify-meta-lines-and-blocks (limit)
5349 (condition-case nil
5350 (org-fontify-meta-lines-and-blocks-1 limit)
5351 (error (message "org-mode fontification error"))))
5353 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5354 "Fontify #+ lines and blocks, in the correct ways."
5355 (let ((case-fold-search t))
5356 (if (re-search-forward
5357 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5358 limit t)
5359 (let ((beg (match-beginning 0))
5360 (block-start (match-end 0))
5361 (block-end nil)
5362 (lang (match-string 7))
5363 (beg1 (line-beginning-position 2))
5364 (dc1 (downcase (match-string 2)))
5365 (dc3 (downcase (match-string 3)))
5366 end end1 quoting block-type ovl)
5367 (cond
5368 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5369 ;; a single line of backend-specific content
5370 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5371 (remove-text-properties (match-beginning 0) (match-end 0)
5372 '(display t invisible t intangible t))
5373 (add-text-properties (match-beginning 1) (match-end 3)
5374 '(font-lock-fontified t face org-meta-line))
5375 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5376 '(font-lock-fontified t face org-block))
5377 ; for backend-specific code
5379 ((and (match-end 4) (equal dc3 "+begin"))
5380 ;; Truly a block
5381 (setq block-type (downcase (match-string 5))
5382 quoting (member block-type org-protecting-blocks))
5383 (when (re-search-forward
5384 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5385 nil t) ;; on purpose, we look further than LIMIT
5386 (setq end (min (point-max) (match-end 0))
5387 end1 (min (point-max) (1- (match-beginning 0))))
5388 (setq block-end (match-beginning 0))
5389 (when quoting
5390 (remove-text-properties beg end
5391 '(display t invisible t intangible t)))
5392 (add-text-properties
5393 beg end
5394 '(font-lock-fontified t font-lock-multiline t))
5395 (add-text-properties beg beg1 '(face org-meta-line))
5396 (add-text-properties end1 (min (point-max) (1+ end))
5397 '(face org-meta-line)) ; for end_src
5398 (cond
5399 ((and lang (not (string= lang "")) org-src-fontify-natively)
5400 (org-src-font-lock-fontify-block lang block-start block-end)
5401 ;; remove old background overlays
5402 (mapc (lambda (ov)
5403 (if (eq (overlay-get ov 'face) 'org-block-background)
5404 (delete-overlay ov)))
5405 (overlays-at (/ (+ beg1 block-end) 2)))
5406 ;; add a background overlay
5407 (setq ovl (make-overlay beg1 block-end))
5408 (overlay-put ovl 'face 'org-block-background)
5409 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5410 (quoting
5411 (add-text-properties beg1 (min (point-max) (1+ end1))
5412 '(face org-block))) ; end of source block
5413 ((not org-fontify-quote-and-verse-blocks))
5414 ((string= block-type "quote")
5415 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5416 ((string= block-type "verse")
5417 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5418 (add-text-properties beg beg1 '(face org-block-begin-line))
5419 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5420 '(face org-block-end-line))
5422 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5423 (add-text-properties
5424 beg (match-end 3)
5425 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5426 '(font-lock-fontified t invisible t)
5427 '(font-lock-fontified t face org-document-info-keyword)))
5428 (add-text-properties
5429 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5430 (if (string-equal dc1 "+title:")
5431 '(font-lock-fontified t face org-document-title)
5432 '(font-lock-fontified t face org-document-info))))
5433 ((or (equal dc1 "+results")
5434 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5435 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5436 "+call:" "+header:" "+headers:" "+name:"))
5437 (and (match-end 4) (equal dc3 "+attr")))
5438 (add-text-properties
5439 beg (match-end 0)
5440 '(font-lock-fontified t face org-meta-line))
5442 ((member dc3 '(" " ""))
5443 (add-text-properties
5444 beg (match-end 0)
5445 '(font-lock-fontified t face font-lock-comment-face)))
5446 ((not (member (char-after beg) '(?\ ?\t)))
5447 ;; just any other in-buffer setting, but not indented
5448 (add-text-properties
5449 beg (match-end 0)
5450 '(font-lock-fontified t face org-meta-line))
5452 (t nil))))))
5454 (defun org-activate-angle-links (limit)
5455 "Run through the buffer and add overlays to links."
5456 (if (and (re-search-forward org-angle-link-re limit t)
5457 (not (org-in-src-block-p)))
5458 (progn
5459 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5460 (add-text-properties (match-beginning 0) (match-end 0)
5461 (list 'mouse-face 'highlight
5462 'keymap org-mouse-map))
5463 (org-rear-nonsticky-at (match-end 0))
5464 t)))
5466 (defun org-activate-footnote-links (limit)
5467 "Run through the buffer and add overlays to footnotes."
5468 (let ((fn (org-footnote-next-reference-or-definition limit)))
5469 (when fn
5470 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5471 (org-remove-flyspell-overlays-in beg end)
5472 (add-text-properties beg end
5473 (list 'mouse-face 'highlight
5474 'keymap org-mouse-map
5475 'help-echo
5476 (if (= (point-at-bol) beg)
5477 "Footnote definition"
5478 "Footnote reference")
5479 'font-lock-fontified t
5480 'font-lock-multiline t
5481 'face 'org-footnote))))))
5483 (defun org-activate-bracket-links (limit)
5484 "Run through the buffer and add overlays to bracketed links."
5485 (if (and (re-search-forward org-bracket-link-regexp limit t)
5486 (not (org-in-src-block-p)))
5487 (let* ((help (concat "LINK: "
5488 (org-match-string-no-properties 1)))
5489 ;; FIXME: above we should remove the escapes.
5490 ;; but that requires another match, protecting match data,
5491 ;; a lot of overhead for font-lock.
5492 (ip (org-maybe-intangible
5493 (list 'invisible 'org-link
5494 'keymap org-mouse-map 'mouse-face 'highlight
5495 'font-lock-multiline t 'help-echo help)))
5496 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5497 'font-lock-multiline t 'help-echo help)))
5498 ;; We need to remove the invisible property here. Table narrowing
5499 ;; may have made some of this invisible.
5500 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5501 (remove-text-properties (match-beginning 0) (match-end 0)
5502 '(invisible nil))
5503 (if (match-end 3)
5504 (progn
5505 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5506 (org-rear-nonsticky-at (match-beginning 3))
5507 (add-text-properties (match-beginning 3) (match-end 3) vp)
5508 (org-rear-nonsticky-at (match-end 3))
5509 (add-text-properties (match-end 3) (match-end 0) ip)
5510 (org-rear-nonsticky-at (match-end 0)))
5511 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5512 (org-rear-nonsticky-at (match-beginning 1))
5513 (add-text-properties (match-beginning 1) (match-end 1) vp)
5514 (org-rear-nonsticky-at (match-end 1))
5515 (add-text-properties (match-end 1) (match-end 0) ip)
5516 (org-rear-nonsticky-at (match-end 0)))
5517 t)))
5519 (defun org-activate-dates (limit)
5520 "Run through the buffer and add overlays to dates."
5521 (if (and (re-search-forward org-tsr-regexp-both limit t)
5522 (not (equal (char-before (match-beginning 0)) 91)))
5523 (progn
5524 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5525 (add-text-properties (match-beginning 0) (match-end 0)
5526 (list 'mouse-face 'highlight
5527 'keymap org-mouse-map))
5528 (org-rear-nonsticky-at (match-end 0))
5529 (when org-display-custom-times
5530 (if (match-end 3)
5531 (org-display-custom-time (match-beginning 3) (match-end 3)))
5532 (org-display-custom-time (match-beginning 1) (match-end 1)))
5533 t)))
5535 (defvar org-target-link-regexp nil
5536 "Regular expression matching radio targets in plain text.")
5537 (make-variable-buffer-local 'org-target-link-regexp)
5538 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5539 "Regular expression matching a link target.")
5540 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5541 "Regular expression matching a radio target.")
5542 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5543 "Regular expression matching any target.")
5545 (defun org-activate-target-links (limit)
5546 "Run through the buffer and add overlays to target matches."
5547 (when org-target-link-regexp
5548 (let ((case-fold-search t))
5549 (if (re-search-forward org-target-link-regexp limit t)
5550 (progn
5551 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5552 (add-text-properties (match-beginning 0) (match-end 0)
5553 (list 'mouse-face 'highlight
5554 'keymap org-mouse-map
5555 'help-echo "Radio target link"
5556 'org-linked-text t))
5557 (org-rear-nonsticky-at (match-end 0))
5558 t)))))
5560 (defun org-update-radio-target-regexp ()
5561 "Find all radio targets in this file and update the regular expression."
5562 (interactive)
5563 (when (memq 'radio org-activate-links)
5564 (setq org-target-link-regexp
5565 (org-make-target-link-regexp (org-all-targets 'radio)))
5566 (org-restart-font-lock)))
5568 (defun org-hide-wide-columns (limit)
5569 (let (s e)
5570 (setq s (text-property-any (point) (or limit (point-max))
5571 'org-cwidth t))
5572 (when s
5573 (setq e (next-single-property-change s 'org-cwidth))
5574 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5575 (goto-char e)
5576 t)))
5578 (defvar org-latex-and-specials-regexp nil
5579 "Regular expression for highlighting export special stuff.")
5580 (defvar org-match-substring-regexp)
5581 (defvar org-match-substring-with-braces-regexp)
5583 ;; This should be with the exporter code, but we also use if for font-locking
5584 (defconst org-export-html-special-string-regexps
5585 '(("\\\\-" . "&shy;")
5586 ("---\\([^-]\\)" . "&mdash;\\1")
5587 ("--\\([^-]\\)" . "&ndash;\\1")
5588 ("\\.\\.\\." . "&hellip;"))
5589 "Regular expressions for special string conversion.")
5592 (defun org-compute-latex-and-specials-regexp ()
5593 "Compute regular expression for stuff treated specially by exporters."
5594 (if (not org-highlight-latex-fragments-and-specials)
5595 (org-set-local 'org-latex-and-specials-regexp nil)
5596 (require 'org-exp)
5597 (let*
5598 ((matchers (plist-get org-format-latex-options :matchers))
5599 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5600 org-latex-regexps)))
5601 (org-export-allow-BIND nil)
5602 (options (org-combine-plists (org-default-export-plist)
5603 (org-infile-export-plist)))
5604 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5605 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5606 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5607 (org-export-html-expand (plist-get options :expand-quoted-html))
5608 (org-export-with-special-strings (plist-get options :special-strings))
5609 (re-sub
5610 (cond
5611 ((equal org-export-with-sub-superscripts '{})
5612 (list org-match-substring-with-braces-regexp))
5613 (org-export-with-sub-superscripts
5614 (list org-match-substring-regexp))))
5615 (re-latex
5616 (if org-export-with-LaTeX-fragments
5617 (mapcar (lambda (x) (nth 1 x)) latexs)))
5618 (re-macros
5619 (if org-export-with-TeX-macros
5620 (list (concat "\\\\"
5621 (regexp-opt
5622 (append
5624 (delq nil
5625 (mapcar 'car-safe
5626 (append org-entities-user
5627 org-entities)))
5628 (if (boundp 'org-latex-entities)
5629 (mapcar (lambda (x)
5630 (or (car-safe x) x))
5631 org-latex-entities)
5632 nil))
5633 'words))) ; FIXME
5635 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5636 (re-special (if org-export-with-special-strings
5637 (mapcar (lambda (x) (car x))
5638 org-export-html-special-string-regexps)))
5639 (re-rest
5640 (delq nil
5641 (list
5642 (if org-export-html-expand "@<[^>\n]+>")
5643 ))))
5644 (org-set-local
5645 'org-latex-and-specials-regexp
5646 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5647 re-rest) "\\|")))))
5649 (defun org-do-latex-and-special-faces (limit)
5650 "Run through the buffer and add overlays to links."
5651 (when org-latex-and-specials-regexp
5652 (let (rtn d)
5653 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5654 limit t))
5655 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5656 'face))
5657 '(org-code org-verbatim underline)))
5658 (progn
5659 (setq rtn t
5660 d (cond ((member (char-after (1+ (match-beginning 0)))
5661 '(?_ ?^)) 1)
5662 (t 0)))
5663 (font-lock-prepend-text-property
5664 (+ d (match-beginning 0)) (match-end 0)
5665 'face 'org-latex-and-export-specials)
5666 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5667 '(font-lock-multiline t)))))
5668 rtn)))
5670 (defun org-restart-font-lock ()
5671 "Restart `font-lock-mode', to force refontification."
5672 (when (and (boundp 'font-lock-mode) font-lock-mode)
5673 (font-lock-mode -1)
5674 (font-lock-mode 1)))
5676 (defun org-all-targets (&optional radio)
5677 "Return a list of all targets in this file.
5678 With optional argument RADIO, only find radio targets."
5679 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5680 rtn)
5681 (save-excursion
5682 (goto-char (point-min))
5683 (while (re-search-forward re nil t)
5684 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5685 rtn)))
5687 (defun org-make-target-link-regexp (targets)
5688 "Make regular expression matching all strings in TARGETS.
5689 The regular expression finds the targets also if there is a line break
5690 between words."
5691 (and targets
5692 (concat
5693 "\\<\\("
5694 (mapconcat
5695 (lambda (x)
5696 (setq x (regexp-quote x))
5697 (while (string-match " +" x)
5698 (setq x (replace-match "\\s-+" t t x)))
5700 targets
5701 "\\|")
5702 "\\)\\>")))
5704 (defun org-activate-tags (limit)
5705 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5706 (progn
5707 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5708 (add-text-properties (match-beginning 1) (match-end 1)
5709 (list 'mouse-face 'highlight
5710 'keymap org-mouse-map))
5711 (org-rear-nonsticky-at (match-end 1))
5712 t)))
5714 (defun org-outline-level ()
5715 "Compute the outline level of the heading at point.
5716 This function assumes that the cursor is at the beginning of a line matched
5717 by `outline-regexp'. Otherwise it returns garbage.
5718 If this is called at a normal headline, the level is the number of stars.
5719 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5720 (save-excursion
5721 (looking-at org-outline-regexp)
5722 (1- (- (match-end 0) (match-beginning 0)))))
5724 (defvar org-font-lock-keywords nil)
5726 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5727 "Regular expression matching a property line.")
5729 (defvar org-font-lock-hook nil
5730 "Functions to be called for special font lock stuff.")
5732 (defvar org-font-lock-set-keywords-hook nil
5733 "Functions that can manipulate `org-font-lock-extra-keywords'.
5734 This is called after `org-font-lock-extra-keywords' is defined, but before
5735 it is installed to be used by font lock. This can be useful if something
5736 needs to be inserted at a specific position in the font-lock sequence.")
5738 (defun org-font-lock-hook (limit)
5739 "Run `org-font-lock-hook' within LIMIT."
5740 (run-hook-with-args 'org-font-lock-hook limit))
5742 (defun org-set-font-lock-defaults ()
5743 "Set font lock defaults for the current buffer."
5744 (let* ((em org-fontify-emphasized-text)
5745 (lk org-activate-links)
5746 (org-font-lock-extra-keywords
5747 (list
5748 ;; Call the hook
5749 '(org-font-lock-hook)
5750 ;; Headlines
5751 `(,(if org-fontify-whole-heading-line
5752 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5753 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5754 (1 (org-get-level-face 1))
5755 (2 (org-get-level-face 2))
5756 (3 (org-get-level-face 3)))
5757 ;; Table lines
5758 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5759 (1 'org-table t))
5760 ;; Table internals
5761 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5762 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5763 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5764 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5765 ;; Drawers
5766 (list org-drawer-regexp '(0 'org-special-keyword t))
5767 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5768 ;; Properties
5769 (list org-property-re
5770 '(1 'org-special-keyword t)
5771 '(3 'org-property-value t))
5772 ;; Links
5773 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5774 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5775 (if (memq 'plain lk) '(org-activate-plain-links))
5776 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5777 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5778 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5779 (if (memq 'footnote lk) '(org-activate-footnote-links))
5780 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5781 '(org-hide-wide-columns (0 nil append))
5782 ;; TODO keyword
5783 (list (format org-heading-keyword-regexp-format
5784 org-todo-regexp)
5785 '(2 (org-get-todo-face 2) t))
5786 ;; DONE
5787 (if org-fontify-done-headline
5788 (list (format org-heading-keyword-regexp-format
5789 (concat
5790 "\\(?:"
5791 (mapconcat 'regexp-quote org-done-keywords "\\|")
5792 "\\)"))
5793 '(2 'org-headline-done t))
5794 nil)
5795 ;; Priorities
5796 '(org-font-lock-add-priority-faces)
5797 ;; Tags
5798 '(org-font-lock-add-tag-faces)
5799 ;; Special keywords
5800 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5801 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5802 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5803 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5804 ;; Emphasis
5805 (if em
5806 (if (featurep 'xemacs)
5807 '(org-do-emphasis-faces (0 nil append))
5808 '(org-do-emphasis-faces)))
5809 ;; Checkboxes
5810 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5811 1 'org-checkbox prepend)
5812 (if (cdr (assq 'checkbox org-list-automatic-rules))
5813 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5814 (0 (org-get-checkbox-statistics-face) t)))
5815 ;; Description list items
5816 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5817 1 'org-list-dt prepend)
5818 ;; ARCHIVEd headings
5819 (list (concat
5820 org-outline-regexp-bol
5821 "\\(.*:" org-archive-tag ":.*\\)")
5822 '(1 'org-archived prepend))
5823 ;; Specials
5824 '(org-do-latex-and-special-faces)
5825 '(org-fontify-entities)
5826 '(org-raise-scripts)
5827 ;; Code
5828 '(org-activate-code (1 'org-code t))
5829 ;; COMMENT
5830 (list (format org-heading-keyword-regexp-format
5831 (concat "\\("
5832 org-comment-string "\\|" org-quote-string
5833 "\\)"))
5834 '(2 'org-special-keyword t))
5835 ;; Blocks and meta lines
5836 '(org-fontify-meta-lines-and-blocks)
5838 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5839 (run-hooks 'org-font-lock-set-keywords-hook)
5840 ;; Now set the full font-lock-keywords
5841 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5842 (org-set-local 'font-lock-defaults
5843 '(org-font-lock-keywords t nil nil backward-paragraph))
5844 (kill-local-variable 'font-lock-keywords) nil))
5846 (defun org-toggle-pretty-entities ()
5847 "Toggle the composition display of entities as UTF8 characters."
5848 (interactive)
5849 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5850 (org-restart-font-lock)
5851 (if org-pretty-entities
5852 (message "Entities are displayed as UTF8 characters")
5853 (save-restriction
5854 (widen)
5855 (org-decompose-region (point-min) (point-max))
5856 (message "Entities are displayed plain"))))
5858 (defvar org-custom-properties-overlays nil
5859 "List of overlays used for custom properties.")
5860 (make-variable-buffer-local 'org-custom-properties-overlays)
5862 (defun org-toggle-custom-properties-visibility ()
5863 "Display or hide properties in `org-custom-properties'."
5864 (interactive)
5865 (if org-custom-properties-overlays
5866 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5867 (setq org-custom-properties-overlays nil))
5868 (unless (not org-custom-properties)
5869 (save-excursion
5870 (save-restriction
5871 (widen)
5872 (goto-char (point-min))
5873 (while (re-search-forward org-property-re nil t)
5874 (mapc (lambda(p)
5875 (when (equal p (substring (match-string 1) 1 -1))
5876 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5877 (overlay-put o 'invisible t)
5878 (overlay-put o 'org-custom-property t)
5879 (push o org-custom-properties-overlays))))
5880 org-custom-properties)))))))
5882 (defun org-fontify-entities (limit)
5883 "Find an entity to fontify."
5884 (let (ee)
5885 (when org-pretty-entities
5886 (catch 'match
5887 (while (re-search-forward
5888 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5889 limit t)
5890 (if (and (not (org-in-indented-comment-line))
5891 (setq ee (org-entity-get (match-string 1)))
5892 (= (length (nth 6 ee)) 1))
5893 (let*
5894 ((end (if (equal (match-string 2) "{}")
5895 (match-end 2)
5896 (match-end 1))))
5897 (add-text-properties
5898 (match-beginning 0) end
5899 (list 'font-lock-fontified t))
5900 (compose-region (match-beginning 0) end
5901 (nth 6 ee) nil)
5902 (backward-char 1)
5903 (throw 'match t))))
5904 nil))))
5906 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5907 "Fontify string S like in Org-mode."
5908 (with-temp-buffer
5909 (insert s)
5910 (let ((org-odd-levels-only odd-levels))
5911 (org-mode)
5912 (font-lock-fontify-buffer)
5913 (buffer-string))))
5915 (defvar org-m nil)
5916 (defvar org-l nil)
5917 (defvar org-f nil)
5918 (defun org-get-level-face (n)
5919 "Get the right face for match N in font-lock matching of headlines."
5920 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5921 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5922 (if org-cycle-level-faces
5923 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5924 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5925 (cond
5926 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5927 ((eq n 2) org-f)
5928 (t (if org-level-color-stars-only nil org-f))))
5931 (defun org-get-todo-face (kwd)
5932 "Get the right face for a TODO keyword KWD.
5933 If KWD is a number, get the corresponding match group."
5934 (if (numberp kwd) (setq kwd (match-string kwd)))
5935 (or (org-face-from-face-or-color
5936 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5937 (and (member kwd org-done-keywords) 'org-done)
5938 'org-todo))
5940 (defun org-face-from-face-or-color (context inherit face-or-color)
5941 "Create a face list that inherits INHERIT, but sets the foreground color.
5942 When FACE-OR-COLOR is not a string, just return it."
5943 (if (stringp face-or-color)
5944 (list :inherit inherit
5945 (cdr (assoc context org-faces-easy-properties))
5946 face-or-color)
5947 face-or-color))
5949 (defun org-font-lock-add-tag-faces (limit)
5950 "Add the special tag faces."
5951 (when (and org-tag-faces org-tags-special-faces-re)
5952 (while (re-search-forward org-tags-special-faces-re limit t)
5953 (add-text-properties (match-beginning 1) (match-end 1)
5954 (list 'face (org-get-tag-face 1)
5955 'font-lock-fontified t))
5956 (backward-char 1))))
5958 (defun org-font-lock-add-priority-faces (limit)
5959 "Add the special priority faces."
5960 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5961 (when (save-match-data (org-at-heading-p))
5962 (add-text-properties
5963 (match-beginning 0) (match-end 0)
5964 (list 'face (or (org-face-from-face-or-color
5965 'priority 'org-special-keyword
5966 (cdr (assoc (char-after (match-beginning 1))
5967 org-priority-faces)))
5968 'org-special-keyword)
5969 'font-lock-fontified t)))))
5971 (defun org-get-tag-face (kwd)
5972 "Get the right face for a TODO keyword KWD.
5973 If KWD is a number, get the corresponding match group."
5974 (if (numberp kwd) (setq kwd (match-string kwd)))
5975 (or (org-face-from-face-or-color
5976 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5977 'org-tag))
5979 (defun org-unfontify-region (beg end &optional maybe_loudly)
5980 "Remove fontification and activation overlays from links."
5981 (font-lock-default-unfontify-region beg end)
5982 (let* ((buffer-undo-list t)
5983 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5984 (inhibit-modification-hooks t)
5985 deactivate-mark buffer-file-name buffer-file-truename)
5986 (org-decompose-region beg end)
5987 (remove-text-properties beg end
5988 '(mouse-face t keymap t org-linked-text t
5989 invisible t intangible t
5990 org-no-flyspell t org-emphasis t))
5991 (org-remove-font-lock-display-properties beg end)))
5993 (defconst org-script-display '(((raise -0.3) (height 0.7))
5994 ((raise 0.3) (height 0.7))
5995 ((raise -0.5))
5996 ((raise 0.5)))
5997 "Display properties for showing superscripts and subscripts.")
5999 (defun org-remove-font-lock-display-properties (beg end)
6000 "Remove specific display properties that have been added by font lock.
6001 The will remove the raise properties that are used to show superscripts
6002 and subscripts."
6003 (let (next prop)
6004 (while (< beg end)
6005 (setq next (next-single-property-change beg 'display nil end)
6006 prop (get-text-property beg 'display))
6007 (if (member prop org-script-display)
6008 (put-text-property beg next 'display nil))
6009 (setq beg next))))
6011 (defun org-raise-scripts (limit)
6012 "Add raise properties to sub/superscripts."
6013 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6014 (if (re-search-forward
6015 (if (eq org-use-sub-superscripts t)
6016 org-match-substring-regexp
6017 org-match-substring-with-braces-regexp)
6018 limit t)
6019 (let* ((pos (point)) table-p comment-p
6020 (mpos (match-beginning 3))
6021 (emph-p (get-text-property mpos 'org-emphasis))
6022 (link-p (get-text-property mpos 'mouse-face))
6023 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6024 (goto-char (point-at-bol))
6025 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6026 comment-p (org-looking-at-p "[ \t]*#"))
6027 (goto-char pos)
6028 ;; FIXME: Should we go back one character here, for a_b^c
6029 ;; (goto-char (1- pos)) ;????????????????????
6030 (if (or comment-p emph-p link-p keyw-p)
6032 (put-text-property (match-beginning 3) (match-end 0)
6033 'display
6034 (if (equal (char-after (match-beginning 2)) ?^)
6035 (nth (if table-p 3 1) org-script-display)
6036 (nth (if table-p 2 0) org-script-display)))
6037 (add-text-properties (match-beginning 2) (match-end 2)
6038 (list 'invisible t
6039 'org-dwidth t 'org-dwidth-n 1))
6040 (if (and (eq (char-after (match-beginning 3)) ?{)
6041 (eq (char-before (match-end 3)) ?}))
6042 (progn
6043 (add-text-properties
6044 (match-beginning 3) (1+ (match-beginning 3))
6045 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6046 (add-text-properties
6047 (1- (match-end 3)) (match-end 3)
6048 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6049 t)))))
6051 ;;;; Visibility cycling, including org-goto and indirect buffer
6053 ;;; Cycling
6055 (defvar org-cycle-global-status nil)
6056 (make-variable-buffer-local 'org-cycle-global-status)
6057 (defvar org-cycle-subtree-status nil)
6058 (make-variable-buffer-local 'org-cycle-subtree-status)
6060 (defvar org-inlinetask-min-level)
6062 ;;;###autoload
6063 (defun org-cycle (&optional arg)
6064 "TAB-action and visibility cycling for Org-mode.
6066 This is the command invoked in Org-mode by the TAB key. Its main purpose
6067 is outline visibility cycling, but it also invokes other actions
6068 in special contexts.
6070 - When this function is called with a prefix argument, rotate the entire
6071 buffer through 3 states (global cycling)
6072 1. OVERVIEW: Show only top-level headlines.
6073 2. CONTENTS: Show all headlines of all levels, but no body text.
6074 3. SHOW ALL: Show everything.
6075 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6076 determined by the variable `org-startup-folded', and by any VISIBILITY
6077 properties in the buffer.
6078 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6079 including any drawers.
6081 - When inside a table, re-align the table and move to the next field.
6083 - When point is at the beginning of a headline, rotate the subtree started
6084 by this line through 3 different states (local cycling)
6085 1. FOLDED: Only the main headline is shown.
6086 2. CHILDREN: The main headline and the direct children are shown.
6087 From this state, you can move to one of the children
6088 and zoom in further.
6089 3. SUBTREE: Show the entire subtree, including body text.
6090 If there is no subtree, switch directly from CHILDREN to FOLDED.
6092 - When point is at the beginning of an empty headline and the variable
6093 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6094 of the headline by demoting and promoting it to likely levels. This
6095 speeds up creation document structure by pressing TAB once or several
6096 times right after creating a new headline.
6098 - When there is a numeric prefix, go up to a heading with level ARG, do
6099 a `show-subtree' and return to the previous cursor position. If ARG
6100 is negative, go up that many levels.
6102 - When point is not at the beginning of a headline, execute the global
6103 binding for TAB, which is re-indenting the line. See the option
6104 `org-cycle-emulate-tab' for details.
6106 - Special case: if point is at the beginning of the buffer and there is
6107 no headline in line 1, this function will act as if called with prefix arg
6108 (C-u TAB, same as S-TAB) also when called without prefix arg.
6109 But only if also the variable `org-cycle-global-at-bob' is t."
6110 (interactive "P")
6111 (org-load-modules-maybe)
6112 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6113 (and org-cycle-level-after-item/entry-creation
6114 (or (org-cycle-level)
6115 (org-cycle-item-indentation))))
6116 (let* ((limit-level
6117 (or org-cycle-max-level
6118 (and (boundp 'org-inlinetask-min-level)
6119 org-inlinetask-min-level
6120 (1- org-inlinetask-min-level))))
6121 (nstars (and limit-level
6122 (if org-odd-levels-only
6123 (and limit-level (1- (* limit-level 2)))
6124 limit-level)))
6125 (org-outline-regexp
6126 (if (not (derived-mode-p 'org-mode))
6127 outline-regexp
6128 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6129 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6130 (not (looking-at org-outline-regexp))))
6131 (org-cycle-hook
6132 (if bob-special
6133 (delq 'org-optimize-window-after-visibility-change
6134 (copy-sequence org-cycle-hook))
6135 org-cycle-hook))
6136 (pos (point)))
6138 (if (or bob-special (equal arg '(4)))
6139 ;; special case: use global cycling
6140 (setq arg t))
6142 (cond
6144 ((equal arg '(16))
6145 (setq last-command 'dummy)
6146 (org-set-startup-visibility)
6147 (message "Startup visibility, plus VISIBILITY properties"))
6149 ((equal arg '(64))
6150 (show-all)
6151 (message "Entire buffer visible, including drawers"))
6153 ;; Table: enter it or move to the next field.
6154 ((org-at-table-p 'any)
6155 (if (org-at-table.el-p)
6156 (message "Use C-c ' to edit table.el tables")
6157 (if arg (org-table-edit-field t)
6158 (org-table-justify-field-maybe)
6159 (call-interactively 'org-table-next-field))))
6161 ((run-hook-with-args-until-success
6162 'org-tab-after-check-for-table-hook))
6164 ;; Global cycling: delegate to `org-cycle-internal-global'.
6165 ((eq arg t) (org-cycle-internal-global))
6167 ;; Drawers: delegate to `org-flag-drawer'.
6168 ((and org-drawers org-drawer-regexp
6169 (save-excursion
6170 (beginning-of-line 1)
6171 (looking-at org-drawer-regexp)))
6172 (org-flag-drawer ; toggle block visibility
6173 (not (get-char-property (match-end 0) 'invisible))))
6175 ;; Show-subtree, ARG levels up from here.
6176 ((integerp arg)
6177 (save-excursion
6178 (org-back-to-heading)
6179 (outline-up-heading (if (< arg 0) (- arg)
6180 (- (funcall outline-level) arg)))
6181 (org-show-subtree)))
6183 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6184 ((and (featurep 'org-inlinetask)
6185 (org-inlinetask-at-task-p)
6186 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6187 (org-inlinetask-toggle-visibility))
6189 ((org-try-cdlatex-tab))
6191 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6192 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6193 (save-excursion (beginning-of-line 1)
6194 (looking-at org-outline-regexp)))
6195 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6196 (org-cycle-internal-local))
6198 ;; From there: TAB emulation and template completion.
6199 (buffer-read-only (org-back-to-heading))
6201 ((run-hook-with-args-until-success
6202 'org-tab-after-check-for-cycling-hook))
6204 ((org-try-structure-completion))
6206 ((run-hook-with-args-until-success
6207 'org-tab-before-tab-emulation-hook))
6209 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6210 (or (not (bolp))
6211 (not (looking-at org-outline-regexp))))
6212 (call-interactively (global-key-binding "\t")))
6214 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6215 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6216 (or (and (eq org-cycle-emulate-tab 'white)
6217 (= (match-end 0) (point-at-eol)))
6218 (and (eq org-cycle-emulate-tab 'whitestart)
6219 (>= (match-end 0) pos))))
6221 (eq org-cycle-emulate-tab t))
6222 (call-interactively (global-key-binding "\t")))
6224 (t (save-excursion
6225 (org-back-to-heading)
6226 (org-cycle)))))))
6228 (defun org-cycle-internal-global ()
6229 "Do the global cycling action."
6230 ;; Hack to avoid display of messages for .org attachments in Gnus
6231 (let ((ga (string-match "\\*fontification" (buffer-name))))
6232 (cond
6233 ((and (eq last-command this-command)
6234 (eq org-cycle-global-status 'overview))
6235 ;; We just created the overview - now do table of contents
6236 ;; This can be slow in very large buffers, so indicate action
6237 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6238 (unless ga (message "CONTENTS..."))
6239 (org-content)
6240 (unless ga (message "CONTENTS...done"))
6241 (setq org-cycle-global-status 'contents)
6242 (run-hook-with-args 'org-cycle-hook 'contents))
6244 ((and (eq last-command this-command)
6245 (eq org-cycle-global-status 'contents))
6246 ;; We just showed the table of contents - now show everything
6247 (run-hook-with-args 'org-pre-cycle-hook 'all)
6248 (show-all)
6249 (unless ga (message "SHOW ALL"))
6250 (setq org-cycle-global-status 'all)
6251 (run-hook-with-args 'org-cycle-hook 'all))
6254 ;; Default action: go to overview
6255 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6256 (org-overview)
6257 (unless ga (message "OVERVIEW"))
6258 (setq org-cycle-global-status 'overview)
6259 (run-hook-with-args 'org-cycle-hook 'overview)))))
6261 (defun org-cycle-internal-local ()
6262 "Do the local cycling action."
6263 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6264 ;; First, determine end of headline (EOH), end of subtree or item
6265 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6266 (save-excursion
6267 (if (org-at-item-p)
6268 (progn
6269 (beginning-of-line)
6270 (setq struct (org-list-struct))
6271 (setq eoh (point-at-eol))
6272 (setq eos (org-list-get-item-end-before-blank (point) struct))
6273 (setq has-children (org-list-has-child-p (point) struct)))
6274 (org-back-to-heading)
6275 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6276 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6277 (setq has-children
6278 (or (save-excursion
6279 (let ((level (funcall outline-level)))
6280 (outline-next-heading)
6281 (and (org-at-heading-p t)
6282 (> (funcall outline-level) level))))
6283 (save-excursion
6284 (org-list-search-forward (org-item-beginning-re) eos t)))))
6285 ;; Determine end invisible part of buffer (EOL)
6286 (beginning-of-line 2)
6287 ;; XEmacs doesn't have `next-single-char-property-change'
6288 (if (featurep 'xemacs)
6289 (while (and (not (eobp)) ;; this is like `next-line'
6290 (get-char-property (1- (point)) 'invisible))
6291 (beginning-of-line 2))
6292 (while (and (not (eobp)) ;; this is like `next-line'
6293 (get-char-property (1- (point)) 'invisible))
6294 (goto-char (next-single-char-property-change (point) 'invisible))
6295 (and (eolp) (beginning-of-line 2))))
6296 (setq eol (point)))
6297 ;; Find out what to do next and set `this-command'
6298 (cond
6299 ((= eos eoh)
6300 ;; Nothing is hidden behind this heading
6301 (unless (org-before-first-heading-p)
6302 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6303 (message "EMPTY ENTRY")
6304 (setq org-cycle-subtree-status nil)
6305 (save-excursion
6306 (goto-char eos)
6307 (outline-next-heading)
6308 (if (outline-invisible-p) (org-flag-heading nil))))
6309 ((and (or (>= eol eos)
6310 (not (string-match "\\S-" (buffer-substring eol eos))))
6311 (or has-children
6312 (not (setq children-skipped
6313 org-cycle-skip-children-state-if-no-children))))
6314 ;; Entire subtree is hidden in one line: children view
6315 (unless (org-before-first-heading-p)
6316 (run-hook-with-args 'org-pre-cycle-hook 'children))
6317 (if (org-at-item-p)
6318 (org-list-set-item-visibility (point-at-bol) struct 'children)
6319 (org-show-entry)
6320 (org-with-limited-levels (show-children))
6321 ;; FIXME: This slows down the func way too much.
6322 ;; How keep drawers hidden in subtree anyway?
6323 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6324 ;; (org-cycle-hide-drawers 'subtree))
6326 ;; Fold every list in subtree to top-level items.
6327 (when (eq org-cycle-include-plain-lists 'integrate)
6328 (save-excursion
6329 (org-back-to-heading)
6330 (while (org-list-search-forward (org-item-beginning-re) eos t)
6331 (beginning-of-line 1)
6332 (let* ((struct (org-list-struct))
6333 (prevs (org-list-prevs-alist struct))
6334 (end (org-list-get-bottom-point struct)))
6335 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6336 (org-list-get-all-items (point) struct prevs))
6337 (goto-char end))))))
6338 (message "CHILDREN")
6339 (save-excursion
6340 (goto-char eos)
6341 (outline-next-heading)
6342 (if (outline-invisible-p) (org-flag-heading nil)))
6343 (setq org-cycle-subtree-status 'children)
6344 (unless (org-before-first-heading-p)
6345 (run-hook-with-args 'org-cycle-hook 'children)))
6346 ((or children-skipped
6347 (and (eq last-command this-command)
6348 (eq org-cycle-subtree-status 'children)))
6349 ;; We just showed the children, or no children are there,
6350 ;; now show everything.
6351 (unless (org-before-first-heading-p)
6352 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6353 (outline-flag-region eoh eos nil)
6354 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6355 (setq org-cycle-subtree-status 'subtree)
6356 (unless (org-before-first-heading-p)
6357 (run-hook-with-args 'org-cycle-hook 'subtree)))
6359 ;; Default action: hide the subtree.
6360 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6361 (outline-flag-region eoh eos t)
6362 (message "FOLDED")
6363 (setq org-cycle-subtree-status 'folded)
6364 (unless (org-before-first-heading-p)
6365 (run-hook-with-args 'org-cycle-hook 'folded))))))
6367 ;;;###autoload
6368 (defun org-global-cycle (&optional arg)
6369 "Cycle the global visibility. For details see `org-cycle'.
6370 With \\[universal-argument] prefix arg, switch to startup visibility.
6371 With a numeric prefix, show all headlines up to that level."
6372 (interactive "P")
6373 (let ((org-cycle-include-plain-lists
6374 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6375 (cond
6376 ((integerp arg)
6377 (show-all)
6378 (hide-sublevels arg)
6379 (setq org-cycle-global-status 'contents))
6380 ((equal arg '(4))
6381 (org-set-startup-visibility)
6382 (message "Startup visibility, plus VISIBILITY properties."))
6384 (org-cycle '(4))))))
6386 (defun org-set-startup-visibility ()
6387 "Set the visibility required by startup options and properties."
6388 (cond
6389 ((eq org-startup-folded t)
6390 (org-cycle '(4)))
6391 ((eq org-startup-folded 'content)
6392 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6393 (org-cycle '(4)) (org-cycle '(4)))))
6394 (unless (eq org-startup-folded 'showeverything)
6395 (if org-hide-block-startup (org-hide-block-all))
6396 (org-set-visibility-according-to-property 'no-cleanup)
6397 (org-cycle-hide-archived-subtrees 'all)
6398 (org-cycle-hide-drawers 'all)
6399 (org-cycle-show-empty-lines t)))
6401 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6402 "Switch subtree visibilities according to :VISIBILITY: property."
6403 (interactive)
6404 (let (org-show-entry-below state)
6405 (save-excursion
6406 (goto-char (point-min))
6407 (while (re-search-forward
6408 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6409 nil t)
6410 (setq state (match-string 1))
6411 (save-excursion
6412 (org-back-to-heading t)
6413 (hide-subtree)
6414 (org-reveal)
6415 (cond
6416 ((equal state '("fold" "folded"))
6417 (hide-subtree))
6418 ((equal state "children")
6419 (org-show-hidden-entry)
6420 (show-children))
6421 ((equal state "content")
6422 (save-excursion
6423 (save-restriction
6424 (org-narrow-to-subtree)
6425 (org-content))))
6426 ((member state '("all" "showall"))
6427 (show-subtree)))))
6428 (unless no-cleanup
6429 (org-cycle-hide-archived-subtrees 'all)
6430 (org-cycle-hide-drawers 'all)
6431 (org-cycle-show-empty-lines 'all)))))
6433 ;; This function uses outline-regexp instead of the more fundamental
6434 ;; org-outline-regexp so that org-cycle-global works outside of Org
6435 ;; buffers, where outline-regexp is needed.
6436 (defun org-overview ()
6437 "Switch to overview mode, showing only top-level headlines.
6438 Really, this shows all headlines with level equal or greater than the level
6439 of the first headline in the buffer. This is important, because if the
6440 first headline is not level one, then (hide-sublevels 1) gives confusing
6441 results."
6442 (interactive)
6443 (let ((l (org-current-line))
6444 (level (save-excursion
6445 (goto-char (point-min))
6446 (if (re-search-forward (concat "^" outline-regexp) nil t)
6447 (progn
6448 (goto-char (match-beginning 0))
6449 (funcall outline-level))))))
6450 (and level (hide-sublevels level))
6451 (recenter '(4))
6452 (org-goto-line l)))
6454 (defun org-content (&optional arg)
6455 "Show all headlines in the buffer, like a table of contents.
6456 With numerical argument N, show content up to level N."
6457 (interactive "P")
6458 (save-excursion
6459 ;; Visit all headings and show their offspring
6460 (and (integerp arg) (org-overview))
6461 (goto-char (point-max))
6462 (catch 'exit
6463 (while (and (progn (condition-case nil
6464 (outline-previous-visible-heading 1)
6465 (error (goto-char (point-min))))
6467 (looking-at org-outline-regexp))
6468 (if (integerp arg)
6469 (show-children (1- arg))
6470 (show-branches))
6471 (if (bobp) (throw 'exit nil))))))
6474 (defun org-optimize-window-after-visibility-change (state)
6475 "Adjust the window after a change in outline visibility.
6476 This function is the default value of the hook `org-cycle-hook'."
6477 (when (get-buffer-window (current-buffer))
6478 (cond
6479 ((eq state 'content) nil)
6480 ((eq state 'all) nil)
6481 ((eq state 'folded) nil)
6482 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6483 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6485 (defun org-remove-empty-overlays-at (pos)
6486 "Remove outline overlays that do not contain non-white stuff."
6487 (mapc
6488 (lambda (o)
6489 (and (eq 'outline (overlay-get o 'invisible))
6490 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6491 (overlay-end o))))
6492 (delete-overlay o)))
6493 (overlays-at pos)))
6495 (defun org-clean-visibility-after-subtree-move ()
6496 "Fix visibility issues after moving a subtree."
6497 ;; First, find a reasonable region to look at:
6498 ;; Start two siblings above, end three below
6499 (let* ((beg (save-excursion
6500 (and (org-get-last-sibling)
6501 (org-get-last-sibling))
6502 (point)))
6503 (end (save-excursion
6504 (and (org-get-next-sibling)
6505 (org-get-next-sibling)
6506 (org-get-next-sibling))
6507 (if (org-at-heading-p)
6508 (point-at-eol)
6509 (point))))
6510 (level (looking-at "\\*+"))
6511 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6512 (save-excursion
6513 (save-restriction
6514 (narrow-to-region beg end)
6515 (when re
6516 ;; Properly fold already folded siblings
6517 (goto-char (point-min))
6518 (while (re-search-forward re nil t)
6519 (if (and (not (outline-invisible-p))
6520 (save-excursion
6521 (goto-char (point-at-eol)) (outline-invisible-p)))
6522 (hide-entry))))
6523 (org-cycle-show-empty-lines 'overview)
6524 (org-cycle-hide-drawers 'overview)))))
6526 (defun org-cycle-show-empty-lines (state)
6527 "Show empty lines above all visible headlines.
6528 The region to be covered depends on STATE when called through
6529 `org-cycle-hook'. Lisp program can use t for STATE to get the
6530 entire buffer covered. Note that an empty line is only shown if there
6531 are at least `org-cycle-separator-lines' empty lines before the headline."
6532 (when (not (= org-cycle-separator-lines 0))
6533 (save-excursion
6534 (let* ((n (abs org-cycle-separator-lines))
6535 (re (cond
6536 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6537 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6538 (t (let ((ns (number-to-string (- n 2))))
6539 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6540 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6541 beg end b e)
6542 (cond
6543 ((memq state '(overview contents t))
6544 (setq beg (point-min) end (point-max)))
6545 ((memq state '(children folded))
6546 (setq beg (point) end (progn (org-end-of-subtree t t)
6547 (beginning-of-line 2)
6548 (point)))))
6549 (when beg
6550 (goto-char beg)
6551 (while (re-search-forward re end t)
6552 (unless (get-char-property (match-end 1) 'invisible)
6553 (setq e (match-end 1))
6554 (if (< org-cycle-separator-lines 0)
6555 (setq b (save-excursion
6556 (goto-char (match-beginning 0))
6557 (org-back-over-empty-lines)
6558 (if (save-excursion
6559 (goto-char (max (point-min) (1- (point))))
6560 (org-at-heading-p))
6561 (1- (point))
6562 (point))))
6563 (setq b (match-beginning 1)))
6564 (outline-flag-region b e nil)))))))
6565 ;; Never hide empty lines at the end of the file.
6566 (save-excursion
6567 (goto-char (point-max))
6568 (outline-previous-heading)
6569 (outline-end-of-heading)
6570 (if (and (looking-at "[ \t\n]+")
6571 (= (match-end 0) (point-max)))
6572 (outline-flag-region (point) (match-end 0) nil))))
6574 (defun org-show-empty-lines-in-parent ()
6575 "Move to the parent and re-show empty lines before visible headlines."
6576 (save-excursion
6577 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6578 (org-cycle-show-empty-lines context))))
6580 (defun org-files-list ()
6581 "Return `org-agenda-files' list, plus all open org-mode files.
6582 This is useful for operations that need to scan all of a user's
6583 open and agenda-wise Org files."
6584 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6585 (dolist (buf (buffer-list))
6586 (with-current-buffer buf
6587 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6588 (let ((file (expand-file-name (buffer-file-name))))
6589 (unless (member file files)
6590 (push file files))))))
6591 files))
6593 (defsubst org-entry-beginning-position ()
6594 "Return the beginning position of the current entry."
6595 (save-excursion (outline-back-to-heading t) (point)))
6597 (defsubst org-entry-end-position ()
6598 "Return the end position of the current entry."
6599 (save-excursion (outline-next-heading) (point)))
6601 (defun org-cycle-hide-drawers (state)
6602 "Re-hide all drawers after a visibility state change."
6603 (when (and (derived-mode-p 'org-mode)
6604 (not (memq state '(overview folded contents))))
6605 (save-excursion
6606 (let* ((globalp (memq state '(contents all)))
6607 (beg (if globalp (point-min) (point)))
6608 (end (if globalp (point-max)
6609 (if (eq state 'children)
6610 (save-excursion (outline-next-heading) (point))
6611 (org-end-of-subtree t)))))
6612 (goto-char beg)
6613 (while (re-search-forward org-drawer-regexp end t)
6614 (org-flag-drawer t))))))
6616 (defun org-flag-drawer (flag)
6617 "When FLAG is non-nil, hide the drawer we are within.
6618 Otherwise make it visible."
6619 (save-excursion
6620 (beginning-of-line 1)
6621 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6622 (let ((b (match-end 0)))
6623 (if (re-search-forward
6624 "^[ \t]*:END:"
6625 (save-excursion (outline-next-heading) (point)) t)
6626 (outline-flag-region b (point-at-eol) flag)
6627 (error ":END: line missing at position %s" b))))))
6629 (defun org-subtree-end-visible-p ()
6630 "Is the end of the current subtree visible?"
6631 (pos-visible-in-window-p
6632 (save-excursion (org-end-of-subtree t) (point))))
6634 (defun org-first-headline-recenter (&optional N)
6635 "Move cursor to the first headline and recenter the headline.
6636 Optional argument N means put the headline into the Nth line of the window."
6637 (goto-char (point-min))
6638 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6639 (beginning-of-line)
6640 (recenter (prefix-numeric-value N))))
6642 ;;; Saving and restoring visibility
6644 (defun org-outline-overlay-data (&optional use-markers)
6645 "Return a list of the locations of all outline overlays.
6646 These are overlays with the `invisible' property value `outline'.
6647 The return value is a list of cons cells, with start and stop
6648 positions for each overlay.
6649 If USE-MARKERS is set, return the positions as markers."
6650 (let (beg end)
6651 (save-excursion
6652 (save-restriction
6653 (widen)
6654 (delq nil
6655 (mapcar (lambda (o)
6656 (when (eq (overlay-get o 'invisible) 'outline)
6657 (setq beg (overlay-start o)
6658 end (overlay-end o))
6659 (and beg end (> end beg)
6660 (if use-markers
6661 (cons (move-marker (make-marker) beg)
6662 (move-marker (make-marker) end))
6663 (cons beg end)))))
6664 (overlays-in (point-min) (point-max))))))))
6666 (defun org-set-outline-overlay-data (data)
6667 "Create visibility overlays for all positions in DATA.
6668 DATA should have been made by `org-outline-overlay-data'."
6669 (let (o)
6670 (save-excursion
6671 (save-restriction
6672 (widen)
6673 (show-all)
6674 (mapc (lambda (c)
6675 (outline-flag-region (car c) (cdr c) t))
6676 data)))))
6678 ;;; Folding of blocks
6680 (defvar org-hide-block-overlays nil
6681 "Overlays hiding blocks.")
6682 (make-variable-buffer-local 'org-hide-block-overlays)
6684 (defun org-block-map (function &optional start end)
6685 "Call FUNCTION at the head of all source blocks in the current buffer.
6686 Optional arguments START and END can be used to limit the range."
6687 (let ((start (or start (point-min)))
6688 (end (or end (point-max))))
6689 (save-excursion
6690 (goto-char start)
6691 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6692 (save-excursion
6693 (save-match-data
6694 (goto-char (match-beginning 0))
6695 (funcall function)))))))
6697 (defun org-hide-block-toggle-all ()
6698 "Toggle the visibility of all blocks in the current buffer."
6699 (org-block-map #'org-hide-block-toggle))
6701 (defun org-hide-block-all ()
6702 "Fold all blocks in the current buffer."
6703 (interactive)
6704 (org-show-block-all)
6705 (org-block-map #'org-hide-block-toggle-maybe))
6707 (defun org-show-block-all ()
6708 "Unfold all blocks in the current buffer."
6709 (interactive)
6710 (mapc 'delete-overlay org-hide-block-overlays)
6711 (setq org-hide-block-overlays nil))
6713 (defun org-hide-block-toggle-maybe ()
6714 "Toggle visibility of block at point."
6715 (interactive)
6716 (let ((case-fold-search t))
6717 (if (save-excursion
6718 (beginning-of-line 1)
6719 (looking-at org-block-regexp))
6720 (progn (org-hide-block-toggle)
6721 t) ;; to signal that we took action
6722 nil))) ;; to signal that we did not
6724 (defun org-hide-block-toggle (&optional force)
6725 "Toggle the visibility of the current block."
6726 (interactive)
6727 (save-excursion
6728 (beginning-of-line)
6729 (if (re-search-forward org-block-regexp nil t)
6730 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6731 (end (match-end 0)) ;; end of entire body
6733 (if (memq t (mapcar (lambda (overlay)
6734 (eq (overlay-get overlay 'invisible)
6735 'org-hide-block))
6736 (overlays-at start)))
6737 (if (or (not force) (eq force 'off))
6738 (mapc (lambda (ov)
6739 (when (member ov org-hide-block-overlays)
6740 (setq org-hide-block-overlays
6741 (delq ov org-hide-block-overlays)))
6742 (when (eq (overlay-get ov 'invisible)
6743 'org-hide-block)
6744 (delete-overlay ov)))
6745 (overlays-at start)))
6746 (setq ov (make-overlay start end))
6747 (overlay-put ov 'invisible 'org-hide-block)
6748 ;; make the block accessible to isearch
6749 (overlay-put
6750 ov 'isearch-open-invisible
6751 (lambda (ov)
6752 (when (member ov org-hide-block-overlays)
6753 (setq org-hide-block-overlays
6754 (delq ov org-hide-block-overlays)))
6755 (when (eq (overlay-get ov 'invisible)
6756 'org-hide-block)
6757 (delete-overlay ov))))
6758 (push ov org-hide-block-overlays)))
6759 (error "Not looking at a source block"))))
6761 ;; org-tab-after-check-for-cycling-hook
6762 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6763 ;; Remove overlays when changing major mode
6764 (add-hook 'org-mode-hook
6765 (lambda () (org-add-hook 'change-major-mode-hook
6766 'org-show-block-all 'append 'local)))
6768 ;;; Org-goto
6770 (defvar org-goto-window-configuration nil)
6771 (defvar org-goto-marker nil)
6772 (defvar org-goto-map)
6773 (defun org-goto-map ()
6774 "Set the keymap `org-goto'."
6775 (setq org-goto-map
6776 (let ((map (make-sparse-keymap)))
6777 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6778 mouse-drag-region universal-argument org-occur))
6779 cmd)
6780 (while (setq cmd (pop cmds))
6781 (substitute-key-definition cmd cmd map global-map)))
6782 (suppress-keymap map)
6783 (org-defkey map "\C-m" 'org-goto-ret)
6784 (org-defkey map [(return)] 'org-goto-ret)
6785 (org-defkey map [(left)] 'org-goto-left)
6786 (org-defkey map [(right)] 'org-goto-right)
6787 (org-defkey map [(control ?g)] 'org-goto-quit)
6788 (org-defkey map "\C-i" 'org-cycle)
6789 (org-defkey map [(tab)] 'org-cycle)
6790 (org-defkey map [(down)] 'outline-next-visible-heading)
6791 (org-defkey map [(up)] 'outline-previous-visible-heading)
6792 (if org-goto-auto-isearch
6793 (if (fboundp 'define-key-after)
6794 (define-key-after map [t] 'org-goto-local-auto-isearch)
6795 nil)
6796 (org-defkey map "q" 'org-goto-quit)
6797 (org-defkey map "n" 'outline-next-visible-heading)
6798 (org-defkey map "p" 'outline-previous-visible-heading)
6799 (org-defkey map "f" 'outline-forward-same-level)
6800 (org-defkey map "b" 'outline-backward-same-level)
6801 (org-defkey map "u" 'outline-up-heading))
6802 (org-defkey map "/" 'org-occur)
6803 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6804 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6805 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6806 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6807 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6808 map)))
6810 (defconst org-goto-help
6811 "Browse buffer copy, to find location or copy text.%s
6812 RET=jump to location C-g=quit and return to previous location
6813 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6815 (defvar org-goto-start-pos) ; dynamically scoped parameter
6817 ;; FIXME: Docstring does not mention both interfaces
6818 (defun org-goto (&optional alternative-interface)
6819 "Look up a different location in the current file, keeping current visibility.
6821 When you want look-up or go to a different location in a
6822 document, the fastest way is often to fold the entire buffer and
6823 then dive into the tree. This method has the disadvantage, that
6824 the previous location will be folded, which may not be what you
6825 want.
6827 This command works around this by showing a copy of the current
6828 buffer in an indirect buffer, in overview mode. You can dive
6829 into the tree in that copy, use org-occur and incremental search
6830 to find a location. When pressing RET or `Q', the command
6831 returns to the original buffer in which the visibility is still
6832 unchanged. After RET it will also jump to the location selected
6833 in the indirect buffer and expose the headline hierarchy above.
6835 With a prefix argument, use the alternative interface: e.g. if
6836 `org-goto-interface' is 'outline use 'outline-path-completion."
6837 (interactive "P")
6838 (org-goto-map)
6839 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6840 (org-refile-use-outline-path t)
6841 (org-refile-target-verify-function nil)
6842 (interface
6843 (if (not alternative-interface)
6844 org-goto-interface
6845 (if (eq org-goto-interface 'outline)
6846 'outline-path-completion
6847 'outline)))
6848 (org-goto-start-pos (point))
6849 (selected-point
6850 (if (eq interface 'outline)
6851 (car (org-get-location (current-buffer) org-goto-help))
6852 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6853 (org-refile-check-position pa)
6854 (nth 3 pa)))))
6855 (if selected-point
6856 (progn
6857 (org-mark-ring-push org-goto-start-pos)
6858 (goto-char selected-point)
6859 (if (or (outline-invisible-p) (org-invisible-p2))
6860 (org-show-context 'org-goto)))
6861 (message "Quit"))))
6863 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6864 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6865 (defvar org-goto-local-auto-isearch-map) ; defined below
6867 (defun org-get-location (buf help)
6868 "Let the user select a location in the Org-mode buffer BUF.
6869 This function uses a recursive edit. It returns the selected position
6870 or nil."
6871 (org-no-popups
6872 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6873 (isearch-hide-immediately nil)
6874 (isearch-search-fun-function
6875 (lambda () 'org-goto-local-search-headings))
6876 (org-goto-selected-point org-goto-exit-command))
6877 (save-excursion
6878 (save-window-excursion
6879 (delete-other-windows)
6880 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6881 (org-pop-to-buffer-same-window
6882 (condition-case nil
6883 (make-indirect-buffer (current-buffer) "*org-goto*")
6884 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6885 (with-output-to-temp-buffer "*Org Help*"
6886 (princ (format help (if org-goto-auto-isearch
6887 " Just type for auto-isearch."
6888 " n/p/f/b/u to navigate, q to quit."))))
6889 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6890 (setq buffer-read-only nil)
6891 (let ((org-startup-truncated t)
6892 (org-startup-folded nil)
6893 (org-startup-align-all-tables nil))
6894 (org-mode)
6895 (org-overview))
6896 (setq buffer-read-only t)
6897 (if (and (boundp 'org-goto-start-pos)
6898 (integer-or-marker-p org-goto-start-pos))
6899 (let ((org-show-hierarchy-above t)
6900 (org-show-siblings t)
6901 (org-show-following-heading t))
6902 (goto-char org-goto-start-pos)
6903 (and (outline-invisible-p) (org-show-context)))
6904 (goto-char (point-min)))
6905 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6906 (message "Select location and press RET")
6907 (use-local-map org-goto-map)
6908 (recursive-edit)))
6909 (kill-buffer "*org-goto*")
6910 (cons org-goto-selected-point org-goto-exit-command))))
6912 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6913 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6914 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6915 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6917 (defun org-goto-local-search-headings (string bound noerror)
6918 "Search and make sure that any matches are in headlines."
6919 (catch 'return
6920 (while (if isearch-forward
6921 (search-forward string bound noerror)
6922 (search-backward string bound noerror))
6923 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6924 (and (member :headline context)
6925 (not (member :tags context))))
6926 (throw 'return (point))))))
6928 (defun org-goto-local-auto-isearch ()
6929 "Start isearch."
6930 (interactive)
6931 (goto-char (point-min))
6932 (let ((keys (this-command-keys)))
6933 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6934 (isearch-mode t)
6935 (isearch-process-search-char (string-to-char keys)))))
6937 (defun org-goto-ret (&optional arg)
6938 "Finish `org-goto' by going to the new location."
6939 (interactive "P")
6940 (setq org-goto-selected-point (point)
6941 org-goto-exit-command 'return)
6942 (throw 'exit nil))
6944 (defun org-goto-left ()
6945 "Finish `org-goto' by going to the new location."
6946 (interactive)
6947 (if (org-at-heading-p)
6948 (progn
6949 (beginning-of-line 1)
6950 (setq org-goto-selected-point (point)
6951 org-goto-exit-command 'left)
6952 (throw 'exit nil))
6953 (error "Not on a heading")))
6955 (defun org-goto-right ()
6956 "Finish `org-goto' by going to the new location."
6957 (interactive)
6958 (if (org-at-heading-p)
6959 (progn
6960 (setq org-goto-selected-point (point)
6961 org-goto-exit-command 'right)
6962 (throw 'exit nil))
6963 (error "Not on a heading")))
6965 (defun org-goto-quit ()
6966 "Finish `org-goto' without cursor motion."
6967 (interactive)
6968 (setq org-goto-selected-point nil)
6969 (setq org-goto-exit-command 'quit)
6970 (throw 'exit nil))
6972 ;;; Indirect buffer display of subtrees
6974 (defvar org-indirect-dedicated-frame nil
6975 "This is the frame being used for indirect tree display.")
6976 (defvar org-last-indirect-buffer nil)
6978 (defun org-tree-to-indirect-buffer (&optional arg)
6979 "Create indirect buffer and narrow it to current subtree.
6980 With a numerical prefix ARG, go up to this level and then take that tree.
6981 If ARG is negative, go up that many levels.
6983 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6984 indirect buffer previously made with this command, to avoid proliferation of
6985 indirect buffers. However, when you call the command with a \
6986 \\[universal-argument] prefix, or
6987 when `org-indirect-buffer-display' is `new-frame', the last buffer
6988 is kept so that you can work with several indirect buffers at the same time.
6989 If `org-indirect-buffer-display' is `dedicated-frame', the \
6990 \\[universal-argument] prefix also
6991 requests that a new frame be made for the new buffer, so that the dedicated
6992 frame is not changed."
6993 (interactive "P")
6994 (let ((cbuf (current-buffer))
6995 (cwin (selected-window))
6996 (pos (point))
6997 beg end level heading ibuf)
6998 (save-excursion
6999 (org-back-to-heading t)
7000 (when (numberp arg)
7001 (setq level (org-outline-level))
7002 (if (< arg 0) (setq arg (+ level arg)))
7003 (while (> (setq level (org-outline-level)) arg)
7004 (org-up-heading-safe)))
7005 (setq beg (point)
7006 heading (org-get-heading))
7007 (org-end-of-subtree t t)
7008 (if (org-at-heading-p) (backward-char 1))
7009 (setq end (point)))
7010 (if (and (buffer-live-p org-last-indirect-buffer)
7011 (not (eq org-indirect-buffer-display 'new-frame))
7012 (not arg))
7013 (kill-buffer org-last-indirect-buffer))
7014 (setq ibuf (org-get-indirect-buffer cbuf)
7015 org-last-indirect-buffer ibuf)
7016 (cond
7017 ((or (eq org-indirect-buffer-display 'new-frame)
7018 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7019 (select-frame (make-frame))
7020 (delete-other-windows)
7021 (org-pop-to-buffer-same-window ibuf)
7022 (org-set-frame-title heading))
7023 ((eq org-indirect-buffer-display 'dedicated-frame)
7024 (raise-frame
7025 (select-frame (or (and org-indirect-dedicated-frame
7026 (frame-live-p org-indirect-dedicated-frame)
7027 org-indirect-dedicated-frame)
7028 (setq org-indirect-dedicated-frame (make-frame)))))
7029 (delete-other-windows)
7030 (org-pop-to-buffer-same-window ibuf)
7031 (org-set-frame-title (concat "Indirect: " heading)))
7032 ((eq org-indirect-buffer-display 'current-window)
7033 (org-pop-to-buffer-same-window ibuf))
7034 ((eq org-indirect-buffer-display 'other-window)
7035 (pop-to-buffer ibuf))
7036 (t (error "Invalid value")))
7037 (if (featurep 'xemacs)
7038 (save-excursion (org-mode) (turn-on-font-lock)))
7039 (narrow-to-region beg end)
7040 (show-all)
7041 (goto-char pos)
7042 (run-hook-with-args 'org-cycle-hook 'all)
7043 (and (window-live-p cwin) (select-window cwin))))
7045 (defun org-get-indirect-buffer (&optional buffer)
7046 (setq buffer (or buffer (current-buffer)))
7047 (let ((n 1) (base (buffer-name buffer)) bname)
7048 (while (buffer-live-p
7049 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7050 (setq n (1+ n)))
7051 (condition-case nil
7052 (make-indirect-buffer buffer bname 'clone)
7053 (error (make-indirect-buffer buffer bname)))))
7055 (defun org-set-frame-title (title)
7056 "Set the title of the current frame to the string TITLE."
7057 ;; FIXME: how to name a single frame in XEmacs???
7058 (unless (featurep 'xemacs)
7059 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7061 ;;;; Structure editing
7063 ;;; Inserting headlines
7065 (defun org-previous-line-empty-p ()
7066 (save-excursion
7067 (and (not (bobp))
7068 (or (beginning-of-line 0) t)
7069 (save-match-data
7070 (looking-at "[ \t]*$")))))
7072 (defun org-insert-heading (&optional force-heading invisible-ok)
7073 "Insert a new heading or item with same depth at point.
7074 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7075 If point is at the beginning of a headline, insert a sibling before the
7076 current headline. If point is not at the beginning, split the line,
7077 create the new headline with the text in the current line after point
7078 \(but see also the variable `org-M-RET-may-split-line').
7080 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7081 This is important for non-interactive uses of the command."
7082 (interactive "P")
7083 (if (or (= (buffer-size) 0)
7084 (and (not (save-excursion
7085 (and (ignore-errors (org-back-to-heading invisible-ok))
7086 (org-at-heading-p))))
7087 (or force-heading (not (org-in-item-p)))))
7088 (progn
7089 (insert "\n* ")
7090 (run-hooks 'org-insert-heading-hook))
7091 (when (or force-heading (not (org-insert-item)))
7092 (let* ((empty-line-p nil)
7093 (level nil)
7094 (on-heading (org-at-heading-p))
7095 (head (save-excursion
7096 (condition-case nil
7097 (progn
7098 (org-back-to-heading invisible-ok)
7099 (when (and (not on-heading)
7100 (featurep 'org-inlinetask)
7101 (integerp org-inlinetask-min-level)
7102 (>= (length (match-string 0))
7103 org-inlinetask-min-level))
7104 ;; Find a heading level before the inline task
7105 (while (and (setq level (org-up-heading-safe))
7106 (>= level org-inlinetask-min-level)))
7107 (if (org-at-heading-p)
7108 (org-back-to-heading invisible-ok)
7109 (error "This should not happen")))
7110 (setq empty-line-p (org-previous-line-empty-p))
7111 (match-string 0))
7112 (error "*"))))
7113 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7114 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7115 pos hide-previous previous-pos)
7116 (cond
7117 ((and (org-at-heading-p) (bolp)
7118 (or (bobp)
7119 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7120 ;; insert before the current line
7121 (open-line (if blank 2 1)))
7122 ((and (bolp)
7123 (not org-insert-heading-respect-content)
7124 (or (bobp)
7125 (save-excursion
7126 (backward-char 1) (not (outline-invisible-p)))))
7127 ;; insert right here
7128 nil)
7130 ;; somewhere in the line
7131 (save-excursion
7132 (setq previous-pos (point-at-bol))
7133 (end-of-line)
7134 (setq hide-previous (outline-invisible-p)))
7135 (and org-insert-heading-respect-content (org-show-subtree))
7136 (let ((split
7137 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7138 (save-excursion
7139 (let ((p (point)))
7140 (goto-char (point-at-bol))
7141 (and (looking-at org-complex-heading-regexp)
7142 (match-beginning 4)
7143 (> p (match-beginning 4)))))))
7144 tags pos)
7145 (cond
7146 (org-insert-heading-respect-content
7147 (org-end-of-subtree nil t)
7148 (when (featurep 'org-inlinetask)
7149 (while (and (not (eobp))
7150 (looking-at "\\(\\*+\\)[ \t]+")
7151 (>= (length (match-string 1))
7152 org-inlinetask-min-level))
7153 (org-end-of-subtree nil t)))
7154 (or (bolp) (newline))
7155 (or (org-previous-line-empty-p)
7156 (and blank (newline)))
7157 (open-line 1))
7158 ((org-at-heading-p)
7159 (when hide-previous
7160 (show-children)
7161 (org-show-entry))
7162 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7163 (setq tags (and (match-end 2) (match-string 2)))
7164 (and (match-end 1)
7165 (delete-region (match-beginning 1) (match-end 1)))
7166 (setq pos (point-at-bol))
7167 (or split (end-of-line 1))
7168 (delete-horizontal-space)
7169 (if (string-match "\\`\\*+\\'"
7170 (buffer-substring (point-at-bol) (point)))
7171 (insert " "))
7172 (newline (if blank 2 1))
7173 (when tags
7174 (save-excursion
7175 (goto-char pos)
7176 (end-of-line 1)
7177 (insert " " tags)
7178 (org-set-tags nil 'align))))
7180 (or split (end-of-line 1))
7181 (newline (if blank 2 1)))))))
7182 (insert head) (just-one-space)
7183 (setq pos (point))
7184 (end-of-line 1)
7185 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7186 (when (and org-insert-heading-respect-content hide-previous)
7187 (save-excursion
7188 (goto-char previous-pos)
7189 (hide-subtree)))
7190 (run-hooks 'org-insert-heading-hook)))))
7192 (defun org-get-heading (&optional no-tags no-todo)
7193 "Return the heading of the current entry, without the stars.
7194 When NO-TAGS is non-nil, don't include tags.
7195 When NO-TODO is non-nil, don't include TODO keywords."
7196 (save-excursion
7197 (org-back-to-heading t)
7198 (cond
7199 ((and no-tags no-todo)
7200 (looking-at org-complex-heading-regexp)
7201 (match-string 4))
7202 (no-tags
7203 (looking-at (concat org-outline-regexp
7204 "\\(.*?\\)"
7205 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7206 (match-string 1))
7207 (no-todo
7208 (looking-at org-todo-line-regexp)
7209 (match-string 3))
7210 (t (looking-at org-heading-regexp)
7211 (match-string 2)))))
7213 (defun org-heading-components ()
7214 "Return the components of the current heading.
7215 This is a list with the following elements:
7216 - the level as an integer
7217 - the reduced level, different if `org-odd-levels-only' is set.
7218 - the TODO keyword, or nil
7219 - the priority character, like ?A, or nil if no priority is given
7220 - the headline text itself, or the tags string if no headline text
7221 - the tags string, or nil."
7222 (save-excursion
7223 (org-back-to-heading t)
7224 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7225 (list (length (match-string 1))
7226 (org-reduced-level (length (match-string 1)))
7227 (org-match-string-no-properties 2)
7228 (and (match-end 3) (aref (match-string 3) 2))
7229 (org-match-string-no-properties 4)
7230 (org-match-string-no-properties 5)))))
7232 (defun org-get-entry ()
7233 "Get the entry text, after heading, entire subtree."
7234 (save-excursion
7235 (org-back-to-heading t)
7236 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7238 (defun org-insert-heading-after-current ()
7239 "Insert a new heading with same level as current, after current subtree."
7240 (interactive)
7241 (org-back-to-heading)
7242 (org-insert-heading)
7243 (org-move-subtree-down)
7244 (end-of-line 1))
7246 (defun org-insert-heading-respect-content (invisible-ok)
7247 "Insert heading with `org-insert-heading-respect-content' set to t."
7248 (interactive "P")
7249 (let ((org-insert-heading-respect-content t))
7250 (org-insert-heading t invisible-ok)))
7252 (defun org-insert-todo-heading-respect-content (&optional force-state)
7253 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7254 (interactive "P")
7255 (let ((org-insert-heading-respect-content t))
7256 (org-insert-todo-heading force-state t)))
7258 (defun org-insert-todo-heading (arg &optional force-heading)
7259 "Insert a new heading with the same level and TODO state as current heading.
7260 If the heading has no TODO state, or if the state is DONE, use the first
7261 state (TODO by default). Also with prefix arg, force first state."
7262 (interactive "P")
7263 (when (or force-heading (not (org-insert-item 'checkbox)))
7264 (org-insert-heading force-heading)
7265 (save-excursion
7266 (org-back-to-heading)
7267 (outline-previous-heading)
7268 (looking-at org-todo-line-regexp))
7269 (let*
7270 ((new-mark-x
7271 (if (or arg
7272 (not (match-beginning 2))
7273 (member (match-string 2) org-done-keywords))
7274 (car org-todo-keywords-1)
7275 (match-string 2)))
7276 (new-mark
7278 (run-hook-with-args-until-success
7279 'org-todo-get-default-hook new-mark-x nil)
7280 new-mark-x)))
7281 (beginning-of-line 1)
7282 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7283 (if org-treat-insert-todo-heading-as-state-change
7284 (org-todo new-mark)
7285 (insert new-mark " "))))
7286 (when org-provide-todo-statistics
7287 (org-update-parent-todo-statistics))))
7289 (defun org-insert-subheading (arg)
7290 "Insert a new subheading and demote it.
7291 Works for outline headings and for plain lists alike."
7292 (interactive "P")
7293 (org-insert-heading arg)
7294 (cond
7295 ((org-at-heading-p) (org-do-demote))
7296 ((org-at-item-p) (org-indent-item))))
7298 (defun org-insert-todo-subheading (arg)
7299 "Insert a new subheading with TODO keyword or checkbox and demote it.
7300 Works for outline headings and for plain lists alike."
7301 (interactive "P")
7302 (org-insert-todo-heading arg)
7303 (cond
7304 ((org-at-heading-p) (org-do-demote))
7305 ((org-at-item-p) (org-indent-item))))
7307 ;;; Promotion and Demotion
7309 (defvar org-after-demote-entry-hook nil
7310 "Hook run after an entry has been demoted.
7311 The cursor will be at the beginning of the entry.
7312 When a subtree is being demoted, the hook will be called for each node.")
7314 (defvar org-after-promote-entry-hook nil
7315 "Hook run after an entry has been promoted.
7316 The cursor will be at the beginning of the entry.
7317 When a subtree is being promoted, the hook will be called for each node.")
7319 (defun org-promote-subtree ()
7320 "Promote the entire subtree.
7321 See also `org-promote'."
7322 (interactive)
7323 (save-excursion
7324 (org-with-limited-levels (org-map-tree 'org-promote)))
7325 (org-fix-position-after-promote))
7327 (defun org-demote-subtree ()
7328 "Demote the entire subtree. See `org-demote'.
7329 See also `org-promote'."
7330 (interactive)
7331 (save-excursion
7332 (org-with-limited-levels (org-map-tree 'org-demote)))
7333 (org-fix-position-after-promote))
7336 (defun org-do-promote ()
7337 "Promote the current heading higher up the tree.
7338 If the region is active in `transient-mark-mode', promote all headings
7339 in the region."
7340 (interactive)
7341 (save-excursion
7342 (if (org-region-active-p)
7343 (org-map-region 'org-promote (region-beginning) (region-end))
7344 (org-promote)))
7345 (org-fix-position-after-promote))
7347 (defun org-do-demote ()
7348 "Demote the current heading lower down the tree.
7349 If the region is active in `transient-mark-mode', demote all headings
7350 in the region."
7351 (interactive)
7352 (save-excursion
7353 (if (org-region-active-p)
7354 (org-map-region 'org-demote (region-beginning) (region-end))
7355 (org-demote)))
7356 (org-fix-position-after-promote))
7358 (defun org-fix-position-after-promote ()
7359 "Make sure that after pro/demotion cursor position is right."
7360 (let ((pos (point)))
7361 (when (save-excursion
7362 (beginning-of-line 1)
7363 (looking-at org-todo-line-regexp)
7364 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7365 (cond ((eobp) (insert " "))
7366 ((eolp) (insert " "))
7367 ((equal (char-after) ?\ ) (forward-char 1))))))
7369 (defun org-current-level ()
7370 "Return the level of the current entry, or nil if before the first headline.
7371 The level is the number of stars at the beginning of the headline."
7372 (save-excursion
7373 (org-with-limited-levels
7374 (if (ignore-errors (org-back-to-heading t))
7375 (funcall outline-level)))))
7377 (defun org-get-previous-line-level ()
7378 "Return the outline depth of the last headline before the current line.
7379 Returns 0 for the first headline in the buffer, and nil if before the
7380 first headline."
7381 (let ((current-level (org-current-level))
7382 (prev-level (when (> (line-number-at-pos) 1)
7383 (save-excursion
7384 (beginning-of-line 0)
7385 (org-current-level)))))
7386 (cond ((null current-level) nil) ; Before first headline
7387 ((null prev-level) 0) ; At first headline
7388 (prev-level))))
7390 (defun org-reduced-level (l)
7391 "Compute the effective level of a heading.
7392 This takes into account the setting of `org-odd-levels-only'."
7393 (cond
7394 ((zerop l) 0)
7395 (org-odd-levels-only (1+ (floor (/ l 2))))
7396 (t l)))
7398 (defun org-level-increment ()
7399 "Return the number of stars that will be added or removed at a
7400 time to headlines when structure editing, based on the value of
7401 `org-odd-levels-only'."
7402 (if org-odd-levels-only 2 1))
7404 (defun org-get-valid-level (level &optional change)
7405 "Rectify a level change under the influence of `org-odd-levels-only'
7406 LEVEL is a current level, CHANGE is by how much the level should be
7407 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7408 even level numbers will become the next higher odd number."
7409 (if org-odd-levels-only
7410 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7411 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7412 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7413 (max 1 (+ level (or change 0)))))
7415 (if (boundp 'define-obsolete-function-alias)
7416 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7417 (define-obsolete-function-alias 'org-get-legal-level
7418 'org-get-valid-level)
7419 (define-obsolete-function-alias 'org-get-legal-level
7420 'org-get-valid-level "23.1")))
7422 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7423 ;; ̀org-with-limited-levels'
7424 (defun org-promote ()
7425 "Promote the current heading higher up the tree.
7426 If the region is active in `transient-mark-mode', promote all headings
7427 in the region."
7428 (org-back-to-heading t)
7429 (let* ((level (save-match-data (funcall outline-level)))
7430 (after-change-functions (remove 'flyspell-after-change-function
7431 after-change-functions))
7432 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7433 (diff (abs (- level (length up-head) -1))))
7434 (cond ((and (= level 1) org-called-with-limited-levels
7435 org-allow-promoting-top-level-subtree)
7436 (replace-match "# " nil t))
7437 ((= level 1)
7438 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7439 (t (replace-match up-head nil t)))
7440 ;; Fixup tag positioning
7441 (unless (= level 1)
7442 (and org-auto-align-tags (org-set-tags nil t))
7443 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7444 (run-hooks 'org-after-promote-entry-hook)))
7446 (defun org-demote ()
7447 "Demote the current heading lower down the tree.
7448 If the region is active in `transient-mark-mode', demote all headings
7449 in the region."
7450 (org-back-to-heading t)
7451 (let* ((level (save-match-data (funcall outline-level)))
7452 (after-change-functions (remove 'flyspell-after-change-function
7453 after-change-functions))
7454 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7455 (diff (abs (- level (length down-head) -1))))
7456 (replace-match down-head nil t)
7457 ;; Fixup tag positioning
7458 (and org-auto-align-tags (org-set-tags nil t))
7459 (if org-adapt-indentation (org-fixup-indentation diff))
7460 (run-hooks 'org-after-demote-entry-hook)))
7462 (defun org-cycle-level ()
7463 "Cycle the level of an empty headline through possible states.
7464 This goes first to child, then to parent, level, then up the hierarchy.
7465 After top level, it switches back to sibling level."
7466 (interactive)
7467 (let ((org-adapt-indentation nil))
7468 (when (org-point-at-end-of-empty-headline)
7469 (setq this-command 'org-cycle-level) ; Only needed for caching
7470 (let ((cur-level (org-current-level))
7471 (prev-level (org-get-previous-line-level)))
7472 (cond
7473 ;; If first headline in file, promote to top-level.
7474 ((= prev-level 0)
7475 (loop repeat (/ (- cur-level 1) (org-level-increment))
7476 do (org-do-promote)))
7477 ;; If same level as prev, demote one.
7478 ((= prev-level cur-level)
7479 (org-do-demote))
7480 ;; If parent is top-level, promote to top level if not already.
7481 ((= prev-level 1)
7482 (loop repeat (/ (- cur-level 1) (org-level-increment))
7483 do (org-do-promote)))
7484 ;; If top-level, return to prev-level.
7485 ((= cur-level 1)
7486 (loop repeat (/ (- prev-level 1) (org-level-increment))
7487 do (org-do-demote)))
7488 ;; If less than prev-level, promote one.
7489 ((< cur-level prev-level)
7490 (org-do-promote))
7491 ;; If deeper than prev-level, promote until higher than
7492 ;; prev-level.
7493 ((> cur-level prev-level)
7494 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7495 do (org-do-promote))))
7496 t))))
7498 (defun org-map-tree (fun)
7499 "Call FUN for every heading underneath the current one."
7500 (org-back-to-heading)
7501 (let ((level (funcall outline-level)))
7502 (save-excursion
7503 (funcall fun)
7504 (while (and (progn
7505 (outline-next-heading)
7506 (> (funcall outline-level) level))
7507 (not (eobp)))
7508 (funcall fun)))))
7510 (defun org-map-region (fun beg end)
7511 "Call FUN for every heading between BEG and END."
7512 (let ((org-ignore-region t))
7513 (save-excursion
7514 (setq end (copy-marker end))
7515 (goto-char beg)
7516 (if (and (re-search-forward org-outline-regexp-bol nil t)
7517 (< (point) end))
7518 (funcall fun))
7519 (while (and (progn
7520 (outline-next-heading)
7521 (< (point) end))
7522 (not (eobp)))
7523 (funcall fun)))))
7525 (defvar org-property-end-re) ; silence byte-compiler
7526 (defun org-fixup-indentation (diff)
7527 "Change the indentation in the current entry by DIFF.
7528 However, if any line in the current entry has no indentation, or if it
7529 would end up with no indentation after the change, nothing at all is done."
7530 (save-excursion
7531 (let ((end (save-excursion (outline-next-heading)
7532 (point-marker)))
7533 (prohibit (if (> diff 0)
7534 "^\\S-"
7535 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7536 col)
7537 (unless (save-excursion (end-of-line 1)
7538 (re-search-forward prohibit end t))
7539 (while (and (< (point) end)
7540 (re-search-forward "^[ \t]+" end t))
7541 (goto-char (match-end 0))
7542 (setq col (current-column))
7543 (if (< diff 0) (replace-match ""))
7544 (org-indent-to-column (+ diff col))))
7545 (move-marker end nil))))
7547 (defun org-convert-to-odd-levels ()
7548 "Convert an org-mode file with all levels allowed to one with odd levels.
7549 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7550 level 5 etc."
7551 (interactive)
7552 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7553 (let ((outline-level 'org-outline-level)
7554 (org-odd-levels-only nil) n)
7555 (save-excursion
7556 (goto-char (point-min))
7557 (while (re-search-forward "^\\*\\*+ " nil t)
7558 (setq n (- (length (match-string 0)) 2))
7559 (while (>= (setq n (1- n)) 0)
7560 (org-demote))
7561 (end-of-line 1))))))
7563 (defun org-convert-to-oddeven-levels ()
7564 "Convert an org-mode file with only odd levels to one with odd/even levels.
7565 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7566 file contains a section with an even level, conversion would
7567 destroy the structure of the file. An error is signaled in this
7568 case."
7569 (interactive)
7570 (goto-char (point-min))
7571 ;; First check if there are no even levels
7572 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7573 (org-show-context t)
7574 (error "Not all levels are odd in this file. Conversion not possible"))
7575 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7576 (let ((outline-regexp org-outline-regexp)
7577 (outline-level 'org-outline-level)
7578 (org-odd-levels-only nil) n)
7579 (save-excursion
7580 (goto-char (point-min))
7581 (while (re-search-forward "^\\*\\*+ " nil t)
7582 (setq n (/ (1- (length (match-string 0))) 2))
7583 (while (>= (setq n (1- n)) 0)
7584 (org-promote))
7585 (end-of-line 1))))))
7587 (defun org-tr-level (n)
7588 "Make N odd if required."
7589 (if org-odd-levels-only (1+ (/ n 2)) n))
7591 ;;; Vertical tree motion, cutting and pasting of subtrees
7593 (defun org-move-subtree-up (&optional arg)
7594 "Move the current subtree up past ARG headlines of the same level."
7595 (interactive "p")
7596 (org-move-subtree-down (- (prefix-numeric-value arg))))
7598 (defun org-move-subtree-down (&optional arg)
7599 "Move the current subtree down past ARG headlines of the same level."
7600 (interactive "p")
7601 (setq arg (prefix-numeric-value arg))
7602 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7603 'org-get-last-sibling))
7604 (ins-point (make-marker))
7605 (cnt (abs arg))
7606 (col (current-column))
7607 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7608 ;; Select the tree
7609 (org-back-to-heading)
7610 (setq beg0 (point))
7611 (save-excursion
7612 (setq ne-beg (org-back-over-empty-lines))
7613 (setq beg (point)))
7614 (save-match-data
7615 (save-excursion (outline-end-of-heading)
7616 (setq folded (outline-invisible-p)))
7617 (outline-end-of-subtree))
7618 (outline-next-heading)
7619 (setq ne-end (org-back-over-empty-lines))
7620 (setq end (point))
7621 (goto-char beg0)
7622 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7623 ;; include less whitespace
7624 (save-excursion
7625 (goto-char beg)
7626 (forward-line (- ne-beg ne-end))
7627 (setq beg (point))))
7628 ;; Find insertion point, with error handling
7629 (while (> cnt 0)
7630 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7631 (progn (goto-char beg0)
7632 (error "Cannot move past superior level or buffer limit")))
7633 (setq cnt (1- cnt)))
7634 (if (> arg 0)
7635 ;; Moving forward - still need to move over subtree
7636 (progn (org-end-of-subtree t t)
7637 (save-excursion
7638 (org-back-over-empty-lines)
7639 (or (bolp) (newline)))))
7640 (setq ne-ins (org-back-over-empty-lines))
7641 (move-marker ins-point (point))
7642 (setq txt (buffer-substring beg end))
7643 (org-save-markers-in-region beg end)
7644 (delete-region beg end)
7645 (org-remove-empty-overlays-at beg)
7646 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7647 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7648 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7649 (let ((bbb (point)))
7650 (insert-before-markers txt)
7651 (org-reinstall-markers-in-region bbb)
7652 (move-marker ins-point bbb))
7653 (or (bolp) (insert "\n"))
7654 (setq ins-end (point))
7655 (goto-char ins-point)
7656 (org-skip-whitespace)
7657 (when (and (< arg 0)
7658 (org-first-sibling-p)
7659 (> ne-ins ne-beg))
7660 ;; Move whitespace back to beginning
7661 (save-excursion
7662 (goto-char ins-end)
7663 (let ((kill-whole-line t))
7664 (kill-line (- ne-ins ne-beg)) (point)))
7665 (insert (make-string (- ne-ins ne-beg) ?\n)))
7666 (move-marker ins-point nil)
7667 (if folded
7668 (hide-subtree)
7669 (org-show-entry)
7670 (show-children)
7671 (org-cycle-hide-drawers 'children))
7672 (org-clean-visibility-after-subtree-move)
7673 ;; move back to the initial column we were at
7674 (move-to-column col)))
7676 (defvar org-subtree-clip ""
7677 "Clipboard for cut and paste of subtrees.
7678 This is actually only a copy of the kill, because we use the normal kill
7679 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7681 (defvar org-subtree-clip-folded nil
7682 "Was the last copied subtree folded?
7683 This is used to fold the tree back after pasting.")
7685 (defun org-cut-subtree (&optional n)
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 cutting it."
7689 (interactive "p")
7690 (org-copy-subtree n 'cut))
7692 (defun org-copy-subtree (&optional n cut force-store-markers)
7693 "Cut the current subtree into the clipboard.
7694 With prefix arg N, cut this many sequential subtrees.
7695 This is a short-hand for marking the subtree and then copying it.
7696 If CUT is non-nil, actually cut the subtree.
7697 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7698 of some markers in the region, even if CUT is non-nil. This is
7699 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7700 (interactive "p")
7701 (let (beg end folded (beg0 (point)))
7702 (if (org-called-interactively-p 'any)
7703 (org-back-to-heading nil) ; take what looks like a subtree
7704 (org-back-to-heading t)) ; take what is really there
7705 (setq beg (point))
7706 (skip-chars-forward " \t\r\n")
7707 (save-match-data
7708 (save-excursion (outline-end-of-heading)
7709 (setq folded (outline-invisible-p)))
7710 (condition-case nil
7711 (org-forward-heading-same-level (1- n) t)
7712 (error nil))
7713 (org-end-of-subtree t t))
7714 (setq end (point))
7715 (goto-char beg0)
7716 (when (> end beg)
7717 (setq org-subtree-clip-folded folded)
7718 (when (or cut force-store-markers)
7719 (org-save-markers-in-region beg end))
7720 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7721 (setq org-subtree-clip (current-kill 0))
7722 (message "%s: Subtree(s) with %d characters"
7723 (if cut "Cut" "Copied")
7724 (length org-subtree-clip)))))
7726 (defun org-paste-subtree (&optional level tree for-yank)
7727 "Paste the clipboard as a subtree, with modification of headline level.
7728 The entire subtree is promoted or demoted in order to match a new headline
7729 level.
7731 If the cursor is at the beginning of a headline, the same level as
7732 that headline is used to paste the tree
7734 If not, the new level is derived from the *visible* headings
7735 before and after the insertion point, and taken to be the inferior headline
7736 level of the two. So if the previous visible heading is level 3 and the
7737 next is level 4 (or vice versa), level 4 will be used for insertion.
7738 This makes sure that the subtree remains an independent subtree and does
7739 not swallow low level entries.
7741 You can also force a different level, either by using a numeric prefix
7742 argument, or by inserting the heading marker by hand. For example, if the
7743 cursor is after \"*****\", then the tree will be shifted to level 5.
7745 If optional TREE is given, use this text instead of the kill ring.
7747 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7748 move back over whitespace before inserting, and move point to the end of
7749 the inserted text when done."
7750 (interactive "P")
7751 (setq tree (or tree (and kill-ring (current-kill 0))))
7752 (unless (org-kill-is-subtree-p tree)
7753 (error "%s"
7754 (substitute-command-keys
7755 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7756 (org-with-limited-levels
7757 (let* ((visp (not (outline-invisible-p)))
7758 (txt tree)
7759 (^re_ "\\(\\*+\\)[ \t]*")
7760 (old-level (if (string-match org-outline-regexp-bol txt)
7761 (- (match-end 0) (match-beginning 0) 1)
7762 -1))
7763 (force-level (cond (level (prefix-numeric-value level))
7764 ((and (looking-at "[ \t]*$")
7765 (string-match
7766 "^\\*+$" (buffer-substring
7767 (point-at-bol) (point))))
7768 (- (match-end 1) (match-beginning 1)))
7769 ((and (bolp)
7770 (looking-at org-outline-regexp))
7771 (- (match-end 0) (point) 1))))
7772 (previous-level (save-excursion
7773 (condition-case nil
7774 (progn
7775 (outline-previous-visible-heading 1)
7776 (if (looking-at ^re_)
7777 (- (match-end 0) (match-beginning 0) 1)
7779 (error 1))))
7780 (next-level (save-excursion
7781 (condition-case nil
7782 (progn
7783 (or (looking-at org-outline-regexp)
7784 (outline-next-visible-heading 1))
7785 (if (looking-at ^re_)
7786 (- (match-end 0) (match-beginning 0) 1)
7788 (error 1))))
7789 (new-level (or force-level (max previous-level next-level)))
7790 (shift (if (or (= old-level -1)
7791 (= new-level -1)
7792 (= old-level new-level))
7794 (- new-level old-level)))
7795 (delta (if (> shift 0) -1 1))
7796 (func (if (> shift 0) 'org-demote 'org-promote))
7797 (org-odd-levels-only nil)
7798 beg end newend)
7799 ;; Remove the forced level indicator
7800 (if force-level
7801 (delete-region (point-at-bol) (point)))
7802 ;; Paste
7803 (beginning-of-line (if (bolp) 1 2))
7804 (setq beg (point))
7805 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7806 (insert-before-markers txt)
7807 (unless (string-match "\n\\'" txt) (insert "\n"))
7808 (setq newend (point))
7809 (org-reinstall-markers-in-region beg)
7810 (setq end (point))
7811 (goto-char beg)
7812 (skip-chars-forward " \t\n\r")
7813 (setq beg (point))
7814 (if (and (outline-invisible-p) visp)
7815 (save-excursion (outline-show-heading)))
7816 ;; Shift if necessary
7817 (unless (= shift 0)
7818 (save-restriction
7819 (narrow-to-region beg end)
7820 (while (not (= shift 0))
7821 (org-map-region func (point-min) (point-max))
7822 (setq shift (+ delta shift)))
7823 (goto-char (point-min))
7824 (setq newend (point-max))))
7825 (when (or (org-called-interactively-p 'interactive) for-yank)
7826 (message "Clipboard pasted as level %d subtree" new-level))
7827 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7828 kill-ring
7829 (eq org-subtree-clip (current-kill 0))
7830 org-subtree-clip-folded)
7831 ;; The tree was folded before it was killed/copied
7832 (hide-subtree))
7833 (and for-yank (goto-char newend)))))
7835 (defun org-kill-is-subtree-p (&optional txt)
7836 "Check if the current kill is an outline subtree, or a set of trees.
7837 Returns nil if kill does not start with a headline, or if the first
7838 headline level is not the largest headline level in the tree.
7839 So this will actually accept several entries of equal levels as well,
7840 which is OK for `org-paste-subtree'.
7841 If optional TXT is given, check this string instead of the current kill."
7842 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7843 (re (org-get-limited-outline-regexp))
7844 (^re (concat "^" re))
7845 (start-level (and kill
7846 (string-match
7847 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7848 kill)
7849 (- (match-end 2) (match-beginning 2) 1)))
7850 (start (1+ (or (match-beginning 2) -1))))
7851 (if (not start-level)
7852 (progn
7853 nil) ;; does not even start with a heading
7854 (catch 'exit
7855 (while (setq start (string-match ^re kill (1+ start)))
7856 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7857 (throw 'exit nil)))
7858 t))))
7860 (defvar org-markers-to-move nil
7861 "Markers that should be moved with a cut-and-paste operation.
7862 Those markers are stored together with their positions relative to
7863 the start of the region.")
7865 (defun org-save-markers-in-region (beg end)
7866 "Check markers in region.
7867 If these markers are between BEG and END, record their position relative
7868 to BEG, so that after moving the block of text, we can put the markers back
7869 into place.
7870 This function gets called just before an entry or tree gets cut from the
7871 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7872 called immediately, to move the markers with the entries."
7873 (setq org-markers-to-move nil)
7874 (when (featurep 'org-clock)
7875 (org-clock-save-markers-for-cut-and-paste beg end))
7876 (when (featurep 'org-agenda)
7877 (org-agenda-save-markers-for-cut-and-paste beg end)))
7879 (defun org-check-and-save-marker (marker beg end)
7880 "Check if MARKER is between BEG and END.
7881 If yes, remember the marker and the distance to BEG."
7882 (when (and (marker-buffer marker)
7883 (equal (marker-buffer marker) (current-buffer)))
7884 (if (and (>= marker beg) (< marker end))
7885 (push (cons marker (- marker beg)) org-markers-to-move))))
7887 (defun org-reinstall-markers-in-region (beg)
7888 "Move all remembered markers to their position relative to BEG."
7889 (mapc (lambda (x)
7890 (move-marker (car x) (+ beg (cdr x))))
7891 org-markers-to-move)
7892 (setq org-markers-to-move nil))
7894 (defun org-narrow-to-subtree ()
7895 "Narrow buffer to the current subtree."
7896 (interactive)
7897 (save-excursion
7898 (save-match-data
7899 (org-with-limited-levels
7900 (narrow-to-region
7901 (progn (org-back-to-heading t) (point))
7902 (progn (org-end-of-subtree t t)
7903 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7904 (point)))))))
7906 (defun org-narrow-to-block ()
7907 "Narrow buffer to the current block."
7908 (interactive)
7909 (let* ((case-fold-search t)
7910 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7911 "^[ \t]*#\\+end_.*")))
7912 (if blockp
7913 (narrow-to-region (car blockp) (cdr blockp))
7914 (error "Not in a block"))))
7916 (eval-when-compile
7917 (defvar org-property-drawer-re))
7919 (defvar org-property-start-re) ;; defined below
7920 (defun org-clone-subtree-with-time-shift (n &optional shift)
7921 "Clone the task (subtree) at point N times.
7922 The clones will be inserted as siblings.
7924 In interactive use, the user will be prompted for the number of
7925 clones to be produced, and for a time SHIFT, which may be a
7926 repeater as used in time stamps, for example `+3d'.
7928 When a valid repeater is given and the entry contains any time
7929 stamps, the clones will become a sequence in time, with time
7930 stamps in the subtree shifted for each clone produced. If SHIFT
7931 is nil or the empty string, time stamps will be left alone. The
7932 ID property of the original subtree is removed.
7934 If the original subtree did contain time stamps with a repeater,
7935 the following will happen:
7936 - the repeater will be removed in each clone
7937 - an additional clone will be produced, with the current, unshifted
7938 date(s) in the entry.
7939 - the original entry will be placed *after* all the clones, with
7940 repeater intact.
7941 - the start days in the repeater in the original entry will be shifted
7942 to past the last clone.
7943 In this way you can spell out a number of instances of a repeating task,
7944 and still retain the repeater to cover future instances of the task."
7945 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7946 (let (beg end template task idprop
7947 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7948 (drawer-re org-drawer-regexp))
7949 (if (not (and (integerp n) (> n 0)))
7950 (error "Invalid number of replications %s" n))
7951 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7952 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7953 shift)))
7954 (error "Invalid shift specification %s" shift))
7955 (when doshift
7956 (setq shift-n (string-to-number (match-string 1 shift))
7957 shift-what (cdr (assoc (match-string 2 shift)
7958 '(("d" . day) ("w" . week)
7959 ("m" . month) ("y" . year))))))
7960 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7961 (setq nmin 1 nmax n)
7962 (org-back-to-heading t)
7963 (setq beg (point))
7964 (setq idprop (org-entry-get nil "ID"))
7965 (org-end-of-subtree t t)
7966 (or (bolp) (insert "\n"))
7967 (setq end (point))
7968 (setq template (buffer-substring beg end))
7969 (when (and doshift
7970 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7971 (delete-region beg end)
7972 (setq end beg)
7973 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7974 (goto-char end)
7975 (loop for n from nmin to nmax do
7976 ;; prepare clone
7977 (with-temp-buffer
7978 (insert template)
7979 (org-mode)
7980 (goto-char (point-min))
7981 (org-show-subtree)
7982 (and idprop (if org-clone-delete-id
7983 (org-entry-delete nil "ID")
7984 (org-id-get-create t)))
7985 (unless (= n 0)
7986 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7987 (kill-whole-line))
7988 (goto-char (point-min))
7989 (while (re-search-forward drawer-re nil t)
7990 (mapc (lambda (d)
7991 (org-remove-empty-drawer-at d (point))) org-drawers)))
7992 (goto-char (point-min))
7993 (when doshift
7994 (while (re-search-forward org-ts-regexp-both nil t)
7995 (org-timestamp-change (* n shift-n) shift-what))
7996 (unless (= n n-no-remove)
7997 (goto-char (point-min))
7998 (while (re-search-forward org-ts-regexp nil t)
7999 (save-excursion
8000 (goto-char (match-beginning 0))
8001 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8002 (delete-region (match-beginning 1) (match-end 1)))))))
8003 (setq task (buffer-string)))
8004 (insert task))
8005 (goto-char beg)))
8007 ;;; Outline Sorting
8009 (defun org-sort (with-case)
8010 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8011 Optional argument WITH-CASE means sort case-sensitively."
8012 (interactive "P")
8013 (cond
8014 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8015 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8017 (org-call-with-arg 'org-sort-entries with-case))))
8019 (defun org-sort-remove-invisible (s)
8020 (remove-text-properties 0 (length s) org-rm-props s)
8021 (while (string-match org-bracket-link-regexp s)
8022 (setq s (replace-match (if (match-end 2)
8023 (match-string 3 s)
8024 (match-string 1 s)) t t s)))
8027 (defvar org-priority-regexp) ; defined later in the file
8029 (defvar org-after-sorting-entries-or-items-hook nil
8030 "Hook that is run after a bunch of entries or items have been sorted.
8031 When children are sorted, the cursor is in the parent line when this
8032 hook gets called. When a region or a plain list is sorted, the cursor
8033 will be in the first entry of the sorted region/list.")
8035 (defun org-sort-entries
8036 (&optional with-case sorting-type getkey-func compare-func property)
8037 "Sort entries on a certain level of an outline tree.
8038 If there is an active region, the entries in the region are sorted.
8039 Else, if the cursor is before the first entry, sort the top-level items.
8040 Else, the children of the entry at point are sorted.
8042 Sorting can be alphabetically, numerically, by date/time as given by
8043 a time stamp, by a property or by priority.
8045 The command prompts for the sorting type unless it has been given to the
8046 function through the SORTING-TYPE argument, which needs to be a character,
8047 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8048 precise meaning of each character:
8050 n Numerically, by converting the beginning of the entry/item to a number.
8051 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8052 o By order of TODO keywords.
8053 t By date/time, either the first active time stamp in the entry, or, if
8054 none exist, by the first inactive one.
8055 s By the scheduled date/time.
8056 d By deadline date/time.
8057 c By creation time, which is assumed to be the first inactive time stamp
8058 at the beginning of a line.
8059 p By priority according to the cookie.
8060 r By the value of a property.
8062 Capital letters will reverse the sort order.
8064 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8065 called with point at the beginning of the record. It must return either
8066 a string or a number that should serve as the sorting key for that record.
8068 Comparing entries ignores case by default. However, with an optional argument
8069 WITH-CASE, the sorting considers case as well."
8070 (interactive "P")
8071 (let ((case-func (if with-case 'identity 'downcase))
8072 (cmstr
8073 ;; The clock marker is lost when using `sort-subr', let's
8074 ;; store the clocking string.
8075 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8076 (save-excursion
8077 (goto-char org-clock-marker)
8078 (looking-back "^.*") (match-string-no-properties 0))))
8079 start beg end stars re re2
8080 txt what tmp)
8081 ;; Find beginning and end of region to sort
8082 (cond
8083 ((org-region-active-p)
8084 ;; we will sort the region
8085 (setq end (region-end)
8086 what "region")
8087 (goto-char (region-beginning))
8088 (if (not (org-at-heading-p)) (outline-next-heading))
8089 (setq start (point)))
8090 ((or (org-at-heading-p)
8091 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8092 ;; we will sort the children of the current headline
8093 (org-back-to-heading)
8094 (setq start (point)
8095 end (progn (org-end-of-subtree t t)
8096 (or (bolp) (insert "\n"))
8097 (org-back-over-empty-lines)
8098 (point))
8099 what "children")
8100 (goto-char start)
8101 (show-subtree)
8102 (outline-next-heading))
8104 ;; we will sort the top-level entries in this file
8105 (goto-char (point-min))
8106 (or (org-at-heading-p) (outline-next-heading))
8107 (setq start (point))
8108 (goto-char (point-max))
8109 (beginning-of-line 1)
8110 (when (looking-at ".*?\\S-")
8111 ;; File ends in a non-white line
8112 (end-of-line 1)
8113 (insert "\n"))
8114 (setq end (point-max))
8115 (setq what "top-level")
8116 (goto-char start)
8117 (show-all)))
8119 (setq beg (point))
8120 (if (>= beg end) (error "Nothing to sort"))
8122 (looking-at "\\(\\*+\\)")
8123 (setq stars (match-string 1)
8124 re (concat "^" (regexp-quote stars) " +")
8125 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8126 txt (buffer-substring beg end))
8127 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8128 (if (and (not (equal stars "*")) (string-match re2 txt))
8129 (error "Region to sort contains a level above the first entry"))
8131 (unless sorting-type
8132 (message
8133 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8134 [t]ime [s]cheduled [d]eadline [c]reated
8135 A/N/P/R/O/F/T/S/D/C means reversed:"
8136 what)
8137 (setq sorting-type (read-char-exclusive))
8139 (and (= (downcase sorting-type) ?f)
8140 (setq getkey-func
8141 (org-icompleting-read "Sort using function: "
8142 obarray 'fboundp t nil nil))
8143 (setq getkey-func (intern getkey-func)))
8145 (and (= (downcase sorting-type) ?r)
8146 (setq property
8147 (org-icompleting-read "Property: "
8148 (mapcar 'list (org-buffer-property-keys t))
8149 nil t))))
8151 (message "Sorting entries...")
8153 (save-restriction
8154 (narrow-to-region start end)
8155 (let ((dcst (downcase sorting-type))
8156 (case-fold-search nil)
8157 (now (current-time)))
8158 (sort-subr
8159 (/= dcst sorting-type)
8160 ;; This function moves to the beginning character of the "record" to
8161 ;; be sorted.
8162 (lambda nil
8163 (if (re-search-forward re nil t)
8164 (goto-char (match-beginning 0))
8165 (goto-char (point-max))))
8166 ;; This function moves to the last character of the "record" being
8167 ;; sorted.
8168 (lambda nil
8169 (save-match-data
8170 (condition-case nil
8171 (outline-forward-same-level 1)
8172 (error
8173 (goto-char (point-max))))))
8174 ;; This function returns the value that gets sorted against.
8175 (lambda nil
8176 (cond
8177 ((= dcst ?n)
8178 (if (looking-at org-complex-heading-regexp)
8179 (string-to-number (match-string 4))
8180 nil))
8181 ((= dcst ?a)
8182 (if (looking-at org-complex-heading-regexp)
8183 (funcall case-func (match-string 4))
8184 nil))
8185 ((= dcst ?t)
8186 (let ((end (save-excursion (outline-next-heading) (point))))
8187 (if (or (re-search-forward org-ts-regexp end t)
8188 (re-search-forward org-ts-regexp-both end t))
8189 (org-time-string-to-seconds (match-string 0))
8190 (org-float-time now))))
8191 ((= dcst ?c)
8192 (let ((end (save-excursion (outline-next-heading) (point))))
8193 (if (re-search-forward
8194 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8195 end t)
8196 (org-time-string-to-seconds (match-string 0))
8197 (org-float-time now))))
8198 ((= dcst ?s)
8199 (let ((end (save-excursion (outline-next-heading) (point))))
8200 (if (re-search-forward org-scheduled-time-regexp end t)
8201 (org-time-string-to-seconds (match-string 1))
8202 (org-float-time now))))
8203 ((= dcst ?d)
8204 (let ((end (save-excursion (outline-next-heading) (point))))
8205 (if (re-search-forward org-deadline-time-regexp end t)
8206 (org-time-string-to-seconds (match-string 1))
8207 (org-float-time now))))
8208 ((= dcst ?p)
8209 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8210 (string-to-char (match-string 2))
8211 org-default-priority))
8212 ((= dcst ?r)
8213 (or (org-entry-get nil property) ""))
8214 ((= dcst ?o)
8215 (if (looking-at org-complex-heading-regexp)
8216 (- 9999 (length (member (match-string 2)
8217 org-todo-keywords-1)))))
8218 ((= dcst ?f)
8219 (if getkey-func
8220 (progn
8221 (setq tmp (funcall getkey-func))
8222 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8223 tmp)
8224 (error "Invalid key function `%s'" getkey-func)))
8225 (t (error "Invalid sorting type `%c'" sorting-type))))
8227 (cond
8228 ((= dcst ?a) 'string<)
8229 ((= dcst ?f) compare-func)
8230 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8231 (run-hooks 'org-after-sorting-entries-or-items-hook)
8232 ;; Reset the clock marker if needed
8233 (when cmstr
8234 (save-excursion
8235 (goto-char start)
8236 (search-forward cmstr nil t)
8237 (move-marker org-clock-marker (point))))
8238 (message "Sorting entries...done")))
8240 (defun org-do-sort (table what &optional with-case sorting-type)
8241 "Sort TABLE of WHAT according to SORTING-TYPE.
8242 The user will be prompted for the SORTING-TYPE if the call to this
8243 function does not specify it. WHAT is only for the prompt, to indicate
8244 what is being sorted. The sorting key will be extracted from
8245 the car of the elements of the table.
8246 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8247 (unless sorting-type
8248 (message
8249 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8250 what)
8251 (setq sorting-type (read-char-exclusive)))
8252 (let ((dcst (downcase sorting-type))
8253 extractfun comparefun)
8254 ;; Define the appropriate functions
8255 (cond
8256 ((= dcst ?n)
8257 (setq extractfun 'string-to-number
8258 comparefun (if (= dcst sorting-type) '< '>)))
8259 ((= dcst ?a)
8260 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8261 (lambda(x) (downcase (org-sort-remove-invisible x))))
8262 comparefun (if (= dcst sorting-type)
8263 'string<
8264 (lambda (a b) (and (not (string< a b))
8265 (not (string= a b)))))))
8266 ((= dcst ?t)
8267 (setq extractfun
8268 (lambda (x)
8269 (if (or (string-match org-ts-regexp x)
8270 (string-match org-ts-regexp-both x))
8271 (org-float-time
8272 (org-time-string-to-time (match-string 0 x)))
8274 comparefun (if (= dcst sorting-type) '< '>)))
8275 (t (error "Invalid sorting type `%c'" sorting-type)))
8277 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8278 table)
8279 (lambda (a b) (funcall comparefun (car a) (car b))))))
8282 ;;; The orgstruct minor mode
8284 ;; Define a minor mode which can be used in other modes in order to
8285 ;; integrate the org-mode structure editing commands.
8287 ;; This is really a hack, because the org-mode structure commands use
8288 ;; keys which normally belong to the major mode. Here is how it
8289 ;; works: The minor mode defines all the keys necessary to operate the
8290 ;; structure commands, but wraps the commands into a function which
8291 ;; tests if the cursor is currently at a headline or a plain list
8292 ;; item. If that is the case, the structure command is used,
8293 ;; temporarily setting many Org-mode variables like regular
8294 ;; expressions for filling etc. However, when any of those keys is
8295 ;; used at a different location, function uses `key-binding' to look
8296 ;; up if the key has an associated command in another currently active
8297 ;; keymap (minor modes, major mode, global), and executes that
8298 ;; command. There might be problems if any of the keys is otherwise
8299 ;; used as a prefix key.
8301 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8302 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8303 ;; addresses this by checking explicitly for both bindings.
8305 (defvar orgstruct-mode-map (make-sparse-keymap)
8306 "Keymap for the minor `orgstruct-mode'.")
8308 (defvar org-local-vars nil
8309 "List of local variables, for use by `orgstruct-mode'.")
8311 ;;;###autoload
8312 (define-minor-mode orgstruct-mode
8313 "Toggle the minor mode `orgstruct-mode'.
8314 This mode is for using Org-mode structure commands in other
8315 modes. The following keys behave as if Org-mode were active, if
8316 the cursor is on a headline, or on a plain list item (both as
8317 defined by Org-mode).
8319 M-up Move entry/item up
8320 M-down Move entry/item down
8321 M-left Promote
8322 M-right Demote
8323 M-S-up Move entry/item up
8324 M-S-down Move entry/item down
8325 M-S-left Promote subtree
8326 M-S-right Demote subtree
8327 M-q Fill paragraph and items like in Org-mode
8328 C-c ^ Sort entries
8329 C-c - Cycle list bullet
8330 TAB Cycle item visibility
8331 M-RET Insert new heading/item
8332 S-M-RET Insert new TODO heading / Checkbox item
8333 C-c C-c Set tags / toggle checkbox"
8334 nil " OrgStruct" nil
8335 (org-load-modules-maybe)
8336 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8338 ;;;###autoload
8339 (defun turn-on-orgstruct ()
8340 "Unconditionally turn on `orgstruct-mode'."
8341 (orgstruct-mode 1))
8343 (defvar org-fb-vars nil)
8344 (make-variable-buffer-local 'org-fb-vars)
8345 (defun orgstruct++-mode (&optional arg)
8346 "Toggle `orgstruct-mode', the enhanced version of it.
8347 In addition to setting orgstruct-mode, this also exports all
8348 indentation and autofilling variables from org-mode into the
8349 buffer. It will also recognize item context in multiline items."
8350 (interactive "P")
8351 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8352 (if (< arg 1)
8353 (progn (orgstruct-mode -1)
8354 (mapc (lambda(v)
8355 (org-set-local (car v)
8356 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8357 org-fb-vars))
8358 (orgstruct-mode 1)
8359 (setq org-fb-vars nil)
8360 (let (var val)
8361 (mapc
8362 (lambda (x)
8363 (when (string-match
8364 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8365 (symbol-name (car x)))
8366 (setq var (car x) val (nth 1 x))
8367 (push (list var `(quote ,(eval var))) org-fb-vars)
8368 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8369 org-local-vars)
8370 (org-set-local 'orgstruct-is-++ t))))
8372 (defvar orgstruct-is-++ nil
8373 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8374 (make-variable-buffer-local 'orgstruct-is-++)
8376 ;;;###autoload
8377 (defun turn-on-orgstruct++ ()
8378 "Unconditionally turn on `orgstruct++-mode'."
8379 (orgstruct++-mode 1))
8381 (defun orgstruct-error ()
8382 "Error when there is no default binding for a structure key."
8383 (interactive)
8384 (error "This key has no function outside structure elements"))
8386 (defun orgstruct-setup ()
8387 "Setup orgstruct keymaps."
8388 (let ((nfunc 0)
8389 (bindings
8390 (list
8391 '([(meta up)] org-metaup)
8392 '([(meta down)] org-metadown)
8393 '([(meta left)] org-metaleft)
8394 '([(meta right)] org-metaright)
8395 '([(meta shift up)] org-shiftmetaup)
8396 '([(meta shift down)] org-shiftmetadown)
8397 '([(meta shift left)] org-shiftmetaleft)
8398 '([(meta shift right)] org-shiftmetaright)
8399 '([?\e (up)] org-metaup)
8400 '([?\e (down)] org-metadown)
8401 '([?\e (left)] org-metaleft)
8402 '([?\e (right)] org-metaright)
8403 '([?\e (shift up)] org-shiftmetaup)
8404 '([?\e (shift down)] org-shiftmetadown)
8405 '([?\e (shift left)] org-shiftmetaleft)
8406 '([?\e (shift right)] org-shiftmetaright)
8407 '([(shift up)] org-shiftup)
8408 '([(shift down)] org-shiftdown)
8409 '([(shift left)] org-shiftleft)
8410 '([(shift right)] org-shiftright)
8411 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8412 '("\M-q" fill-paragraph)
8413 '("\C-c^" org-sort)
8414 '("\C-c-" org-cycle-list-bullet)))
8415 elt key fun cmd)
8416 (while (setq elt (pop bindings))
8417 (setq nfunc (1+ nfunc))
8418 (setq key (org-key (car elt))
8419 fun (nth 1 elt)
8420 cmd (orgstruct-make-binding fun nfunc key))
8421 (org-defkey orgstruct-mode-map key cmd))
8423 ;; Prevent an error for users who forgot to make autoloads
8424 (require 'org-element)
8426 ;; Special treatment needed for TAB and RET
8427 (org-defkey orgstruct-mode-map [(tab)]
8428 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8429 (org-defkey orgstruct-mode-map "\C-i"
8430 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8432 (org-defkey orgstruct-mode-map "\M-\C-m"
8433 (orgstruct-make-binding 'org-insert-heading 105
8434 "\M-\C-m" [(meta return)]))
8435 (org-defkey orgstruct-mode-map [(meta return)]
8436 (orgstruct-make-binding 'org-insert-heading 106
8437 [(meta return)] "\M-\C-m"))
8439 (org-defkey orgstruct-mode-map [(shift meta return)]
8440 (orgstruct-make-binding 'org-insert-todo-heading 107
8441 [(meta return)] "\M-\C-m"))
8443 (org-defkey orgstruct-mode-map "\e\C-m"
8444 (orgstruct-make-binding 'org-insert-heading 108
8445 "\e\C-m" [?\e (return)]))
8446 (org-defkey orgstruct-mode-map [?\e (return)]
8447 (orgstruct-make-binding 'org-insert-heading 109
8448 [?\e (return)] "\e\C-m"))
8449 (org-defkey orgstruct-mode-map [?\e (shift return)]
8450 (orgstruct-make-binding 'org-insert-todo-heading 110
8451 [?\e (return)] "\e\C-m"))
8453 (unless org-local-vars
8454 (setq org-local-vars (org-get-local-variables)))
8458 (defun orgstruct-make-binding (fun n &rest keys)
8459 "Create a function for binding in the structure minor mode.
8460 FUN is the command to call inside a table. N is used to create a unique
8461 command name. KEYS are keys that should be checked in for a command
8462 to execute outside of tables."
8463 (eval
8464 (list 'defun
8465 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8466 '(arg)
8467 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8468 "Outside of structure, run the binding of `"
8469 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8470 "'.")
8471 '(interactive "p")
8472 (list 'if
8473 `(org-context-p 'headline 'item
8474 (and orgstruct-is-++
8475 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8476 'item-body))
8477 (list 'org-run-like-in-org-mode (list 'quote fun))
8478 (list 'let '(orgstruct-mode)
8479 (list 'call-interactively
8480 (append '(or)
8481 (mapcar (lambda (k)
8482 (list 'key-binding k))
8483 keys)
8484 '('orgstruct-error))))))))
8486 (defun org-contextualize-keys (alist contexts)
8487 "Return valid elements in ALIST depending on CONTEXTS.
8489 `org-agenda-custom-commands' or `org-capture-templates' are the
8490 values used for ALIST, and `org-agenda-custom-commands-contexts'
8491 or `org-capture-templates-contexts' are the associated contexts
8492 definitions."
8493 (let ((contexts
8494 ;; normalize contexts
8495 (mapcar
8496 (lambda(c) (cond ((listp (cadr c))
8497 (list (car c) (car c) (cadr c)))
8498 ((string= "" (cadr c))
8499 (list (car c) (car c) (caddr c)))
8500 (t c))) contexts))
8501 (a alist) c r s)
8502 ;; loop over all commands or templates
8503 (while (setq c (pop a))
8504 (let (vrules repl)
8505 (cond
8506 ((not (assoc (car c) contexts))
8507 (push c r))
8508 ((and (assoc (car c) contexts)
8509 (setq vrules (org-contextualize-validate-key
8510 (car c) contexts)))
8511 (mapc (lambda (vr)
8512 (when (not (equal (car vr) (cadr vr)))
8513 (setq repl vr))) vrules)
8514 (if (not repl) (push c r)
8515 (push (cadr repl) s)
8516 (push
8517 (cons (car c)
8518 (cdr (or (assoc (cadr repl) alist)
8519 (error "Undefined key `%s' as contextual replacement for `%s'"
8520 (cadr repl) (car c)))))
8521 r))))))
8522 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8523 (delq
8525 (delete-dups
8526 (mapcar (lambda (x)
8527 (let ((tpl (car x)))
8528 (when (not (delq
8530 (mapcar (lambda(y)
8531 (equal y tpl)) s))) x)))
8532 (reverse r))))))
8534 (defun org-contextualize-validate-key (key contexts)
8535 "Check CONTEXTS for agenda or capture KEY."
8536 (let (r rr res)
8537 (while (setq r (pop contexts))
8538 (mapc
8539 (lambda (rr)
8540 (when
8541 (and (equal key (car r))
8542 (if (functionp rr) (funcall rr)
8543 (or (and (eq (car rr) 'in-file)
8544 (buffer-file-name)
8545 (string-match (cdr rr) (buffer-file-name)))
8546 (and (eq (car rr) 'in-mode)
8547 (string-match (cdr rr) (symbol-name major-mode)))
8548 (when (and (eq (car rr) 'not-in-file)
8549 (buffer-file-name))
8550 (not (string-match (cdr rr) (buffer-file-name))))
8551 (when (eq (car rr) 'not-in-mode)
8552 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8553 (push r res)))
8554 (car (last r))))
8555 (delete-dups (delq nil res))))
8557 (defun org-context-p (&rest contexts)
8558 "Check if local context is any of CONTEXTS.
8559 Possible values in the list of contexts are `table', `headline', and `item'."
8560 (let ((pos (point)))
8561 (goto-char (point-at-bol))
8562 (prog1 (or (and (memq 'table contexts)
8563 (looking-at "[ \t]*|"))
8564 (and (memq 'headline contexts)
8565 (looking-at org-outline-regexp))
8566 (and (memq 'item contexts)
8567 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8568 (and (memq 'item-body contexts)
8569 (org-in-item-p)))
8570 (goto-char pos))))
8572 (defun org-get-local-variables ()
8573 "Return a list of all local variables in an Org mode buffer."
8574 (let (varlist)
8575 (with-current-buffer (get-buffer-create "*Org tmp*")
8576 (erase-buffer)
8577 (org-mode)
8578 (setq varlist (buffer-local-variables)))
8579 (kill-buffer "*Org tmp*")
8580 (delq nil
8581 (mapcar
8582 (lambda (x)
8583 (setq x
8584 (if (symbolp x)
8585 (list x)
8586 (list (car x) (list 'quote (cdr x)))))
8587 (if (string-match
8588 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8589 (symbol-name (car x)))
8590 x nil))
8591 varlist))))
8593 (defun org-clone-local-variables (from-buffer &optional regexp)
8594 "Clone local variables from FROM-BUFFER.
8595 Optional argument REGEXP selects variables to clone."
8596 (mapc
8597 (lambda (pair)
8598 (and (symbolp (car pair))
8599 (or (null regexp)
8600 (string-match regexp (symbol-name (car pair))))
8601 (set (make-local-variable (car pair))
8602 (cdr pair))))
8603 (buffer-local-variables from-buffer)))
8605 ;;;###autoload
8606 (defun org-run-like-in-org-mode (cmd)
8607 "Run a command, pretending that the current buffer is in Org-mode.
8608 This will temporarily bind local variables that are typically bound in
8609 Org-mode to the values they have in Org-mode, and then interactively
8610 call CMD."
8611 (org-load-modules-maybe)
8612 (unless org-local-vars
8613 (setq org-local-vars (org-get-local-variables)))
8614 (eval (list 'let org-local-vars
8615 (list 'call-interactively (list 'quote cmd)))))
8617 ;;;; Archiving
8619 (defun org-get-category (&optional pos force-refresh)
8620 "Get the category applying to position POS."
8621 (save-match-data
8622 (if force-refresh (org-refresh-category-properties))
8623 (let ((pos (or pos (point))))
8624 (or (get-text-property pos 'org-category)
8625 (progn (org-refresh-category-properties)
8626 (get-text-property pos 'org-category))))))
8628 (defun org-refresh-category-properties ()
8629 "Refresh category text properties in the buffer."
8630 (let ((case-fold-search t)
8631 (inhibit-read-only t)
8632 (def-cat (cond
8633 ((null org-category)
8634 (if buffer-file-name
8635 (file-name-sans-extension
8636 (file-name-nondirectory buffer-file-name))
8637 "???"))
8638 ((symbolp org-category) (symbol-name org-category))
8639 (t org-category)))
8640 beg end cat pos optionp)
8641 (org-unmodified
8642 (save-excursion
8643 (save-restriction
8644 (widen)
8645 (goto-char (point-min))
8646 (put-text-property (point) (point-max) 'org-category def-cat)
8647 (while (re-search-forward
8648 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8649 (setq pos (match-end 0)
8650 optionp (equal (char-after (match-beginning 0)) ?#)
8651 cat (org-trim (match-string 2)))
8652 (if optionp
8653 (setq beg (point-at-bol) end (point-max))
8654 (org-back-to-heading t)
8655 (setq beg (point) end (org-end-of-subtree t t)))
8656 (put-text-property beg end 'org-category cat)
8657 (put-text-property beg end 'org-category-position beg)
8658 (goto-char pos)))))))
8660 (defun org-refresh-properties (dprop tprop)
8661 "Refresh buffer text properties.
8662 DPROP is the drawer property and TPROP is the corresponding text
8663 property to set."
8664 (let ((case-fold-search t)
8665 (inhibit-read-only t) p)
8666 (org-unmodified
8667 (save-excursion
8668 (save-restriction
8669 (widen)
8670 (goto-char (point-min))
8671 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8672 (setq p (org-match-string-no-properties 1))
8673 (save-excursion
8674 (org-back-to-heading t)
8675 (put-text-property
8676 (point-at-bol) (point-at-eol) tprop p))))))))
8679 ;;;; Link Stuff
8681 ;;; Link abbreviations
8683 (defun org-link-expand-abbrev (link)
8684 "Apply replacements as defined in `org-link-abbrev-alist'."
8685 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8686 (let* ((key (match-string 1 link))
8687 (as (or (assoc key org-link-abbrev-alist-local)
8688 (assoc key org-link-abbrev-alist)))
8689 (tag (and (match-end 2) (match-string 3 link)))
8690 rpl)
8691 (if (not as)
8692 link
8693 (setq rpl (cdr as))
8694 (cond
8695 ((symbolp rpl) (funcall rpl tag))
8696 ((string-match "%(\\([^)]+\\))" rpl)
8697 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8698 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8699 ((string-match "%h" rpl)
8700 (replace-match (url-hexify-string (or tag "")) t t rpl))
8701 (t (concat rpl tag)))))
8702 link))
8704 ;;; Storing and inserting links
8706 (defvar org-insert-link-history nil
8707 "Minibuffer history for links inserted with `org-insert-link'.")
8709 (defvar org-stored-links nil
8710 "Contains the links stored with `org-store-link'.")
8712 (defvar org-store-link-plist nil
8713 "Plist with info about the most recently link created with `org-store-link'.")
8715 (defvar org-link-protocols nil
8716 "Link protocols added to Org-mode using `org-add-link-type'.")
8718 (defvar org-store-link-functions nil
8719 "List of functions that are called to create and store a link.
8720 Each function will be called in turn until one returns a non-nil
8721 value. Each function should check if it is responsible for creating
8722 this link (for example by looking at the major mode).
8723 If not, it must exit and return nil.
8724 If yes, it should return a non-nil value after a calling
8725 `org-store-link-props' with a list of properties and values.
8726 Special properties are:
8728 :type The link prefix, like \"http\". This must be given.
8729 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8730 This is obligatory as well.
8731 :description Optional default description for the second pair
8732 of brackets in an Org-mode link. The user can still change
8733 this when inserting this link into an Org-mode buffer.
8735 In addition to these, any additional properties can be specified
8736 and then used in capture templates.")
8738 (defun org-add-link-type (type &optional follow export)
8739 "Add TYPE to the list of `org-link-types'.
8740 Re-compute all regular expressions depending on `org-link-types'
8742 FOLLOW and EXPORT are two functions.
8744 FOLLOW should take the link path as the single argument and do whatever
8745 is necessary to follow the link, for example find a file or display
8746 a mail message.
8748 EXPORT should format the link path for export to one of the export formats.
8749 It should be a function accepting three arguments:
8751 path the path of the link, the text after the prefix (like \"http:\")
8752 desc the description of the link, if any, or a description added by
8753 org-export-normalize-links if there is none
8754 format the export format, a symbol like `html' or `latex' or `ascii'..
8756 The function may use the FORMAT information to return different values
8757 depending on the format. The return value will be put literally into
8758 the exported file. If the return value is nil, this means Org should
8759 do what it normally does with links which do not have EXPORT defined.
8761 Org-mode has a built-in default for exporting links. If you are happy with
8762 this default, there is no need to define an export function for the link
8763 type. For a simple example of an export function, see `org-bbdb.el'."
8764 (add-to-list 'org-link-types type t)
8765 (org-make-link-regexps)
8766 (if (assoc type org-link-protocols)
8767 (setcdr (assoc type org-link-protocols) (list follow export))
8768 (push (list type follow export) org-link-protocols)))
8770 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8771 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8773 ;;;###autoload
8774 (defun org-store-link (arg)
8775 "\\<org-mode-map>Store an org-link to the current location.
8776 This link is added to `org-stored-links' and can later be inserted
8777 into an org-buffer with \\[org-insert-link].
8779 For some link types, a prefix arg is interpreted:
8780 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8781 For file links, arg negates `org-context-in-file-links'."
8782 (interactive "P")
8783 (org-load-modules-maybe)
8784 (setq org-store-link-plist nil) ; reset
8785 (org-with-limited-levels
8786 (let (link cpltxt desc description search txt custom-id agenda-link)
8787 (cond
8789 ((run-hook-with-args-until-success 'org-store-link-functions)
8790 (setq link (plist-get org-store-link-plist :link)
8791 desc (or (plist-get org-store-link-plist :description) link)))
8793 ((org-src-edit-buffer-p)
8794 (let (label gc)
8795 (while (or (not label)
8796 (save-excursion
8797 (save-restriction
8798 (widen)
8799 (goto-char (point-min))
8800 (re-search-forward
8801 (regexp-quote (format org-coderef-label-format label))
8802 nil t))))
8803 (when label (message "Label exists already") (sit-for 2))
8804 (setq label (read-string "Code line label: " label)))
8805 (end-of-line 1)
8806 (setq link (format org-coderef-label-format label))
8807 (setq gc (- 79 (length link)))
8808 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8809 (insert link)
8810 (setq link (concat "(" label ")") desc nil)))
8812 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8813 ;; We are in the agenda, link to referenced location
8814 (let ((m (or (get-text-property (point) 'org-hd-marker)
8815 (get-text-property (point) 'org-marker))))
8816 (when m
8817 (org-with-point-at m
8818 (setq agenda-link
8819 (if (org-called-interactively-p 'any)
8820 (call-interactively 'org-store-link)
8821 (org-store-link nil)))))))
8823 ((eq major-mode 'calendar-mode)
8824 (let ((cd (calendar-cursor-to-date)))
8825 (setq link
8826 (format-time-string
8827 (car org-time-stamp-formats)
8828 (apply 'encode-time
8829 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8830 nil nil nil))))
8831 (org-store-link-props :type "calendar" :date cd)))
8833 ((eq major-mode 'help-mode)
8834 (setq link (concat "help:" (save-excursion
8835 (goto-char (point-min))
8836 (looking-at "^[^ ]+")
8837 (match-string 0))))
8838 (org-store-link-props :type "help"))
8840 ((eq major-mode 'w3-mode)
8841 (setq cpltxt (if (and (buffer-name)
8842 (not (string-match "Untitled" (buffer-name))))
8843 (buffer-name)
8844 (url-view-url t))
8845 link (url-view-url t))
8846 (org-store-link-props :type "w3" :url (url-view-url t)))
8848 ((eq major-mode 'w3m-mode)
8849 (setq cpltxt (or w3m-current-title w3m-current-url)
8850 link w3m-current-url)
8851 (org-store-link-props :type "w3m" :url (url-view-url t)))
8853 ((setq search (run-hook-with-args-until-success
8854 'org-create-file-search-functions))
8855 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8856 "::" search))
8857 (setq cpltxt (or description link)))
8859 ((eq major-mode 'image-mode)
8860 (setq cpltxt (concat "file:"
8861 (abbreviate-file-name buffer-file-name))
8862 link cpltxt)
8863 (org-store-link-props :type "image" :file buffer-file-name))
8865 ((eq major-mode 'dired-mode)
8866 ;; link to the file in the current line
8867 (let ((file (dired-get-filename nil t)))
8868 (setq file (if file
8869 (abbreviate-file-name
8870 (expand-file-name (dired-get-filename nil t)))
8871 ;; otherwise, no file so use current directory.
8872 default-directory))
8873 (setq cpltxt (concat "file:" file)
8874 link cpltxt)))
8876 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8877 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8878 (cond
8879 ((org-in-regexp "<<\\(.*?\\)>>")
8880 (setq cpltxt
8881 (concat "file:"
8882 (abbreviate-file-name
8883 (buffer-file-name (buffer-base-buffer)))
8884 "::" (match-string 1))
8885 link cpltxt))
8886 ((and (featurep 'org-id)
8887 (or (eq org-id-link-to-org-use-id t)
8888 (and (org-called-interactively-p 'any)
8889 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8890 (and (eq org-id-link-to-org-use-id
8891 'create-if-interactive-and-no-custom-id)
8892 (not custom-id))))
8893 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8894 ;; We can make a link using the ID.
8895 (setq link (condition-case nil
8896 (prog1 (org-id-store-link)
8897 (setq desc (plist-get org-store-link-plist :description)))
8898 (error
8899 ;; probably before first headline, link to file only
8900 (concat "file:"
8901 (abbreviate-file-name
8902 (buffer-file-name (buffer-base-buffer))))))))
8904 ;; Just link to current headline
8905 (setq cpltxt (concat "file:"
8906 (abbreviate-file-name
8907 (buffer-file-name (buffer-base-buffer)))))
8908 ;; Add a context search string
8909 (when (org-xor org-context-in-file-links arg)
8910 (setq txt (cond
8911 ((org-at-heading-p) nil)
8912 ((org-region-active-p)
8913 (buffer-substring (region-beginning) (region-end)))))
8914 (when (or (null txt) (string-match "\\S-" txt))
8915 (setq cpltxt
8916 (concat cpltxt "::"
8917 (condition-case nil
8918 (org-make-org-heading-search-string txt)
8919 (error "")))
8920 desc (or (nth 4 (ignore-errors
8921 (org-heading-components))) "NONE"))))
8922 (if (string-match "::\\'" cpltxt)
8923 (setq cpltxt (substring cpltxt 0 -2)))
8924 (setq link cpltxt))))
8926 ((buffer-file-name (buffer-base-buffer))
8927 ;; Just link to this file here.
8928 (setq cpltxt (concat "file:"
8929 (abbreviate-file-name
8930 (buffer-file-name (buffer-base-buffer)))))
8931 ;; Add a context string
8932 (when (org-xor org-context-in-file-links arg)
8933 (setq txt (if (org-region-active-p)
8934 (buffer-substring (region-beginning) (region-end))
8935 (buffer-substring (point-at-bol) (point-at-eol))))
8936 ;; Only use search option if there is some text.
8937 (when (string-match "\\S-" txt)
8938 (setq cpltxt
8939 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8940 desc "NONE")))
8941 (setq link cpltxt))
8943 ((org-called-interactively-p 'interactive)
8944 (error "Cannot link to a buffer which is not visiting a file"))
8946 (t (setq link nil)))
8948 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8949 (setq link (or link cpltxt)
8950 desc (or desc cpltxt))
8951 (if (equal desc "NONE") (setq desc nil))
8953 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8954 (progn
8955 (setq org-stored-links
8956 (cons (list link desc) org-stored-links))
8957 (message "Stored: %s" (or desc link))
8958 (when custom-id
8959 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8960 "::#" custom-id))
8961 (setq org-stored-links
8962 (cons (list link desc) org-stored-links))))
8963 (or agenda-link (and link (org-make-link-string link desc)))))))
8965 (defun org-store-link-props (&rest plist)
8966 "Store link properties, extract names and addresses."
8967 (let (x adr)
8968 (when (setq x (plist-get plist :from))
8969 (setq adr (mail-extract-address-components x))
8970 (setq plist (plist-put plist :fromname (car adr)))
8971 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8972 (when (setq x (plist-get plist :to))
8973 (setq adr (mail-extract-address-components x))
8974 (setq plist (plist-put plist :toname (car adr)))
8975 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8976 (let ((from (plist-get plist :from))
8977 (to (plist-get plist :to)))
8978 (when (and from to org-from-is-user-regexp)
8979 (setq plist
8980 (plist-put plist :fromto
8981 (if (string-match org-from-is-user-regexp from)
8982 (concat "to %t")
8983 (concat "from %f"))))))
8984 (setq org-store-link-plist plist))
8986 (defun org-add-link-props (&rest plist)
8987 "Add these properties to the link property list."
8988 (let (key value)
8989 (while plist
8990 (setq key (pop plist) value (pop plist))
8991 (setq org-store-link-plist
8992 (plist-put org-store-link-plist key value)))))
8994 (defun org-email-link-description (&optional fmt)
8995 "Return the description part of an email link.
8996 This takes information from `org-store-link-plist' and formats it
8997 according to FMT (default from `org-email-link-description-format')."
8998 (setq fmt (or fmt org-email-link-description-format))
8999 (let* ((p org-store-link-plist)
9000 (to (plist-get p :toaddress))
9001 (from (plist-get p :fromaddress))
9002 (table
9003 (list
9004 (cons "%c" (plist-get p :fromto))
9005 (cons "%F" (plist-get p :from))
9006 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9007 (cons "%T" (plist-get p :to))
9008 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9009 (cons "%s" (plist-get p :subject))
9010 (cons "%d" (plist-get p :date))
9011 (cons "%m" (plist-get p :message-id)))))
9012 (when (string-match "%c" fmt)
9013 ;; Check if the user wrote this message
9014 (if (and org-from-is-user-regexp from to
9015 (save-match-data (string-match org-from-is-user-regexp from)))
9016 (setq fmt (replace-match "to %t" t t fmt))
9017 (setq fmt (replace-match "from %f" t t fmt))))
9018 (org-replace-escapes fmt table)))
9020 (defun org-make-org-heading-search-string (&optional string heading)
9021 "Make search string for STRING or current headline."
9022 (interactive)
9023 (let ((s (or string (org-get-heading)))
9024 (lines org-context-in-file-links))
9025 (unless (and string (not heading))
9026 ;; We are using a headline, clean up garbage in there.
9027 (if (string-match org-todo-regexp s)
9028 (setq s (replace-match "" t t s)))
9029 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9030 (setq s (replace-match "" t t s)))
9031 (setq s (org-trim s))
9032 (if (string-match (concat "^\\(" org-quote-string "\\|"
9033 org-comment-string "\\)") s)
9034 (setq s (replace-match "" t t s)))
9035 (while (string-match org-ts-regexp s)
9036 (setq s (replace-match "" t t s))))
9037 (or string (setq s (concat "*" s))) ; Add * for headlines
9038 (when (and string (integerp lines) (> lines 0))
9039 (let ((slines (org-split-string s "\n")))
9040 (when (< lines (length slines))
9041 (setq s (mapconcat
9042 'identity
9043 (reverse (nthcdr (- (length slines) lines)
9044 (reverse slines))) "\n")))))
9045 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9047 (defun org-make-link-string (link &optional description)
9048 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9049 (unless (string-match "\\S-" link)
9050 (error "Empty link"))
9051 (when (and description
9052 (stringp description)
9053 (not (string-match "\\S-" description)))
9054 (setq description nil))
9055 (when (stringp description)
9056 ;; Remove brackets from the description, they are fatal.
9057 (while (string-match "\\[" description)
9058 (setq description (replace-match "{" t t description)))
9059 (while (string-match "\\]" description)
9060 (setq description (replace-match "}" t t description))))
9061 (when (equal link description)
9062 ;; No description needed, it is identical
9063 (setq description nil))
9064 (when (and (not description)
9065 (not (string-match (org-image-file-name-regexp) link))
9066 (not (equal link (org-link-escape link))))
9067 (setq description (org-extract-attributes link)))
9068 (setq link
9069 (cond ((string-match (org-image-file-name-regexp) link) link)
9070 ((string-match org-link-types-re link)
9071 (concat (match-string 1 link)
9072 (org-link-escape (substring link (match-end 1)))))
9073 (t (org-link-escape link))))
9074 (concat "[[" link "]"
9075 (if description (concat "[" description "]") "")
9076 "]"))
9078 (defconst org-link-escape-chars
9079 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9080 "List of characters that should be escaped in link.
9081 This is the list that is used for internal purposes.")
9083 (defconst org-link-escape-chars-browser
9084 '(?\ )
9085 "List of escapes for characters that are problematic in links.
9086 This is the list that is used before handing over to the browser.")
9088 (defun org-link-escape (text &optional table merge)
9089 "Return percent escaped representation of TEXT.
9090 TEXT is a string with the text to escape.
9091 Optional argument TABLE is a list with characters that should be
9092 escaped. When nil, `org-link-escape-chars' is used.
9093 If optional argument MERGE is set, merge TABLE into
9094 `org-link-escape-chars'."
9095 (cond
9096 ((and table merge)
9097 (mapc (lambda (defchr)
9098 (unless (member defchr table)
9099 (setq table (cons defchr table)))) org-link-escape-chars))
9100 ((null table)
9101 (setq table org-link-escape-chars)))
9102 (mapconcat
9103 (lambda (char)
9104 (if (or (member char table)
9105 (and (or (< char 32) (= char 37) (> char 126))
9106 org-url-hexify-p))
9107 (mapconcat (lambda (sequence-element)
9108 (format "%%%.2X" sequence-element))
9109 (or (encode-coding-char char 'utf-8)
9110 (error "Unable to percent escape character: %s"
9111 (char-to-string char))) "")
9112 (char-to-string char))) text ""))
9114 (defun org-link-unescape (str)
9115 "Unhex hexified Unicode strings as returned from the JavaScript function
9116 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9117 (unless (and (null str) (string= "" str))
9118 (let ((pos 0) (case-fold-search t) unhexed)
9119 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9120 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9121 (setq str (replace-match unhexed t t str))
9122 (setq pos (+ pos (length unhexed))))))
9123 str)
9125 (defun org-link-unescape-compound (hex)
9126 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9127 Note: this function also decodes single byte encodings like
9128 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9129 (save-match-data
9130 (let* ((bytes (cdr (split-string hex "%")))
9131 (ret "")
9132 (eat 0)
9133 (sum 0))
9134 (while bytes
9135 (let* ((val (string-to-number (pop bytes) 16))
9136 (shift-xor
9137 (if (= 0 eat)
9138 (cond
9139 ((>= val 252) (cons 6 252))
9140 ((>= val 248) (cons 5 248))
9141 ((>= val 240) (cons 4 240))
9142 ((>= val 224) (cons 3 224))
9143 ((>= val 192) (cons 2 192))
9144 (t (cons 0 0)))
9145 (cons 6 128))))
9146 (if (>= val 192) (setq eat (car shift-xor)))
9147 (setq val (logxor val (cdr shift-xor)))
9148 (setq sum (+ (lsh sum (car shift-xor)) val))
9149 (if (> eat 0) (setq eat (- eat 1)))
9150 (cond
9151 ((= 0 eat) ;multi byte
9152 (setq ret (concat ret (org-char-to-string sum)))
9153 (setq sum 0))
9154 ((not bytes) ; single byte(s)
9155 (setq ret (org-link-unescape-single-byte-sequence hex))))
9156 )) ;; end (while bytes
9157 ret )))
9159 (defun org-link-unescape-single-byte-sequence (hex)
9160 "Unhexify hex-encoded single byte character sequences."
9161 (mapconcat (lambda (byte)
9162 (char-to-string (string-to-number byte 16)))
9163 (cdr (split-string hex "%")) ""))
9165 (defun org-xor (a b)
9166 "Exclusive or."
9167 (if a (not b) b))
9169 (defun org-fixup-message-id-for-http (s)
9170 "Replace special characters in a message id, so it can be used in an http query."
9171 (when (string-match "%" s)
9172 (setq s (mapconcat (lambda (c)
9173 (if (eq c ?%)
9174 "%25"
9175 (char-to-string c)))
9176 s "")))
9177 (while (string-match "<" s)
9178 (setq s (replace-match "%3C" t t s)))
9179 (while (string-match ">" s)
9180 (setq s (replace-match "%3E" t t s)))
9181 (while (string-match "@" s)
9182 (setq s (replace-match "%40" t t s)))
9185 (defun org-link-prettify (link)
9186 "Return a human-readable representation of LINK.
9187 The car of LINK must be a raw link the cdr of LINK must be either
9188 a link description or nil."
9189 (let ((desc (or (cadr link) "<no description>")))
9190 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9191 "<" (car link) ">")))
9193 ;;;###autoload
9194 (defun org-insert-link-global ()
9195 "Insert a link like Org-mode does.
9196 This command can be called in any mode to insert a link in Org-mode syntax."
9197 (interactive)
9198 (org-load-modules-maybe)
9199 (org-run-like-in-org-mode 'org-insert-link))
9201 (defun org-insert-all-links (&optional keep)
9202 "Insert all links in `org-stored-links'."
9203 (interactive "P")
9204 (let ((links (copy-sequence org-stored-links)) l)
9205 (while (setq l (if keep (pop links) (pop org-stored-links)))
9206 (insert "- ")
9207 (org-insert-link nil (car l) (cadr l))
9208 (insert "\n"))))
9210 (defun org-link-fontify-links-to-this-file ()
9211 "Fontify links to the current file in `org-stored-links'."
9212 (let ((f (buffer-file-name)) a b)
9213 (setq a (mapcar (lambda(l)
9214 (let ((ll (car l)))
9215 (when (and (string-match "^file:\\(.+\\)::" ll)
9216 (equal f (expand-file-name (match-string 1 ll))))
9217 ll)))
9218 org-stored-links))
9219 (when (featurep 'org-id)
9220 (setq b (mapcar (lambda(l)
9221 (let ((ll (car l)))
9222 (when (and (string-match "^id:\\(.+\\)$" ll)
9223 (equal f (expand-file-name
9224 (or (org-id-find-id-file
9225 (match-string 1 ll)) ""))))
9226 ll)))
9227 org-stored-links)))
9228 (mapcar (lambda(l)
9229 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9230 (delq nil (append a b)))))
9232 (defvar org-link-links-in-this-file nil)
9233 (defun org-insert-link (&optional complete-file link-location default-description)
9234 "Insert a link. At the prompt, enter the link.
9236 Completion can be used to insert any of the link protocol prefixes like
9237 http or ftp in use.
9239 The history can be used to select a link previously stored with
9240 `org-store-link'. When the empty string is entered (i.e. if you just
9241 press RET at the prompt), the link defaults to the most recently
9242 stored link. As SPC triggers completion in the minibuffer, you need to
9243 use M-SPC or C-q SPC to force the insertion of a space character.
9245 You will also be prompted for a description, and if one is given, it will
9246 be displayed in the buffer instead of the link.
9248 If there is already a link at point, this command will allow you to edit link
9249 and description parts.
9251 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9252 be selected using completion. The path to the file will be relative to the
9253 current directory if the file is in the current directory or a subdirectory.
9254 Otherwise, the link will be the absolute path as completed in the minibuffer
9255 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9256 option `org-link-file-path-type'.
9258 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9259 the current directory or below.
9261 With three \\[universal-argument] prefixes, negate the meaning of
9262 `org-keep-stored-link-after-insertion'.
9264 If `org-make-link-description-function' is non-nil, this function will be
9265 called with the link target, and the result will be the default
9266 link description.
9268 If the LINK-LOCATION parameter is non-nil, this value will be
9269 used as the link location instead of reading one interactively.
9271 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9272 be used as the default description."
9273 (interactive "P")
9274 (let* ((wcf (current-window-configuration))
9275 (region (if (org-region-active-p)
9276 (buffer-substring (region-beginning) (region-end))))
9277 (remove (and region (list (region-beginning) (region-end))))
9278 (desc region)
9279 tmphist ; byte-compile incorrectly complains about this
9280 (link link-location)
9281 (abbrevs org-link-abbrev-alist-local)
9282 entry file all-prefixes auto-desc)
9283 (cond
9284 (link-location) ; specified by arg, just use it.
9285 ((org-in-regexp org-bracket-link-regexp 1)
9286 ;; We do have a link at point, and we are going to edit it.
9287 (setq remove (list (match-beginning 0) (match-end 0)))
9288 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9289 (setq link (read-string "Link: "
9290 (org-link-unescape
9291 (org-match-string-no-properties 1)))))
9292 ((or (org-in-regexp org-angle-link-re)
9293 (org-in-regexp org-plain-link-re))
9294 ;; Convert to bracket link
9295 (setq remove (list (match-beginning 0) (match-end 0))
9296 link (read-string "Link: "
9297 (org-remove-angle-brackets (match-string 0)))))
9298 ((member complete-file '((4) (16)))
9299 ;; Completing read for file names.
9300 (setq link (org-file-complete-link complete-file)))
9302 ;; Read link, with completion for stored links.
9303 (org-link-fontify-links-to-this-file)
9304 (org-switch-to-buffer-other-window "*Org Links*")
9305 (with-current-buffer "*Org Links*"
9306 (erase-buffer)
9307 (insert "Insert a link.
9308 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9309 (when org-stored-links
9310 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9311 (insert (mapconcat 'org-link-prettify
9312 (reverse org-stored-links) "\n")))
9313 (goto-char (point-min)))
9314 (let ((cw (selected-window)))
9315 (select-window (get-buffer-window "*Org Links*" 'visible))
9316 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9317 (unless (pos-visible-in-window-p (point-max))
9318 (org-fit-window-to-buffer))
9319 (and (window-live-p cw) (select-window cw)))
9320 ;; Fake a link history, containing the stored links.
9321 (setq tmphist (append (mapcar 'car org-stored-links)
9322 org-insert-link-history))
9323 (setq all-prefixes (append (mapcar 'car abbrevs)
9324 (mapcar 'car org-link-abbrev-alist)
9325 org-link-types))
9326 (unwind-protect
9327 (progn
9328 (setq link
9329 (let ((org-completion-use-ido nil)
9330 (org-completion-use-iswitchb nil))
9331 (org-completing-read
9332 "Link: "
9333 (append
9334 (mapcar (lambda (x) (list (concat x ":")))
9335 all-prefixes)
9336 (mapcar 'car org-stored-links)
9337 (mapcar 'cadr org-stored-links))
9338 nil nil nil
9339 'tmphist
9340 (caar org-stored-links))))
9341 (if (not (string-match "\\S-" link))
9342 (error "No link selected"))
9343 (mapc (lambda(l)
9344 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9345 org-stored-links)
9346 (if (or (member link all-prefixes)
9347 (and (equal ":" (substring link -1))
9348 (member (substring link 0 -1) all-prefixes)
9349 (setq link (substring link 0 -1))))
9350 (setq link (org-link-try-special-completion link))))
9351 (set-window-configuration wcf)
9352 (kill-buffer "*Org Links*"))
9353 (setq entry (assoc link org-stored-links))
9354 (or entry (push link org-insert-link-history))
9355 (setq desc (or desc (nth 1 entry)))))
9357 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9358 (not org-keep-stored-link-after-insertion))
9359 (setq org-stored-links (delq (assoc link org-stored-links)
9360 org-stored-links)))
9362 (if (string-match org-plain-link-re link)
9363 ;; URL-like link, normalize the use of angular brackets.
9364 (setq link (org-remove-angle-brackets link)))
9366 ;; Check if we are linking to the current file with a search
9367 ;; option If yes, simplify the link by using only the search
9368 ;; option.
9369 (when (and buffer-file-name
9370 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9371 (let* ((path (match-string 1 link))
9372 (case-fold-search nil)
9373 (search (match-string 2 link)))
9374 (save-match-data
9375 (if (equal (file-truename buffer-file-name) (file-truename path))
9376 ;; We are linking to this same file, with a search option
9377 (setq link search)))))
9379 ;; Check if we can/should use a relative path. If yes, simplify the link
9380 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9381 (let* ((type (match-string 1 link))
9382 (path (match-string 2 link))
9383 (origpath path)
9384 (case-fold-search nil))
9385 (cond
9386 ((or (eq org-link-file-path-type 'absolute)
9387 (equal complete-file '(16)))
9388 (setq path (abbreviate-file-name (expand-file-name path))))
9389 ((eq org-link-file-path-type 'noabbrev)
9390 (setq path (expand-file-name path)))
9391 ((eq org-link-file-path-type 'relative)
9392 (setq path (file-relative-name path)))
9394 (save-match-data
9395 (if (string-match (concat "^" (regexp-quote
9396 (expand-file-name
9397 (file-name-as-directory
9398 default-directory))))
9399 (expand-file-name path))
9400 ;; We are linking a file with relative path name.
9401 (setq path (substring (expand-file-name path)
9402 (match-end 0)))
9403 (setq path (abbreviate-file-name (expand-file-name path)))))))
9404 (setq link (concat type path))
9405 (if (equal desc origpath)
9406 (setq desc path))))
9408 (if org-make-link-description-function
9409 (setq desc
9410 (or (condition-case nil
9411 (funcall org-make-link-description-function link desc)
9412 (error (progn (message "Can't get link description from `%s'"
9413 (symbol-name org-make-link-description-function))
9414 (sit-for 2) nil)))
9415 (read-string "Description: " default-description)))
9416 (if default-description (setq desc default-description)
9417 (setq desc (or (and auto-desc desc)
9418 (read-string "Description: " desc)))))
9420 (unless (string-match "\\S-" desc) (setq desc nil))
9421 (if remove (apply 'delete-region remove))
9422 (insert (org-make-link-string link desc))))
9424 (defun org-link-try-special-completion (type)
9425 "If there is completion support for link type TYPE, offer it."
9426 (let ((fun (intern (concat "org-" type "-complete-link"))))
9427 (if (functionp fun)
9428 (funcall fun)
9429 (read-string "Link (no completion support): " (concat type ":")))))
9431 (defun org-file-complete-link (&optional arg)
9432 "Create a file link using completion."
9433 (let (file link)
9434 (setq file (read-file-name "File: "))
9435 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9436 (pwd1 (file-name-as-directory (abbreviate-file-name
9437 (expand-file-name ".")))))
9438 (cond
9439 ((equal arg '(16))
9440 (setq link (concat
9441 "file:"
9442 (abbreviate-file-name (expand-file-name file)))))
9443 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9444 (setq link (concat "file:" (match-string 1 file))))
9445 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9446 (expand-file-name file))
9447 (setq link (concat
9448 "file:" (match-string 1 (expand-file-name file)))))
9449 (t (setq link (concat "file:" file)))))
9450 link))
9452 (defun org-completing-read (&rest args)
9453 "Completing-read with SPACE being a normal character."
9454 (let ((enable-recursive-minibuffers t)
9455 (minibuffer-local-completion-map
9456 (copy-keymap minibuffer-local-completion-map)))
9457 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9458 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9459 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9460 (apply 'org-icompleting-read args)))
9462 (defun org-completing-read-no-i (&rest args)
9463 (let (org-completion-use-ido org-completion-use-iswitchb)
9464 (apply 'org-completing-read args)))
9466 (defun org-iswitchb-completing-read (prompt choices &rest args)
9467 "Use iswitch as a completing-read replacement to choose from choices.
9468 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9469 from."
9470 (let* ((iswitchb-use-virtual-buffers nil)
9471 (iswitchb-make-buflist-hook
9472 (lambda ()
9473 (setq iswitchb-temp-buflist choices))))
9474 (iswitchb-read-buffer prompt)))
9476 (defun org-icompleting-read (&rest args)
9477 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9478 (org-without-partial-completion
9479 (if (and org-completion-use-ido
9480 (fboundp 'ido-completing-read)
9481 (boundp 'ido-mode) ido-mode
9482 (listp (second args)))
9483 (let ((ido-enter-matching-directory nil))
9484 (apply 'ido-completing-read (concat (car args))
9485 (if (consp (car (nth 1 args)))
9486 (mapcar 'car (nth 1 args))
9487 (nth 1 args))
9488 (cddr args)))
9489 (if (and org-completion-use-iswitchb
9490 (boundp 'iswitchb-mode) iswitchb-mode
9491 (listp (second args)))
9492 (apply 'org-iswitchb-completing-read (concat (car args))
9493 (if (consp (car (nth 1 args)))
9494 (mapcar 'car (nth 1 args))
9495 (nth 1 args))
9496 (cddr args))
9497 (apply 'completing-read args)))))
9499 (defun org-extract-attributes (s)
9500 "Extract the attributes cookie from a string and set as text property."
9501 (let (a attr (start 0) key value)
9502 (save-match-data
9503 (when (string-match "{{\\([^}]+\\)}}$" s)
9504 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9505 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9506 (setq key (match-string 1 a) value (match-string 2 a)
9507 start (match-end 0)
9508 attr (plist-put attr (intern key) value))))
9509 (org-add-props s nil 'org-attr attr))
9512 (defun org-extract-attributes-from-string (tag)
9513 (let (key value attr)
9514 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9515 (setq key (match-string 1 tag) value (match-string 2 tag)
9516 tag (replace-match "" t t tag)
9517 attr (plist-put attr (intern key) value)))
9518 (cons tag attr)))
9520 (defun org-attributes-to-string (plist)
9521 "Format a property list into an HTML attribute list."
9522 (let ((s "") key value)
9523 (while plist
9524 (setq key (pop plist) value (pop plist))
9525 (and value
9526 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9529 ;;; Opening/following a link
9531 (defvar org-link-search-failed nil)
9533 (defvar org-open-link-functions nil
9534 "Hook for functions finding a plain text link.
9535 These functions must take a single argument, the link content.
9536 They will be called for links that look like [[link text][description]]
9537 when LINK TEXT does not have a protocol like \"http:\" and does not look
9538 like a filename (e.g. \"./blue.png\").
9540 These functions will be called *before* Org attempts to resolve the
9541 link by doing text searches in the current buffer - so if you want a
9542 link \"[[target]]\" to still find \"<<target>>\", your function should
9543 handle this as a special case.
9545 When the function does handle the link, it must return a non-nil value.
9546 If it decides that it is not responsible for this link, it must return
9547 nil to indicate that that Org-mode can continue with other options
9548 like exact and fuzzy text search.")
9550 (defun org-next-link ()
9551 "Move forward to the next link.
9552 If the link is in hidden text, expose it."
9553 (interactive)
9554 (when (and org-link-search-failed (eq this-command last-command))
9555 (goto-char (point-min))
9556 (message "Link search wrapped back to beginning of buffer"))
9557 (setq org-link-search-failed nil)
9558 (let* ((pos (point))
9559 (ct (org-context))
9560 (a (assoc :link ct)))
9561 (if a (goto-char (nth 2 a)))
9562 (if (re-search-forward org-any-link-re nil t)
9563 (progn
9564 (goto-char (match-beginning 0))
9565 (if (outline-invisible-p) (org-show-context)))
9566 (goto-char pos)
9567 (setq org-link-search-failed t)
9568 (error "No further link found"))))
9570 (defun org-previous-link ()
9571 "Move backward to the previous link.
9572 If the link is in hidden text, expose it."
9573 (interactive)
9574 (when (and org-link-search-failed (eq this-command last-command))
9575 (goto-char (point-max))
9576 (message "Link search wrapped back to end of buffer"))
9577 (setq org-link-search-failed nil)
9578 (let* ((pos (point))
9579 (ct (org-context))
9580 (a (assoc :link ct)))
9581 (if a (goto-char (nth 1 a)))
9582 (if (re-search-backward org-any-link-re nil t)
9583 (progn
9584 (goto-char (match-beginning 0))
9585 (if (outline-invisible-p) (org-show-context)))
9586 (goto-char pos)
9587 (setq org-link-search-failed t)
9588 (error "No further link found"))))
9590 (defun org-translate-link (s)
9591 "Translate a link string if a translation function has been defined."
9592 (if (and org-link-translation-function
9593 (fboundp org-link-translation-function)
9594 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9595 (progn
9596 (setq s (funcall org-link-translation-function
9597 (match-string 1 s) (match-string 2 s)))
9598 (concat (car s) ":" (cdr s)))
9601 (defun org-translate-link-from-planner (type path)
9602 "Translate a link from Emacs Planner syntax so that Org can follow it.
9603 This is still an experimental function, your mileage may vary."
9604 (cond
9605 ((member type '("http" "https" "news" "ftp"))
9606 ;; standard Internet links are the same.
9607 nil)
9608 ((and (equal type "irc") (string-match "^//" path))
9609 ;; Planner has two / at the beginning of an irc link, we have 1.
9610 ;; We should have zero, actually....
9611 (setq path (substring path 1)))
9612 ((and (equal type "lisp") (string-match "^/" path))
9613 ;; Planner has a slash, we do not.
9614 (setq type "elisp" path (substring path 1)))
9615 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9616 ;; A typical message link. Planner has the id after the final slash,
9617 ;; we separate it with a hash mark
9618 (setq path (concat (match-string 1 path) "#"
9619 (org-remove-angle-brackets (match-string 2 path)))))
9621 (cons type path))
9623 (defun org-find-file-at-mouse (ev)
9624 "Open file link or URL at mouse."
9625 (interactive "e")
9626 (mouse-set-point ev)
9627 (org-open-at-point 'in-emacs))
9629 (defun org-open-at-mouse (ev)
9630 "Open file link or URL at mouse.
9631 See the docstring of `org-open-file' for details."
9632 (interactive "e")
9633 (mouse-set-point ev)
9634 (if (eq major-mode 'org-agenda-mode)
9635 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9636 (org-open-at-point))
9638 (defvar org-window-config-before-follow-link nil
9639 "The window configuration before following a link.
9640 This is saved in case the need arises to restore it.")
9642 (defvar org-open-link-marker (make-marker)
9643 "Marker pointing to the location where `org-open-at-point; was called.")
9645 ;;;###autoload
9646 (defun org-open-at-point-global ()
9647 "Follow a link like Org-mode does.
9648 This command can be called in any mode to follow a link that has
9649 Org-mode syntax."
9650 (interactive)
9651 (org-run-like-in-org-mode 'org-open-at-point))
9653 ;;;###autoload
9654 (defun org-open-link-from-string (s &optional arg reference-buffer)
9655 "Open a link in the string S, as if it was in Org-mode."
9656 (interactive "sLink: \nP")
9657 (let ((reference-buffer (or reference-buffer (current-buffer))))
9658 (with-temp-buffer
9659 (let ((org-inhibit-startup (not reference-buffer)))
9660 (org-mode)
9661 (insert s)
9662 (goto-char (point-min))
9663 (when reference-buffer
9664 (setq org-link-abbrev-alist-local
9665 (with-current-buffer reference-buffer
9666 org-link-abbrev-alist-local)))
9667 (org-open-at-point arg reference-buffer)))))
9669 (defvar org-open-at-point-functions nil
9670 "Hook that is run when following a link at point.
9672 Functions in this hook must return t if they identify and follow
9673 a link at point. If they don't find anything interesting at point,
9674 they must return nil.")
9676 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9677 (defun org-open-at-point (&optional arg reference-buffer)
9678 "Open link at or after point.
9679 If there is no link at point, this function will search forward up to
9680 the end of the current line.
9681 Normally, files will be opened by an appropriate application. If the
9682 optional prefix argument ARG is non-nil, Emacs will visit the file.
9683 With a double prefix argument, try to open outside of Emacs, in the
9684 application the system uses for this file type."
9685 (interactive "P")
9686 ;; if in a code block, then open the block's results
9687 (unless (call-interactively #'org-babel-open-src-block-result)
9688 (org-load-modules-maybe)
9689 (move-marker org-open-link-marker (point))
9690 (setq org-window-config-before-follow-link (current-window-configuration))
9691 (org-remove-occur-highlights nil nil t)
9692 (cond
9693 ((and (org-at-heading-p)
9694 (not (org-at-timestamp-p t))
9695 (not (org-in-regexp
9696 (concat org-plain-link-re "\\|"
9697 org-bracket-link-regexp "\\|"
9698 org-angle-link-re "\\|"
9699 "[ \t]:[^ \t\n]+:[ \t]*$")))
9700 (not (get-text-property (point) 'org-linked-text)))
9701 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9702 (lk0 (car lkall))
9703 (lk (if (stringp lk0) (list lk0) lk0))
9704 (lkend (cdr lkall)))
9705 (mapcar (lambda(l)
9706 (search-forward l nil lkend)
9707 (goto-char (match-beginning 0))
9708 (org-open-at-point))
9709 lk))
9710 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9711 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9712 ((and (org-at-timestamp-p t)
9713 (not (org-in-regexp org-bracket-link-regexp)))
9714 (org-follow-timestamp-link))
9715 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9716 (not (org-in-regexp org-any-link-re)))
9717 (org-footnote-action))
9719 (let (type path link line search (pos (point)))
9720 (catch 'match
9721 (save-excursion
9722 (skip-chars-forward "^]\n\r")
9723 (when (org-in-regexp org-bracket-link-regexp 1)
9724 (setq link (org-extract-attributes
9725 (org-link-unescape (org-match-string-no-properties 1))))
9726 (while (string-match " *\n *" link)
9727 (setq link (replace-match " " t t link)))
9728 (setq link (org-link-expand-abbrev link))
9729 (cond
9730 ((or (file-name-absolute-p link)
9731 (string-match "^\\.\\.?/" link))
9732 (setq type "file" path link))
9733 ((string-match org-link-re-with-space3 link)
9734 (setq type (match-string 1 link) path (match-string 2 link)))
9735 ((string-match "^help:+\\(.+\\)" link)
9736 (setq type "help" path (match-string 1 link)))
9737 (t (setq type "thisfile" path link)))
9738 (throw 'match t)))
9740 (when (get-text-property (point) 'org-linked-text)
9741 (setq type "thisfile"
9742 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9743 (1+ (point)) (point))
9744 path (buffer-substring
9745 (or (previous-single-property-change pos 'org-linked-text)
9746 (point-min))
9747 (or (next-single-property-change pos 'org-linked-text)
9748 (point-max))))
9749 (throw 'match t))
9751 (save-excursion
9752 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9753 (when (or (org-in-regexp org-angle-link-re)
9754 (and plinkpos (goto-char (car plinkpos))
9755 (save-match-data (not (looking-back "\\[\\[")))))
9756 (setq type (match-string 1)
9757 path (org-link-unescape (match-string 2)))
9758 (throw 'match t))))
9759 (save-excursion
9760 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9761 (setq type "tags"
9762 path (match-string 1))
9763 (while (string-match ":" path)
9764 (setq path (replace-match "+" t t path)))
9765 (throw 'match t)))
9766 (when (org-in-regexp "<\\([^><\n]+\\)>")
9767 (setq type "tree-match"
9768 path (match-string 1))
9769 (throw 'match t)))
9770 (unless path
9771 (user-error "No link found"))
9773 ;; switch back to reference buffer
9774 ;; needed when if called in a temporary buffer through
9775 ;; org-open-link-from-string
9776 (with-current-buffer (or reference-buffer (current-buffer))
9778 ;; Remove any trailing spaces in path
9779 (if (string-match " +\\'" path)
9780 (setq path (replace-match "" t t path)))
9781 (if (and org-link-translation-function
9782 (fboundp org-link-translation-function))
9783 ;; Check if we need to translate the link
9784 (let ((tmp (funcall org-link-translation-function type path)))
9785 (setq type (car tmp) path (cdr tmp))))
9787 (cond
9789 ((assoc type org-link-protocols)
9790 (funcall (nth 1 (assoc type org-link-protocols)) path))
9792 ((equal type "help")
9793 (let ((f-or-v (intern path)))
9794 (cond ((fboundp f-or-v)
9795 (describe-function f-or-v))
9796 ((boundp f-or-v)
9797 (describe-variable f-or-v))
9798 (t (error "Not a known function or variable")))))
9800 ((equal type "mailto")
9801 (let ((cmd (car org-link-mailto-program))
9802 (args (cdr org-link-mailto-program)) args1
9803 (address path) (subject "") a)
9804 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9805 (setq address (match-string 1 path)
9806 subject (org-link-escape (match-string 2 path))))
9807 (while args
9808 (cond
9809 ((not (stringp (car args))) (push (pop args) args1))
9810 (t (setq a (pop args))
9811 (if (string-match "%a" a)
9812 (setq a (replace-match address t t a)))
9813 (if (string-match "%s" a)
9814 (setq a (replace-match subject t t a)))
9815 (push a args1))))
9816 (apply cmd (nreverse args1))))
9818 ((member type '("http" "https" "ftp" "news"))
9819 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9820 (org-link-escape
9821 path org-link-escape-chars-browser)
9822 path))))
9824 ((string= type "doi")
9825 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9826 (org-link-escape
9827 path org-link-escape-chars-browser)
9828 path))))
9830 ((member type '("message"))
9831 (browse-url (concat type ":" path)))
9833 ((string= type "tags")
9834 (org-tags-view arg path))
9836 ((string= type "tree-match")
9837 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9839 ((string= type "file")
9840 (if (string-match "::\\([0-9]+\\)\\'" path)
9841 (setq line (string-to-number (match-string 1 path))
9842 path (substring path 0 (match-beginning 0)))
9843 (if (string-match "::\\(.+\\)\\'" path)
9844 (setq search (match-string 1 path)
9845 path (substring path 0 (match-beginning 0)))))
9846 (if (string-match "[*?{]" (file-name-nondirectory path))
9847 (dired path)
9848 (org-open-file path arg line search)))
9850 ((string= type "shell")
9851 (let ((buf (generate-new-buffer "*Org Shell Output"))
9852 (cmd path))
9853 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9854 (string-match org-confirm-shell-link-not-regexp cmd))
9855 (not org-confirm-shell-link-function)
9856 (funcall org-confirm-shell-link-function
9857 (format "Execute \"%s\" in shell? "
9858 (org-add-props cmd nil
9859 'face 'org-warning))))
9860 (progn
9861 (message "Executing %s" cmd)
9862 (shell-command cmd buf)
9863 (if (featurep 'midnight)
9864 (setq clean-buffer-list-kill-buffer-names
9865 (cons buf clean-buffer-list-kill-buffer-names))))
9866 (error "Abort"))))
9868 ((string= type "elisp")
9869 (let ((cmd path))
9870 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9871 (string-match org-confirm-elisp-link-not-regexp cmd))
9872 (not org-confirm-elisp-link-function)
9873 (funcall org-confirm-elisp-link-function
9874 (format "Execute \"%s\" as elisp? "
9875 (org-add-props cmd nil
9876 'face 'org-warning))))
9877 (message "%s => %s" cmd
9878 (if (equal (string-to-char cmd) ?\()
9879 (eval (read cmd))
9880 (call-interactively (read cmd))))
9881 (error "Abort"))))
9883 ((and (string= type "thisfile")
9884 (run-hook-with-args-until-success
9885 'org-open-link-functions path)))
9887 ((string= type "thisfile")
9888 (if arg
9889 (switch-to-buffer-other-window
9890 (org-get-buffer-for-internal-link (current-buffer)))
9891 (org-mark-ring-push))
9892 (let ((cmd `(org-link-search
9893 ,path
9894 ,(cond ((equal arg '(4)) ''occur)
9895 ((equal arg '(16)) ''org-occur))
9896 ,pos)))
9897 (condition-case nil (let ((org-link-search-inhibit-query t))
9898 (eval cmd))
9899 (error (progn (widen) (eval cmd))))))
9901 (t (browse-url-at-point)))))))
9902 (move-marker org-open-link-marker nil)
9903 (run-hook-with-args 'org-follow-link-hook)))
9905 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9906 "Offer links in the current entry and return the selected link.
9907 If there is only one link, return it.
9908 If NTH is an integer, return the NTH link found.
9909 If ZERO is a string, check also this string for a link, and if
9910 there is one, return it."
9911 (with-current-buffer buffer
9912 (save-excursion
9913 (save-restriction
9914 (widen)
9915 (goto-char marker)
9916 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9917 "\\(" org-angle-link-re "\\)\\|"
9918 "\\(" org-plain-link-re "\\)"))
9919 (cnt ?0)
9920 (in-emacs (if (integerp nth) nil nth))
9921 have-zero end links link c)
9922 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9923 (push (match-string 0 zero) links)
9924 (setq cnt (1- cnt) have-zero t))
9925 (save-excursion
9926 (org-back-to-heading t)
9927 (setq end (save-excursion (outline-next-heading) (point)))
9928 (while (re-search-forward re end t)
9929 (push (match-string 0) links))
9930 (setq links (org-uniquify (reverse links))))
9931 (cond
9932 ((null links)
9933 (message "No links"))
9934 ((equal (length links) 1)
9935 (setq link (car links)))
9936 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9937 (setq link (nth (if have-zero nth (1- nth)) links)))
9938 (t ; we have to select a link
9939 (save-excursion
9940 (save-window-excursion
9941 (delete-other-windows)
9942 (with-output-to-temp-buffer "*Select Link*"
9943 (mapc (lambda (l)
9944 (if (not (string-match org-bracket-link-regexp l))
9945 (princ (format "[%c] %s\n" (incf cnt)
9946 (org-remove-angle-brackets l)))
9947 (if (match-end 3)
9948 (princ (format "[%c] %s (%s)\n" (incf cnt)
9949 (match-string 3 l) (match-string 1 l)))
9950 (princ (format "[%c] %s\n" (incf cnt)
9951 (match-string 1 l))))))
9952 links))
9953 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9954 (message "Select link to open, RET to open all:")
9955 (setq c (read-char-exclusive))
9956 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9957 (when (equal c ?q) (error "Abort"))
9958 (if (equal c ?\C-m)
9959 (setq link links)
9960 (setq nth (- c ?0))
9961 (if have-zero (setq nth (1+ nth)))
9962 (unless (and (integerp nth) (>= (length links) nth))
9963 (error "Invalid link selection"))
9964 (setq link (nth (1- nth) links)))))
9965 (cons link end))))))
9967 ;; Add special file links that specify the way of opening
9969 (org-add-link-type "file+sys" 'org-open-file-with-system)
9970 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9971 (defun org-open-file-with-system (path)
9972 "Open file at PATH using the system way of opening it."
9973 (org-open-file path 'system))
9974 (defun org-open-file-with-emacs (path)
9975 "Open file at PATH in Emacs."
9976 (org-open-file path 'emacs))
9977 (defun org-remove-file-link-modifiers ()
9978 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9979 (goto-char (point-min))
9980 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9981 (org-if-unprotected
9982 (replace-match "file:" t t))))
9983 (eval-after-load "org-exp"
9984 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9985 'org-remove-file-link-modifiers))
9987 ;;; File search
9989 (defvar org-create-file-search-functions nil
9990 "List of functions to construct the right search string for a file link.
9991 These functions are called in turn with point at the location to
9992 which the link should point.
9994 A function in the hook should first test if it would like to
9995 handle this file type, for example by checking the `major-mode'
9996 or the file extension. If it decides not to handle this file, it
9997 should just return nil to give other functions a chance. If it
9998 does handle the file, it must return the search string to be used
9999 when following the link. The search string will be part of the
10000 file link, given after a double colon, and `org-open-at-point'
10001 will automatically search for it. If special measures must be
10002 taken to make the search successful, another function should be
10003 added to the companion hook `org-execute-file-search-functions',
10004 which see.
10006 A function in this hook may also use `setq' to set the variable
10007 `description' to provide a suggestion for the descriptive text to
10008 be used for this link when it gets inserted into an Org-mode
10009 buffer with \\[org-insert-link].")
10011 (defvar org-execute-file-search-functions nil
10012 "List of functions to execute a file search triggered by a link.
10014 Functions added to this hook must accept a single argument, the
10015 search string that was part of the file link, the part after the
10016 double colon. The function must first check if it would like to
10017 handle this search, for example by checking the `major-mode' or
10018 the file extension. If it decides not to handle this search, it
10019 should just return nil to give other functions a chance. If it
10020 does handle the search, it must return a non-nil value to keep
10021 other functions from trying.
10023 Each function can access the current prefix argument through the
10024 variable `current-prefix-argument'. Note that a single prefix is
10025 used to force opening a link in Emacs, so it may be good to only
10026 use a numeric or double prefix to guide the search function.
10028 In case this is needed, a function in this hook can also restore
10029 the window configuration before `org-open-at-point' was called using:
10031 (set-window-configuration org-window-config-before-follow-link)")
10033 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10034 (defun org-link-search (s &optional type avoid-pos stealth)
10035 "Search for a link search option.
10036 If S is surrounded by forward slashes, it is interpreted as a
10037 regular expression. In org-mode files, this will create an `org-occur'
10038 sparse tree. In ordinary files, `occur' will be used to list matches.
10039 If the current buffer is in `dired-mode', grep will be used to search
10040 in all files. If AVOID-POS is given, ignore matches near that position.
10042 When optional argument STEALTH is non-nil, do not modify
10043 visibility around point, thus ignoring
10044 `org-show-hierarchy-above', `org-show-following-heading' and
10045 `org-show-siblings' variables."
10046 (let ((case-fold-search t)
10047 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10048 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10049 (append '(("") (" ") ("\t") ("\n"))
10050 org-emphasis-alist)
10051 "\\|") "\\)"))
10052 (pos (point))
10053 (pre nil) (post nil)
10054 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10055 (cond
10056 ;; First check if there are any special search functions
10057 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10058 ;; Now try the builtin stuff
10059 ((and (equal (string-to-char s0) ?#)
10060 (> (length s0) 1)
10061 (save-excursion
10062 (goto-char (point-min))
10063 (and
10064 (re-search-forward
10065 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10066 (setq type 'dedicated
10067 pos (match-beginning 0))))
10068 ;; There is an exact target for this
10069 (goto-char pos)
10070 (org-back-to-heading t)))
10071 ((save-excursion
10072 (goto-char (point-min))
10073 (and
10074 (re-search-forward
10075 (concat "<<" (regexp-quote s0) ">>") nil t)
10076 (setq type 'dedicated
10077 pos (match-beginning 0))))
10078 ;; There is an exact target for this
10079 (goto-char pos))
10080 ((save-excursion
10081 (goto-char (point-min))
10082 (and
10083 (re-search-forward
10084 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10085 (setq type 'dedicated pos (match-beginning 0))))
10086 ;; Found an invisible target.
10087 (goto-char pos))
10088 ((save-excursion
10089 (goto-char (point-min))
10090 (and
10091 (re-search-forward
10092 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10093 (setq type 'dedicated pos (match-beginning 0))))
10094 ;; Found an element with a matching #+name affiliated keyword.
10095 (goto-char pos))
10096 ((and (string-match "^(\\(.*\\))$" s0)
10097 (save-excursion
10098 (goto-char (point-min))
10099 (and
10100 (re-search-forward
10101 (concat "[^[]" (regexp-quote
10102 (format org-coderef-label-format
10103 (match-string 1 s0))))
10104 nil t)
10105 (setq type 'dedicated
10106 pos (1+ (match-beginning 0))))))
10107 ;; There is a coderef target for this
10108 (goto-char pos))
10109 ((string-match "^/\\(.*\\)/$" s)
10110 ;; A regular expression
10111 (cond
10112 ((derived-mode-p 'org-mode)
10113 (org-occur (match-string 1 s)))
10114 ;;((eq major-mode 'dired-mode)
10115 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10116 (t (org-do-occur (match-string 1 s)))))
10117 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10118 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10119 (goto-char (point-min))
10120 (cond
10121 ((let (case-fold-search)
10122 (re-search-forward (format org-complex-heading-regexp-format
10123 (regexp-quote s))
10124 nil t))
10125 ;; OK, found a match
10126 (setq type 'dedicated)
10127 (goto-char (match-beginning 0)))
10128 ((and (not org-link-search-inhibit-query)
10129 (eq org-link-search-must-match-exact-headline 'query-to-create)
10130 (y-or-n-p "No match - create this as a new heading? "))
10131 (goto-char (point-max))
10132 (or (bolp) (newline))
10133 (insert "* " s "\n")
10134 (beginning-of-line 0))
10136 (goto-char pos)
10137 (error "No match"))))
10139 ;; A normal search string
10140 (when (equal (string-to-char s) ?*)
10141 ;; Anchor on headlines, post may include tags.
10142 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10143 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10144 s (substring s 1)))
10145 (remove-text-properties
10146 0 (length s)
10147 '(face nil mouse-face nil keymap nil fontified nil) s)
10148 ;; Make a series of regular expressions to find a match
10149 (setq words (org-split-string s "[ \n\r\t]+")
10151 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10152 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10153 "\\)" markers)
10154 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10155 re2a (concat "[ \t\r\n]" re2a_)
10156 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10157 re4 (concat "[^a-zA-Z_]" re4_)
10159 re1 (concat pre re2 post)
10160 re3 (concat pre (if pre re4_ re4) post)
10161 re5 (concat pre ".*" re4)
10162 re2 (concat pre re2)
10163 re2a (concat pre (if pre re2a_ re2a))
10164 re4 (concat pre (if pre re4_ re4))
10165 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10166 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10167 re5 "\\)"
10169 (cond
10170 ((eq type 'org-occur) (org-occur reall))
10171 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10172 (t (goto-char (point-min))
10173 (setq type 'fuzzy)
10174 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10175 (org-search-not-self 1 re1 nil t)
10176 (org-search-not-self 1 re2 nil t)
10177 (org-search-not-self 1 re2a nil t)
10178 (org-search-not-self 1 re3 nil t)
10179 (org-search-not-self 1 re4 nil t)
10180 (org-search-not-self 1 re5 nil t)
10182 (goto-char (match-beginning 1))
10183 (goto-char pos)
10184 (error "No match"))))))
10185 (and (derived-mode-p 'org-mode)
10186 (not stealth)
10187 (org-show-context 'link-search))
10188 type))
10190 (defun org-search-not-self (group &rest args)
10191 "Execute `re-search-forward', but only accept matches that do not
10192 enclose the position of `org-open-link-marker'."
10193 (let ((m org-open-link-marker))
10194 (catch 'exit
10195 (while (apply 're-search-forward args)
10196 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10197 (goto-char (match-end group))
10198 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10199 (> (match-beginning 0) (marker-position m))
10200 (< (match-end 0) (marker-position m)))
10201 (save-match-data
10202 (or (not (org-in-regexp
10203 org-bracket-link-analytic-regexp 1))
10204 (not (match-end 4)) ; no description
10205 (and (<= (match-beginning 4) (point))
10206 (>= (match-end 4) (point))))))
10207 (throw 'exit (point))))))))
10209 (defun org-get-buffer-for-internal-link (buffer)
10210 "Return a buffer to be used for displaying the link target of internal links."
10211 (cond
10212 ((not org-display-internal-link-with-indirect-buffer)
10213 buffer)
10214 ((string-match "(Clone)$" (buffer-name buffer))
10215 (message "Buffer is already a clone, not making another one")
10216 ;; we also do not modify visibility in this case
10217 buffer)
10218 (t ; make a new indirect buffer for displaying the link
10219 (let* ((bn (buffer-name buffer))
10220 (ibn (concat bn "(Clone)"))
10221 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10222 (with-current-buffer ib (org-overview))
10223 ib))))
10225 (defun org-do-occur (regexp &optional cleanup)
10226 "Call the Emacs command `occur'.
10227 If CLEANUP is non-nil, remove the printout of the regular expression
10228 in the *Occur* buffer. This is useful if the regex is long and not useful
10229 to read."
10230 (occur regexp)
10231 (when cleanup
10232 (let ((cwin (selected-window)) win beg end)
10233 (when (setq win (get-buffer-window "*Occur*"))
10234 (select-window win))
10235 (goto-char (point-min))
10236 (when (re-search-forward "match[a-z]+" nil t)
10237 (setq beg (match-end 0))
10238 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10239 (setq end (1- (match-beginning 0)))))
10240 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10241 (goto-char (point-min))
10242 (select-window cwin))))
10244 ;;; The mark ring for links jumps
10246 (defvar org-mark-ring nil
10247 "Mark ring for positions before jumps in Org-mode.")
10248 (defvar org-mark-ring-last-goto nil
10249 "Last position in the mark ring used to go back.")
10250 ;; Fill and close the ring
10251 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10252 (loop for i from 1 to org-mark-ring-length do
10253 (push (make-marker) org-mark-ring))
10254 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10255 org-mark-ring)
10257 (defun org-mark-ring-push (&optional pos buffer)
10258 "Put the current position or POS into the mark ring and rotate it."
10259 (interactive)
10260 (setq pos (or pos (point)))
10261 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10262 (move-marker (car org-mark-ring)
10263 (or pos (point))
10264 (or buffer (current-buffer)))
10265 (message "%s"
10266 (substitute-command-keys
10267 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10269 (defun org-mark-ring-goto (&optional n)
10270 "Jump to the previous position in the mark ring.
10271 With prefix arg N, jump back that many stored positions. When
10272 called several times in succession, walk through the entire ring.
10273 Org-mode commands jumping to a different position in the current file,
10274 or to another Org-mode file, automatically push the old position
10275 onto the ring."
10276 (interactive "p")
10277 (let (p m)
10278 (if (eq last-command this-command)
10279 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10280 (setq p org-mark-ring))
10281 (setq org-mark-ring-last-goto p)
10282 (setq m (car p))
10283 (org-pop-to-buffer-same-window (marker-buffer m))
10284 (goto-char m)
10285 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10287 (defun org-remove-angle-brackets (s)
10288 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10289 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10291 (defun org-add-angle-brackets (s)
10292 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10293 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10295 (defun org-remove-double-quotes (s)
10296 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10297 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10300 ;;; Following specific links
10302 (defun org-follow-timestamp-link ()
10303 "Open an agenda view for the time-stamp date/range at point."
10304 (cond
10305 ((org-at-date-range-p t)
10306 (let ((org-agenda-start-on-weekday)
10307 (t1 (match-string 1))
10308 (t2 (match-string 2)) tt1 tt2)
10309 (setq tt1 (time-to-days (org-time-string-to-time t1))
10310 tt2 (time-to-days (org-time-string-to-time t2)))
10311 (let ((org-agenda-buffer-tmp-name
10312 (format "*Org Agenda(a:%s)"
10313 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10314 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10315 ((org-at-timestamp-p t)
10316 (let ((org-agenda-buffer-tmp-name
10317 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10318 (org-agenda-list nil (time-to-days (org-time-string-to-time
10319 (substring (match-string 1) 0 10)))
10320 1)))
10321 (t (error "This should not happen"))))
10324 ;;; Following file links
10325 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10326 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10327 (declare-function mailcap-mime-info
10328 "mailcap" (string &optional request no-decode))
10329 (defvar org-wait nil)
10330 (defun org-open-file (path &optional in-emacs line search)
10331 "Open the file at PATH.
10332 First, this expands any special file name abbreviations. Then the
10333 configuration variable `org-file-apps' is checked if it contains an
10334 entry for this file type, and if yes, the corresponding command is launched.
10336 If no application is found, Emacs simply visits the file.
10338 With optional prefix argument IN-EMACS, Emacs will visit the file.
10339 With a double \\[universal-argument] \\[universal-argument] \
10340 prefix arg, Org tries to avoid opening in Emacs
10341 and to use an external application to visit the file.
10343 Optional LINE specifies a line to go to, optional SEARCH a string
10344 to search for. If LINE or SEARCH is given, the file will be
10345 opened in Emacs, unless an entry from org-file-apps that makes
10346 use of groups in a regexp matches.
10348 If you want to change the way frames are used when following a
10349 link, please customize `org-link-frame-setup'.
10351 If the file does not exist, an error is thrown."
10352 (let* ((file (if (equal path "")
10353 buffer-file-name
10354 (substitute-in-file-name (expand-file-name path))))
10355 (file-apps (append org-file-apps (org-default-apps)))
10356 (apps (org-remove-if
10357 'org-file-apps-entry-match-against-dlink-p file-apps))
10358 (apps-dlink (org-remove-if-not
10359 'org-file-apps-entry-match-against-dlink-p file-apps))
10360 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10361 (dirp (if remp nil (file-directory-p file)))
10362 (file (if (and dirp org-open-directory-means-index-dot-org)
10363 (concat (file-name-as-directory file) "index.org")
10364 file))
10365 (a-m-a-p (assq 'auto-mode apps))
10366 (dfile (downcase file))
10367 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10368 (link (cond ((and (eq line nil)
10369 (eq search nil))
10370 file)
10371 (line
10372 (concat file "::" (number-to-string line)))
10373 (search
10374 (concat file "::" search))))
10375 (dlink (downcase link))
10376 (old-buffer (current-buffer))
10377 (old-pos (point))
10378 (old-mode major-mode)
10379 ext cmd link-match-data)
10380 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10381 (setq ext (match-string 1 dfile))
10382 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10383 (setq ext (match-string 1 dfile))))
10384 (cond
10385 ((member in-emacs '((16) system))
10386 (setq cmd (cdr (assoc 'system apps))))
10387 (in-emacs (setq cmd 'emacs))
10389 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10390 (and dirp (cdr (assoc 'directory apps)))
10391 ; first, try matching against apps-dlink
10392 ; if we get a match here, store the match data for later
10393 (let ((match (assoc-default dlink apps-dlink
10394 'string-match)))
10395 (if match
10396 (progn (setq link-match-data (match-data))
10397 match)
10398 (progn (setq in-emacs (or in-emacs line search))
10399 nil))) ; if we have no match in apps-dlink,
10400 ; always open the file in emacs if line or search
10401 ; is given (for backwards compatibility)
10402 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10403 'string-match)
10404 (cdr (assoc ext apps))
10405 (cdr (assoc t apps))))))
10406 (when (eq cmd 'system)
10407 (setq cmd (cdr (assoc 'system apps))))
10408 (when (eq cmd 'default)
10409 (setq cmd (cdr (assoc t apps))))
10410 (when (eq cmd 'mailcap)
10411 (require 'mailcap)
10412 (mailcap-parse-mailcaps)
10413 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10414 (command (mailcap-mime-info mime-type)))
10415 (if (stringp command)
10416 (setq cmd command)
10417 (setq cmd 'emacs))))
10418 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10419 (not (file-exists-p file))
10420 (not org-open-non-existing-files))
10421 (error "No such file: %s" file))
10422 (cond
10423 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10424 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10425 (while (string-match "['\"]%s['\"]" cmd)
10426 (setq cmd (replace-match "%s" t t cmd)))
10427 (while (string-match "%s" cmd)
10428 (setq cmd (replace-match
10429 (save-match-data
10430 (shell-quote-argument
10431 (convert-standard-filename file)))
10432 t t cmd)))
10434 ;; Replace "%1", "%2" etc. in command with group matches from regex
10435 (save-match-data
10436 (let ((match-index 1)
10437 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10438 (set-match-data link-match-data)
10439 (while (<= match-index number-of-groups)
10440 (let ((regex (concat "%" (number-to-string match-index)))
10441 (replace-with (match-string match-index dlink)))
10442 (while (string-match regex cmd)
10443 (setq cmd (replace-match replace-with t t cmd))))
10444 (setq match-index (+ match-index 1)))))
10446 (save-window-excursion
10447 (start-process-shell-command cmd nil cmd)
10448 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10450 ((or (stringp cmd)
10451 (eq cmd 'emacs))
10452 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10453 (widen)
10454 (if line (org-goto-line line)
10455 (if search (org-link-search search))))
10456 ((consp cmd)
10457 (let ((file (convert-standard-filename file)))
10458 (save-match-data
10459 (set-match-data link-match-data)
10460 (eval cmd))))
10461 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10462 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10463 (or (not (equal old-buffer (current-buffer)))
10464 (not (equal old-pos (point))))
10465 (org-mark-ring-push old-pos old-buffer))))
10467 (defun org-file-apps-entry-match-against-dlink-p (entry)
10468 "This function returns non-nil if `entry' uses a regular
10469 expression which should be matched against the whole link by
10470 org-open-file.
10472 It assumes that is the case when the entry uses a regular
10473 expression which has at least one grouping construct and the
10474 action is either a lisp form or a command string containing
10475 '%1', i.e. using at least one subexpression match as a
10476 parameter."
10477 (let ((selector (car entry))
10478 (action (cdr entry)))
10479 (if (stringp selector)
10480 (and (> (regexp-opt-depth selector) 0)
10481 (or (and (stringp action)
10482 (string-match "%[0-9]" action))
10483 (consp action)))
10484 nil)))
10486 (defun org-default-apps ()
10487 "Return the default applications for this operating system."
10488 (cond
10489 ((eq system-type 'darwin)
10490 org-file-apps-defaults-macosx)
10491 ((eq system-type 'windows-nt)
10492 org-file-apps-defaults-windowsnt)
10493 (t org-file-apps-defaults-gnu)))
10495 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10496 "Convert extensions to regular expressions in the cars of LIST.
10497 Also, weed out any non-string entries, because the return value is used
10498 only for regexp matching.
10499 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10500 point to the symbol `emacs', indicating that the file should
10501 be opened in Emacs."
10502 (append
10503 (delq nil
10504 (mapcar (lambda (x)
10505 (if (not (stringp (car x)))
10507 (if (string-match "\\W" (car x))
10509 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10510 list))
10511 (if add-auto-mode
10512 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10514 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10515 (defun org-file-remote-p (file)
10516 "Test whether FILE specifies a location on a remote system.
10517 Return non-nil if the location is indeed remote.
10519 For example, the filename \"/user@host:/foo\" specifies a location
10520 on the system \"/user@host:\"."
10521 (cond ((fboundp 'file-remote-p)
10522 (file-remote-p file))
10523 ((fboundp 'tramp-handle-file-remote-p)
10524 (tramp-handle-file-remote-p file))
10525 ((and (boundp 'ange-ftp-name-format)
10526 (string-match (car ange-ftp-name-format) file))
10527 t)))
10530 ;;;; Refiling
10532 (defun org-get-org-file ()
10533 "Read a filename, with default directory `org-directory'."
10534 (let ((default (or org-default-notes-file remember-data-file)))
10535 (read-file-name (format "File name [%s]: " default)
10536 (file-name-as-directory org-directory)
10537 default)))
10539 (defun org-notes-order-reversed-p ()
10540 "Check if the current file should receive notes in reversed order."
10541 (cond
10542 ((not org-reverse-note-order) nil)
10543 ((eq t org-reverse-note-order) t)
10544 ((not (listp org-reverse-note-order)) nil)
10545 (t (catch 'exit
10546 (let ((all org-reverse-note-order)
10547 entry)
10548 (while (setq entry (pop all))
10549 (if (string-match (car entry) buffer-file-name)
10550 (throw 'exit (cdr entry))))
10551 nil)))))
10553 (defvar org-refile-target-table nil
10554 "The list of refile targets, created by `org-refile'.")
10556 (defvar org-agenda-new-buffers nil
10557 "Buffers created to visit agenda files.")
10559 (defvar org-refile-cache nil
10560 "Cache for refile targets.")
10562 (defvar org-refile-markers nil
10563 "All the markers used for caching refile locations.")
10565 (defun org-refile-marker (pos)
10566 "Get a new refile marker, but only if caching is in use."
10567 (if (not org-refile-use-cache)
10569 (let ((m (make-marker)))
10570 (move-marker m pos)
10571 (push m org-refile-markers)
10572 m)))
10574 (defun org-refile-cache-clear ()
10575 "Clear the refile cache and disable all the markers."
10576 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10577 (setq org-refile-markers nil)
10578 (setq org-refile-cache nil)
10579 (message "Refile cache has been cleared"))
10581 (defun org-refile-cache-check-set (set)
10582 "Check if all the markers in the cache still have live buffers."
10583 (let (marker)
10584 (catch 'exit
10585 (while (and set (setq marker (nth 3 (pop set))))
10586 ;; if org-refile-use-outline-path is 'file, marker may be nil
10587 (when (and marker (null (marker-buffer marker)))
10588 (message "not found") (sit-for 3)
10589 (throw 'exit nil)))
10590 t)))
10592 (defun org-refile-cache-put (set &rest identifiers)
10593 "Push the refile targets SET into the cache, under IDENTIFIERS."
10594 (let* ((key (sha1 (prin1-to-string identifiers)))
10595 (entry (assoc key org-refile-cache)))
10596 (if entry
10597 (setcdr entry set)
10598 (push (cons key set) org-refile-cache))))
10600 (defun org-refile-cache-get (&rest identifiers)
10601 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10602 (cond
10603 ((not org-refile-cache) nil)
10604 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10606 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10607 org-refile-cache))))
10608 (and set (org-refile-cache-check-set set) set)))))
10610 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10611 "Produce a table with refile targets."
10612 (let ((case-fold-search nil)
10613 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10614 (entries (or org-refile-targets '((nil . (:level . 1)))))
10615 targets tgs txt re files f desc descre fast-path-p level pos0)
10616 (message "Getting targets...")
10617 (with-current-buffer (or default-buffer (current-buffer))
10618 (while (setq entry (pop entries))
10619 (setq files (car entry) desc (cdr entry))
10620 (setq fast-path-p nil)
10621 (cond
10622 ((null files) (setq files (list (current-buffer))))
10623 ((eq files 'org-agenda-files)
10624 (setq files (org-agenda-files 'unrestricted)))
10625 ((and (symbolp files) (fboundp files))
10626 (setq files (funcall files)))
10627 ((and (symbolp files) (boundp files))
10628 (setq files (symbol-value files))))
10629 (if (stringp files) (setq files (list files)))
10630 (cond
10631 ((eq (car desc) :tag)
10632 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10633 ((eq (car desc) :todo)
10634 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10635 ((eq (car desc) :regexp)
10636 (setq descre (cdr desc)))
10637 ((eq (car desc) :level)
10638 (setq descre (concat "^\\*\\{" (number-to-string
10639 (if org-odd-levels-only
10640 (1- (* 2 (cdr desc)))
10641 (cdr desc)))
10642 "\\}[ \t]")))
10643 ((eq (car desc) :maxlevel)
10644 (setq fast-path-p t)
10645 (setq descre (concat "^\\*\\{1," (number-to-string
10646 (if org-odd-levels-only
10647 (1- (* 2 (cdr desc)))
10648 (cdr desc)))
10649 "\\}[ \t]")))
10650 (t (error "Bad refiling target description %s" desc)))
10651 (while (setq f (pop files))
10652 (with-current-buffer
10653 (if (bufferp f) f (org-get-agenda-file-buffer f))
10655 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10656 (progn
10657 (if (bufferp f) (setq f (buffer-file-name
10658 (buffer-base-buffer f))))
10659 (setq f (and f (expand-file-name f)))
10660 (if (eq org-refile-use-outline-path 'file)
10661 (push (list (file-name-nondirectory f) f nil nil) tgs))
10662 (save-excursion
10663 (save-restriction
10664 (widen)
10665 (goto-char (point-min))
10666 (while (re-search-forward descre nil t)
10667 (goto-char (setq pos0 (point-at-bol)))
10668 (catch 'next
10669 (when org-refile-target-verify-function
10670 (save-match-data
10671 (or (funcall org-refile-target-verify-function)
10672 (throw 'next t))))
10673 (when (and (looking-at org-complex-heading-regexp)
10674 (not (member (match-string 4) excluded-entries))
10675 (match-string 4))
10676 (setq level (org-reduced-level
10677 (- (match-end 1) (match-beginning 1)))
10678 txt (org-link-display-format (match-string 4))
10679 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10680 re (format org-complex-heading-regexp-format
10681 (regexp-quote (match-string 4))))
10682 (when org-refile-use-outline-path
10683 (setq txt (mapconcat
10684 'org-protect-slash
10685 (append
10686 (if (eq org-refile-use-outline-path
10687 'file)
10688 (list (file-name-nondirectory
10689 (buffer-file-name
10690 (buffer-base-buffer))))
10691 (if (eq org-refile-use-outline-path
10692 'full-file-path)
10693 (list (buffer-file-name
10694 (buffer-base-buffer)))))
10695 (org-get-outline-path fast-path-p
10696 level txt)
10697 (list txt))
10698 "/")))
10699 (push (list txt f re (org-refile-marker (point)))
10700 tgs)))
10701 (when (= (point) pos0)
10702 ;; verification function has not moved point
10703 (goto-char (point-at-eol))))))))
10704 (when org-refile-use-cache
10705 (org-refile-cache-put tgs (buffer-file-name) descre))
10706 (setq targets (append tgs targets))
10707 ))))
10708 (message "Getting targets...done")
10709 (nreverse targets)))
10711 (defun org-protect-slash (s)
10712 (while (string-match "/" s)
10713 (setq s (replace-match "\\" t t s)))
10716 (defvar org-olpa (make-vector 20 nil))
10718 (defun org-get-outline-path (&optional fastp level heading)
10719 "Return the outline path to the current entry, as a list.
10721 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10722 routine which makes outline path derivations for an entire file,
10723 avoiding backtracing. Refile target collection makes use of that."
10724 (if fastp
10725 (progn
10726 (if (> level 19)
10727 (error "Outline path failure, more than 19 levels"))
10728 (loop for i from level upto 19 do
10729 (aset org-olpa i nil))
10730 (prog1
10731 (delq nil (append org-olpa nil))
10732 (aset org-olpa level heading)))
10733 (let (rtn case-fold-search)
10734 (save-excursion
10735 (save-restriction
10736 (widen)
10737 (while (org-up-heading-safe)
10738 (when (looking-at org-complex-heading-regexp)
10739 (push (org-match-string-no-properties 4) rtn)))
10740 rtn)))))
10742 (defun org-format-outline-path (path &optional width prefix)
10743 "Format the outline path PATH for display.
10744 Width is the maximum number of characters that is available.
10745 Prefix is a prefix to be included in the returned string,
10746 such as the file name."
10747 (setq width (or width 79))
10748 (if prefix (setq width (- width (length prefix))))
10749 (if (not path)
10750 (or prefix "")
10751 (let* ((nsteps (length path))
10752 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10753 (maxwidth (if (<= total-width width)
10754 10000 ;; everything fits
10755 ;; we need to shorten the level headings
10756 (/ (- width nsteps) nsteps)))
10757 (org-odd-levels-only nil)
10758 (n 0)
10759 (total (1+ (length prefix))))
10760 (setq maxwidth (max maxwidth 10))
10761 (concat prefix
10762 (mapconcat
10763 (lambda (h)
10764 (setq n (1+ n))
10765 (if (and (= n nsteps) (< maxwidth 10000))
10766 (setq maxwidth (- total-width total)))
10767 (if (< (length h) maxwidth)
10768 (progn (setq total (+ total (length h) 1)) h)
10769 (setq h (substring h 0 (- maxwidth 2))
10770 total (+ total maxwidth 1))
10771 (if (string-match "[ \t]+\\'" h)
10772 (setq h (substring h 0 (match-beginning 0))))
10773 (setq h (concat h "..")))
10774 (org-add-props h nil 'face
10775 (nth (% (1- n) org-n-level-faces)
10776 org-level-faces))
10778 path "/")))))
10780 (defun org-display-outline-path (&optional file current)
10781 "Display the current outline path in the echo area."
10782 (interactive "P")
10783 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10784 (case-fold-search nil)
10785 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10786 (if current (setq path (append path
10787 (save-excursion
10788 (org-back-to-heading t)
10789 (if (looking-at org-complex-heading-regexp)
10790 (list (match-string 4)))))))
10791 (message "%s"
10792 (org-format-outline-path
10793 path
10794 (1- (frame-width))
10795 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10797 (defvar org-refile-history nil
10798 "History for refiling operations.")
10800 (defvar org-after-refile-insert-hook nil
10801 "Hook run after `org-refile' has inserted its stuff at the new location.
10802 Note that this is still *before* the stuff will be removed from
10803 the *old* location.")
10805 (defvar org-capture-last-stored-marker)
10806 (defun org-refile (&optional goto default-buffer rfloc)
10807 "Move the entry or entries at point to another heading.
10808 The list of target headings is compiled using the information in
10809 `org-refile-targets', which see.
10811 At the target location, the entry is filed as a subitem of the target
10812 heading. Depending on `org-reverse-note-order', the new subitem will
10813 either be the first or the last subitem.
10815 If there is an active region, all entries in that region will be moved.
10816 However, the region must fulfill the requirement that the first heading
10817 is the first one sets the top-level of the moved text - at most siblings
10818 below it are allowed.
10820 With prefix arg GOTO, the command will only visit the target location
10821 and not actually move anything.
10823 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10824 go to the location where the last refiling operation has put the subtree.
10825 With a prefix argument of `2', refile to the running clock.
10827 RFLOC can be a refile location obtained in a different way.
10829 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10831 If you are using target caching (see `org-refile-use-cache'),
10832 you have to clear the target cache in order to find new targets.
10833 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10834 prefix argument (`C-u C-u C-u C-c C-w')."
10836 (interactive "P")
10837 (if (member goto '(0 (64)))
10838 (org-refile-cache-clear)
10839 (let* ((cbuf (current-buffer))
10840 (regionp (org-region-active-p))
10841 (region-start (and regionp (region-beginning)))
10842 (region-end (and regionp (region-end)))
10843 (region-length (and regionp (- region-end region-start)))
10844 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10845 pos it nbuf file re level reversed)
10846 (setq last-command nil)
10847 (when regionp
10848 (goto-char region-start)
10849 (or (bolp) (goto-char (point-at-bol)))
10850 (setq region-start (point))
10851 (unless (or (org-kill-is-subtree-p
10852 (buffer-substring region-start region-end))
10853 (prog1 org-refile-active-region-within-subtree
10854 (org-toggle-heading)))
10855 (error "The region is not a (sequence of) subtree(s)")))
10856 (if (equal goto '(16))
10857 (org-refile-goto-last-stored)
10858 (when (or
10859 (and (equal goto 2)
10860 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10861 (prog1
10862 (setq it (list (or org-clock-heading "running clock")
10863 (buffer-file-name
10864 (marker-buffer org-clock-hd-marker))
10866 (marker-position org-clock-hd-marker)))
10867 (setq goto nil)))
10868 (setq it (or rfloc
10869 (let (heading-text)
10870 (save-excursion
10871 (unless goto
10872 (org-back-to-heading t)
10873 (setq heading-text
10874 (nth 4 (org-heading-components))))
10875 (org-refile-get-location
10876 (cond (goto "Goto")
10877 (regionp "Refile region to")
10878 (t (concat "Refile subtree \""
10879 heading-text "\" to")))
10880 default-buffer
10881 (and (not (equal '(4) goto))
10882 org-refile-allow-creating-parent-nodes)
10883 goto))))))
10884 (setq file (nth 1 it)
10885 re (nth 2 it)
10886 pos (nth 3 it))
10887 (if (and (not goto)
10889 (equal (buffer-file-name) file)
10890 (if regionp
10891 (and (>= pos region-start)
10892 (<= pos region-end))
10893 (and (>= pos (point))
10894 (< pos (save-excursion
10895 (org-end-of-subtree t t))))))
10896 (error "Cannot refile to position inside the tree or region"))
10898 (setq nbuf (or (find-buffer-visiting file)
10899 (find-file-noselect file)))
10900 (if goto
10901 (progn
10902 (org-pop-to-buffer-same-window nbuf)
10903 (goto-char pos)
10904 (org-show-context 'org-goto))
10905 (if regionp
10906 (progn
10907 (org-kill-new (buffer-substring region-start region-end))
10908 (org-save-markers-in-region region-start region-end))
10909 (org-copy-subtree 1 nil t))
10910 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10911 (find-file-noselect file)))
10912 (setq reversed (org-notes-order-reversed-p))
10913 (save-excursion
10914 (save-restriction
10915 (widen)
10916 (if pos
10917 (progn
10918 (goto-char pos)
10919 (looking-at org-outline-regexp)
10920 (setq level (org-get-valid-level (funcall outline-level) 1))
10921 (goto-char
10922 (if reversed
10923 (or (outline-next-heading) (point-max))
10924 (or (save-excursion (org-get-next-sibling))
10925 (org-end-of-subtree t t)
10926 (point-max)))))
10927 (setq level 1)
10928 (if (not reversed)
10929 (goto-char (point-max))
10930 (goto-char (point-min))
10931 (or (outline-next-heading) (goto-char (point-max)))))
10932 (if (not (bolp)) (newline))
10933 (org-paste-subtree level)
10934 (when org-log-refile
10935 (org-add-log-setup 'refile nil nil 'findpos
10936 org-log-refile)
10937 (unless (eq org-log-refile 'note)
10938 (save-excursion (org-add-log-note))))
10939 (and org-auto-align-tags
10940 (let ((org-loop-over-headlines-in-active-region nil))
10941 (org-set-tags nil t)))
10942 (with-demoted-errors
10943 (bookmark-set "org-refile-last-stored"))
10944 ;; If we are refiling for capture, make sure that the
10945 ;; last-capture pointers point here
10946 (when (org-bound-and-true-p org-refile-for-capture)
10947 (with-demoted-errors
10948 (bookmark-set "org-capture-last-stored-marker"))
10949 (move-marker org-capture-last-stored-marker (point)))
10950 (if (fboundp 'deactivate-mark) (deactivate-mark))
10951 (run-hooks 'org-after-refile-insert-hook))))
10952 (if regionp
10953 (delete-region (point) (+ (point) region-length))
10954 (org-cut-subtree))
10955 (when (featurep 'org-inlinetask)
10956 (org-inlinetask-remove-END-maybe))
10957 (setq org-markers-to-move nil)
10958 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10960 (defun org-refile-goto-last-stored ()
10961 "Go to the location where the last refile was stored."
10962 (interactive)
10963 (bookmark-jump "org-refile-last-stored")
10964 (message "This is the location of the last refile"))
10966 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10967 no-exclude)
10968 "Prompt the user for a refile location, using PROMPT.
10969 PROMPT should not be suffixed with a colon and a space, because
10970 this function appends the default value from
10971 `org-refile-history' automatically, if that is not empty.
10972 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10973 this is used for the GOTO interface."
10974 (let ((org-refile-targets org-refile-targets)
10975 (org-refile-use-outline-path org-refile-use-outline-path)
10976 excluded-entries)
10977 (when (and (derived-mode-p 'org-mode)
10978 (not org-refile-use-cache)
10979 (not no-exclude))
10980 (org-map-tree
10981 (lambda()
10982 (setq excluded-entries
10983 (append excluded-entries (list (org-get-heading t t)))))))
10984 (setq org-refile-target-table
10985 (org-refile-get-targets default-buffer excluded-entries)))
10986 (unless org-refile-target-table
10987 (error "No refile targets"))
10988 (let* ((prompt (concat prompt
10989 (and (car org-refile-history)
10990 (concat " (default " (car org-refile-history) ")"))
10991 ": "))
10992 (cbuf (current-buffer))
10993 (partial-completion-mode nil)
10994 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10995 (cfunc (if (and org-refile-use-outline-path
10996 org-outline-path-complete-in-steps)
10997 'org-olpath-completing-read
10998 'org-icompleting-read))
10999 (extra (if org-refile-use-outline-path "/" ""))
11000 (filename (and cfn (expand-file-name cfn)))
11001 (tbl (mapcar
11002 (lambda (x)
11003 (if (and (not (member org-refile-use-outline-path
11004 '(file full-file-path)))
11005 (not (equal filename (nth 1 x))))
11006 (cons (concat (car x) extra " ("
11007 (file-name-nondirectory (nth 1 x)) ")")
11008 (cdr x))
11009 (cons (concat (car x) extra) (cdr x))))
11010 org-refile-target-table))
11011 (completion-ignore-case t)
11012 pa answ parent-target child parent old-hist)
11013 (setq old-hist org-refile-history)
11014 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11015 nil 'org-refile-history (car org-refile-history)))
11016 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11017 (org-refile-check-position pa)
11018 (if pa
11019 (progn
11020 (when (or (not org-refile-history)
11021 (not (eq old-hist org-refile-history))
11022 (not (equal (car pa) (car org-refile-history))))
11023 (setq org-refile-history
11024 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11025 org-refile-history
11026 (cdr org-refile-history))))
11027 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11028 (pop org-refile-history)))
11030 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11031 (progn
11032 (setq parent (match-string 1 answ)
11033 child (match-string 2 answ))
11034 (setq parent-target (or (assoc parent tbl)
11035 (assoc (concat parent "/") tbl)))
11036 (when (and parent-target
11037 (or (eq new-nodes t)
11038 (and (eq new-nodes 'confirm)
11039 (y-or-n-p (format "Create new node \"%s\"? "
11040 child)))))
11041 (org-refile-new-child parent-target child)))
11042 (error "Invalid target location")))))
11044 (declare-function org-string-nw-p "org-macs" (s))
11045 (defun org-refile-check-position (refile-pointer)
11046 "Check if the refile pointer matches the headline to which it points."
11047 (let* ((file (nth 1 refile-pointer))
11048 (re (nth 2 refile-pointer))
11049 (pos (nth 3 refile-pointer))
11050 buffer)
11051 (if (and (not (markerp pos)) (not file))
11052 (error "Please save the buffer to a file before refiling")
11053 (when (org-string-nw-p re)
11054 (setq buffer (if (markerp pos)
11055 (marker-buffer pos)
11056 (or (find-buffer-visiting file)
11057 (find-file-noselect file))))
11058 (with-current-buffer buffer
11059 (save-excursion
11060 (save-restriction
11061 (widen)
11062 (goto-char pos)
11063 (beginning-of-line 1)
11064 (unless (org-looking-at-p re)
11065 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11067 (defun org-refile-new-child (parent-target child)
11068 "Use refile target PARENT-TARGET to add new CHILD below it."
11069 (unless parent-target
11070 (error "Cannot find parent for new node"))
11071 (let ((file (nth 1 parent-target))
11072 (pos (nth 3 parent-target))
11073 level)
11074 (with-current-buffer (or (find-buffer-visiting file)
11075 (find-file-noselect file))
11076 (save-excursion
11077 (save-restriction
11078 (widen)
11079 (if pos
11080 (goto-char pos)
11081 (goto-char (point-max))
11082 (if (not (bolp)) (newline)))
11083 (when (looking-at org-outline-regexp)
11084 (setq level (funcall outline-level))
11085 (org-end-of-subtree t t))
11086 (org-back-over-empty-lines)
11087 (insert "\n" (make-string
11088 (if pos (org-get-valid-level level 1) 1) ?*)
11089 " " child "\n")
11090 (beginning-of-line 0)
11091 (list (concat (car parent-target) "/" child) file "" (point)))))))
11093 (defun org-olpath-completing-read (prompt collection &rest args)
11094 "Read an outline path like a file name."
11095 (let ((thetable collection)
11096 (org-completion-use-ido nil) ; does not work with ido.
11097 (org-completion-use-iswitchb nil)) ; or iswitchb
11098 (apply
11099 'org-icompleting-read prompt
11100 (lambda (string predicate &optional flag)
11101 (let (rtn r f (l (length string)))
11102 (cond
11103 ((eq flag nil)
11104 ;; try completion
11105 (try-completion string thetable))
11106 ((eq flag t)
11107 ;; all-completions
11108 (setq rtn (all-completions string thetable predicate))
11109 (mapcar
11110 (lambda (x)
11111 (setq r (substring x l))
11112 (if (string-match " ([^)]*)$" x)
11113 (setq f (match-string 0 x))
11114 (setq f ""))
11115 (if (string-match "/" r)
11116 (concat string (substring r 0 (match-end 0)) f)
11118 rtn))
11119 ((eq flag 'lambda)
11120 ;; exact match?
11121 (assoc string thetable)))))
11122 args)))
11124 ;;;; Dynamic blocks
11126 (defun org-find-dblock (name)
11127 "Find the first dynamic block with name NAME in the buffer.
11128 If not found, stay at current position and return nil."
11129 (let ((case-fold-search t) pos)
11130 (save-excursion
11131 (goto-char (point-min))
11132 (setq pos (and (re-search-forward
11133 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11134 (match-beginning 0))))
11135 (if pos (goto-char pos))
11136 pos))
11138 (defconst org-dblock-start-re
11139 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11140 "Matches the start line of a dynamic block, with parameters.")
11142 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11143 "Matches the end of a dynamic block.")
11145 (defun org-create-dblock (plist)
11146 "Create a dynamic block section, with parameters taken from PLIST.
11147 PLIST must contain a :name entry which is used as name of the block."
11148 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11149 (end-of-line 1)
11150 (newline))
11151 (let ((col (current-column))
11152 (name (plist-get plist :name)))
11153 (insert "#+BEGIN: " name)
11154 (while plist
11155 (if (eq (car plist) :name)
11156 (setq plist (cddr plist))
11157 (insert " " (prin1-to-string (pop plist)))))
11158 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11159 (beginning-of-line -2)))
11161 (defun org-prepare-dblock ()
11162 "Prepare dynamic block for refresh.
11163 This empties the block, puts the cursor at the insert position and returns
11164 the property list including an extra property :name with the block name."
11165 (unless (looking-at org-dblock-start-re)
11166 (error "Not at a dynamic block"))
11167 (let* ((begdel (1+ (match-end 0)))
11168 (name (org-no-properties (match-string 1)))
11169 (params (append (list :name name)
11170 (read (concat "(" (match-string 3) ")")))))
11171 (save-excursion
11172 (beginning-of-line 1)
11173 (skip-chars-forward " \t")
11174 (setq params (plist-put params :indentation-column (current-column))))
11175 (unless (re-search-forward org-dblock-end-re nil t)
11176 (error "Dynamic block not terminated"))
11177 (setq params
11178 (append params
11179 (list :content (buffer-substring
11180 begdel (match-beginning 0)))))
11181 (delete-region begdel (match-beginning 0))
11182 (goto-char begdel)
11183 (open-line 1)
11184 params))
11186 (defun org-map-dblocks (&optional command)
11187 "Apply COMMAND to all dynamic blocks in the current buffer.
11188 If COMMAND is not given, use `org-update-dblock'."
11189 (let ((cmd (or command 'org-update-dblock)))
11190 (save-excursion
11191 (goto-char (point-min))
11192 (while (re-search-forward org-dblock-start-re nil t)
11193 (goto-char (match-beginning 0))
11194 (save-excursion
11195 (condition-case nil
11196 (funcall cmd)
11197 (error (message "Error during update of dynamic block"))))
11198 (unless (re-search-forward org-dblock-end-re nil t)
11199 (error "Dynamic block not terminated"))))))
11201 (defun org-dblock-update (&optional arg)
11202 "User command for updating dynamic blocks.
11203 Update the dynamic block at point. With prefix ARG, update all dynamic
11204 blocks in the buffer."
11205 (interactive "P")
11206 (if arg
11207 (org-update-all-dblocks)
11208 (or (looking-at org-dblock-start-re)
11209 (org-beginning-of-dblock))
11210 (org-update-dblock)))
11212 (defun org-update-dblock ()
11213 "Update the dynamic block at point.
11214 This means to empty the block, parse for parameters and then call
11215 the correct writing function."
11216 (interactive)
11217 (save-window-excursion
11218 (let* ((pos (point))
11219 (line (org-current-line))
11220 (params (org-prepare-dblock))
11221 (name (plist-get params :name))
11222 (indent (plist-get params :indentation-column))
11223 (cmd (intern (concat "org-dblock-write:" name))))
11224 (message "Updating dynamic block `%s' at line %d..." name line)
11225 (funcall cmd params)
11226 (message "Updating dynamic block `%s' at line %d...done" name line)
11227 (goto-char pos)
11228 (when (and indent (> indent 0))
11229 (setq indent (make-string indent ?\ ))
11230 (save-excursion
11231 (org-beginning-of-dblock)
11232 (forward-line 1)
11233 (while (not (looking-at org-dblock-end-re))
11234 (insert indent)
11235 (beginning-of-line 2))
11236 (when (looking-at org-dblock-end-re)
11237 (and (looking-at "[ \t]+")
11238 (replace-match ""))
11239 (insert indent)))))))
11241 (defun org-beginning-of-dblock ()
11242 "Find the beginning of the dynamic block at point.
11243 Error if there is no such block at point."
11244 (let ((pos (point))
11245 beg)
11246 (end-of-line 1)
11247 (if (and (re-search-backward org-dblock-start-re nil t)
11248 (setq beg (match-beginning 0))
11249 (re-search-forward org-dblock-end-re nil t)
11250 (> (match-end 0) pos))
11251 (goto-char beg)
11252 (goto-char pos)
11253 (error "Not in a dynamic block"))))
11255 (defun org-update-all-dblocks ()
11256 "Update all dynamic blocks in the buffer.
11257 This function can be used in a hook."
11258 (interactive)
11259 (when (derived-mode-p 'org-mode)
11260 (org-map-dblocks 'org-update-dblock)))
11263 ;;;; Completion
11265 (defconst org-additional-option-like-keywords
11266 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11267 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11268 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11269 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11270 "BEGIN:" "END:"
11271 "ORGTBL" "TBLFM:" "TBLNAME:"
11272 "BEGIN_EXAMPLE" "END_EXAMPLE"
11273 "BEGIN_VERBATIM" "END_VERBATIM"
11274 "BEGIN_QUOTE" "END_QUOTE"
11275 "BEGIN_VERSE" "END_VERSE"
11276 "BEGIN_CENTER" "END_CENTER"
11277 "BEGIN_SRC" "END_SRC"
11278 "BEGIN_RESULT" "END_RESULT"
11279 "BEGIN_lstlisting" "END_lstlisting"
11280 "NAME:" "RESULTS:"
11281 "HEADER:" "HEADERS:"
11282 "COLUMNS:" "PROPERTY:"
11283 "CAPTION:" "LABEL:"
11284 "SETUPFILE:"
11285 "INCLUDE:" "INDEX:"
11286 "BIND:"
11287 "MACRO:"))
11289 (defconst org-options-keywords
11290 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11291 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11292 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11293 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11294 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11295 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11296 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11298 (defconst org-additional-option-like-keywords-for-flyspell
11299 (delete-dups
11300 (split-string
11301 (mapconcat (lambda(k)
11302 (replace-regexp-in-string
11303 "_\\|:" " "
11304 (concat k " " (downcase k) " " (upcase k))))
11305 (append org-options-keywords org-additional-option-like-keywords)
11306 " ")
11307 " +" t)))
11309 (defcustom org-structure-template-alist
11310 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11311 "<src lang=\"?\">\n\n</src>")
11312 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11313 "<example>\n?\n</example>")
11314 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11315 "<quote>\n?\n</quote>")
11316 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11317 "<verse>\n?\n</verse>")
11318 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11319 "<verbatim>\n?\n</verbatim>")
11320 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11321 "<center>\n?\n</center>")
11322 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11323 "<literal style=\"latex\">\n?\n</literal>")
11324 ("L" "#+LaTeX: "
11325 "<literal style=\"latex\">?</literal>")
11326 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11327 "<literal style=\"html\">\n?\n</literal>")
11328 ("H" "#+HTML: "
11329 "<literal style=\"html\">?</literal>")
11330 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11331 ("A" "#+ASCII: ")
11332 ("i" "#+INDEX: ?"
11333 "#+INDEX: ?")
11334 ("I" "#+INCLUDE: %file ?"
11335 "<include file=%file markup=\"?\">"))
11336 "Structure completion elements.
11337 This is a list of abbreviation keys and values. The value gets inserted
11338 if you type `<' followed by the key and then press the completion key,
11339 usually `M-TAB'. %file will be replaced by a file name after prompting
11340 for the file using completion. The cursor will be placed at the position
11341 of the `?` in the template.
11342 There are two templates for each key, the first uses the original Org syntax,
11343 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11344 the default when the /org-mtags.el/ module has been loaded. See also the
11345 variable `org-mtags-prefer-muse-templates'."
11346 :group 'org-completion
11347 :type '(repeat
11348 (string :tag "Key")
11349 (string :tag "Template")
11350 (string :tag "Muse Template")))
11352 (defun org-try-structure-completion ()
11353 "Try to complete a structure template before point.
11354 This looks for strings like \"<e\" on an otherwise empty line and
11355 expands them."
11356 (let ((l (buffer-substring (point-at-bol) (point)))
11358 (when (and (looking-at "[ \t]*$")
11359 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11360 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11361 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11362 (match-beginning 1)) a)
11363 t)))
11365 (defun org-complete-expand-structure-template (start cell)
11366 "Expand a structure template."
11367 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11368 (rpl (nth (if musep 2 1) cell))
11369 (ind ""))
11370 (delete-region start (point))
11371 (when (string-match "\\`#\\+" rpl)
11372 (cond
11373 ((bolp))
11374 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11375 (setq ind (buffer-substring (point-at-bol) (point))))
11376 (t (newline))))
11377 (setq start (point))
11378 (if (string-match "%file" rpl)
11379 (setq rpl (replace-match
11380 (concat
11381 "\""
11382 (save-match-data
11383 (abbreviate-file-name (read-file-name "Include file: ")))
11384 "\"")
11385 t t rpl)))
11386 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11387 (concat "\n" ind)))
11388 (insert rpl)
11389 (if (re-search-backward "\\?" start t) (delete-char 1))))
11391 ;;;; TODO, DEADLINE, Comments
11393 (defun org-toggle-comment ()
11394 "Change the COMMENT state of an entry."
11395 (interactive)
11396 (save-excursion
11397 (org-back-to-heading)
11398 (let (case-fold-search)
11399 (cond
11400 ((looking-at (format org-heading-keyword-regexp-format
11401 org-comment-string))
11402 (goto-char (match-end 1))
11403 (looking-at (concat " +" org-comment-string))
11404 (replace-match "" t t)
11405 (when (eolp) (insert " ")))
11406 ((looking-at org-outline-regexp)
11407 (goto-char (match-end 0))
11408 (insert org-comment-string " "))))))
11410 (defvar org-last-todo-state-is-todo nil
11411 "This is non-nil when the last TODO state change led to a TODO state.
11412 If the last change removed the TODO tag or switched to DONE, then
11413 this is nil.")
11415 (defvar org-setting-tags nil) ; dynamically skipped
11417 (defvar org-todo-setup-filter-hook nil
11418 "Hook for functions that pre-filter todo specs.
11419 Each function takes a todo spec and returns either nil or the spec
11420 transformed into canonical form." )
11422 (defvar org-todo-get-default-hook nil
11423 "Hook for functions that get a default item for todo.
11424 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11425 nil or a string to be used for the todo mark." )
11427 (defvar org-agenda-headline-snapshot-before-repeat)
11429 (defun org-current-effective-time ()
11430 "Return current time adjusted for `org-extend-today-until' variable."
11431 (let* ((ct (org-current-time))
11432 (dct (decode-time ct))
11433 (ct1
11434 (if (and org-use-effective-time
11435 (< (nth 2 dct) org-extend-today-until))
11436 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11437 ct)))
11438 ct1))
11440 (defun org-todo-yesterday (&optional arg)
11441 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11442 (interactive "P")
11443 (if (eq major-mode 'org-agenda-mode)
11444 (apply 'org-agenda-todo-yesterday arg)
11445 (let* ((hour (third (decode-time
11446 (org-current-time))))
11447 (org-extend-today-until (1+ hour)))
11448 (org-todo arg))))
11450 (defun org-todo (&optional arg)
11451 "Change the TODO state of an item.
11452 The state of an item is given by a keyword at the start of the heading,
11453 like
11454 *** TODO Write paper
11455 *** DONE Call mom
11457 The different keywords are specified in the variable `org-todo-keywords'.
11458 By default the available states are \"TODO\" and \"DONE\".
11459 So for this example: when the item starts with TODO, it is changed to DONE.
11460 When it starts with DONE, the DONE is removed. And when neither TODO nor
11461 DONE are present, add TODO at the beginning of the heading.
11463 With \\[universal-argument] prefix arg, use completion to determine the new \
11464 state.
11465 With numeric prefix arg, switch to that state.
11466 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11467 keywords (nextset).
11468 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11469 With a numeric prefix arg of 0, inhibit note taking for the change.
11471 For calling through lisp, arg is also interpreted in the following way:
11472 'none -> empty state
11473 \"\"(empty string) -> switch to empty state
11474 'done -> switch to DONE
11475 'nextset -> switch to the next set of keywords
11476 'previousset -> switch to the previous set of keywords
11477 \"WAITING\" -> switch to the specified keyword, but only if it
11478 really is a member of `org-todo-keywords'."
11479 (interactive "P")
11480 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11481 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11482 'region-start-level 'region))
11483 org-loop-over-headlines-in-active-region)
11484 (org-map-entries
11485 `(org-todo ,arg)
11486 org-loop-over-headlines-in-active-region
11487 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11488 (if (equal arg '(16)) (setq arg 'nextset))
11489 (let ((org-blocker-hook org-blocker-hook)
11490 commentp
11491 case-fold-search)
11492 (when (equal arg '(64))
11493 (setq arg nil org-blocker-hook nil))
11494 (when (and org-blocker-hook
11495 (or org-inhibit-blocking
11496 (org-entry-get nil "NOBLOCKING")))
11497 (setq org-blocker-hook nil))
11498 (save-excursion
11499 (catch 'exit
11500 (org-back-to-heading t)
11501 (when (looking-at (concat "^\\*+ " org-comment-string))
11502 (org-toggle-comment)
11503 (setq commentp t))
11504 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11505 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11506 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11507 (let* ((match-data (match-data))
11508 (startpos (point-at-bol))
11509 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11510 (org-log-done org-log-done)
11511 (org-log-repeat org-log-repeat)
11512 (org-todo-log-states org-todo-log-states)
11513 (org-inhibit-logging
11514 (if (equal arg 0)
11515 (progn (setq arg nil) 'note) org-inhibit-logging))
11516 (this (match-string 1))
11517 (hl-pos (match-beginning 0))
11518 (head (org-get-todo-sequence-head this))
11519 (ass (assoc head org-todo-kwd-alist))
11520 (interpret (nth 1 ass))
11521 (done-word (nth 3 ass))
11522 (final-done-word (nth 4 ass))
11523 (org-last-state (or this ""))
11524 (completion-ignore-case t)
11525 (member (member this org-todo-keywords-1))
11526 (tail (cdr member))
11527 (org-state (cond
11528 ((and org-todo-key-trigger
11529 (or (and (equal arg '(4))
11530 (eq org-use-fast-todo-selection 'prefix))
11531 (and (not arg) org-use-fast-todo-selection
11532 (not (eq org-use-fast-todo-selection
11533 'prefix)))))
11534 ;; Use fast selection
11535 (org-fast-todo-selection))
11536 ((and (equal arg '(4))
11537 (or (not org-use-fast-todo-selection)
11538 (not org-todo-key-trigger)))
11539 ;; Read a state with completion
11540 (org-icompleting-read
11541 "State: " (mapcar (lambda(x) (list x))
11542 org-todo-keywords-1)
11543 nil t))
11544 ((eq arg 'right)
11545 (if this
11546 (if tail (car tail) nil)
11547 (car org-todo-keywords-1)))
11548 ((eq arg 'left)
11549 (if (equal member org-todo-keywords-1)
11551 (if this
11552 (nth (- (length org-todo-keywords-1)
11553 (length tail) 2)
11554 org-todo-keywords-1)
11555 (org-last org-todo-keywords-1))))
11556 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11557 (setq arg nil))) ; hack to fall back to cycling
11558 (arg
11559 ;; user or caller requests a specific state
11560 (cond
11561 ((equal arg "") nil)
11562 ((eq arg 'none) nil)
11563 ((eq arg 'done) (or done-word (car org-done-keywords)))
11564 ((eq arg 'nextset)
11565 (or (car (cdr (member head org-todo-heads)))
11566 (car org-todo-heads)))
11567 ((eq arg 'previousset)
11568 (let ((org-todo-heads (reverse org-todo-heads)))
11569 (or (car (cdr (member head org-todo-heads)))
11570 (car org-todo-heads))))
11571 ((car (member arg org-todo-keywords-1)))
11572 ((stringp arg)
11573 (error "State `%s' not valid in this file" arg))
11574 ((nth (1- (prefix-numeric-value arg))
11575 org-todo-keywords-1))))
11576 ((null member) (or head (car org-todo-keywords-1)))
11577 ((equal this final-done-word) nil) ;; -> make empty
11578 ((null tail) nil) ;; -> first entry
11579 ((memq interpret '(type priority))
11580 (if (eq this-command last-command)
11581 (car tail)
11582 (if (> (length tail) 0)
11583 (or done-word (car org-done-keywords))
11584 nil)))
11586 (car tail))))
11587 (org-state (or
11588 (run-hook-with-args-until-success
11589 'org-todo-get-default-hook org-state org-last-state)
11590 org-state))
11591 (next (if org-state (concat " " org-state " ") " "))
11592 (change-plist (list :type 'todo-state-change :from this :to org-state
11593 :position startpos))
11594 dolog now-done-p)
11595 (when org-blocker-hook
11596 (setq org-last-todo-state-is-todo
11597 (not (member this org-done-keywords)))
11598 (unless (save-excursion
11599 (save-match-data
11600 (org-with-wide-buffer
11601 (run-hook-with-args-until-failure
11602 'org-blocker-hook change-plist))))
11603 (if (org-called-interactively-p 'interactive)
11604 (error "TODO state change from %s to %s blocked" this org-state)
11605 ;; fail silently
11606 (message "TODO state change from %s to %s blocked" this org-state)
11607 (throw 'exit nil))))
11608 (store-match-data match-data)
11609 (replace-match next t t)
11610 (unless (pos-visible-in-window-p hl-pos)
11611 (message "TODO state changed to %s" (org-trim next)))
11612 (unless head
11613 (setq head (org-get-todo-sequence-head org-state)
11614 ass (assoc head org-todo-kwd-alist)
11615 interpret (nth 1 ass)
11616 done-word (nth 3 ass)
11617 final-done-word (nth 4 ass)))
11618 (when (memq arg '(nextset previousset))
11619 (message "Keyword-Set %d/%d: %s"
11620 (- (length org-todo-sets) -1
11621 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11622 (length org-todo-sets)
11623 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11624 (setq org-last-todo-state-is-todo
11625 (not (member org-state org-done-keywords)))
11626 (setq now-done-p (and (member org-state org-done-keywords)
11627 (not (member this org-done-keywords))))
11628 (and logging (org-local-logging logging))
11629 (when (and (or org-todo-log-states org-log-done)
11630 (not (eq org-inhibit-logging t))
11631 (not (memq arg '(nextset previousset))))
11632 ;; we need to look at recording a time and note
11633 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11634 (nth 2 (assoc this org-todo-log-states))))
11635 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11636 (setq dolog 'time))
11637 (when (and org-state
11638 (member org-state org-not-done-keywords)
11639 (not (member this org-not-done-keywords)))
11640 ;; This is now a todo state and was not one before
11641 ;; If there was a CLOSED time stamp, get rid of it.
11642 (org-add-planning-info nil nil 'closed))
11643 (when (and now-done-p org-log-done)
11644 ;; It is now done, and it was not done before
11645 (org-add-planning-info 'closed (org-current-effective-time))
11646 (if (and (not dolog) (eq 'note org-log-done))
11647 (org-add-log-setup 'done org-state this 'findpos 'note)))
11648 (when (and org-state dolog)
11649 ;; This is a non-nil state, and we need to log it
11650 (org-add-log-setup 'state org-state this 'findpos dolog)))
11651 ;; Fixup tag positioning
11652 (org-todo-trigger-tag-changes org-state)
11653 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11654 (when org-provide-todo-statistics
11655 (org-update-parent-todo-statistics))
11656 (run-hooks 'org-after-todo-state-change-hook)
11657 (if (and arg (not (member org-state org-done-keywords)))
11658 (setq head (org-get-todo-sequence-head org-state)))
11659 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11660 ;; Do we need to trigger a repeat?
11661 (when now-done-p
11662 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11663 ;; This is for the agenda, take a snapshot of the headline.
11664 (save-match-data
11665 (setq org-agenda-headline-snapshot-before-repeat
11666 (org-get-heading))))
11667 (org-auto-repeat-maybe org-state))
11668 ;; Fixup cursor location if close to the keyword
11669 (if (and (outline-on-heading-p)
11670 (not (bolp))
11671 (save-excursion (beginning-of-line 1)
11672 (looking-at org-todo-line-regexp))
11673 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11674 (progn
11675 (goto-char (or (match-end 2) (match-end 1)))
11676 (and (looking-at " ") (just-one-space))))
11677 (when org-trigger-hook
11678 (save-excursion
11679 (run-hook-with-args 'org-trigger-hook change-plist)))
11680 (when commentp (org-toggle-comment))))))))
11682 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11683 "Block turning an entry into a TODO, using the hierarchy.
11684 This checks whether the current task should be blocked from state
11685 changes. Such blocking occurs when:
11687 1. The task has children which are not all in a completed state.
11689 2. A task has a parent with the property :ORDERED:, and there
11690 are siblings prior to the current task with incomplete
11691 status.
11693 3. The parent of the task is blocked because it has siblings that should
11694 be done first, or is child of a block grandparent TODO entry."
11696 (if (not org-enforce-todo-dependencies)
11697 t ; if locally turned off don't block
11698 (catch 'dont-block
11699 ;; If this is not a todo state change, or if this entry is already DONE,
11700 ;; do not block
11701 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11702 (member (plist-get change-plist :from)
11703 (cons 'done org-done-keywords))
11704 (member (plist-get change-plist :to)
11705 (cons 'todo org-not-done-keywords))
11706 (not (plist-get change-plist :to)))
11707 (throw 'dont-block t))
11708 ;; If this task has children, and any are undone, it's blocked
11709 (save-excursion
11710 (org-back-to-heading t)
11711 (let ((this-level (funcall outline-level)))
11712 (outline-next-heading)
11713 (let ((child-level (funcall outline-level)))
11714 (while (and (not (eobp))
11715 (> child-level this-level))
11716 ;; this todo has children, check whether they are all
11717 ;; completed
11718 (if (and (not (org-entry-is-done-p))
11719 (org-entry-is-todo-p))
11720 (throw 'dont-block nil))
11721 (outline-next-heading)
11722 (setq child-level (funcall outline-level))))))
11723 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11724 ;; any previous siblings are undone, it's blocked
11725 (save-excursion
11726 (org-back-to-heading t)
11727 (let* ((pos (point))
11728 (parent-pos (and (org-up-heading-safe) (point))))
11729 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11730 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11731 (forward-line 1)
11732 (re-search-forward org-not-done-heading-regexp pos t))
11733 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11734 ;; Search further up the hierarchy, to see if an ancestor is blocked
11735 (while t
11736 (goto-char parent-pos)
11737 (if (not (looking-at org-not-done-heading-regexp))
11738 (throw 'dont-block t)) ; do not block, parent is not a TODO
11739 (setq pos (point))
11740 (setq parent-pos (and (org-up-heading-safe) (point)))
11741 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11742 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11743 (forward-line 1)
11744 (re-search-forward org-not-done-heading-regexp pos t))
11745 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11747 (defcustom org-track-ordered-property-with-tag nil
11748 "Should the ORDERED property also be shown as a tag?
11749 The ORDERED property decides if an entry should require subtasks to be
11750 completed in sequence. Since a property is not very visible, setting
11751 this option means that toggling the ORDERED property with the command
11752 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11753 not relevant for the behavior, but it makes things more visible.
11755 Note that toggling the tag with tags commands will not change the property
11756 and therefore not influence behavior!
11758 This can be t, meaning the tag ORDERED should be used, It can also be a
11759 string to select a different tag for this task."
11760 :group 'org-todo
11761 :type '(choice
11762 (const :tag "No tracking" nil)
11763 (const :tag "Track with ORDERED tag" t)
11764 (string :tag "Use other tag")))
11766 (defun org-toggle-ordered-property ()
11767 "Toggle the ORDERED property of the current entry.
11768 For better visibility, you can track the value of this property with a tag.
11769 See variable `org-track-ordered-property-with-tag'."
11770 (interactive)
11771 (let* ((t1 org-track-ordered-property-with-tag)
11772 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11773 (save-excursion
11774 (org-back-to-heading)
11775 (if (org-entry-get nil "ORDERED")
11776 (progn
11777 (org-delete-property "ORDERED")
11778 (and tag (org-toggle-tag tag 'off))
11779 (message "Subtasks can be completed in arbitrary order"))
11780 (org-entry-put nil "ORDERED" "t")
11781 (and tag (org-toggle-tag tag 'on))
11782 (message "Subtasks must be completed in sequence")))))
11784 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11785 (defun org-block-todo-from-checkboxes (change-plist)
11786 "Block turning an entry into a TODO, using checkboxes.
11787 This checks whether the current task should be blocked from state
11788 changes because there are unchecked boxes in this entry."
11789 (if (not org-enforce-todo-checkbox-dependencies)
11790 t ; if locally turned off don't block
11791 (catch 'dont-block
11792 ;; If this is not a todo state change, or if this entry is already DONE,
11793 ;; do not block
11794 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11795 (member (plist-get change-plist :from)
11796 (cons 'done org-done-keywords))
11797 (member (plist-get change-plist :to)
11798 (cons 'todo org-not-done-keywords))
11799 (not (plist-get change-plist :to)))
11800 (throw 'dont-block t))
11801 ;; If this task has checkboxes that are not checked, it's blocked
11802 (save-excursion
11803 (org-back-to-heading t)
11804 (let ((beg (point)) end)
11805 (outline-next-heading)
11806 (setq end (point))
11807 (goto-char beg)
11808 (if (org-list-search-forward
11809 (concat (org-item-beginning-re)
11810 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11811 "\\[[- ]\\]")
11812 end t)
11813 (progn
11814 (if (boundp 'org-blocked-by-checkboxes)
11815 (setq org-blocked-by-checkboxes t))
11816 (throw 'dont-block nil)))))
11817 t))) ; do not block
11819 (defun org-entry-blocked-p ()
11820 "Is the current entry blocked?"
11821 (org-with-buffer-modified-unmodified
11822 (if (org-entry-get nil "NOBLOCKING")
11823 nil ;; Never block this entry
11824 (not
11825 (run-hook-with-args-until-failure
11826 'org-blocker-hook
11827 (list :type 'todo-state-change
11828 :position (point)
11829 :from 'todo
11830 :to 'done))))))
11832 (defun org-update-statistics-cookies (all)
11833 "Update the statistics cookie, either from TODO or from checkboxes.
11834 This should be called with the cursor in a line with a statistics cookie."
11835 (interactive "P")
11836 (if all
11837 (progn
11838 (org-update-checkbox-count 'all)
11839 (org-map-entries 'org-update-parent-todo-statistics))
11840 (if (not (org-at-heading-p))
11841 (org-update-checkbox-count)
11842 (let ((pos (point-marker))
11843 end l1 l2)
11844 (ignore-errors (org-back-to-heading t))
11845 (if (not (org-at-heading-p))
11846 (org-update-checkbox-count)
11847 (setq l1 (org-outline-level))
11848 (setq end (save-excursion
11849 (outline-next-heading)
11850 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11851 (point)))
11852 (if (and (save-excursion
11853 (re-search-forward
11854 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11855 (not (save-excursion (re-search-forward
11856 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11857 (org-update-checkbox-count)
11858 (if (and l2 (> l2 l1))
11859 (progn
11860 (goto-char end)
11861 (org-update-parent-todo-statistics))
11862 (goto-char pos)
11863 (beginning-of-line 1)
11864 (while (re-search-forward
11865 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11866 (point-at-eol) t)
11867 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11868 (goto-char pos)
11869 (move-marker pos nil)))))
11871 (defvar org-entry-property-inherited-from) ;; defined below
11872 (defun org-update-parent-todo-statistics ()
11873 "Update any statistics cookie in the parent of the current headline.
11874 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11875 the entire subtree and this will travel up the hierarchy and update
11876 statistics everywhere."
11877 (let* ((prop (save-excursion (org-up-heading-safe)
11878 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11879 (recursive (or (not org-hierarchical-todo-statistics)
11880 (and prop (string-match "\\<recursive\\>" prop))))
11881 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11883 (first t)
11884 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11885 level ltoggle l1 new ndel
11886 (cnt-all 0) (cnt-done 0) is-percent kwd
11887 checkbox-beg ov ovs ove cookie-present)
11888 (catch 'exit
11889 (save-excursion
11890 (beginning-of-line 1)
11891 (setq ltoggle (funcall outline-level))
11892 ;; Three situations are to consider:
11894 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11895 ;; to the top-level ancestor on the headline;
11897 ;; 2. If parent has "recursive" property, repeat up to the
11898 ;; headline setting that property, taking inheritance into
11899 ;; account;
11901 ;; 3. Else, move up to direct parent and proceed only once.
11902 (while (and (setq level (org-up-heading-safe))
11903 (or recursive first)
11904 (>= (point) lim))
11905 (setq first nil cookie-present nil)
11906 (unless (and level
11907 (not (string-match
11908 "\\<checkbox\\>"
11909 (downcase (or (org-entry-get nil "COOKIE_DATA")
11910 "")))))
11911 (throw 'exit nil))
11912 (while (re-search-forward box-re (point-at-eol) t)
11913 (setq cnt-all 0 cnt-done 0 cookie-present t)
11914 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11915 (save-match-data
11916 (unless (outline-next-heading) (throw 'exit nil))
11917 (while (and (looking-at org-complex-heading-regexp)
11918 (> (setq l1 (length (match-string 1))) level))
11919 (setq kwd (and (or recursive (= l1 ltoggle))
11920 (match-string 2)))
11921 (if (or (eq org-provide-todo-statistics 'all-headlines)
11922 (and (listp org-provide-todo-statistics)
11923 (or (member kwd org-provide-todo-statistics)
11924 (member kwd org-done-keywords))))
11925 (setq cnt-all (1+ cnt-all))
11926 (if (eq org-provide-todo-statistics t)
11927 (and kwd (setq cnt-all (1+ cnt-all)))))
11928 (and (member kwd org-done-keywords)
11929 (setq cnt-done (1+ cnt-done)))
11930 (outline-next-heading)))
11931 (setq new
11932 (if is-percent
11933 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11934 (format "[%d/%d]" cnt-done cnt-all))
11935 ndel (- (match-end 0) checkbox-beg))
11936 ;; handle overlays when updating cookie from column view
11937 (when (setq ov (car (overlays-at checkbox-beg)))
11938 (setq ovs (overlay-start ov) ove (overlay-end ov))
11939 (delete-overlay ov))
11940 (goto-char checkbox-beg)
11941 (insert new)
11942 (delete-region (point) (+ (point) ndel))
11943 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11944 (when ov (move-overlay ov ovs ove)))
11945 (when cookie-present
11946 (run-hook-with-args 'org-after-todo-statistics-hook
11947 cnt-done (- cnt-all cnt-done))))))
11948 (run-hooks 'org-todo-statistics-hook)))
11950 (defvar org-after-todo-statistics-hook nil
11951 "Hook that is called after a TODO statistics cookie has been updated.
11952 Each function is called with two arguments: the number of not-done entries
11953 and the number of done entries.
11955 For example, the following function, when added to this hook, will switch
11956 an entry to DONE when all children are done, and back to TODO when new
11957 entries are set to a TODO status. Note that this hook is only called
11958 when there is a statistics cookie in the headline!
11960 (defun org-summary-todo (n-done n-not-done)
11961 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11962 (let (org-log-done org-log-states) ; turn off logging
11963 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11966 (defvar org-todo-statistics-hook nil
11967 "Hook that is run whenever Org thinks TODO statistics should be updated.
11968 This hook runs even if there is no statistics cookie present, in which case
11969 `org-after-todo-statistics-hook' would not run.")
11971 (defun org-todo-trigger-tag-changes (state)
11972 "Apply the changes defined in `org-todo-state-tags-triggers'."
11973 (let ((l org-todo-state-tags-triggers)
11974 changes)
11975 (when (or (not state) (equal state ""))
11976 (setq changes (append changes (cdr (assoc "" l)))))
11977 (when (and (stringp state) (> (length state) 0))
11978 (setq changes (append changes (cdr (assoc state l)))))
11979 (when (member state org-not-done-keywords)
11980 (setq changes (append changes (cdr (assoc 'todo l)))))
11981 (when (member state org-done-keywords)
11982 (setq changes (append changes (cdr (assoc 'done l)))))
11983 (dolist (c changes)
11984 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11986 (defun org-local-logging (value)
11987 "Get logging settings from a property VALUE."
11988 (let* (words w a)
11989 ;; directly set the variables, they are already local.
11990 (setq org-log-done nil
11991 org-log-repeat nil
11992 org-todo-log-states nil)
11993 (setq words (org-split-string value))
11994 (while (setq w (pop words))
11995 (cond
11996 ((setq a (assoc w org-startup-options))
11997 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11998 (set (nth 1 a) (nth 2 a))))
11999 ((setq a (org-extract-log-state-settings w))
12000 (and (member (car a) org-todo-keywords-1)
12001 (push a org-todo-log-states)))))))
12003 (defun org-get-todo-sequence-head (kwd)
12004 "Return the head of the TODO sequence to which KWD belongs.
12005 If KWD is not set, check if there is a text property remembering the
12006 right sequence."
12007 (let (p)
12008 (cond
12009 ((not kwd)
12010 (or (get-text-property (point-at-bol) 'org-todo-head)
12011 (progn
12012 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12013 nil (point-at-eol)))
12014 (get-text-property p 'org-todo-head))))
12015 ((not (member kwd org-todo-keywords-1))
12016 (car org-todo-keywords-1))
12017 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12019 (defun org-fast-todo-selection ()
12020 "Fast TODO keyword selection with single keys.
12021 Returns the new TODO keyword, or nil if no state change should occur."
12022 (let* ((fulltable org-todo-key-alist)
12023 (done-keywords org-done-keywords) ;; needed for the faces.
12024 (maxlen (apply 'max (mapcar
12025 (lambda (x)
12026 (if (stringp (car x)) (string-width (car x)) 0))
12027 fulltable)))
12028 (expert nil)
12029 (fwidth (+ maxlen 3 1 3))
12030 (ncol (/ (- (window-width) 4) fwidth))
12031 tg cnt e c tbl
12032 groups ingroup)
12033 (save-excursion
12034 (save-window-excursion
12035 (if expert
12036 (set-buffer (get-buffer-create " *Org todo*"))
12037 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12038 (erase-buffer)
12039 (org-set-local 'org-done-keywords done-keywords)
12040 (setq tbl fulltable cnt 0)
12041 (while (setq e (pop tbl))
12042 (cond
12043 ((equal e '(:startgroup))
12044 (push '() groups) (setq ingroup t)
12045 (when (not (= cnt 0))
12046 (setq cnt 0)
12047 (insert "\n"))
12048 (insert "{ "))
12049 ((equal e '(:endgroup))
12050 (setq ingroup nil cnt 0)
12051 (insert "}\n"))
12052 ((equal e '(:newline))
12053 (when (not (= cnt 0))
12054 (setq cnt 0)
12055 (insert "\n")
12056 (setq e (car tbl))
12057 (while (equal (car tbl) '(:newline))
12058 (insert "\n")
12059 (setq tbl (cdr tbl)))))
12061 (setq tg (car e) c (cdr e))
12062 (if ingroup (push tg (car groups)))
12063 (setq tg (org-add-props tg nil 'face
12064 (org-get-todo-face tg)))
12065 (if (and (= cnt 0) (not ingroup)) (insert " "))
12066 (insert "[" c "] " tg (make-string
12067 (- fwidth 4 (length tg)) ?\ ))
12068 (when (= (setq cnt (1+ cnt)) ncol)
12069 (insert "\n")
12070 (if ingroup (insert " "))
12071 (setq cnt 0)))))
12072 (insert "\n")
12073 (goto-char (point-min))
12074 (if (not expert) (org-fit-window-to-buffer))
12075 (message "[a-z..]:Set [SPC]:clear")
12076 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12077 (cond
12078 ((or (= c ?\C-g)
12079 (and (= c ?q) (not (rassoc c fulltable))))
12080 (setq quit-flag t))
12081 ((= c ?\ ) nil)
12082 ((setq e (rassoc c fulltable) tg (car e))
12084 (t (setq quit-flag t)))))))
12086 (defun org-entry-is-todo-p ()
12087 (member (org-get-todo-state) org-not-done-keywords))
12089 (defun org-entry-is-done-p ()
12090 (member (org-get-todo-state) org-done-keywords))
12092 (defun org-get-todo-state ()
12093 (save-excursion
12094 (org-back-to-heading t)
12095 (and (looking-at org-todo-line-regexp)
12096 (match-end 2)
12097 (match-string 2))))
12099 (defun org-at-date-range-p (&optional inactive-ok)
12100 "Is the cursor inside a date range?"
12101 (interactive)
12102 (save-excursion
12103 (catch 'exit
12104 (let ((pos (point)))
12105 (skip-chars-backward "^[<\r\n")
12106 (skip-chars-backward "<[")
12107 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12108 (>= (match-end 0) pos)
12109 (throw 'exit t))
12110 (skip-chars-backward "^<[\r\n")
12111 (skip-chars-backward "<[")
12112 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12113 (>= (match-end 0) pos)
12114 (throw 'exit t)))
12115 nil)))
12117 (defun org-get-repeat (&optional tagline)
12118 "Check if there is a deadline/schedule with repeater in this entry."
12119 (save-match-data
12120 (save-excursion
12121 (org-back-to-heading t)
12122 (and (re-search-forward (if tagline
12123 (concat tagline "\\s-*" org-repeat-re)
12124 org-repeat-re)
12125 (org-entry-end-position) t)
12126 (match-string-no-properties 1)))))
12128 (defvar org-last-changed-timestamp)
12129 (defvar org-last-inserted-timestamp)
12130 (defvar org-log-post-message)
12131 (defvar org-log-note-purpose)
12132 (defvar org-log-note-how)
12133 (defvar org-log-note-extra)
12134 (defun org-auto-repeat-maybe (done-word)
12135 "Check if the current headline contains a repeated deadline/schedule.
12136 If yes, set TODO state back to what it was and change the base date
12137 of repeating deadline/scheduled time stamps to new date.
12138 This function is run automatically after each state change to a DONE state."
12139 ;; last-state is dynamically scoped into this function
12140 (let* ((repeat (org-get-repeat))
12141 (aa (assoc org-last-state org-todo-kwd-alist))
12142 (interpret (nth 1 aa))
12143 (head (nth 2 aa))
12144 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12145 (msg "Entry repeats: ")
12146 (org-log-done nil)
12147 (org-todo-log-states nil)
12148 re type n what ts time to-state)
12149 (when repeat
12150 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12151 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12152 org-todo-repeat-to-state))
12153 (unless (and to-state (member to-state org-todo-keywords-1))
12154 (setq to-state (if (eq interpret 'type) org-last-state head)))
12155 (org-todo to-state)
12156 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12157 (org-entry-put nil "LAST_REPEAT" (format-time-string
12158 (org-time-stamp-format t t))))
12159 (when org-log-repeat
12160 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12161 (memq 'org-add-log-note post-command-hook))
12162 ;; OK, we are already setup for some record
12163 (if (eq org-log-repeat 'note)
12164 ;; make sure we take a note, not only a time stamp
12165 (setq org-log-note-how 'note))
12166 ;; Set up for taking a record
12167 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12168 org-last-state
12169 'findpos org-log-repeat)))
12170 (org-back-to-heading t)
12171 (org-add-planning-info nil nil 'closed)
12172 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12173 org-deadline-time-regexp "\\)\\|\\("
12174 org-ts-regexp "\\)"))
12175 (while (re-search-forward
12176 re (save-excursion (outline-next-heading) (point)) t)
12177 (setq type (if (match-end 1) org-scheduled-string
12178 (if (match-end 3) org-deadline-string "Plain:"))
12179 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12180 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12181 (setq n (string-to-number (match-string 2 ts))
12182 what (match-string 3 ts))
12183 (if (equal what "w") (setq n (* n 7) what "d"))
12184 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12185 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12186 ;; Preparation, see if we need to modify the start date for the change
12187 (when (match-end 1)
12188 (setq time (save-match-data (org-time-string-to-time ts)))
12189 (cond
12190 ((equal (match-string 1 ts) ".")
12191 ;; Shift starting date to today
12192 (org-timestamp-change
12193 (- (org-today) (time-to-days time))
12194 'day))
12195 ((equal (match-string 1 ts) "+")
12196 (let ((nshiftmax 10) (nshift 0))
12197 (while (or (= nshift 0)
12198 (<= (time-to-days time)
12199 (time-to-days (current-time))))
12200 (when (= (incf nshift) nshiftmax)
12201 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12202 (error "Abort")))
12203 (org-timestamp-change n (cdr (assoc what whata)))
12204 (org-at-timestamp-p t)
12205 (setq ts (match-string 1))
12206 (setq time (save-match-data (org-time-string-to-time ts)))))
12207 (org-timestamp-change (- n) (cdr (assoc what whata)))
12208 ;; rematch, so that we have everything in place for the real shift
12209 (org-at-timestamp-p t)
12210 (setq ts (match-string 1))
12211 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12212 (org-timestamp-change n (cdr (assoc what whata)))
12213 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12214 (setq org-log-post-message msg)
12215 (message "%s" msg))))
12217 (defun org-show-todo-tree (arg)
12218 "Make a compact tree which shows all headlines marked with TODO.
12219 The tree will show the lines where the regexp matches, and all higher
12220 headlines above the match.
12221 With a \\[universal-argument] prefix, prompt for a regexp to match.
12222 With a numeric prefix N, construct a sparse tree for the Nth element
12223 of `org-todo-keywords-1'."
12224 (interactive "P")
12225 (let ((case-fold-search nil)
12226 (kwd-re
12227 (cond ((null arg) org-not-done-regexp)
12228 ((equal arg '(4))
12229 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12230 (mapcar 'list org-todo-keywords-1))))
12231 (concat "\\("
12232 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12233 "\\)\\>")))
12234 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12235 (regexp-quote (nth (1- (prefix-numeric-value arg))
12236 org-todo-keywords-1)))
12237 (t (error "Invalid prefix argument: %s" arg)))))
12238 (message "%d TODO entries found"
12239 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12241 (defun org-deadline (&optional remove time)
12242 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12243 With argument REMOVE, remove any deadline from the item.
12244 With argument TIME, set the deadline at the corresponding date. TIME
12245 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12246 (interactive "P")
12247 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12248 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12249 'region-start-level 'region))
12250 org-loop-over-headlines-in-active-region)
12251 (org-map-entries
12252 `(org-deadline ',remove ,time)
12253 org-loop-over-headlines-in-active-region
12254 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12255 (let* ((old-date (org-entry-get nil "DEADLINE"))
12256 (repeater (and old-date
12257 (string-match
12258 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12259 old-date)
12260 (match-string 1 old-date))))
12261 (if remove
12262 (progn
12263 (when (and old-date org-log-redeadline)
12264 (org-add-log-setup 'deldeadline nil old-date 'findpos
12265 org-log-redeadline))
12266 (org-remove-timestamp-with-keyword org-deadline-string)
12267 (message "Item no longer has a deadline."))
12268 (org-add-planning-info 'deadline time 'closed)
12269 (when (and old-date org-log-redeadline
12270 (not (equal old-date
12271 (substring org-last-inserted-timestamp 1 -1))))
12272 (org-add-log-setup 'redeadline nil old-date 'findpos
12273 org-log-redeadline))
12274 (when repeater
12275 (save-excursion
12276 (org-back-to-heading t)
12277 (when (re-search-forward (concat org-deadline-string " "
12278 org-last-inserted-timestamp)
12279 (save-excursion
12280 (outline-next-heading) (point)) t)
12281 (goto-char (1- (match-end 0)))
12282 (insert " " repeater)
12283 (setq org-last-inserted-timestamp
12284 (concat (substring org-last-inserted-timestamp 0 -1)
12285 " " repeater
12286 (substring org-last-inserted-timestamp -1))))))
12287 (message "Deadline on %s" org-last-inserted-timestamp)))))
12289 (defun org-schedule (&optional remove time)
12290 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12291 With argument REMOVE, remove any scheduling date from the item.
12292 With argument TIME, scheduled at the corresponding date. TIME can
12293 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12294 (interactive "P")
12295 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12296 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12297 'region-start-level 'region))
12298 org-loop-over-headlines-in-active-region)
12299 (org-map-entries
12300 `(org-schedule ',remove ,time)
12301 org-loop-over-headlines-in-active-region
12302 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12303 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12304 (repeater (and old-date
12305 (string-match
12306 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12307 old-date)
12308 (match-string 1 old-date))))
12309 (if remove
12310 (progn
12311 (when (and old-date org-log-reschedule)
12312 (org-add-log-setup 'delschedule nil old-date 'findpos
12313 org-log-reschedule))
12314 (org-remove-timestamp-with-keyword org-scheduled-string)
12315 (message "Item is no longer scheduled."))
12316 (org-add-planning-info 'scheduled time 'closed)
12317 (when (and old-date org-log-reschedule
12318 (not (equal old-date
12319 (substring org-last-inserted-timestamp 1 -1))))
12320 (org-add-log-setup 'reschedule nil old-date 'findpos
12321 org-log-reschedule))
12322 (when repeater
12323 (save-excursion
12324 (org-back-to-heading t)
12325 (when (re-search-forward (concat org-scheduled-string " "
12326 org-last-inserted-timestamp)
12327 (save-excursion
12328 (outline-next-heading) (point)) t)
12329 (goto-char (1- (match-end 0)))
12330 (insert " " repeater)
12331 (setq org-last-inserted-timestamp
12332 (concat (substring org-last-inserted-timestamp 0 -1)
12333 " " repeater
12334 (substring org-last-inserted-timestamp -1))))))
12335 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12337 (defun org-get-scheduled-time (pom &optional inherit)
12338 "Get the scheduled time as a time tuple, of a format suitable
12339 for calling org-schedule with, or if there is no scheduling,
12340 returns nil."
12341 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12342 (when time
12343 (apply 'encode-time (org-parse-time-string time)))))
12345 (defun org-get-deadline-time (pom &optional inherit)
12346 "Get the deadline as a time tuple, of a format suitable for
12347 calling org-deadline with, or if there is no scheduling, returns
12348 nil."
12349 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12350 (when time
12351 (apply 'encode-time (org-parse-time-string time)))))
12353 (defun org-remove-timestamp-with-keyword (keyword)
12354 "Remove all time stamps with KEYWORD in the current entry."
12355 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12356 beg)
12357 (save-excursion
12358 (org-back-to-heading t)
12359 (setq beg (point))
12360 (outline-next-heading)
12361 (while (re-search-backward re beg t)
12362 (replace-match "")
12363 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12364 (equal (char-before) ?\ ))
12365 (backward-delete-char 1)
12366 (if (string-match "^[ \t]*$" (buffer-substring
12367 (point-at-bol) (point-at-eol)))
12368 (delete-region (point-at-bol)
12369 (min (point-max) (1+ (point-at-eol))))))))))
12371 (defun org-add-planning-info (what &optional time &rest remove)
12372 "Insert new timestamp with keyword in the line directly after the headline.
12373 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12374 If non is given, the user is prompted for a date.
12375 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12376 be removed."
12377 (interactive)
12378 (let (org-time-was-given org-end-time-was-given ts
12379 end default-time default-input)
12381 (catch 'exit
12382 (when (and (memq what '(scheduled deadline))
12383 (or (not time)
12384 (and (stringp time)
12385 (string-match "^[-+]+[0-9]" time))))
12386 ;; Try to get a default date/time from existing timestamp
12387 (save-excursion
12388 (org-back-to-heading t)
12389 (setq end (save-excursion (outline-next-heading) (point)))
12390 (when (re-search-forward (if (eq what 'scheduled)
12391 org-scheduled-time-regexp
12392 org-deadline-time-regexp)
12393 end t)
12394 (setq ts (match-string 1)
12395 default-time
12396 (apply 'encode-time (org-parse-time-string ts))
12397 default-input (and ts (org-get-compact-tod ts))))))
12398 (when what
12399 (setq time
12400 (if (stringp time)
12401 ;; This is a string (relative or absolute), set proper date
12402 (apply 'encode-time
12403 (org-read-date-analyze
12404 time default-time (decode-time default-time)))
12405 ;; If necessary, get the time from the user
12406 (or time (org-read-date nil 'to-time nil nil
12407 default-time default-input)))))
12409 (when (and org-insert-labeled-timestamps-at-point
12410 (member what '(scheduled deadline)))
12411 (insert
12412 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12413 (org-insert-time-stamp time org-time-was-given
12414 nil nil nil (list org-end-time-was-given))
12415 (setq what nil))
12416 (save-excursion
12417 (save-restriction
12418 (let (col list elt ts buffer-invisibility-spec)
12419 (org-back-to-heading t)
12420 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12421 (goto-char (match-end 1))
12422 (setq col (current-column))
12423 (goto-char (match-end 0))
12424 (if (eobp) (insert "\n") (forward-char 1))
12425 (when (and (not what)
12426 (not (looking-at
12427 (concat "[ \t]*"
12428 org-keyword-time-not-clock-regexp))))
12429 ;; Nothing to add, nothing to remove...... :-)
12430 (throw 'exit nil))
12431 (if (and (not (looking-at org-outline-regexp))
12432 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12433 "[^\r\n]*"))
12434 (not (equal (match-string 1) org-clock-string)))
12435 (narrow-to-region (match-beginning 0) (match-end 0))
12436 (insert-before-markers "\n")
12437 (backward-char 1)
12438 (narrow-to-region (point) (point))
12439 (and org-adapt-indentation (org-indent-to-column col)))
12440 ;; Check if we have to remove something.
12441 (setq list (cons what remove))
12442 (while list
12443 (setq elt (pop list))
12444 (when (or (and (eq elt 'scheduled)
12445 (re-search-forward org-scheduled-time-regexp nil t))
12446 (and (eq elt 'deadline)
12447 (re-search-forward org-deadline-time-regexp nil t))
12448 (and (eq elt 'closed)
12449 (re-search-forward org-closed-time-regexp nil t)))
12450 (replace-match "")
12451 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12452 (and (looking-at "[ \t]+") (replace-match ""))
12453 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12454 (when what
12455 (insert
12456 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12457 (cond ((eq what 'scheduled) org-scheduled-string)
12458 ((eq what 'deadline) org-deadline-string)
12459 ((eq what 'closed) org-closed-string))
12460 " ")
12461 (setq ts (org-insert-time-stamp
12462 time
12463 (or org-time-was-given
12464 (and (eq what 'closed) org-log-done-with-time))
12465 (eq what 'closed)
12466 nil nil (list org-end-time-was-given)))
12467 (insert
12468 (if (not (or (bolp) (eq (char-before) ?\ )
12469 (memq (char-after) '(32 10))
12470 (eobp))) " " ""))
12471 (end-of-line 1))
12472 (goto-char (point-min))
12473 (widen)
12474 (if (and (looking-at "[ \t]*\n")
12475 (equal (char-before) ?\n))
12476 (delete-region (1- (point)) (point-at-eol)))
12477 ts))))))
12479 (defvar org-log-note-marker (make-marker))
12480 (defvar org-log-note-purpose nil)
12481 (defvar org-log-note-state nil)
12482 (defvar org-log-note-previous-state nil)
12483 (defvar org-log-note-how nil)
12484 (defvar org-log-note-extra nil)
12485 (defvar org-log-note-window-configuration nil)
12486 (defvar org-log-note-return-to (make-marker))
12487 (defvar org-log-note-effective-time nil
12488 "Remembered current time so that dynamically scoped
12489 `org-extend-today-until' affects tha timestamps in state change
12490 log")
12492 (defvar org-log-post-message nil
12493 "Message to be displayed after a log note has been stored.
12494 The auto-repeater uses this.")
12496 (defun org-add-note ()
12497 "Add a note to the current entry.
12498 This is done in the same way as adding a state change note."
12499 (interactive)
12500 (org-add-log-setup 'note nil nil 'findpos nil))
12502 (defvar org-property-end-re)
12503 (defun org-add-log-setup (&optional purpose state prev-state
12504 findpos how extra)
12505 "Set up the post command hook to take a note.
12506 If this is about to TODO state change, the new state is expected in STATE.
12507 When FINDPOS is non-nil, find the correct position for the note in
12508 the current entry. If not, assume that it can be inserted at point.
12509 HOW is an indicator what kind of note should be created.
12510 EXTRA is additional text that will be inserted into the notes buffer."
12511 (let* ((org-log-into-drawer (org-log-into-drawer))
12512 (drawer (cond ((stringp org-log-into-drawer)
12513 org-log-into-drawer)
12514 (org-log-into-drawer "LOGBOOK"))))
12515 (save-restriction
12516 (save-excursion
12517 (when findpos
12518 (org-back-to-heading t)
12519 (narrow-to-region (point) (save-excursion
12520 (outline-next-heading) (point)))
12521 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12522 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12523 "[^\r\n]*\\)?"))
12524 (goto-char (match-end 0))
12525 (cond
12526 (drawer
12527 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12528 nil t)
12529 (progn
12530 (goto-char (match-end 0))
12531 (or org-log-states-order-reversed
12532 (and (re-search-forward org-property-end-re nil t)
12533 (goto-char (1- (match-beginning 0))))))
12534 (insert "\n:" drawer ":\n:END:")
12535 (beginning-of-line 0)
12536 (org-indent-line)
12537 (beginning-of-line 2)
12538 (org-indent-line)
12539 (end-of-line 0)))
12540 ((and org-log-state-notes-insert-after-drawers
12541 (save-excursion
12542 (forward-line) (looking-at org-drawer-regexp)))
12543 (forward-line)
12544 (while (looking-at org-drawer-regexp)
12545 (goto-char (match-end 0))
12546 (re-search-forward org-property-end-re (point-max) t)
12547 (forward-line))
12548 (forward-line -1)))
12549 (unless org-log-states-order-reversed
12550 (and (= (char-after) ?\n) (forward-char 1))
12551 (org-skip-over-state-notes)
12552 (skip-chars-backward " \t\n\r")))
12553 (move-marker org-log-note-marker (point))
12554 (setq org-log-note-purpose purpose
12555 org-log-note-state state
12556 org-log-note-previous-state prev-state
12557 org-log-note-how how
12558 org-log-note-extra extra
12559 org-log-note-effective-time (org-current-effective-time))
12560 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12562 (defun org-skip-over-state-notes ()
12563 "Skip past the list of State notes in an entry."
12564 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12565 (when (ignore-errors (goto-char (org-in-item-p)))
12566 (let* ((struct (org-list-struct))
12567 (prevs (org-list-prevs-alist struct)))
12568 (while (looking-at "[ \t]*- State")
12569 (goto-char (or (org-list-get-next-item (point) struct prevs)
12570 (org-list-get-item-end (point) struct)))))))
12572 (defun org-add-log-note (&optional purpose)
12573 "Pop up a window for taking a note, and add this note later at point."
12574 (remove-hook 'post-command-hook 'org-add-log-note)
12575 (setq org-log-note-window-configuration (current-window-configuration))
12576 (delete-other-windows)
12577 (move-marker org-log-note-return-to (point))
12578 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12579 (goto-char org-log-note-marker)
12580 (org-switch-to-buffer-other-window "*Org Note*")
12581 (erase-buffer)
12582 (if (memq org-log-note-how '(time state))
12583 (let (current-prefix-arg) (org-store-log-note))
12584 (let ((org-inhibit-startup t)) (org-mode))
12585 (insert (format "# Insert note for %s.
12586 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12587 (cond
12588 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12589 ((eq org-log-note-purpose 'done) "closed todo item")
12590 ((eq org-log-note-purpose 'state)
12591 (format "state change from \"%s\" to \"%s\""
12592 (or org-log-note-previous-state "")
12593 (or org-log-note-state "")))
12594 ((eq org-log-note-purpose 'reschedule)
12595 "rescheduling")
12596 ((eq org-log-note-purpose 'delschedule)
12597 "no longer scheduled")
12598 ((eq org-log-note-purpose 'redeadline)
12599 "changing deadline")
12600 ((eq org-log-note-purpose 'deldeadline)
12601 "removing deadline")
12602 ((eq org-log-note-purpose 'refile)
12603 "refiling")
12604 ((eq org-log-note-purpose 'note)
12605 "this entry")
12606 (t (error "This should not happen")))))
12607 (if org-log-note-extra (insert org-log-note-extra))
12608 (org-set-local 'org-finish-function 'org-store-log-note)
12609 (run-hooks 'org-log-buffer-setup-hook)))
12611 (defvar org-note-abort nil) ; dynamically scoped
12612 (defun org-store-log-note ()
12613 "Finish taking a log note, and insert it to where it belongs."
12614 (let ((txt (buffer-string))
12615 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12616 lines ind bul)
12617 (kill-buffer (current-buffer))
12618 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12619 (setq txt (replace-match "" t t txt)))
12620 (if (string-match "\\s-+\\'" txt)
12621 (setq txt (replace-match "" t t txt)))
12622 (setq lines (org-split-string txt "\n"))
12623 (when (and note (string-match "\\S-" note))
12624 (setq note
12625 (org-replace-escapes
12626 note
12627 (list (cons "%u" (user-login-name))
12628 (cons "%U" user-full-name)
12629 (cons "%t" (format-time-string
12630 (org-time-stamp-format 'long 'inactive)
12631 org-log-note-effective-time))
12632 (cons "%T" (format-time-string
12633 (org-time-stamp-format 'long nil)
12634 org-log-note-effective-time))
12635 (cons "%d" (format-time-string
12636 (org-time-stamp-format nil 'inactive)
12637 org-log-note-effective-time))
12638 (cons "%D" (format-time-string
12639 (org-time-stamp-format nil nil)
12640 org-log-note-effective-time))
12641 (cons "%s" (if org-log-note-state
12642 (concat "\"" org-log-note-state "\"")
12643 ""))
12644 (cons "%S" (if org-log-note-previous-state
12645 (concat "\"" org-log-note-previous-state "\"")
12646 "\"\"")))))
12647 (if lines (setq note (concat note " \\\\")))
12648 (push note lines))
12649 (when (or current-prefix-arg org-note-abort)
12650 (when org-log-into-drawer
12651 (org-remove-empty-drawer-at
12652 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12653 org-log-note-marker))
12654 (setq lines nil))
12655 (when lines
12656 (with-current-buffer (marker-buffer org-log-note-marker)
12657 (save-excursion
12658 (goto-char org-log-note-marker)
12659 (move-marker org-log-note-marker nil)
12660 (end-of-line 1)
12661 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12662 (setq ind (save-excursion
12663 (if (ignore-errors (goto-char (org-in-item-p)))
12664 (let ((struct (org-list-struct)))
12665 (org-list-get-ind
12666 (org-list-get-top-point struct) struct))
12667 (skip-chars-backward " \r\t\n")
12668 (cond
12669 ((and (org-at-heading-p)
12670 org-adapt-indentation)
12671 (1+ (org-current-level)))
12672 ((org-at-heading-p) 0)
12673 (t (org-get-indentation))))))
12674 (setq bul (org-list-bullet-string "-"))
12675 (org-indent-line-to ind)
12676 (insert bul (pop lines))
12677 (let ((ind-body (+ (length bul) ind)))
12678 (while lines
12679 (insert "\n")
12680 (org-indent-line-to ind-body)
12681 (insert (pop lines))))
12682 (message "Note stored")
12683 (org-back-to-heading t)
12684 (org-cycle-hide-drawers 'children)))))
12685 (set-window-configuration org-log-note-window-configuration)
12686 (with-current-buffer (marker-buffer org-log-note-return-to)
12687 (goto-char org-log-note-return-to))
12688 (move-marker org-log-note-return-to nil)
12689 (and org-log-post-message (message "%s" org-log-post-message)))
12691 (defun org-remove-empty-drawer-at (drawer pos)
12692 "Remove an empty drawer DRAWER at position POS.
12693 POS may also be a marker."
12694 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12695 (save-excursion
12696 (save-restriction
12697 (widen)
12698 (goto-char pos)
12699 (if (org-in-regexp
12700 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12701 (replace-match ""))))))
12703 (defvar org-ts-type nil)
12704 (defun org-sparse-tree (&optional arg type)
12705 "Create a sparse tree, prompt for the details.
12706 This command can create sparse trees. You first need to select the type
12707 of match used to create the tree:
12709 t Show all TODO entries.
12710 T Show entries with a specific TODO keyword.
12711 m Show entries selected by a tags/property match.
12712 p Enter a property name and its value (both with completion on existing
12713 names/values) and show entries with that property.
12714 r Show entries matching a regular expression (`/' can be used as well).
12715 b Show deadlines and scheduled items before a date.
12716 a Show deadlines and scheduled items after a date.
12717 d Show deadlines due within `org-deadline-warning-days'.
12718 D Show deadlines and scheduled items between a date range."
12719 (interactive "P")
12720 (let (ans kwd value ts-type)
12721 (setq type (or type org-sparse-tree-default-date-type))
12722 (setq org-ts-type type)
12723 (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"
12724 (cond ((eq type 'all) "all timestamps")
12725 ((eq type 'scheduled) "only scheduled")
12726 ((eq type 'deadline) "only deadline")
12727 ((eq type 'active) "only active timestamps")
12728 ((eq type 'inactive) "only inactive timestamps")
12729 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12730 (t "scheduled/deadline")))
12731 (setq ans (read-char-exclusive))
12732 (cond
12733 ((equal ans ?c)
12734 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12735 ((equal ans ?d)
12736 (call-interactively 'org-check-deadlines))
12737 ((equal ans ?b)
12738 (call-interactively 'org-check-before-date))
12739 ((equal ans ?a)
12740 (call-interactively 'org-check-after-date))
12741 ((equal ans ?D)
12742 (call-interactively 'org-check-dates-range))
12743 ((equal ans ?t)
12744 (call-interactively 'org-show-todo-tree))
12745 ((equal ans ?T)
12746 (org-show-todo-tree '(4)))
12747 ((member ans '(?T ?m))
12748 (call-interactively 'org-match-sparse-tree))
12749 ((member ans '(?p ?P))
12750 (setq kwd (org-icompleting-read "Property: "
12751 (mapcar 'list (org-buffer-property-keys))))
12752 (setq value (org-icompleting-read "Value: "
12753 (mapcar 'list (org-property-values kwd))))
12754 (unless (string-match "\\`{.*}\\'" value)
12755 (setq value (concat "\"" value "\"")))
12756 (org-match-sparse-tree arg (concat kwd "=" value)))
12757 ((member ans '(?r ?R ?/))
12758 (call-interactively 'org-occur))
12759 (t (error "No such sparse tree command \"%c\"" ans)))))
12761 (defvar org-occur-highlights nil
12762 "List of overlays used for occur matches.")
12763 (make-variable-buffer-local 'org-occur-highlights)
12764 (defvar org-occur-parameters nil
12765 "Parameters of the active org-occur calls.
12766 This is a list, each call to org-occur pushes as cons cell,
12767 containing the regular expression and the callback, onto the list.
12768 The list can contain several entries if `org-occur' has been called
12769 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12770 will only contain one set of parameters. When the highlights are
12771 removed (for example with `C-c C-c', or with the next edit (depending
12772 on `org-remove-highlights-with-change'), this variable is emptied
12773 as well.")
12774 (make-variable-buffer-local 'org-occur-parameters)
12776 (defun org-occur (regexp &optional keep-previous callback)
12777 "Make a compact tree which shows all matches of REGEXP.
12778 The tree will show the lines where the regexp matches, and all higher
12779 headlines above the match. It will also show the heading after the match,
12780 to make sure editing the matching entry is easy.
12781 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12782 call to `org-occur' will be kept, to allow stacking of calls to this
12783 command.
12784 If CALLBACK is non-nil, it is a function which is called to confirm
12785 that the match should indeed be shown."
12786 (interactive "sRegexp: \nP")
12787 (when (equal regexp "")
12788 (error "Regexp cannot be empty"))
12789 (unless keep-previous
12790 (org-remove-occur-highlights nil nil t))
12791 (push (cons regexp callback) org-occur-parameters)
12792 (let ((cnt 0))
12793 (save-excursion
12794 (goto-char (point-min))
12795 (if (or (not keep-previous) ; do not want to keep
12796 (not org-occur-highlights)) ; no previous matches
12797 ;; hide everything
12798 (org-overview))
12799 (while (re-search-forward regexp nil t)
12800 (when (or (not callback)
12801 (save-match-data (funcall callback)))
12802 (setq cnt (1+ cnt))
12803 (when org-highlight-sparse-tree-matches
12804 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12805 (org-show-context 'occur-tree))))
12806 (when org-remove-highlights-with-change
12807 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12808 nil 'local))
12809 (unless org-sparse-tree-open-archived-trees
12810 (org-hide-archived-subtrees (point-min) (point-max)))
12811 (run-hooks 'org-occur-hook)
12812 (if (org-called-interactively-p 'interactive)
12813 (message "%d match(es) for regexp %s" cnt regexp))
12814 cnt))
12816 (defun org-occur-next-match (&optional n reset)
12817 "Function for `next-error-function' to find sparse tree matches.
12818 N is the number of matches to move, when negative move backwards.
12819 RESET is entirely ignored - this function always goes back to the
12820 starting point when no match is found."
12821 (let* ((limit (if (< n 0) (point-min) (point-max)))
12822 (search-func (if (< n 0)
12823 'previous-single-char-property-change
12824 'next-single-char-property-change))
12825 (n (abs n))
12826 (pos (point))
12828 (catch 'exit
12829 (while (setq p1 (funcall search-func (point) 'org-type))
12830 (when (equal p1 limit)
12831 (goto-char pos)
12832 (error "No more matches"))
12833 (when (equal (get-char-property p1 'org-type) 'org-occur)
12834 (setq n (1- n))
12835 (when (= n 0)
12836 (goto-char p1)
12837 (throw 'exit (point))))
12838 (goto-char p1))
12839 (goto-char p1)
12840 (error "No more matches"))))
12842 (defun org-show-context (&optional key)
12843 "Make sure point and context are visible.
12844 How much context is shown depends upon the variables
12845 `org-show-hierarchy-above', `org-show-following-heading',
12846 `org-show-entry-below' and `org-show-siblings'."
12847 (let ((heading-p (org-at-heading-p t))
12848 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12849 (following-p (org-get-alist-option org-show-following-heading key))
12850 (entry-p (org-get-alist-option org-show-entry-below key))
12851 (siblings-p (org-get-alist-option org-show-siblings key)))
12852 ;; Show heading or entry text
12853 (if (and heading-p (not entry-p))
12854 (org-flag-heading nil) ; only show the heading
12855 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12856 (org-show-hidden-entry))) ; show entire entry
12857 (when following-p
12858 ;; Show next sibling, or heading below text
12859 (save-excursion
12860 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12861 (org-flag-heading nil))))
12862 (when siblings-p (org-show-siblings))
12863 (when hierarchy-p
12864 ;; show all higher headings, possibly with siblings
12865 (save-excursion
12866 (while (and (condition-case nil
12867 (progn (org-up-heading-all 1) t)
12868 (error nil))
12869 (not (bobp)))
12870 (org-flag-heading nil)
12871 (when siblings-p (org-show-siblings)))))
12872 (org-fix-ellipsis-at-bol)))
12874 (defvar org-reveal-start-hook nil
12875 "Hook run before revealing a location.")
12877 (defun org-reveal (&optional siblings)
12878 "Show current entry, hierarchy above it, and the following headline.
12879 This can be used to show a consistent set of context around locations
12880 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12881 not t for the search context.
12883 With optional argument SIBLINGS, on each level of the hierarchy all
12884 siblings are shown. This repairs the tree structure to what it would
12885 look like when opened with hierarchical calls to `org-cycle'.
12886 With double optional argument \\[universal-argument] \\[universal-argument], \
12887 go to the parent and show the
12888 entire tree."
12889 (interactive "P")
12890 (run-hooks 'org-reveal-start-hook)
12891 (let ((org-show-hierarchy-above t)
12892 (org-show-following-heading t)
12893 (org-show-siblings (if siblings t org-show-siblings)))
12894 (org-show-context nil))
12895 (when (equal siblings '(16))
12896 (save-excursion
12897 (when (org-up-heading-safe)
12898 (org-show-subtree)
12899 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12901 (defun org-highlight-new-match (beg end)
12902 "Highlight from BEG to END and mark the highlight is an occur headline."
12903 (let ((ov (make-overlay beg end)))
12904 (overlay-put ov 'face 'secondary-selection)
12905 (overlay-put ov 'org-type 'org-occur)
12906 (push ov org-occur-highlights)))
12908 (defun org-remove-occur-highlights (&optional beg end noremove)
12909 "Remove the occur highlights from the buffer.
12910 BEG and END are ignored. If NOREMOVE is nil, remove this function
12911 from the `before-change-functions' in the current buffer."
12912 (interactive)
12913 (unless org-inhibit-highlight-removal
12914 (mapc 'delete-overlay org-occur-highlights)
12915 (setq org-occur-highlights nil)
12916 (setq org-occur-parameters nil)
12917 (unless noremove
12918 (remove-hook 'before-change-functions
12919 'org-remove-occur-highlights 'local))))
12921 ;;;; Priorities
12923 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12924 "Regular expression matching the priority indicator.")
12926 (defvar org-remove-priority-next-time nil)
12928 (defun org-priority-up ()
12929 "Increase the priority of the current item."
12930 (interactive)
12931 (org-priority 'up))
12933 (defun org-priority-down ()
12934 "Decrease the priority of the current item."
12935 (interactive)
12936 (org-priority 'down))
12938 (defun org-priority (&optional action show)
12939 "Change the priority of an item.
12940 ACTION can be `set', `up', `down', or a character."
12941 (interactive "P")
12942 (if (equal action '(4))
12943 (org-show-priority)
12944 (unless org-enable-priority-commands
12945 (error "Priority commands are disabled"))
12946 (setq action (or action 'set))
12947 (let (current new news have remove)
12948 (save-excursion
12949 (org-back-to-heading t)
12950 (if (looking-at org-priority-regexp)
12951 (setq current (string-to-char (match-string 2))
12952 have t))
12953 (cond
12954 ((eq action 'remove)
12955 (setq remove t new ?\ ))
12956 ((or (eq action 'set)
12957 (if (featurep 'xemacs) (characterp action) (integerp action)))
12958 (if (not (eq action 'set))
12959 (setq new action)
12960 (message "Priority %c-%c, SPC to remove: "
12961 org-highest-priority org-lowest-priority)
12962 (save-match-data
12963 (setq new (read-char-exclusive))))
12964 (if (and (= (upcase org-highest-priority) org-highest-priority)
12965 (= (upcase org-lowest-priority) org-lowest-priority))
12966 (setq new (upcase new)))
12967 (cond ((equal new ?\ ) (setq remove t))
12968 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12969 (error "Priority must be between `%c' and `%c'"
12970 org-highest-priority org-lowest-priority))))
12971 ((eq action 'up)
12972 (setq new (if have
12973 (1- current) ; normal cycling
12974 ;; last priority was empty
12975 (if (eq last-command this-command)
12976 org-lowest-priority ; wrap around empty to lowest
12977 ;; default
12978 (if org-priority-start-cycle-with-default
12979 org-default-priority
12980 (1- org-default-priority))))))
12981 ((eq action 'down)
12982 (setq new (if have
12983 (1+ current) ; normal cycling
12984 ;; last priority was empty
12985 (if (eq last-command this-command)
12986 org-highest-priority ; wrap around empty to highest
12987 ;; default
12988 (if org-priority-start-cycle-with-default
12989 org-default-priority
12990 (1+ org-default-priority))))))
12991 (t (error "Invalid action")))
12992 (if (or (< (upcase new) org-highest-priority)
12993 (> (upcase new) org-lowest-priority))
12994 (if (and (memq action '(up down))
12995 (not have) (not (eq last-command this-command)))
12996 ;; `new' is from default priority
12997 (error
12998 "The default can not be set, see `org-default-priority' why")
12999 ;; normal cycling: `new' is beyond highest/lowest priority
13000 ;; and is wrapped around to the empty priority
13001 (setq remove t)))
13002 (setq news (format "%c" new))
13003 (if have
13004 (if remove
13005 (replace-match "" t t nil 1)
13006 (replace-match news t t nil 2))
13007 (if remove
13008 (error "No priority cookie found in line")
13009 (let ((case-fold-search nil))
13010 (looking-at org-todo-line-regexp))
13011 (if (match-end 2)
13012 (progn
13013 (goto-char (match-end 2))
13014 (insert " [#" news "]"))
13015 (goto-char (match-beginning 3))
13016 (insert "[#" news "] "))))
13017 (org-preserve-lc (org-set-tags nil 'align)))
13018 (if remove
13019 (message "Priority removed")
13020 (message "Priority of current item set to %s" news)))))
13022 (defun org-show-priority ()
13023 "Show the priority of the current item.
13024 This priority is composed of the main priority given with the [#A] cookies,
13025 and by additional input from the age of a schedules or deadline entry."
13026 (interactive)
13027 (let ((pri (if (eq major-mode 'org-agenda-mode)
13028 (org-get-at-bol 'priority)
13029 (save-excursion
13030 (save-match-data
13031 (beginning-of-line)
13032 (and (looking-at org-heading-regexp)
13033 (org-get-priority (match-string 0))))))))
13034 (message "Priority is %d" (if pri pri -1000))))
13036 (defun org-get-priority (s)
13037 "Find priority cookie and return priority."
13038 (save-match-data
13039 (if (functionp org-get-priority-function)
13040 (funcall org-get-priority-function)
13041 (if (not (string-match org-priority-regexp s))
13042 (* 1000 (- org-lowest-priority org-default-priority))
13043 (* 1000 (- org-lowest-priority
13044 (string-to-char (match-string 2 s))))))))
13046 ;;;; Tags
13048 (defvar org-agenda-archives-mode)
13049 (defvar org-map-continue-from nil
13050 "Position from where mapping should continue.
13051 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13053 (defvar org-scanner-tags nil
13054 "The current tag list while the tags scanner is running.")
13055 (defvar org-trust-scanner-tags nil
13056 "Should `org-get-tags-at' use the tags for the scanner.
13057 This is for internal dynamical scoping only.
13058 When this is non-nil, the function `org-get-tags-at' will return the value
13059 of `org-scanner-tags' instead of building the list by itself. This
13060 can lead to large speed-ups when the tags scanner is used in a file with
13061 many entries, and when the list of tags is retrieved, for example to
13062 obtain a list of properties. Building the tags list for each entry in such
13063 a file becomes an N^2 operation - but with this variable set, it scales
13064 as N.")
13066 (defun org-scan-tags (action matcher todo-only &optional start-level)
13067 "Scan headline tags with inheritance and produce output ACTION.
13069 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13070 or `agenda' to produce an entry list for an agenda view. It can also be
13071 a Lisp form or a function that should be called at each matched headline, in
13072 this case the return value is a list of all return values from these calls.
13074 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13075 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13076 only lines with a not-done TODO keyword are included in the output.
13077 This should be the same variable that was scoped into
13078 and set by `org-make-tags-matcher' when it constructed MATCHER.
13080 START-LEVEL can be a string with asterisks, reducing the scope to
13081 headlines matching this string."
13082 (require 'org-agenda)
13083 (let* ((re (concat "^"
13084 (if start-level
13085 ;; Get the correct level to match
13086 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13087 org-outline-regexp)
13088 " *\\(\\<\\("
13089 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13090 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13091 (props (list 'face 'default
13092 'done-face 'org-agenda-done
13093 'undone-face 'default
13094 'mouse-face 'highlight
13095 'org-not-done-regexp org-not-done-regexp
13096 'org-todo-regexp org-todo-regexp
13097 'org-complex-heading-regexp org-complex-heading-regexp
13098 'help-echo
13099 (format "mouse-2 or RET jump to org file %s"
13100 (abbreviate-file-name
13101 (or (buffer-file-name (buffer-base-buffer))
13102 (buffer-name (buffer-base-buffer)))))))
13103 (case-fold-search nil)
13104 (org-map-continue-from nil)
13105 lspos tags tags-list
13106 (tags-alist (list (cons 0 org-file-tags)))
13107 (llast 0) rtn rtn1 level category i txt
13108 todo marker entry priority)
13109 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13110 (setq action (list 'lambda nil action)))
13111 (save-excursion
13112 (goto-char (point-min))
13113 (when (eq action 'sparse-tree)
13114 (org-overview)
13115 (org-remove-occur-highlights))
13116 (while (re-search-forward re nil t)
13117 (setq org-map-continue-from nil)
13118 (catch :skip
13119 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13120 tags (if (match-end 4) (org-match-string-no-properties 4)))
13121 (goto-char (setq lspos (match-beginning 0)))
13122 (setq level (org-reduced-level (funcall outline-level))
13123 category (org-get-category))
13124 (setq i llast llast level)
13125 ;; remove tag lists from same and sublevels
13126 (while (>= i level)
13127 (when (setq entry (assoc i tags-alist))
13128 (setq tags-alist (delete entry tags-alist)))
13129 (setq i (1- i)))
13130 ;; add the next tags
13131 (when tags
13132 (setq tags (org-split-string tags ":")
13133 tags-alist
13134 (cons (cons level tags) tags-alist)))
13135 ;; compile tags for current headline
13136 (setq tags-list
13137 (if org-use-tag-inheritance
13138 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13139 tags)
13140 org-scanner-tags tags-list)
13141 (when org-use-tag-inheritance
13142 (setcdr (car tags-alist)
13143 (mapcar (lambda (x)
13144 (setq x (copy-sequence x))
13145 (org-add-prop-inherited x))
13146 (cdar tags-alist))))
13147 (when (and tags org-use-tag-inheritance
13148 (or (not (eq t org-use-tag-inheritance))
13149 org-tags-exclude-from-inheritance))
13150 ;; selective inheritance, remove uninherited ones
13151 (setcdr (car tags-alist)
13152 (org-remove-uninherited-tags (cdar tags-alist))))
13153 (when (and
13155 ;; eval matcher only when the todo condition is OK
13156 (and (or (not todo-only) (member todo org-not-done-keywords))
13157 (let ((case-fold-search t) (org-trust-scanner-tags t))
13158 (eval matcher)))
13160 ;; Call the skipper, but return t if it does not skip,
13161 ;; so that the `and' form continues evaluating
13162 (progn
13163 (unless (eq action 'sparse-tree) (org-agenda-skip))
13166 ;; Check if timestamps are deselecting this entry
13167 (or (not todo-only)
13168 (and (member todo org-not-done-keywords)
13169 (or (not org-agenda-tags-todo-honor-ignore-options)
13170 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13172 ;; select this headline
13173 (cond
13174 ((eq action 'sparse-tree)
13175 (and org-highlight-sparse-tree-matches
13176 (org-get-heading) (match-end 0)
13177 (org-highlight-new-match
13178 (match-beginning 1) (match-end 1)))
13179 (org-show-context 'tags-tree))
13180 ((eq action 'agenda)
13181 (setq txt (org-agenda-format-item
13183 (concat
13184 (if (eq org-tags-match-list-sublevels 'indented)
13185 (make-string (1- level) ?.) "")
13186 (org-get-heading))
13187 category
13188 tags-list)
13189 priority (org-get-priority txt))
13190 (goto-char lspos)
13191 (setq marker (org-agenda-new-marker))
13192 (org-add-props txt props
13193 'org-marker marker 'org-hd-marker marker 'org-category category
13194 'todo-state todo
13195 'priority priority 'type "tagsmatch")
13196 (push txt rtn))
13197 ((functionp action)
13198 (setq org-map-continue-from nil)
13199 (save-excursion
13200 (setq rtn1 (funcall action))
13201 (push rtn1 rtn)))
13202 (t (error "Invalid action")))
13204 ;; if we are to skip sublevels, jump to end of subtree
13205 (unless org-tags-match-list-sublevels
13206 (org-end-of-subtree t)
13207 (backward-char 1))))
13208 ;; Get the correct position from where to continue
13209 (if org-map-continue-from
13210 (goto-char org-map-continue-from)
13211 (and (= (point) lspos) (end-of-line 1)))))
13212 (when (and (eq action 'sparse-tree)
13213 (not org-sparse-tree-open-archived-trees))
13214 (org-hide-archived-subtrees (point-min) (point-max)))
13215 (nreverse rtn)))
13217 (defun org-remove-uninherited-tags (tags)
13218 "Remove all tags that are not inherited from the list TAGS."
13219 (cond
13220 ((eq org-use-tag-inheritance t)
13221 (if org-tags-exclude-from-inheritance
13222 (org-delete-all org-tags-exclude-from-inheritance tags)
13223 tags))
13224 ((not org-use-tag-inheritance) nil)
13225 ((stringp org-use-tag-inheritance)
13226 (delq nil (mapcar
13227 (lambda (x)
13228 (if (and (string-match org-use-tag-inheritance x)
13229 (not (member x org-tags-exclude-from-inheritance)))
13230 x nil))
13231 tags)))
13232 ((listp org-use-tag-inheritance)
13233 (delq nil (mapcar
13234 (lambda (x)
13235 (if (member x org-use-tag-inheritance) x nil))
13236 tags)))))
13238 (defun org-match-sparse-tree (&optional todo-only match)
13239 "Create a sparse tree according to tags string MATCH.
13240 MATCH can contain positive and negative selection of tags, like
13241 \"+WORK+URGENT-WITHBOSS\".
13242 If optional argument TODO-ONLY is non-nil, only select lines that are
13243 also TODO lines."
13244 (interactive "P")
13245 (org-agenda-prepare-buffers (list (current-buffer)))
13246 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13248 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13250 (defvar org-cached-props nil)
13251 (defun org-cached-entry-get (pom property)
13252 (if (or (eq t org-use-property-inheritance)
13253 (and (stringp org-use-property-inheritance)
13254 (string-match org-use-property-inheritance property))
13255 (and (listp org-use-property-inheritance)
13256 (member property org-use-property-inheritance)))
13257 ;; Caching is not possible, check it directly
13258 (org-entry-get pom property 'inherit)
13259 ;; Get all properties, so that we can do complicated checks easily
13260 (cdr (assoc property (or org-cached-props
13261 (setq org-cached-props
13262 (org-entry-properties pom)))))))
13264 (defun org-global-tags-completion-table (&optional files)
13265 "Return the list of all tags in all agenda buffer/files.
13266 Optional FILES argument is a list of files which can be used
13267 instead of the agenda files."
13268 (save-excursion
13269 (org-uniquify
13270 (delq nil
13271 (apply 'append
13272 (mapcar
13273 (lambda (file)
13274 (set-buffer (find-file-noselect file))
13275 (append (org-get-buffer-tags)
13276 (mapcar (lambda (x) (if (stringp (car-safe x))
13277 (list (car-safe x)) nil))
13278 org-tag-alist)))
13279 (if (and files (car files))
13280 files
13281 (org-agenda-files))))))))
13283 (defun org-make-tags-matcher (match)
13284 "Create the TAGS/TODO matcher form for the selection string MATCH.
13286 The variable `todo-only' is scoped dynamically into this function.
13287 It will be set to t if the matcher restricts matching to TODO entries,
13288 otherwise will not be touched.
13290 Returns a cons of the selection string MATCH and the constructed
13291 lisp form implementing the matcher. The matcher is to be evaluated
13292 at an Org entry, with point on the headline, and returns t if the
13293 entry matches the selection string MATCH. The returned lisp form
13294 references two variables with information about the entry, which
13295 must be bound around the form's evaluation: todo, the TODO keyword
13296 at the entry (or nil of none); and tags-list, the list of all tags
13297 at the entry including inherited ones. Additionally, the category
13298 of the entry (if any) must be specified as the text property
13299 'org-category on the headline.
13301 See also `org-scan-tags'.
13303 (declare (special todo-only))
13304 (unless (boundp 'todo-only)
13305 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13306 (unless match
13307 ;; Get a new match request, with completion
13308 (let ((org-last-tags-completion-table
13309 (org-global-tags-completion-table)))
13310 (setq match (org-completing-read-no-i
13311 "Match: " 'org-tags-completion-function nil nil nil
13312 'org-tags-history))))
13314 ;; Parse the string and create a lisp form
13315 (let ((match0 match)
13316 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13317 minus tag mm
13318 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13319 orterms term orlist re-p str-p level-p level-op time-p
13320 prop-p pn pv po gv rest)
13321 (if (string-match "/+" match)
13322 ;; match contains also a todo-matching request
13323 (progn
13324 (setq tagsmatch (substring match 0 (match-beginning 0))
13325 todomatch (substring match (match-end 0)))
13326 (if (string-match "^!" todomatch)
13327 (setq todo-only t todomatch (substring todomatch 1)))
13328 (if (string-match "^\\s-*$" todomatch)
13329 (setq todomatch nil)))
13330 ;; only matching tags
13331 (setq tagsmatch match todomatch nil))
13333 ;; Make the tags matcher
13334 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13335 (setq tagsmatcher t)
13336 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13337 (while (setq term (pop orterms))
13338 (while (and (equal (substring term -1) "\\") orterms)
13339 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13340 (while (string-match re term)
13341 (setq rest (substring term (match-end 0))
13342 minus (and (match-end 1)
13343 (equal (match-string 1 term) "-"))
13344 tag (save-match-data (replace-regexp-in-string
13345 "\\\\-" "-"
13346 (match-string 2 term)))
13347 re-p (equal (string-to-char tag) ?{)
13348 level-p (match-end 4)
13349 prop-p (match-end 5)
13350 mm (cond
13351 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13352 (level-p
13353 (setq level-op (org-op-to-function (match-string 3 term)))
13354 `(,level-op level ,(string-to-number
13355 (match-string 4 term))))
13356 (prop-p
13357 (setq pn (match-string 5 term)
13358 po (match-string 6 term)
13359 pv (match-string 7 term)
13360 re-p (equal (string-to-char pv) ?{)
13361 str-p (equal (string-to-char pv) ?\")
13362 time-p (save-match-data
13363 (string-match "^\"[[<].*[]>]\"$" pv))
13364 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13365 (if time-p (setq pv (org-matcher-time pv)))
13366 (setq po (org-op-to-function po (if time-p 'time str-p)))
13367 (cond
13368 ((equal pn "CATEGORY")
13369 (setq gv '(get-text-property (point) 'org-category)))
13370 ((equal pn "TODO")
13371 (setq gv 'todo))
13373 (setq gv `(org-cached-entry-get nil ,pn))))
13374 (if re-p
13375 (if (eq po 'org<>)
13376 `(not (string-match ,pv (or ,gv "")))
13377 `(string-match ,pv (or ,gv "")))
13378 (if str-p
13379 `(,po (or ,gv "") ,pv)
13380 `(,po (string-to-number (or ,gv ""))
13381 ,(string-to-number pv) ))))
13382 (t `(member ,tag tags-list)))
13383 mm (if minus (list 'not mm) mm)
13384 term rest)
13385 (push mm tagsmatcher))
13386 (push (if (> (length tagsmatcher) 1)
13387 (cons 'and tagsmatcher)
13388 (car tagsmatcher))
13389 orlist)
13390 (setq tagsmatcher nil))
13391 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13392 (setq tagsmatcher
13393 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13394 ;; Make the todo matcher
13395 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13396 (setq todomatcher t)
13397 (setq orterms (org-split-string todomatch "|") orlist nil)
13398 (while (setq term (pop orterms))
13399 (while (string-match re term)
13400 (setq minus (and (match-end 1)
13401 (equal (match-string 1 term) "-"))
13402 kwd (match-string 2 term)
13403 re-p (equal (string-to-char kwd) ?{)
13404 term (substring term (match-end 0))
13405 mm (if re-p
13406 `(string-match ,(substring kwd 1 -1) todo)
13407 (list 'equal 'todo kwd))
13408 mm (if minus (list 'not mm) mm))
13409 (push mm todomatcher))
13410 (push (if (> (length todomatcher) 1)
13411 (cons 'and todomatcher)
13412 (car todomatcher))
13413 orlist)
13414 (setq todomatcher nil))
13415 (setq todomatcher (if (> (length orlist) 1)
13416 (cons 'or orlist) (car orlist))))
13418 ;; Return the string and lisp forms of the matcher
13419 (setq matcher (if todomatcher
13420 (list 'and tagsmatcher todomatcher)
13421 tagsmatcher))
13422 (when todo-only
13423 (setq matcher (list 'and '(member todo org-not-done-keywords)
13424 matcher)))
13425 (cons match0 matcher)))
13427 (defun org-op-to-function (op &optional stringp)
13428 "Turn an operator into the appropriate function."
13429 (setq op
13430 (cond
13431 ((equal op "<" ) '(< string< org-time<))
13432 ((equal op ">" ) '(> org-string> org-time>))
13433 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13434 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13435 ((member op '("=" "==")) '(= string= org-time=))
13436 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13437 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13439 (defun org<> (a b) (not (= a b)))
13440 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13441 (defun org-string>= (a b) (not (string< a b)))
13442 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13443 (defun org-string<> (a b) (not (string= a b)))
13444 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13445 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13446 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13447 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13448 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13449 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13450 (defun org-2ft (s)
13451 "Convert S to a floating point time.
13452 If S is already a number, just return it. If it is a string, parse
13453 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13454 (cond
13455 ((numberp s) s)
13456 ((stringp s)
13457 (condition-case nil
13458 (float-time (apply 'encode-time (org-parse-time-string s)))
13459 (error 0.)))
13460 (t 0.)))
13462 (defun org-time-today ()
13463 "Time in seconds today at 0:00.
13464 Returns the float number of seconds since the beginning of the
13465 epoch to the beginning of today (00:00)."
13466 (float-time (apply 'encode-time
13467 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13469 (defun org-matcher-time (s)
13470 "Interpret a time comparison value."
13471 (save-match-data
13472 (cond
13473 ((string= s "<now>") (float-time))
13474 ((string= s "<today>") (org-time-today))
13475 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13476 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13477 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13478 (+ (org-time-today)
13479 (* (string-to-number (match-string 1 s))
13480 (cdr (assoc (match-string 2 s)
13481 '(("d" . 86400.0) ("w" . 604800.0)
13482 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13483 (t (org-2ft s)))))
13485 (defun org-match-any-p (re list)
13486 "Does re match any element of list?"
13487 (setq list (mapcar (lambda (x) (string-match re x)) list))
13488 (delq nil list))
13490 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13491 (defvar org-tags-overlay (make-overlay 1 1))
13492 (org-detach-overlay org-tags-overlay)
13494 (defun org-get-local-tags-at (&optional pos)
13495 "Get a list of tags defined in the current headline."
13496 (org-get-tags-at pos 'local))
13498 (defun org-get-local-tags ()
13499 "Get a list of tags defined in the current headline."
13500 (org-get-tags-at nil 'local))
13502 (defun org-get-tags-at (&optional pos local)
13503 "Get a list of all headline tags applicable at POS.
13504 POS defaults to point. If tags are inherited, the list contains
13505 the targets in the same sequence as the headlines appear, i.e.
13506 the tags of the current headline come last.
13507 When LOCAL is non-nil, only return tags from the current headline,
13508 ignore inherited ones."
13509 (interactive)
13510 (if (and org-trust-scanner-tags
13511 (or (not pos) (equal pos (point)))
13512 (not local))
13513 org-scanner-tags
13514 (let (tags ltags lastpos parent)
13515 (save-excursion
13516 (save-restriction
13517 (widen)
13518 (goto-char (or pos (point)))
13519 (save-match-data
13520 (catch 'done
13521 (condition-case nil
13522 (progn
13523 (org-back-to-heading t)
13524 (while (not (equal lastpos (point)))
13525 (setq lastpos (point))
13526 (when (looking-at
13527 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13528 (setq ltags (org-split-string
13529 (org-match-string-no-properties 1) ":"))
13530 (when parent
13531 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13532 (setq tags (append
13533 (if parent
13534 (org-remove-uninherited-tags ltags)
13535 ltags)
13536 tags)))
13537 (or org-use-tag-inheritance (throw 'done t))
13538 (if local (throw 'done t))
13539 (or (org-up-heading-safe) (error nil))
13540 (setq parent t)))
13541 (error nil)))))
13542 (if local
13543 tags
13544 (reverse (delete-dups
13545 (reverse (append
13546 (org-remove-uninherited-tags
13547 org-file-tags) tags)))))))))
13549 (defun org-add-prop-inherited (s)
13550 (add-text-properties 0 (length s) '(inherited t) s)
13553 (defun org-toggle-tag (tag &optional onoff)
13554 "Toggle the tag TAG for the current line.
13555 If ONOFF is `on' or `off', don't toggle but set to this state."
13556 (let (res current)
13557 (save-excursion
13558 (org-back-to-heading t)
13559 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13560 (point-at-eol) t)
13561 (progn
13562 (setq current (match-string 1))
13563 (replace-match ""))
13564 (setq current ""))
13565 (setq current (nreverse (org-split-string current ":")))
13566 (cond
13567 ((eq onoff 'on)
13568 (setq res t)
13569 (or (member tag current) (push tag current)))
13570 ((eq onoff 'off)
13571 (or (not (member tag current)) (setq current (delete tag current))))
13572 (t (if (member tag current)
13573 (setq current (delete tag current))
13574 (setq res t)
13575 (push tag current))))
13576 (end-of-line 1)
13577 (if current
13578 (progn
13579 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13580 (org-set-tags nil t))
13581 (delete-horizontal-space))
13582 (run-hooks 'org-after-tags-change-hook))
13583 res))
13585 (defun org-align-tags-here (to-col)
13586 ;; Assumes that this is a headline
13587 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13588 (beginning-of-line 1)
13589 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13590 (< pos (match-beginning 2)))
13591 (progn
13592 (setq tags-l (- (match-end 2) (match-beginning 2)))
13593 (goto-char (match-beginning 1))
13594 (insert " ")
13595 (delete-region (point) (1+ (match-beginning 2)))
13596 (setq ncol (max (current-column)
13597 (1+ col)
13598 (if (> to-col 0)
13599 to-col
13600 (- (abs to-col) tags-l))))
13601 (setq p (point))
13602 (insert (make-string (- ncol (current-column)) ?\ ))
13603 (setq ncol (current-column))
13604 (when indent-tabs-mode (tabify p (point-at-eol)))
13605 (org-move-to-column (min ncol col) t))
13606 (goto-char pos))))
13608 (defun org-set-tags-command (&optional arg just-align)
13609 "Call the set-tags command for the current entry."
13610 (interactive "P")
13611 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13612 (org-set-tags arg just-align)
13613 (save-excursion
13614 (unless (and (org-region-active-p)
13615 org-loop-over-headlines-in-active-region)
13616 (org-back-to-heading t))
13617 (org-set-tags arg just-align))))
13619 (defun org-set-tags-to (data)
13620 "Set the tags of the current entry to DATA, replacing the current tags.
13621 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13622 If DATA is nil or the empty string, any tags will be removed."
13623 (interactive "sTags: ")
13624 (setq data
13625 (cond
13626 ((eq data nil) "")
13627 ((equal data "") "")
13628 ((stringp data)
13629 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13630 ":"))
13631 ((listp data)
13632 (concat ":" (mapconcat 'identity data ":") ":"))))
13633 (when data
13634 (save-excursion
13635 (org-back-to-heading t)
13636 (when (looking-at org-complex-heading-regexp)
13637 (if (match-end 5)
13638 (progn
13639 (goto-char (match-beginning 5))
13640 (insert data)
13641 (delete-region (point) (point-at-eol))
13642 (org-set-tags nil 'align))
13643 (goto-char (point-at-eol))
13644 (insert " " data)
13645 (org-set-tags nil 'align)))
13646 (beginning-of-line 1)
13647 (if (looking-at ".*?\\([ \t]+\\)$")
13648 (delete-region (match-beginning 1) (match-end 1))))))
13650 (defun org-align-all-tags ()
13651 "Align the tags i all headings."
13652 (interactive)
13653 (save-excursion
13654 (or (ignore-errors (org-back-to-heading t))
13655 (outline-next-heading))
13656 (if (org-at-heading-p)
13657 (org-set-tags t)
13658 (message "No headings"))))
13660 (defvar org-indent-indentation-per-level)
13661 (defun org-set-tags (&optional arg just-align)
13662 "Set the tags for the current headline.
13663 With prefix ARG, realign all tags in headings in the current buffer."
13664 (interactive "P")
13665 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13666 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13667 'region-start-level 'region))
13668 org-loop-over-headlines-in-active-region)
13669 (org-map-entries
13670 ;; We don't use ARG and JUST-ALIGN here these args are not
13671 ;; useful when looping over headlines
13672 `(org-set-tags)
13673 org-loop-over-headlines-in-active-region
13674 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13675 (let* ((re org-outline-regexp-bol)
13676 (current (unless arg (org-get-tags-string)))
13677 (col (current-column))
13678 (org-setting-tags t)
13679 table current-tags inherited-tags ; computed below when needed
13680 tags p0 c0 c1 rpl di tc level)
13681 (if arg
13682 (save-excursion
13683 (goto-char (point-min))
13684 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13685 (while (re-search-forward re nil t)
13686 (org-set-tags nil t)
13687 (end-of-line 1)))
13688 (message "All tags realigned to column %d" org-tags-column))
13689 (if just-align
13690 (setq tags current)
13691 ;; Get a new set of tags from the user
13692 (save-excursion
13693 (setq table (append org-tag-persistent-alist
13694 (or org-tag-alist (org-get-buffer-tags))
13695 (and
13696 org-complete-tags-always-offer-all-agenda-tags
13697 (org-global-tags-completion-table
13698 (org-agenda-files))))
13699 org-last-tags-completion-table table
13700 current-tags (org-split-string current ":")
13701 inherited-tags (nreverse
13702 (nthcdr (length current-tags)
13703 (nreverse (org-get-tags-at))))
13704 tags
13705 (if (or (eq t org-use-fast-tag-selection)
13706 (and org-use-fast-tag-selection
13707 (delq nil (mapcar 'cdr table))))
13708 (org-fast-tag-selection
13709 current-tags inherited-tags table
13710 (if org-fast-tag-selection-include-todo
13711 org-todo-key-alist))
13712 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13713 (org-trim
13714 (org-icompleting-read "Tags: "
13715 'org-tags-completion-function
13716 nil nil current 'org-tags-history))))))
13717 (while (string-match "[-+&]+" tags)
13718 ;; No boolean logic, just a list
13719 (setq tags (replace-match ":" t t tags))))
13721 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13723 (if org-tags-sort-function
13724 (setq tags (mapconcat 'identity
13725 (sort (org-split-string
13726 tags (org-re "[^[:alnum:]_@#%]+"))
13727 org-tags-sort-function) ":")))
13729 (if (string-match "\\`[\t ]*\\'" tags)
13730 (setq tags "")
13731 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13732 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13734 ;; Insert new tags at the correct column
13735 (beginning-of-line 1)
13736 (setq level (or (and (looking-at org-outline-regexp)
13737 (- (match-end 0) (point) 1))
13739 (cond
13740 ((and (equal current "") (equal tags "")))
13741 ((re-search-forward
13742 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13743 (point-at-eol) t)
13744 (if (equal tags "")
13745 (setq rpl "")
13746 (goto-char (match-beginning 0))
13747 (setq c0 (current-column)
13748 ;; compute offset for the case of org-indent-mode active
13749 di (if org-indent-mode
13750 (* (1- org-indent-indentation-per-level) (1- level))
13752 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13753 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13754 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13755 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13756 (replace-match rpl t t)
13757 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13758 tags)
13759 (t (error "Tags alignment failed")))
13760 (org-move-to-column col)
13761 (unless just-align
13762 (run-hooks 'org-after-tags-change-hook))))))
13764 (defun org-change-tag-in-region (beg end tag off)
13765 "Add or remove TAG for each entry in the region.
13766 This works in the agenda, and also in an org-mode buffer."
13767 (interactive
13768 (list (region-beginning) (region-end)
13769 (let ((org-last-tags-completion-table
13770 (if (derived-mode-p 'org-mode)
13771 (org-get-buffer-tags)
13772 (org-global-tags-completion-table))))
13773 (org-icompleting-read
13774 "Tag: " 'org-tags-completion-function nil nil nil
13775 'org-tags-history))
13776 (progn
13777 (message "[s]et or [r]emove? ")
13778 (equal (read-char-exclusive) ?r))))
13779 (if (fboundp 'deactivate-mark) (deactivate-mark))
13780 (let ((agendap (equal major-mode 'org-agenda-mode))
13781 l1 l2 m buf pos newhead (cnt 0))
13782 (goto-char end)
13783 (setq l2 (1- (org-current-line)))
13784 (goto-char beg)
13785 (setq l1 (org-current-line))
13786 (loop for l from l1 to l2 do
13787 (org-goto-line l)
13788 (setq m (get-text-property (point) 'org-hd-marker))
13789 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13790 (and agendap m))
13791 (setq buf (if agendap (marker-buffer m) (current-buffer))
13792 pos (if agendap m (point)))
13793 (with-current-buffer buf
13794 (save-excursion
13795 (save-restriction
13796 (goto-char pos)
13797 (setq cnt (1+ cnt))
13798 (org-toggle-tag tag (if off 'off 'on))
13799 (setq newhead (org-get-heading)))))
13800 (and agendap (org-agenda-change-all-lines newhead m))))
13801 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13803 (defun org-tags-completion-function (string predicate &optional flag)
13804 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13805 (confirm (lambda (x) (stringp (car x)))))
13806 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13807 (setq s1 (match-string 1 string)
13808 s2 (match-string 2 string))
13809 (setq s1 "" s2 string))
13810 (cond
13811 ((eq flag nil)
13812 ;; try completion
13813 (setq rtn (try-completion s2 ctable confirm))
13814 (if (stringp rtn)
13815 (setq rtn
13816 (concat s1 s2 (substring rtn (length s2))
13817 (if (and org-add-colon-after-tag-completion
13818 (assoc rtn ctable))
13819 ":" ""))))
13820 rtn)
13821 ((eq flag t)
13822 ;; all-completions
13823 (all-completions s2 ctable confirm)
13825 ((eq flag 'lambda)
13826 ;; exact match?
13827 (assoc s2 ctable)))
13830 (defun org-fast-tag-insert (kwd tags face &optional end)
13831 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13832 (insert (format "%-12s" (concat kwd ":"))
13833 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13834 (or end "")))
13836 (defun org-fast-tag-show-exit (flag)
13837 (save-excursion
13838 (org-goto-line 3)
13839 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13840 (replace-match ""))
13841 (when flag
13842 (end-of-line 1)
13843 (org-move-to-column (- (window-width) 19) t)
13844 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13846 (defun org-set-current-tags-overlay (current prefix)
13847 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13848 (if (featurep 'xemacs)
13849 (org-overlay-display org-tags-overlay (concat prefix s)
13850 'secondary-selection)
13851 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13852 (org-overlay-display org-tags-overlay (concat prefix s)))))
13854 (defvar org-last-tag-selection-key nil)
13855 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13856 "Fast tag selection with single keys.
13857 CURRENT is the current list of tags in the headline, INHERITED is the
13858 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13859 possibly with grouping information. TODO-TABLE is a similar table with
13860 TODO keywords, should these have keys assigned to them.
13861 If the keys are nil, a-z are automatically assigned.
13862 Returns the new tags string, or nil to not change the current settings."
13863 (let* ((fulltable (append table todo-table))
13864 (maxlen (apply 'max (mapcar
13865 (lambda (x)
13866 (if (stringp (car x)) (string-width (car x)) 0))
13867 fulltable)))
13868 (buf (current-buffer))
13869 (expert (eq org-fast-tag-selection-single-key 'expert))
13870 (buffer-tags nil)
13871 (fwidth (+ maxlen 3 1 3))
13872 (ncol (/ (- (window-width) 4) fwidth))
13873 (i-face 'org-done)
13874 (c-face 'org-todo)
13875 tg cnt e c char c1 c2 ntable tbl rtn
13876 ov-start ov-end ov-prefix
13877 (exit-after-next org-fast-tag-selection-single-key)
13878 (done-keywords org-done-keywords)
13879 groups ingroup)
13880 (save-excursion
13881 (beginning-of-line 1)
13882 (if (looking-at
13883 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13884 (setq ov-start (match-beginning 1)
13885 ov-end (match-end 1)
13886 ov-prefix "")
13887 (setq ov-start (1- (point-at-eol))
13888 ov-end (1+ ov-start))
13889 (skip-chars-forward "^\n\r")
13890 (setq ov-prefix
13891 (concat
13892 (buffer-substring (1- (point)) (point))
13893 (if (> (current-column) org-tags-column)
13895 (make-string (- org-tags-column (current-column)) ?\ ))))))
13896 (move-overlay org-tags-overlay ov-start ov-end)
13897 (save-window-excursion
13898 (if expert
13899 (set-buffer (get-buffer-create " *Org tags*"))
13900 (delete-other-windows)
13901 (split-window-vertically)
13902 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13903 (erase-buffer)
13904 (org-set-local 'org-done-keywords done-keywords)
13905 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13906 (org-fast-tag-insert "Current" current c-face "\n\n")
13907 (org-fast-tag-show-exit exit-after-next)
13908 (org-set-current-tags-overlay current ov-prefix)
13909 (setq tbl fulltable char ?a cnt 0)
13910 (while (setq e (pop tbl))
13911 (cond
13912 ((equal (car e) :startgroup)
13913 (push '() groups) (setq ingroup t)
13914 (when (not (= cnt 0))
13915 (setq cnt 0)
13916 (insert "\n"))
13917 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13918 ((equal (car e) :endgroup)
13919 (setq ingroup nil cnt 0)
13920 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13921 ((equal e '(:newline))
13922 (when (not (= cnt 0))
13923 (setq cnt 0)
13924 (insert "\n")
13925 (setq e (car tbl))
13926 (while (equal (car tbl) '(:newline))
13927 (insert "\n")
13928 (setq tbl (cdr tbl)))))
13930 (setq tg (copy-sequence (car e)) c2 nil)
13931 (if (cdr e)
13932 (setq c (cdr e))
13933 ;; automatically assign a character.
13934 (setq c1 (string-to-char
13935 (downcase (substring
13936 tg (if (= (string-to-char tg) ?@) 1 0)))))
13937 (if (or (rassoc c1 ntable) (rassoc c1 table))
13938 (while (or (rassoc char ntable) (rassoc char table))
13939 (setq char (1+ char)))
13940 (setq c2 c1))
13941 (setq c (or c2 char)))
13942 (if ingroup (push tg (car groups)))
13943 (setq tg (org-add-props tg nil 'face
13944 (cond
13945 ((not (assoc tg table))
13946 (org-get-todo-face tg))
13947 ((member tg current) c-face)
13948 ((member tg inherited) i-face))))
13949 (if (and (= cnt 0) (not ingroup)) (insert " "))
13950 (insert "[" c "] " tg (make-string
13951 (- fwidth 4 (length tg)) ?\ ))
13952 (push (cons tg c) ntable)
13953 (when (= (setq cnt (1+ cnt)) ncol)
13954 (insert "\n")
13955 (if ingroup (insert " "))
13956 (setq cnt 0)))))
13957 (setq ntable (nreverse ntable))
13958 (insert "\n")
13959 (goto-char (point-min))
13960 (if (not expert) (org-fit-window-to-buffer))
13961 (setq rtn
13962 (catch 'exit
13963 (while t
13964 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13965 (if (not groups) "no " "")
13966 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13967 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13968 (setq org-last-tag-selection-key c)
13969 (cond
13970 ((= c ?\r) (throw 'exit t))
13971 ((= c ?!)
13972 (setq groups (not groups))
13973 (goto-char (point-min))
13974 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13975 ((= c ?\C-c)
13976 (if (not expert)
13977 (org-fast-tag-show-exit
13978 (setq exit-after-next (not exit-after-next)))
13979 (setq expert nil)
13980 (delete-other-windows)
13981 (set-window-buffer (split-window-vertically) " *Org tags*")
13982 (org-switch-to-buffer-other-window " *Org tags*")
13983 (org-fit-window-to-buffer)))
13984 ((or (= c ?\C-g)
13985 (and (= c ?q) (not (rassoc c ntable))))
13986 (org-detach-overlay org-tags-overlay)
13987 (setq quit-flag t))
13988 ((= c ?\ )
13989 (setq current nil)
13990 (if exit-after-next (setq exit-after-next 'now)))
13991 ((= c ?\t)
13992 (condition-case nil
13993 (setq tg (org-icompleting-read
13994 "Tag: "
13995 (or buffer-tags
13996 (with-current-buffer buf
13997 (org-get-buffer-tags)))))
13998 (quit (setq tg "")))
13999 (when (string-match "\\S-" tg)
14000 (add-to-list 'buffer-tags (list tg))
14001 (if (member tg current)
14002 (setq current (delete tg current))
14003 (push tg current)))
14004 (if exit-after-next (setq exit-after-next 'now)))
14005 ((setq e (rassoc c todo-table) tg (car e))
14006 (with-current-buffer buf
14007 (save-excursion (org-todo tg)))
14008 (if exit-after-next (setq exit-after-next 'now)))
14009 ((setq e (rassoc c ntable) tg (car e))
14010 (if (member tg current)
14011 (setq current (delete tg current))
14012 (loop for g in groups do
14013 (if (member tg g)
14014 (mapc (lambda (x)
14015 (setq current (delete x current)))
14016 g)))
14017 (push tg current))
14018 (if exit-after-next (setq exit-after-next 'now))))
14020 ;; Create a sorted list
14021 (setq current
14022 (sort current
14023 (lambda (a b)
14024 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14025 (if (eq exit-after-next 'now) (throw 'exit t))
14026 (goto-char (point-min))
14027 (beginning-of-line 2)
14028 (delete-region (point) (point-at-eol))
14029 (org-fast-tag-insert "Current" current c-face)
14030 (org-set-current-tags-overlay current ov-prefix)
14031 (while (re-search-forward
14032 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14033 (setq tg (match-string 1))
14034 (add-text-properties
14035 (match-beginning 1) (match-end 1)
14036 (list 'face
14037 (cond
14038 ((member tg current) c-face)
14039 ((member tg inherited) i-face)
14040 (t (get-text-property (match-beginning 1) 'face))))))
14041 (goto-char (point-min)))))
14042 (org-detach-overlay org-tags-overlay)
14043 (if rtn
14044 (mapconcat 'identity current ":")
14045 nil))))
14047 (defun org-get-tags-string ()
14048 "Get the TAGS string in the current headline."
14049 (unless (org-at-heading-p t)
14050 (error "Not on a heading"))
14051 (save-excursion
14052 (beginning-of-line 1)
14053 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14054 (org-match-string-no-properties 1)
14055 "")))
14057 (defun org-get-tags ()
14058 "Get the list of tags specified in the current headline."
14059 (org-split-string (org-get-tags-string) ":"))
14061 (defun org-get-buffer-tags ()
14062 "Get a table of all tags used in the buffer, for completion."
14063 (let (tags)
14064 (save-excursion
14065 (goto-char (point-min))
14066 (while (re-search-forward
14067 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14068 (when (equal (char-after (point-at-bol 0)) ?*)
14069 (mapc (lambda (x) (add-to-list 'tags x))
14070 (org-split-string (org-match-string-no-properties 1) ":")))))
14071 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14072 (mapcar 'list tags)))
14074 ;;;; The mapping API
14076 (defun org-map-entries (func &optional match scope &rest skip)
14077 "Call FUNC at each headline selected by MATCH in SCOPE.
14079 FUNC is a function or a lisp form. The function will be called without
14080 arguments, with the cursor positioned at the beginning of the headline.
14081 The return values of all calls to the function will be collected and
14082 returned as a list.
14084 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14085 does not need to preserve point. After evaluation, the cursor will be
14086 moved to the end of the line (presumably of the headline of the
14087 processed entry) and search continues from there. Under some
14088 circumstances, this may not produce the wanted results. For example,
14089 if you have removed (e.g. archived) the current (sub)tree it could
14090 mean that the next entry will be skipped entirely. In such cases, you
14091 can specify the position from where search should continue by making
14092 FUNC set the variable `org-map-continue-from' to the desired buffer
14093 position.
14095 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14096 Only headlines that are matched by this query will be considered during
14097 the iteration. When MATCH is nil or t, all headlines will be
14098 visited by the iteration.
14100 SCOPE determines the scope of this command. It can be any of:
14102 nil The current buffer, respecting the restriction if any
14103 tree The subtree started with the entry at point
14104 region The entries within the active region, if any
14105 region-start-level
14106 The entries within the active region, but only those at
14107 the same level than the first one.
14108 file The current buffer, without restriction
14109 file-with-archives
14110 The current buffer, and any archives associated with it
14111 agenda All agenda files
14112 agenda-with-archives
14113 All agenda files with any archive files associated with them
14114 \(file1 file2 ...)
14115 If this is a list, all files in the list will be scanned
14117 The remaining args are treated as settings for the skipping facilities of
14118 the scanner. The following items can be given here:
14120 archive skip trees with the archive tag
14121 comment skip trees with the COMMENT keyword
14122 function or Emacs Lisp form:
14123 will be used as value for `org-agenda-skip-function', so
14124 whenever the function returns a position, FUNC will not be
14125 called for that entry and search will continue from the
14126 position returned
14128 If your function needs to retrieve the tags including inherited tags
14129 at the *current* entry, you can use the value of the variable
14130 `org-scanner-tags' which will be much faster than getting the value
14131 with `org-get-tags-at'. If your function gets properties with
14132 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14133 to t around the call to `org-entry-properties' to get the same speedup.
14134 Note that if your function moves around to retrieve tags and properties at
14135 a *different* entry, you cannot use these techniques."
14136 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14137 (not (org-region-active-p)))
14138 (let* ((org-agenda-archives-mode nil) ; just to make sure
14139 (org-agenda-skip-archived-trees (memq 'archive skip))
14140 (org-agenda-skip-comment-trees (memq 'comment skip))
14141 (org-agenda-skip-function
14142 (car (org-delete-all '(comment archive) skip)))
14143 (org-tags-match-list-sublevels t)
14144 (start-level (eq scope 'region-start-level))
14145 matcher file res
14146 org-todo-keywords-for-agenda
14147 org-done-keywords-for-agenda
14148 org-todo-keyword-alist-for-agenda
14149 org-drawers-for-agenda
14150 org-tag-alist-for-agenda
14151 todo-only)
14153 (cond
14154 ((eq match t) (setq matcher t))
14155 ((eq match nil) (setq matcher t))
14156 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14158 (save-excursion
14159 (save-restriction
14160 (cond ((eq scope 'tree)
14161 (org-back-to-heading t)
14162 (org-narrow-to-subtree)
14163 (setq scope nil))
14164 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14165 (org-region-active-p))
14166 ;; If needed, set start-level to a string like "2"
14167 (when start-level
14168 (save-excursion
14169 (goto-char (region-beginning))
14170 (unless (org-at-heading-p) (outline-next-heading))
14171 (setq start-level (org-current-level))))
14172 (narrow-to-region (region-beginning)
14173 (save-excursion
14174 (goto-char (region-end))
14175 (unless (and (bolp) (org-at-heading-p))
14176 (outline-next-heading))
14177 (point)))
14178 (setq scope nil)))
14180 (if (not scope)
14181 (progn
14182 (org-agenda-prepare-buffers
14183 (list (buffer-file-name (current-buffer))))
14184 (setq res (org-scan-tags func matcher todo-only start-level)))
14185 ;; Get the right scope
14186 (cond
14187 ((and scope (listp scope) (symbolp (car scope)))
14188 (setq scope (eval scope)))
14189 ((eq scope 'agenda)
14190 (setq scope (org-agenda-files t)))
14191 ((eq scope 'agenda-with-archives)
14192 (setq scope (org-agenda-files t))
14193 (setq scope (org-add-archive-files scope)))
14194 ((eq scope 'file)
14195 (setq scope (list (buffer-file-name))))
14196 ((eq scope 'file-with-archives)
14197 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14198 (org-agenda-prepare-buffers scope)
14199 (while (setq file (pop scope))
14200 (with-current-buffer (org-find-base-buffer-visiting file)
14201 (save-excursion
14202 (save-restriction
14203 (widen)
14204 (goto-char (point-min))
14205 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14206 res)))
14208 ;;;; Properties
14210 ;;; Setting and retrieving properties
14212 (defconst org-special-properties
14213 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14214 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14215 "The special properties valid in Org-mode.
14217 These are properties that are not defined in the property drawer,
14218 but in some other way.")
14220 (defconst org-default-properties
14221 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14222 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14223 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14224 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14225 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14226 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14227 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14228 "Some properties that are used by Org-mode for various purposes.
14229 Being in this list makes sure that they are offered for completion.")
14231 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14232 "Regular expression matching the first line of a property drawer.")
14234 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14235 "Regular expression matching the last line of a property drawer.")
14237 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14238 "Regular expression matching the first line of a property drawer.")
14240 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14241 "Regular expression matching the first line of a property drawer.")
14243 (defconst org-property-drawer-re
14244 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14245 org-property-end-re "\\)\n?")
14246 "Matches an entire property drawer.")
14248 (defconst org-clock-drawer-re
14249 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14250 org-property-end-re "\\)\n?")
14251 "Matches an entire clock drawer.")
14253 (defsubst org-re-property (property)
14254 "Return a regexp matching a PROPERTY line.
14255 Match group 1 will be set to the value."
14256 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14258 (defsubst org-re-property-keyword (property)
14259 "Return a regexp matching a PROPERTY line, possibly with no
14260 value for the property."
14261 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14263 (defun org-property-action ()
14264 "Do an action on properties."
14265 (interactive)
14266 (let (c)
14267 (org-at-property-p)
14268 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14269 (setq c (read-char-exclusive))
14270 (cond
14271 ((equal c ?s)
14272 (call-interactively 'org-set-property))
14273 ((equal c ?d)
14274 (call-interactively 'org-delete-property))
14275 ((equal c ?D)
14276 (call-interactively 'org-delete-property-globally))
14277 ((equal c ?c)
14278 (call-interactively 'org-compute-property-at-point))
14279 (t (error "No such property action %c" c)))))
14281 (defun org-inc-effort ()
14282 "Increment the value of the effort property in the current entry."
14283 (interactive)
14284 (org-set-effort nil t))
14286 (defun org-set-effort (&optional value increment)
14287 "Set the effort property of the current entry.
14288 With numerical prefix arg, use the nth allowed value, 0 stands for the
14289 10th allowed value.
14291 When INCREMENT is non-nil, set the property to the next allowed value."
14292 (interactive "P")
14293 (if (equal value 0) (setq value 10))
14294 (let* ((completion-ignore-case t)
14295 (prop org-effort-property)
14296 (cur (org-entry-get nil prop))
14297 (allowed (org-property-get-allowed-values nil prop 'table))
14298 (existing (mapcar 'list (org-property-values prop)))
14300 (val (cond
14301 ((stringp value) value)
14302 ((and allowed (integerp value))
14303 (or (car (nth (1- value) allowed))
14304 (car (org-last allowed))))
14305 ((and allowed increment)
14306 (or (caadr (member (list cur) allowed))
14307 (error "Allowed effort values are not set")))
14308 (allowed
14309 (message "Select 1-9,0, [RET%s]: %s"
14310 (if cur (concat "=" cur) "")
14311 (mapconcat 'car allowed " "))
14312 (setq rpl (read-char-exclusive))
14313 (if (equal rpl ?\r)
14315 (setq rpl (- rpl ?0))
14316 (if (equal rpl 0) (setq rpl 10))
14317 (if (and (> rpl 0) (<= rpl (length allowed)))
14318 (car (nth (1- rpl) allowed))
14319 (org-completing-read "Effort: " allowed nil))))
14321 (let (org-completion-use-ido org-completion-use-iswitchb)
14322 (org-completing-read
14323 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14324 (concat "[" cur "]") "")
14325 ": ")
14326 existing nil nil "" nil cur))))))
14327 (unless (equal (org-entry-get nil prop) val)
14328 (org-entry-put nil prop val))
14329 (save-excursion
14330 (org-back-to-heading t)
14331 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14332 (message "%s is now %s" prop val)))
14334 (defun org-at-property-p ()
14335 "Is cursor inside a property drawer?"
14336 (save-excursion
14337 (beginning-of-line 1)
14338 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14339 (save-match-data ;; Used by calling procedures
14340 (let ((p (point))
14341 (range (unless (org-before-first-heading-p)
14342 (org-get-property-block))))
14343 (and range (<= (car range) p) (< p (cdr range))))))))
14345 (defun org-get-property-block (&optional beg end force)
14346 "Return the (beg . end) range of the body of the property drawer.
14347 BEG and END are the beginning and end of the current subtree, or of
14348 the part before the first headline. If they are not given, they will
14349 be found. If the drawer does not exist and FORCE is non-nil, create
14350 the drawer."
14351 (catch 'exit
14352 (save-excursion
14353 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14354 (progn (org-back-to-heading t) (point))))
14355 (end (or end (and (not (outline-next-heading)) (point-max))
14356 (point))))
14357 (goto-char beg)
14358 (if (re-search-forward org-property-start-re end t)
14359 (setq beg (1+ (match-end 0)))
14360 (if force
14361 (save-excursion
14362 (org-insert-property-drawer)
14363 (setq end (progn (outline-next-heading) (point))))
14364 (throw 'exit nil))
14365 (goto-char beg)
14366 (if (re-search-forward org-property-start-re end t)
14367 (setq beg (1+ (match-end 0)))))
14368 (if (re-search-forward org-property-end-re end t)
14369 (setq end (match-beginning 0))
14370 (or force (throw 'exit nil))
14371 (goto-char beg)
14372 (setq end beg)
14373 (org-indent-line)
14374 (insert ":END:\n"))
14375 (cons beg end)))))
14377 (defun org-entry-properties (&optional pom which specific)
14378 "Get all properties of the entry at point-or-marker POM.
14379 This includes the TODO keyword, the tags, time strings for deadline,
14380 scheduled, and clocking, and any additional properties defined in the
14381 entry. The return value is an alist, keys may occur multiple times
14382 if the property key was used several times.
14383 POM may also be nil, in which case the current entry is used.
14384 If WHICH is nil or `all', get all properties. If WHICH is
14385 `special' or `standard', only get that subclass. If WHICH
14386 is a string only get exactly this property. SPECIFIC can be a string, the
14387 specific property we are interested in. Specifying it can speed
14388 things up because then unnecessary parsing is avoided."
14389 (setq which (or which 'all))
14390 (org-with-point-at pom
14391 (let ((clockstr (substring org-clock-string 0 -1))
14392 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14393 (case-fold-search nil)
14394 beg end range props sum-props key key1 value string clocksum clocksumt)
14395 (save-excursion
14396 (when (condition-case nil
14397 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14398 (error nil))
14399 (setq beg (point))
14400 (setq sum-props (get-text-property (point) 'org-summaries))
14401 (setq clocksum (get-text-property (point) :org-clock-minutes)
14402 clocksumt (get-text-property (point) :org-clock-minutes-today))
14403 (outline-next-heading)
14404 (setq end (point))
14405 (when (memq which '(all special))
14406 ;; Get the special properties, like TODO and tags
14407 (goto-char beg)
14408 (when (and (or (not specific) (string= specific "TODO"))
14409 (looking-at org-todo-line-regexp) (match-end 2))
14410 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14411 (when (and (or (not specific) (string= specific "PRIORITY"))
14412 (looking-at org-priority-regexp))
14413 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14414 (when (or (not specific) (string= specific "FILE"))
14415 (push (cons "FILE" buffer-file-name) props))
14416 (when (and (or (not specific) (string= specific "TAGS"))
14417 (setq value (org-get-tags-string))
14418 (string-match "\\S-" value))
14419 (push (cons "TAGS" value) props))
14420 (when (and (or (not specific) (string= specific "ALLTAGS"))
14421 (setq value (org-get-tags-at)))
14422 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14423 ":"))
14424 props))
14425 (when (or (not specific) (string= specific "BLOCKED"))
14426 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14427 (when (or (not specific)
14428 (member specific
14429 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14430 "TIMESTAMP" "TIMESTAMP_IA")))
14431 (catch 'match
14432 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14433 (setq key (if (match-end 1)
14434 (substring (org-match-string-no-properties 1)
14435 0 -1))
14436 string (if (equal key clockstr)
14437 (org-trim
14438 (buffer-substring-no-properties
14439 (match-beginning 3) (goto-char
14440 (point-at-eol))))
14441 (substring (org-match-string-no-properties 3)
14442 1 -1)))
14443 ;; Get the correct property name from the key. This is
14444 ;; necessary if the user has configured time keywords.
14445 (setq key1 (concat key ":"))
14446 (cond
14447 ((not key)
14448 (setq key
14449 (if (= (char-after (match-beginning 3)) ?\[)
14450 "TIMESTAMP_IA" "TIMESTAMP")))
14451 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14452 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14453 ((equal key1 org-closed-string) (setq key "CLOSED"))
14454 ((equal key1 org-clock-string) (setq key "CLOCK")))
14455 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14456 (progn
14457 (push (cons key string) props)
14458 ;; no need to search further if match is found
14459 (throw 'match t))
14460 (when (or (equal key "CLOCK") (not (assoc key props)))
14461 (push (cons key string) props)))))))
14463 (when (memq which '(all standard))
14464 ;; Get the standard properties, like :PROP: ...
14465 (setq range (org-get-property-block beg end))
14466 (when range
14467 (goto-char (car range))
14468 (while (re-search-forward
14469 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14470 (cdr range) t)
14471 (setq key (org-match-string-no-properties 1)
14472 value (org-trim (or (org-match-string-no-properties 2) "")))
14473 (unless (member key excluded)
14474 (push (cons key (or value "")) props)))))
14475 (if clocksum
14476 (push (cons "CLOCKSUM"
14477 (org-columns-number-to-string (/ (float clocksum) 60.)
14478 'add_times))
14479 props))
14480 (if clocksumt
14481 (push (cons "CLOCKSUM_T"
14482 (org-columns-number-to-string (/ (float clocksumt) 60.)
14483 'add_times))
14484 props))
14485 (unless (assoc "CATEGORY" props)
14486 (push (cons "CATEGORY" (org-get-category)) props))
14487 (append sum-props (nreverse props)))))))
14489 (defun org-entry-get (pom property &optional inherit literal-nil)
14490 "Get value of PROPERTY for entry or content at point-or-marker POM.
14491 If INHERIT is non-nil and the entry does not have the property,
14492 then also check higher levels of the hierarchy.
14493 If INHERIT is the symbol `selective', use inheritance only if the setting
14494 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14495 If the property is present but empty, the return value is the empty string.
14496 If the property is not present at all, nil is returned.
14498 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14499 do not interpret it as the list atom nil. This is used for inheritance
14500 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14501 (org-with-point-at pom
14502 (if (and inherit (if (eq inherit 'selective)
14503 (org-property-inherit-p property)
14505 (org-entry-get-with-inheritance property literal-nil)
14506 (if (member property org-special-properties)
14507 ;; We need a special property. Use `org-entry-properties' to
14508 ;; retrieve it, but specify the wanted property
14509 (cdr (assoc property (org-entry-properties nil 'special property)))
14510 (let ((range (org-get-property-block)))
14511 (when (and range (not (eq (car range) (cdr range))))
14512 (let* ((props (list (or (assoc property org-file-properties)
14513 (assoc property org-global-properties)
14514 (assoc property org-global-properties-fixed))))
14515 (ap (lambda (key)
14516 (when (re-search-forward
14517 (org-re-property key) (cdr range) t)
14518 (setq props
14519 (org-update-property-plist
14521 (if (match-end 1)
14522 (org-match-string-no-properties 1) "")
14523 props)))))
14524 val)
14525 (goto-char (car range))
14526 (funcall ap property)
14527 (goto-char (car range))
14528 (while (funcall ap (concat property "+")))
14529 (setq val (cdr (assoc property props)))
14530 (when val (if literal-nil val (org-not-nil val))))))))))
14532 (defun org-property-or-variable-value (var &optional inherit)
14533 "Check if there is a property fixing the value of VAR.
14534 If yes, return this value. If not, return the current value of the variable."
14535 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14536 (if (and prop (stringp prop) (string-match "\\S-" prop))
14537 (read prop)
14538 (symbol-value var))))
14540 (defun org-entry-delete (pom property)
14541 "Delete the property PROPERTY from entry at point-or-marker POM."
14542 (org-with-point-at pom
14543 (if (member property org-special-properties)
14544 nil ; cannot delete these properties.
14545 (let ((range (org-get-property-block)))
14546 (if (and range
14547 (goto-char (car range))
14548 (re-search-forward
14549 (org-re-property property)
14550 (cdr range) t))
14551 (progn
14552 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14554 nil)))))
14556 ;; Multi-values properties are properties that contain multiple values
14557 ;; These values are assumed to be single words, separated by whitespace.
14558 (defun org-entry-add-to-multivalued-property (pom property value)
14559 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14560 (let* ((old (org-entry-get pom property))
14561 (values (and old (org-split-string old "[ \t]"))))
14562 (setq value (org-entry-protect-space value))
14563 (unless (member value values)
14564 (setq values (cons value values))
14565 (org-entry-put pom property
14566 (mapconcat 'identity values " ")))))
14568 (defun org-entry-remove-from-multivalued-property (pom property value)
14569 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14570 (let* ((old (org-entry-get pom property))
14571 (values (and old (org-split-string old "[ \t]"))))
14572 (setq value (org-entry-protect-space value))
14573 (when (member value values)
14574 (setq values (delete value values))
14575 (org-entry-put pom property
14576 (mapconcat 'identity values " ")))))
14578 (defun org-entry-member-in-multivalued-property (pom property value)
14579 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14580 (let* ((old (org-entry-get pom property))
14581 (values (and old (org-split-string old "[ \t]"))))
14582 (setq value (org-entry-protect-space value))
14583 (member value values)))
14585 (defun org-entry-get-multivalued-property (pom property)
14586 "Return a list of values in a multivalued property."
14587 (let* ((value (org-entry-get pom property))
14588 (values (and value (org-split-string value "[ \t]"))))
14589 (mapcar 'org-entry-restore-space values)))
14591 (defun org-entry-put-multivalued-property (pom property &rest values)
14592 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14593 VALUES should be a list of strings. Spaces will be protected."
14594 (org-entry-put pom property
14595 (mapconcat 'org-entry-protect-space values " "))
14596 (let* ((value (org-entry-get pom property))
14597 (values (and value (org-split-string value "[ \t]"))))
14598 (mapcar 'org-entry-restore-space values)))
14600 (defun org-entry-protect-space (s)
14601 "Protect spaces and newline in string S."
14602 (while (string-match " " s)
14603 (setq s (replace-match "%20" t t s)))
14604 (while (string-match "\n" s)
14605 (setq s (replace-match "%0A" t t s)))
14608 (defun org-entry-restore-space (s)
14609 "Restore spaces and newline in string S."
14610 (while (string-match "%20" s)
14611 (setq s (replace-match " " t t s)))
14612 (while (string-match "%0A" s)
14613 (setq s (replace-match "\n" t t s)))
14616 (defvar org-entry-property-inherited-from (make-marker)
14617 "Marker pointing to the entry from where a property was inherited.
14618 Each call to `org-entry-get-with-inheritance' will set this marker to the
14619 location of the entry where the inheritance search matched. If there was
14620 no match, the marker will point nowhere.
14621 Note that also `org-entry-get' calls this function, if the INHERIT flag
14622 is set.")
14624 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14625 "Get PROPERTY of entry or content at point, search higher levels if needed.
14626 The search will stop at the first ancestor which has the property defined.
14627 If the value found is \"nil\", return nil to show that the property
14628 should be considered as undefined (this is the meaning of nil here).
14629 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14630 (move-marker org-entry-property-inherited-from nil)
14631 (let (tmp)
14632 (save-excursion
14633 (save-restriction
14634 (widen)
14635 (catch 'ex
14636 (while t
14637 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14638 (or (ignore-errors (org-back-to-heading t))
14639 (goto-char (point-min)))
14640 (move-marker org-entry-property-inherited-from (point))
14641 (throw 'ex tmp))
14642 (or (ignore-errors (org-up-heading-safe))
14643 (throw 'ex nil))))))
14644 (setq tmp (or tmp
14645 (cdr (assoc property org-file-properties))
14646 (cdr (assoc property org-global-properties))
14647 (cdr (assoc property org-global-properties-fixed))))
14648 (if literal-nil tmp (org-not-nil tmp))))
14650 (defvar org-property-changed-functions nil
14651 "Hook called when the value of a property has changed.
14652 Each hook function should accept two arguments, the name of the property
14653 and the new value.")
14655 (defun org-entry-put (pom property value)
14656 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14657 (org-with-point-at pom
14658 (org-back-to-heading t)
14659 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14660 range)
14661 (cond
14662 ((equal property "TODO")
14663 (when (and (stringp value) (string-match "\\S-" value)
14664 (not (member value org-todo-keywords-1)))
14665 (error "\"%s\" is not a valid TODO state" value))
14666 (if (or (not value)
14667 (not (string-match "\\S-" value)))
14668 (setq value 'none))
14669 (org-todo value)
14670 (org-set-tags nil 'align))
14671 ((equal property "PRIORITY")
14672 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14673 (string-to-char value) ?\ ))
14674 (org-set-tags nil 'align))
14675 ((equal property "SCHEDULED")
14676 (if (re-search-forward org-scheduled-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-schedule)))
14681 (call-interactively 'org-schedule)))
14682 ((equal property "DEADLINE")
14683 (if (re-search-forward org-deadline-time-regexp end t)
14684 (cond
14685 ((eq value 'earlier) (org-timestamp-change -1 'day))
14686 ((eq value 'later) (org-timestamp-change 1 'day))
14687 (t (call-interactively 'org-deadline)))
14688 (call-interactively 'org-deadline)))
14689 ((member property org-special-properties)
14690 (error "The %s property can not yet be set with `org-entry-put'"
14691 property))
14692 (t ; a non-special property
14693 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14694 (setq range (org-get-property-block beg end 'force))
14695 (goto-char (car range))
14696 (if (re-search-forward
14697 (org-re-property-keyword property) (cdr range) t)
14698 (progn
14699 (delete-region (match-beginning 0) (match-end 0))
14700 (goto-char (match-beginning 0)))
14701 (goto-char (cdr range))
14702 (insert "\n")
14703 (backward-char 1)
14704 (org-indent-line))
14705 (insert ":" property ":")
14706 (and value (insert " " value))
14707 (org-indent-line)))))
14708 (run-hook-with-args 'org-property-changed-functions property value)))
14710 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14711 "Get all property keys in the current buffer.
14712 With INCLUDE-SPECIALS, also list the special properties that reflect things
14713 like tags and TODO state.
14714 With INCLUDE-DEFAULTS, also include properties that has special meaning
14715 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14716 and others.
14717 With INCLUDE-COLUMNS, also include property names given in COLUMN
14718 formats in the current buffer."
14719 (let (rtn range cfmt s p)
14720 (save-excursion
14721 (save-restriction
14722 (widen)
14723 (goto-char (point-min))
14724 (while (re-search-forward org-property-start-re nil t)
14725 (setq range (org-get-property-block))
14726 (goto-char (car range))
14727 (while (re-search-forward
14728 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14729 (cdr range) t)
14730 (add-to-list 'rtn (org-match-string-no-properties 1)))
14731 (outline-next-heading))))
14733 (when include-specials
14734 (setq rtn (append org-special-properties rtn)))
14736 (when include-defaults
14737 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14738 (add-to-list 'rtn org-effort-property))
14740 (when include-columns
14741 (save-excursion
14742 (save-restriction
14743 (widen)
14744 (goto-char (point-min))
14745 (while (re-search-forward
14746 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14747 nil t)
14748 (setq cfmt (match-string 2) s 0)
14749 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14750 cfmt s)
14751 (setq s (match-end 0)
14752 p (match-string 1 cfmt))
14753 (unless (or (equal p "ITEM")
14754 (member p org-special-properties))
14755 (add-to-list 'rtn (match-string 1 cfmt))))))))
14757 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14759 (defun org-property-values (key)
14760 "Return a list of all values of property KEY in the current buffer."
14761 (save-excursion
14762 (save-restriction
14763 (widen)
14764 (goto-char (point-min))
14765 (let ((re (org-re-property key))
14766 values)
14767 (while (re-search-forward re nil t)
14768 (add-to-list 'values (org-trim (match-string 1))))
14769 (delete "" values)))))
14771 (defun org-insert-property-drawer ()
14772 "Insert a property drawer into the current entry."
14773 (org-back-to-heading t)
14774 (looking-at org-outline-regexp)
14775 (let ((indent (if org-adapt-indentation
14776 (- (match-end 0) (match-beginning 0))
14778 (beg (point))
14779 (re (concat "^[ \t]*" org-keyword-time-regexp))
14780 end hiddenp)
14781 (outline-next-heading)
14782 (setq end (point))
14783 (goto-char beg)
14784 (while (re-search-forward re end t))
14785 (setq hiddenp (outline-invisible-p))
14786 (end-of-line 1)
14787 (and (equal (char-after) ?\n) (forward-char 1))
14788 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14789 (if (member (match-string 1) '("CLOCK:" ":END:"))
14790 ;; just skip this line
14791 (beginning-of-line 2)
14792 ;; Drawer start, find the end
14793 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14794 (beginning-of-line 1)))
14795 (org-skip-over-state-notes)
14796 (skip-chars-backward " \t\n\r")
14797 (if (eq (char-before) ?*) (forward-char 1))
14798 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14799 (beginning-of-line 0)
14800 (org-indent-to-column indent)
14801 (beginning-of-line 2)
14802 (org-indent-to-column indent)
14803 (beginning-of-line 0)
14804 (if hiddenp
14805 (save-excursion
14806 (org-back-to-heading t)
14807 (hide-entry))
14808 (org-flag-drawer t))))
14810 (defun org-insert-drawer (&optional arg drawer)
14811 "Insert a drawer at point.
14813 Optional argument DRAWER, when non-nil, is a string representing
14814 drawer's name. Otherwise, the user is prompted for a name.
14816 If a region is active, insert the drawer around that region
14817 instead.
14819 Point is left between drawer's boundaries."
14820 (interactive "P")
14821 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14822 "LOGBOOK"))
14823 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14824 ;; internally by Org. They are meant to be inserted
14825 ;; automatically.
14826 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14827 ;; Remove system drawers from list. Note: For some reason,
14828 ;; `org-completing-read' ignores the predicate while
14829 ;; `completing-read' handles it fine.
14830 (drawer (if arg "PROPERTIES"
14831 (or drawer
14832 (completing-read
14833 "Drawer: " org-drawers
14834 (lambda (d) (not (member d system-drawers))))))))
14835 (cond
14836 ;; With C-u, fall back on `org-insert-property-drawer'
14837 (arg (org-insert-property-drawer))
14838 ;; With an active region, insert a drawer at point.
14839 ((not (org-region-active-p))
14840 (progn
14841 (unless (bolp) (insert "\n"))
14842 (insert (format ":%s:\n\n:END:\n" drawer))
14843 (forward-line -2)))
14844 ;; Otherwise, insert the drawer at point
14846 (let ((rbeg (region-beginning))
14847 (rend (copy-marker (region-end))))
14848 (unwind-protect
14849 (progn
14850 (goto-char rbeg)
14851 (beginning-of-line)
14852 (when (save-excursion
14853 (re-search-forward org-outline-regexp-bol rend t))
14854 (error "Drawers cannot contain headlines"))
14855 ;; Position point at the beginning of the first
14856 ;; non-blank line in region. Insert drawer's opening
14857 ;; there, then indent it.
14858 (org-skip-whitespace)
14859 (beginning-of-line)
14860 (insert ":" drawer ":\n")
14861 (forward-line -1)
14862 (indent-for-tab-command)
14863 ;; Move point to the beginning of the first blank line
14864 ;; after the last non-blank line in region. Insert
14865 ;; drawer's closing, then indent it.
14866 (goto-char rend)
14867 (skip-chars-backward " \r\t\n")
14868 (insert "\n:END:")
14869 (deactivate-mark t)
14870 (indent-for-tab-command)
14871 (unless (eolp) (insert "\n")))
14872 ;; Clear marker, whatever the outcome of insertion is.
14873 (set-marker rend nil)))))))
14875 (defvar org-property-set-functions-alist nil
14876 "Property set function alist.
14877 Each entry should have the following format:
14879 (PROPERTY . READ-FUNCTION)
14881 The read function will be called with the same argument as
14882 `org-completing-read'.")
14884 (defun org-set-property-function (property)
14885 "Get the function that should be used to set PROPERTY.
14886 This is computed according to `org-property-set-functions-alist'."
14887 (or (cdr (assoc property org-property-set-functions-alist))
14888 'org-completing-read))
14890 (defun org-read-property-value (property)
14891 "Read PROPERTY value from user."
14892 (let* ((completion-ignore-case t)
14893 (allowed (org-property-get-allowed-values nil property 'table))
14894 (cur (org-entry-get nil property))
14895 (prompt (concat property " value"
14896 (if (and cur (string-match "\\S-" cur))
14897 (concat " [" cur "]") "") ": "))
14898 (set-function (org-set-property-function property))
14899 (val (if allowed
14900 (funcall set-function prompt allowed nil
14901 (not (get-text-property 0 'org-unrestricted
14902 (caar allowed))))
14903 (let (org-completion-use-ido org-completion-use-iswitchb)
14904 (funcall set-function prompt
14905 (mapcar 'list (org-property-values property))
14906 nil nil "" nil cur)))))
14907 (if (equal val "")
14909 val)))
14911 (defvar org-last-set-property nil)
14912 (defun org-read-property-name ()
14913 "Read a property name."
14914 (let* ((completion-ignore-case t)
14915 (keys (org-buffer-property-keys nil t t))
14916 (default-prop (or (save-excursion
14917 (save-match-data
14918 (beginning-of-line)
14919 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14920 (null (string= (match-string 1) "END"))
14921 (match-string 1))))
14922 org-last-set-property))
14923 (property (org-icompleting-read
14924 (concat "Property"
14925 (if default-prop (concat " [" default-prop "]") "")
14926 ": ")
14927 (mapcar 'list keys)
14928 nil nil nil nil
14929 default-prop
14931 (if (member property keys)
14932 property
14933 (or (cdr (assoc (downcase property)
14934 (mapcar (lambda (x) (cons (downcase x) x))
14935 keys)))
14936 property))))
14938 (defun org-set-property (property value)
14939 "In the current entry, set PROPERTY to VALUE.
14940 When called interactively, this will prompt for a property name, offering
14941 completion on existing and default properties. And then it will prompt
14942 for a value, offering completion either on allowed values (via an inherited
14943 xxx_ALL property) or on existing values in other instances of this property
14944 in the current file."
14945 (interactive (list nil nil))
14946 (let* ((property (or property (org-read-property-name)))
14947 (value (or value (org-read-property-value property)))
14948 (fn (cdr (assoc property org-properties-postprocess-alist))))
14949 (setq org-last-set-property property)
14950 ;; Possibly postprocess the inserted value:
14951 (when fn (setq value (funcall fn value)))
14952 (unless (equal (org-entry-get nil property) value)
14953 (org-entry-put nil property value))))
14955 (defun org-delete-property (property)
14956 "In the current entry, delete PROPERTY."
14957 (interactive
14958 (let* ((completion-ignore-case t)
14959 (prop (org-icompleting-read "Property: "
14960 (org-entry-properties nil 'standard))))
14961 (list prop)))
14962 (message "Property %s %s" property
14963 (if (org-entry-delete nil property)
14964 "deleted"
14965 "was not present in the entry")))
14967 (defun org-delete-property-globally (property)
14968 "Remove PROPERTY globally, from all entries."
14969 (interactive
14970 (let* ((completion-ignore-case t)
14971 (prop (org-icompleting-read
14972 "Globally remove property: "
14973 (mapcar 'list (org-buffer-property-keys)))))
14974 (list prop)))
14975 (save-excursion
14976 (save-restriction
14977 (widen)
14978 (goto-char (point-min))
14979 (let ((cnt 0))
14980 (while (re-search-forward
14981 (org-re-property property)
14982 nil t)
14983 (setq cnt (1+ cnt))
14984 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14985 (message "Property \"%s\" removed from %d entries" property cnt)))))
14987 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14989 (defun org-compute-property-at-point ()
14990 "Compute the property at point.
14991 This looks for an enclosing column format, extracts the operator and
14992 then applies it to the property in the column format's scope."
14993 (interactive)
14994 (unless (org-at-property-p)
14995 (error "Not at a property"))
14996 (let ((prop (org-match-string-no-properties 2)))
14997 (org-columns-get-format-and-top-level)
14998 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14999 (error "No operator defined for property %s" prop))
15000 (org-columns-compute prop)))
15002 (defvar org-property-allowed-value-functions nil
15003 "Hook for functions supplying allowed values for a specific property.
15004 The functions must take a single argument, the name of the property, and
15005 return a flat list of allowed values. If \":ETC\" is one of
15006 the values, this means that these values are intended as defaults for
15007 completion, but that other values should be allowed too.
15008 The functions must return nil if they are not responsible for this
15009 property.")
15011 (defun org-property-get-allowed-values (pom property &optional table)
15012 "Get allowed values for the property PROPERTY.
15013 When TABLE is non-nil, return an alist that can directly be used for
15014 completion."
15015 (let (vals)
15016 (cond
15017 ((equal property "TODO")
15018 (setq vals (org-with-point-at pom
15019 (append org-todo-keywords-1 '("")))))
15020 ((equal property "PRIORITY")
15021 (let ((n org-lowest-priority))
15022 (while (>= n org-highest-priority)
15023 (push (char-to-string n) vals)
15024 (setq n (1- n)))))
15025 ((member property org-special-properties))
15026 ((setq vals (run-hook-with-args-until-success
15027 'org-property-allowed-value-functions property)))
15029 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15030 (when (and vals (string-match "\\S-" vals))
15031 (setq vals (car (read-from-string (concat "(" vals ")"))))
15032 (setq vals (mapcar (lambda (x)
15033 (cond ((stringp x) x)
15034 ((numberp x) (number-to-string x))
15035 ((symbolp x) (symbol-name x))
15036 (t "???")))
15037 vals)))))
15038 (when (member ":ETC" vals)
15039 (setq vals (remove ":ETC" vals))
15040 (org-add-props (car vals) '(org-unrestricted t)))
15041 (if table (mapcar 'list vals) vals)))
15043 (defun org-property-previous-allowed-value (&optional previous)
15044 "Switch to the next allowed value for this property."
15045 (interactive)
15046 (org-property-next-allowed-value t))
15048 (defun org-property-next-allowed-value (&optional previous)
15049 "Switch to the next allowed value for this property."
15050 (interactive)
15051 (unless (org-at-property-p)
15052 (error "Not at a property"))
15053 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15054 (key (match-string 2))
15055 (value (match-string 3))
15056 (allowed (or (org-property-get-allowed-values (point) key)
15057 (and (member value '("[ ]" "[-]" "[X]"))
15058 '("[ ]" "[X]"))))
15059 nval)
15060 (unless allowed
15061 (error "Allowed values for this property have not been defined"))
15062 (if previous (setq allowed (reverse allowed)))
15063 (if (member value allowed)
15064 (setq nval (car (cdr (member value allowed)))))
15065 (setq nval (or nval (car allowed)))
15066 (if (equal nval value)
15067 (error "Only one allowed value for this property"))
15068 (org-at-property-p)
15069 (replace-match (concat " :" key ": " nval) t t)
15070 (org-indent-line)
15071 (beginning-of-line 1)
15072 (skip-chars-forward " \t")
15073 (when (equal prop org-effort-property)
15074 (save-excursion
15075 (org-back-to-heading t)
15076 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15077 (run-hook-with-args 'org-property-changed-functions key nval)))
15079 (defun org-find-olp (path &optional this-buffer)
15080 "Return a marker pointing to the entry at outline path OLP.
15081 If anything goes wrong, throw an error.
15082 You can wrap this call to catch the error like this:
15084 (condition-case msg
15085 (org-mobile-locate-entry (match-string 4))
15086 (error (nth 1 msg)))
15088 The return value will then be either a string with the error message,
15089 or a marker if everything is OK.
15091 If THIS-BUFFER is set, the outline path does not contain a file,
15092 only headings."
15093 (let* ((file (if this-buffer buffer-file-name (pop path)))
15094 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15095 (level 1)
15096 (lmin 1)
15097 (lmax 1)
15098 limit re end found pos heading cnt flevel)
15099 (unless buffer (error "File not found :%s" file))
15100 (with-current-buffer buffer
15101 (save-excursion
15102 (save-restriction
15103 (widen)
15104 (setq limit (point-max))
15105 (goto-char (point-min))
15106 (while (setq heading (pop path))
15107 (setq re (format org-complex-heading-regexp-format
15108 (regexp-quote heading)))
15109 (setq cnt 0 pos (point))
15110 (while (re-search-forward re end t)
15111 (setq level (- (match-end 1) (match-beginning 1)))
15112 (if (and (>= level lmin) (<= level lmax))
15113 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15114 (when (= cnt 0) (error "Heading not found on level %d: %s"
15115 lmax heading))
15116 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15117 lmax heading))
15118 (goto-char found)
15119 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15120 (setq end (save-excursion (org-end-of-subtree t t))))
15121 (when (org-at-heading-p)
15122 (point-marker)))))))
15124 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15125 "Find node HEADING in BUFFER.
15126 Return a marker to the heading if it was found, or nil if not.
15127 If POS-ONLY is set, return just the position instead of a marker.
15129 The heading text must match exact, but it may have a TODO keyword,
15130 a priority cookie and tags in the standard locations."
15131 (with-current-buffer (or buffer (current-buffer))
15132 (save-excursion
15133 (save-restriction
15134 (widen)
15135 (goto-char (point-min))
15136 (let (case-fold-search)
15137 (if (re-search-forward
15138 (format org-complex-heading-regexp-format
15139 (regexp-quote heading)) nil t)
15140 (if pos-only
15141 (match-beginning 0)
15142 (move-marker (make-marker) (match-beginning 0)))))))))
15144 (defun org-find-exact-heading-in-directory (heading &optional dir)
15145 "Find Org node headline HEADING in all .org files in directory DIR.
15146 When the target headline is found, return a marker to this location."
15147 (let ((files (directory-files (or dir default-directory)
15148 nil "\\`[^.#].*\\.org\\'"))
15149 file visiting m buffer)
15150 (catch 'found
15151 (while (setq file (pop files))
15152 (message "trying %s" file)
15153 (setq visiting (org-find-base-buffer-visiting file))
15154 (setq buffer (or visiting (find-file-noselect file)))
15155 (setq m (org-find-exact-headline-in-buffer
15156 heading buffer))
15157 (when (and (not m) (not visiting)) (kill-buffer buffer))
15158 (and m (throw 'found m))))))
15160 (defun org-find-entry-with-id (ident)
15161 "Locate the entry that contains the ID property with exact value IDENT.
15162 IDENT can be a string, a symbol or a number, this function will search for
15163 the string representation of it.
15164 Return the position where this entry starts, or nil if there is no such entry."
15165 (interactive "sID: ")
15166 (let ((id (cond
15167 ((stringp ident) ident)
15168 ((symbol-name ident) (symbol-name ident))
15169 ((numberp ident) (number-to-string ident))
15170 (t (error "IDENT %s must be a string, symbol or number" ident))))
15171 (case-fold-search nil))
15172 (save-excursion
15173 (save-restriction
15174 (widen)
15175 (goto-char (point-min))
15176 (when (re-search-forward
15177 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15178 nil t)
15179 (org-back-to-heading t)
15180 (point))))))
15182 ;;;; Timestamps
15184 (defvar org-last-changed-timestamp nil)
15185 (defvar org-last-inserted-timestamp nil
15186 "The last time stamp inserted with `org-insert-time-stamp'.")
15187 (defvar org-time-was-given) ; dynamically scoped parameter
15188 (defvar org-end-time-was-given) ; dynamically scoped parameter
15189 (defvar org-ts-what) ; dynamically scoped parameter
15191 (defun org-time-stamp (arg &optional inactive)
15192 "Prompt for a date/time and insert a time stamp.
15193 If the user specifies a time like HH:MM or if this command is
15194 called with at least one prefix argument, the time stamp contains
15195 the date and the time. Otherwise, only the date is be included.
15197 All parts of a date not specified by the user is filled in from
15198 the current date/time. So if you just press return without
15199 typing anything, the time stamp will represent the current
15200 date/time.
15202 If there is already a timestamp at the cursor, it will be
15203 modified.
15205 With two universal prefix arguments, insert an active timestamp
15206 with the current time without prompting the user."
15207 (interactive "P")
15208 (let* ((ts nil)
15209 (default-time
15210 ;; Default time is either today, or, when entering a range,
15211 ;; the range start.
15212 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15213 (save-excursion
15214 (re-search-backward
15215 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15216 (- (point) 20) t)))
15217 (apply 'encode-time (org-parse-time-string (match-string 1)))
15218 (current-time)))
15219 (default-input (and ts (org-get-compact-tod ts)))
15220 (repeater (save-excursion
15221 (save-match-data
15222 (beginning-of-line)
15223 (when (re-search-forward
15224 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15225 (save-excursion (progn (end-of-line) (point))) t)
15226 (match-string 0)))))
15227 org-time-was-given org-end-time-was-given time)
15228 (cond
15229 ((and (org-at-timestamp-p t)
15230 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15231 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15232 (insert "--")
15233 (setq time (let ((this-command this-command))
15234 (org-read-date arg 'totime nil nil
15235 default-time default-input inactive)))
15236 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15237 ((org-at-timestamp-p t)
15238 (setq time (let ((this-command this-command))
15239 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15240 (when (org-at-timestamp-p t) ; just to get the match data
15241 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15242 (replace-match "")
15243 (setq org-last-changed-timestamp
15244 (org-insert-time-stamp
15245 time (or org-time-was-given arg)
15246 inactive nil nil (list org-end-time-was-given)))
15247 (when repeater (goto-char (1- (point))) (insert " " repeater)
15248 (setq org-last-changed-timestamp
15249 (concat (substring org-last-inserted-timestamp 0 -1)
15250 " " repeater ">"))))
15251 (message "Timestamp updated"))
15252 ((equal arg '(16))
15253 (org-insert-time-stamp (current-time) t))
15255 (setq time (let ((this-command this-command))
15256 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15257 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15258 nil nil (list org-end-time-was-given))))))
15260 ;; FIXME: can we use this for something else, like computing time differences?
15261 (defun org-get-compact-tod (s)
15262 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15263 (let* ((t1 (match-string 1 s))
15264 (h1 (string-to-number (match-string 2 s)))
15265 (m1 (string-to-number (match-string 3 s)))
15266 (t2 (and (match-end 4) (match-string 5 s)))
15267 (h2 (and t2 (string-to-number (match-string 6 s))))
15268 (m2 (and t2 (string-to-number (match-string 7 s))))
15269 dh dm)
15270 (if (not t2)
15272 (setq dh (- h2 h1) dm (- m2 m1))
15273 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15274 (concat t1 "+" (number-to-string dh)
15275 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15277 (defun org-time-stamp-inactive (&optional arg)
15278 "Insert an inactive time stamp.
15279 An inactive time stamp is enclosed in square brackets instead of angle
15280 brackets. It is inactive in the sense that it does not trigger agenda entries,
15281 does not link to the calendar and cannot be changed with the S-cursor keys.
15282 So these are more for recording a certain time/date."
15283 (interactive "P")
15284 (org-time-stamp arg 'inactive))
15286 (defvar org-date-ovl (make-overlay 1 1))
15287 (overlay-put org-date-ovl 'face 'org-date-selected)
15288 (org-detach-overlay org-date-ovl)
15290 (defvar org-ans1) ; dynamically scoped parameter
15291 (defvar org-ans2) ; dynamically scoped parameter
15293 (defvar org-plain-time-of-day-regexp) ; defined below
15295 (defvar org-overriding-default-time nil) ; dynamically scoped
15296 (defvar org-read-date-overlay nil)
15297 (defvar org-dcst nil) ; dynamically scoped
15298 (defvar org-read-date-history nil)
15299 (defvar org-read-date-final-answer nil)
15300 (defvar org-read-date-analyze-futurep nil)
15301 (defvar org-read-date-analyze-forced-year nil)
15302 (defvar org-read-date-inactive)
15304 (defun org-read-date (&optional org-with-time to-time from-string prompt
15305 default-time default-input inactive)
15306 "Read a date, possibly a time, and make things smooth for the user.
15307 The prompt will suggest to enter an ISO date, but you can also enter anything
15308 which will at least partially be understood by `parse-time-string'.
15309 Unrecognized parts of the date will default to the current day, month, year,
15310 hour and minute. If this command is called to replace a timestamp at point,
15311 or to enter the second timestamp of a range, the default time is taken
15312 from the existing stamp. Furthermore, the command prefers the future,
15313 so if you are giving a date where the year is not given, and the day-month
15314 combination is already past in the current year, it will assume you
15315 mean next year. For details, see the manual. A few examples:
15317 3-2-5 --> 2003-02-05
15318 feb 15 --> currentyear-02-15
15319 2/15 --> currentyear-02-15
15320 sep 12 9 --> 2009-09-12
15321 12:45 --> today 12:45
15322 22 sept 0:34 --> currentyear-09-22 0:34
15323 12 --> currentyear-currentmonth-12
15324 Fri --> nearest Friday (today or later)
15325 etc.
15327 Furthermore you can specify a relative date by giving, as the *first* thing
15328 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15329 change in days weeks, months, years.
15330 With a single plus or minus, the date is relative to today. With a double
15331 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15332 +4d --> four days from today
15333 +4 --> same as above
15334 +2w --> two weeks from today
15335 ++5 --> five days from default date
15337 The function understands only English month and weekday abbreviations.
15339 While prompting, a calendar is popped up - you can also select the
15340 date with the mouse (button 1). The calendar shows a period of three
15341 months. To scroll it to other months, use the keys `>' and `<'.
15342 If you don't like the calendar, turn it off with
15343 \(setq org-read-date-popup-calendar nil)
15345 With optional argument TO-TIME, the date will immediately be converted
15346 to an internal time.
15347 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15348 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15349 still enter a time, and this function will inform the calling routine
15350 about this change. The calling routine may then choose to change the
15351 format used to insert the time stamp into the buffer to include the time.
15352 With optional argument FROM-STRING, read from this string instead from
15353 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15354 the time/date that is used for everything that is not specified by the
15355 user."
15356 (require 'parse-time)
15357 (let* ((org-time-stamp-rounding-minutes
15358 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15359 (org-dcst org-display-custom-times)
15360 (ct (org-current-time))
15361 (org-def (or org-overriding-default-time default-time ct))
15362 (org-defdecode (decode-time org-def))
15363 (dummy (progn
15364 (when (< (nth 2 org-defdecode) org-extend-today-until)
15365 (setcar (nthcdr 2 org-defdecode) -1)
15366 (setcar (nthcdr 1 org-defdecode) 59)
15367 (setq org-def (apply 'encode-time org-defdecode)
15368 org-defdecode (decode-time org-def)))))
15369 (mouse-autoselect-window nil) ; Don't let the mouse jump
15370 (calendar-frame-setup nil)
15371 (calendar-setup nil)
15372 (calendar-move-hook nil)
15373 (calendar-view-diary-initially-flag nil)
15374 (calendar-view-holidays-initially-flag nil)
15375 (timestr (format-time-string
15376 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15377 (prompt (concat (if prompt (concat prompt " ") "")
15378 (format "Date+time [%s]: " timestr)))
15379 ans (org-ans0 "") org-ans1 org-ans2 final)
15381 (cond
15382 (from-string (setq ans from-string))
15383 (org-read-date-popup-calendar
15384 (save-excursion
15385 (save-window-excursion
15386 (calendar)
15387 (org-eval-in-calendar '(setq cursor-type nil) t)
15388 (unwind-protect
15389 (progn
15390 (calendar-forward-day (- (time-to-days org-def)
15391 (calendar-absolute-from-gregorian
15392 (calendar-current-date))))
15393 (org-eval-in-calendar nil t)
15394 (let* ((old-map (current-local-map))
15395 (map (copy-keymap calendar-mode-map))
15396 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15397 (org-defkey map (kbd "RET") 'org-calendar-select)
15398 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15399 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15400 (org-defkey minibuffer-local-map [(meta shift left)]
15401 (lambda () (interactive)
15402 (org-eval-in-calendar '(calendar-backward-month 1))))
15403 (org-defkey minibuffer-local-map [(meta shift right)]
15404 (lambda () (interactive)
15405 (org-eval-in-calendar '(calendar-forward-month 1))))
15406 (org-defkey minibuffer-local-map [(meta shift up)]
15407 (lambda () (interactive)
15408 (org-eval-in-calendar '(calendar-backward-year 1))))
15409 (org-defkey minibuffer-local-map [(meta shift down)]
15410 (lambda () (interactive)
15411 (org-eval-in-calendar '(calendar-forward-year 1))))
15412 (org-defkey minibuffer-local-map [?\e (shift left)]
15413 (lambda () (interactive)
15414 (org-eval-in-calendar '(calendar-backward-month 1))))
15415 (org-defkey minibuffer-local-map [?\e (shift right)]
15416 (lambda () (interactive)
15417 (org-eval-in-calendar '(calendar-forward-month 1))))
15418 (org-defkey minibuffer-local-map [?\e (shift up)]
15419 (lambda () (interactive)
15420 (org-eval-in-calendar '(calendar-backward-year 1))))
15421 (org-defkey minibuffer-local-map [?\e (shift down)]
15422 (lambda () (interactive)
15423 (org-eval-in-calendar '(calendar-forward-year 1))))
15424 (org-defkey minibuffer-local-map [(shift up)]
15425 (lambda () (interactive)
15426 (org-eval-in-calendar '(calendar-backward-week 1))))
15427 (org-defkey minibuffer-local-map [(shift down)]
15428 (lambda () (interactive)
15429 (org-eval-in-calendar '(calendar-forward-week 1))))
15430 (org-defkey minibuffer-local-map [(shift left)]
15431 (lambda () (interactive)
15432 (org-eval-in-calendar '(calendar-backward-day 1))))
15433 (org-defkey minibuffer-local-map [(shift right)]
15434 (lambda () (interactive)
15435 (org-eval-in-calendar '(calendar-forward-day 1))))
15436 (org-defkey minibuffer-local-map ">"
15437 (lambda () (interactive)
15438 (org-eval-in-calendar '(scroll-calendar-left 1))))
15439 (org-defkey minibuffer-local-map "<"
15440 (lambda () (interactive)
15441 (org-eval-in-calendar '(scroll-calendar-right 1))))
15442 (org-defkey minibuffer-local-map "\C-v"
15443 (lambda () (interactive)
15444 (org-eval-in-calendar
15445 '(calendar-scroll-left-three-months 1))))
15446 (org-defkey minibuffer-local-map "\M-v"
15447 (lambda () (interactive)
15448 (org-eval-in-calendar
15449 '(calendar-scroll-right-three-months 1))))
15450 (run-hooks 'org-read-date-minibuffer-setup-hook)
15451 (unwind-protect
15452 (progn
15453 (use-local-map map)
15454 (setq org-read-date-inactive inactive)
15455 (add-hook 'post-command-hook 'org-read-date-display)
15456 (setq org-ans0 (read-string prompt default-input
15457 'org-read-date-history nil))
15458 ;; org-ans0: from prompt
15459 ;; org-ans1: from mouse click
15460 ;; org-ans2: from calendar motion
15461 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15462 (remove-hook 'post-command-hook 'org-read-date-display)
15463 (use-local-map old-map)
15464 (when org-read-date-overlay
15465 (delete-overlay org-read-date-overlay)
15466 (setq org-read-date-overlay nil)))))
15467 (bury-buffer "*Calendar*")))))
15469 (t ; Naked prompt only
15470 (unwind-protect
15471 (setq ans (read-string prompt default-input
15472 'org-read-date-history timestr))
15473 (when org-read-date-overlay
15474 (delete-overlay org-read-date-overlay)
15475 (setq org-read-date-overlay nil)))))
15477 (setq final (org-read-date-analyze ans org-def org-defdecode))
15479 (when org-read-date-analyze-forced-year
15480 (message "Year was forced into %s"
15481 (if org-read-date-force-compatible-dates
15482 "compatible range (1970-2037)"
15483 "range representable on this machine"))
15484 (ding))
15486 ;; One round trip to get rid of 34th of August and stuff like that....
15487 (setq final (decode-time (apply 'encode-time final)))
15489 (setq org-read-date-final-answer ans)
15491 (if to-time
15492 (apply 'encode-time final)
15493 (if (and (boundp 'org-time-was-given) org-time-was-given)
15494 (format "%04d-%02d-%02d %02d:%02d"
15495 (nth 5 final) (nth 4 final) (nth 3 final)
15496 (nth 2 final) (nth 1 final))
15497 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15499 (defvar org-def)
15500 (defvar org-defdecode)
15501 (defvar org-with-time)
15502 (defun org-read-date-display ()
15503 "Display the current date prompt interpretation in the minibuffer."
15504 (when org-read-date-display-live
15505 (when org-read-date-overlay
15506 (delete-overlay org-read-date-overlay))
15507 (when (minibufferp (current-buffer))
15508 (save-excursion
15509 (end-of-line 1)
15510 (while (not (equal (buffer-substring
15511 (max (point-min) (- (point) 4)) (point))
15512 " "))
15513 (insert " ")))
15514 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15515 " " (or org-ans1 org-ans2)))
15516 (org-end-time-was-given nil)
15517 (f (org-read-date-analyze ans org-def org-defdecode))
15518 (fmts (if org-dcst
15519 org-time-stamp-custom-formats
15520 org-time-stamp-formats))
15521 (fmt (if (or org-with-time
15522 (and (boundp 'org-time-was-given) org-time-was-given))
15523 (cdr fmts)
15524 (car fmts)))
15525 (txt (format-time-string fmt (apply 'encode-time f)))
15526 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15527 (txt (concat "=> " txt)))
15528 (when (and org-end-time-was-given
15529 (string-match org-plain-time-of-day-regexp txt))
15530 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15531 org-end-time-was-given
15532 (substring txt (match-end 0)))))
15533 (when org-read-date-analyze-futurep
15534 (setq txt (concat txt " (=>F)")))
15535 (setq org-read-date-overlay
15536 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15537 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15539 (defun org-read-date-analyze (ans org-def org-defdecode)
15540 "Analyze the combined answer of the date prompt."
15541 ;; FIXME: cleanup and comment
15542 (let ((nowdecode (decode-time (current-time)))
15543 delta deltan deltaw deltadef year month day
15544 hour minute second wday pm h2 m2 tl wday1
15545 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15546 (setq org-read-date-analyze-futurep nil
15547 org-read-date-analyze-forced-year nil)
15548 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15549 (setq ans "+0"))
15551 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15552 (setq ans (replace-match "" t t ans)
15553 deltan (car delta)
15554 deltaw (nth 1 delta)
15555 deltadef (nth 2 delta)))
15557 ;; Check if there is an iso week date in there. If yes, store the
15558 ;; info and postpone interpreting it until the rest of the parsing
15559 ;; is done.
15560 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15561 (setq iso-year (if (match-end 1)
15562 (org-small-year-to-year
15563 (string-to-number (match-string 1 ans))))
15564 iso-weekday (if (match-end 3)
15565 (string-to-number (match-string 3 ans)))
15566 iso-week (string-to-number (match-string 2 ans)))
15567 (setq ans (replace-match "" t t ans)))
15569 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15570 (when (string-match
15571 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15572 (setq year (if (match-end 2)
15573 (string-to-number (match-string 2 ans))
15574 (progn (setq kill-year t)
15575 (string-to-number (format-time-string "%Y"))))
15576 month (string-to-number (match-string 3 ans))
15577 day (string-to-number (match-string 4 ans)))
15578 (if (< year 100) (setq year (+ 2000 year)))
15579 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15580 t nil ans)))
15582 ;; Help matching dotted european dates
15583 (when (string-match
15584 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15585 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15586 (setq kill-year t)
15587 (string-to-number (format-time-string "%Y")))
15588 day (string-to-number (match-string 1 ans))
15589 month (string-to-number (match-string 2 ans))
15590 ans (replace-match (format "%04d-%02d-%02d" year month day)
15591 t nil ans)))
15593 ;; Help matching american dates, like 5/30 or 5/30/7
15594 (when (string-match
15595 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15596 (setq year (if (match-end 4)
15597 (string-to-number (match-string 4 ans))
15598 (progn (setq kill-year t)
15599 (string-to-number (format-time-string "%Y"))))
15600 month (string-to-number (match-string 1 ans))
15601 day (string-to-number (match-string 2 ans)))
15602 (if (< year 100) (setq year (+ 2000 year)))
15603 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15604 t nil ans)))
15605 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15606 ;; If there is a time with am/pm, and *no* time without it, we convert
15607 ;; so that matching will be successful.
15608 (loop for i from 1 to 2 do ; twice, for end time as well
15609 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15610 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15611 (setq hour (string-to-number (match-string 1 ans))
15612 minute (if (match-end 3)
15613 (string-to-number (match-string 3 ans))
15615 pm (equal ?p
15616 (string-to-char (downcase (match-string 4 ans)))))
15617 (if (and (= hour 12) (not pm))
15618 (setq hour 0)
15619 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15620 (setq ans (replace-match (format "%02d:%02d" hour minute)
15621 t t ans))))
15623 ;; Check if a time range is given as a duration
15624 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15625 (setq hour (string-to-number (match-string 1 ans))
15626 h2 (+ hour (string-to-number (match-string 3 ans)))
15627 minute (string-to-number (match-string 2 ans))
15628 m2 (+ minute (if (match-end 5) (string-to-number
15629 (match-string 5 ans))0)))
15630 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15631 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15632 t t ans)))
15634 ;; Check if there is a time range
15635 (when (boundp 'org-end-time-was-given)
15636 (setq org-time-was-given nil)
15637 (when (and (string-match org-plain-time-of-day-regexp ans)
15638 (match-end 8))
15639 (setq org-end-time-was-given (match-string 8 ans))
15640 (setq ans (concat (substring ans 0 (match-beginning 7))
15641 (substring ans (match-end 7))))))
15643 (setq tl (parse-time-string ans)
15644 day (or (nth 3 tl) (nth 3 org-defdecode))
15645 month (or (nth 4 tl)
15646 (if (and org-read-date-prefer-future
15647 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15648 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15649 (nth 4 org-defdecode)))
15650 year (or (and (not kill-year) (nth 5 tl))
15651 (if (and org-read-date-prefer-future
15652 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15653 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15654 (nth 5 org-defdecode)))
15655 hour (or (nth 2 tl) (nth 2 org-defdecode))
15656 minute (or (nth 1 tl) (nth 1 org-defdecode))
15657 second (or (nth 0 tl) 0)
15658 wday (nth 6 tl))
15660 (when (and (eq org-read-date-prefer-future 'time)
15661 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15662 (equal day (nth 3 nowdecode))
15663 (equal month (nth 4 nowdecode))
15664 (equal year (nth 5 nowdecode))
15665 (nth 2 tl)
15666 (or (< (nth 2 tl) (nth 2 nowdecode))
15667 (and (= (nth 2 tl) (nth 2 nowdecode))
15668 (nth 1 tl)
15669 (< (nth 1 tl) (nth 1 nowdecode)))))
15670 (setq day (1+ day)
15671 futurep t))
15673 ;; Special date definitions below
15674 (cond
15675 (iso-week
15676 ;; There was an iso week
15677 (require 'cal-iso)
15678 (setq futurep nil)
15679 (setq year (or iso-year year)
15680 day (or iso-weekday wday 1)
15681 wday nil ; to make sure that the trigger below does not match
15682 iso-date (calendar-gregorian-from-absolute
15683 (calendar-absolute-from-iso
15684 (list iso-week day year))))
15685 ; FIXME: Should we also push ISO weeks into the future?
15686 ; (when (and org-read-date-prefer-future
15687 ; (not iso-year)
15688 ; (< (calendar-absolute-from-gregorian iso-date)
15689 ; (time-to-days (current-time))))
15690 ; (setq year (1+ year)
15691 ; iso-date (calendar-gregorian-from-absolute
15692 ; (calendar-absolute-from-iso
15693 ; (list iso-week day year)))))
15694 (setq month (car iso-date)
15695 year (nth 2 iso-date)
15696 day (nth 1 iso-date)))
15697 (deltan
15698 (setq futurep nil)
15699 (unless deltadef
15700 (let ((now (decode-time (current-time))))
15701 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15702 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15703 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15704 ((equal deltaw "m") (setq month (+ month deltan)))
15705 ((equal deltaw "y") (setq year (+ year deltan)))))
15706 ((and wday (not (nth 3 tl)))
15707 ;; Weekday was given, but no day, so pick that day in the week
15708 ;; on or after the derived date.
15709 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15710 (unless (equal wday wday1)
15711 (setq day (+ day (% (- wday wday1 -7) 7))))))
15712 (if (and (boundp 'org-time-was-given)
15713 (nth 2 tl))
15714 (setq org-time-was-given t))
15715 (if (< year 100) (setq year (+ 2000 year)))
15716 ;; Check of the date is representable
15717 (if org-read-date-force-compatible-dates
15718 (progn
15719 (if (< year 1970)
15720 (setq year 1970 org-read-date-analyze-forced-year t))
15721 (if (> year 2037)
15722 (setq year 2037 org-read-date-analyze-forced-year t)))
15723 (condition-case nil
15724 (ignore (encode-time second minute hour day month year))
15725 (error
15726 (setq year (nth 5 org-defdecode))
15727 (setq org-read-date-analyze-forced-year t))))
15728 (setq org-read-date-analyze-futurep futurep)
15729 (list second minute hour day month year)))
15731 (defvar parse-time-weekdays)
15732 (defun org-read-date-get-relative (s today default)
15733 "Check string S for special relative date string.
15734 TODAY and DEFAULT are internal times, for today and for a default.
15735 Return shift list (N what def-flag)
15736 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15737 N is the number of WHATs to shift.
15738 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15739 the DEFAULT date rather than TODAY."
15740 (require 'parse-time)
15741 (when (and
15742 (string-match
15743 (concat
15744 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15745 "\\([0-9]+\\)?"
15746 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15747 "\\([ \t]\\|$\\)") s)
15748 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15749 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15750 (string-to-char (substring (match-string 1 s) -1))
15751 ?+))
15752 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15753 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15754 (what (if (match-end 3) (match-string 3 s) "d"))
15755 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15756 (date (if rel default today))
15757 (wday (nth 6 (decode-time date)))
15758 delta)
15759 (if wday1
15760 (progn
15761 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15762 (if (= dir ?-) (setq delta (- delta 7)))
15763 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15764 (list delta "d" rel))
15765 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15767 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15768 "Turn a user-specified date into the internal representation.
15769 The internal representation needed by the calendar is (month day year).
15770 This is a wrapper to handle the brain-dead convention in calendar that
15771 user function argument order change dependent on argument order."
15772 (if (boundp 'calendar-date-style)
15773 (cond
15774 ((eq calendar-date-style 'american)
15775 (list arg1 arg2 arg3))
15776 ((eq calendar-date-style 'european)
15777 (list arg2 arg1 arg3))
15778 ((eq calendar-date-style 'iso)
15779 (list arg2 arg3 arg1)))
15780 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15781 (if (org-bound-and-true-p european-calendar-style)
15782 (list arg2 arg1 arg3)
15783 (list arg1 arg2 arg3)))))
15785 (defun org-eval-in-calendar (form &optional keepdate)
15786 "Eval FORM in the calendar window and return to current window.
15787 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15788 otherwise stick to the current value of `org-ans2'."
15789 (let ((sf (selected-frame))
15790 (sw (selected-window)))
15791 (select-window (get-buffer-window "*Calendar*" t))
15792 (eval form)
15793 (when (and (not keepdate) (calendar-cursor-to-date))
15794 (let* ((date (calendar-cursor-to-date))
15795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15796 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15797 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15798 (select-window sw)
15799 (org-select-frame-set-input-focus sf)))
15801 (defun org-calendar-select ()
15802 "Return to `org-read-date' with the date currently selected.
15803 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15804 (interactive)
15805 (when (calendar-cursor-to-date)
15806 (let* ((date (calendar-cursor-to-date))
15807 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15808 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15809 (if (active-minibuffer-window) (exit-minibuffer))))
15811 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15812 "Insert a date stamp for the date given by the internal TIME.
15813 WITH-HM means use the stamp format that includes the time of the day.
15814 INACTIVE means use square brackets instead of angular ones, so that the
15815 stamp will not contribute to the agenda.
15816 PRE and POST are optional strings to be inserted before and after the
15817 stamp.
15818 The command returns the inserted time stamp."
15819 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15820 stamp)
15821 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15822 (insert-before-markers (or pre ""))
15823 (when (listp extra)
15824 (setq extra (car extra))
15825 (if (and (stringp extra)
15826 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15827 (setq extra (format "-%02d:%02d"
15828 (string-to-number (match-string 1 extra))
15829 (string-to-number (match-string 2 extra))))
15830 (setq extra nil)))
15831 (when extra
15832 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15833 (insert-before-markers (setq stamp (format-time-string fmt time)))
15834 (insert-before-markers (or post ""))
15835 (setq org-last-inserted-timestamp stamp)))
15837 (defun org-toggle-time-stamp-overlays ()
15838 "Toggle the use of custom time stamp formats."
15839 (interactive)
15840 (setq org-display-custom-times (not org-display-custom-times))
15841 (unless org-display-custom-times
15842 (let ((p (point-min)) (bmp (buffer-modified-p)))
15843 (while (setq p (next-single-property-change p 'display))
15844 (if (and (get-text-property p 'display)
15845 (eq (get-text-property p 'face) 'org-date))
15846 (remove-text-properties
15847 p (setq p (next-single-property-change p 'display))
15848 '(display t))))
15849 (set-buffer-modified-p bmp)))
15850 (if (featurep 'xemacs)
15851 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15852 (org-restart-font-lock)
15853 (setq org-table-may-need-update t)
15854 (if org-display-custom-times
15855 (message "Time stamps are overlaid with custom format")
15856 (message "Time stamp overlays removed")))
15858 (defun org-display-custom-time (beg end)
15859 "Overlay modified time stamp format over timestamp between BEG and END."
15860 (let* ((ts (buffer-substring beg end))
15861 t1 w1 with-hm tf time str w2 (off 0))
15862 (save-match-data
15863 (setq t1 (org-parse-time-string ts t))
15864 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15865 (setq off (- (match-end 0) (match-beginning 0)))))
15866 (setq end (- end off))
15867 (setq w1 (- end beg)
15868 with-hm (and (nth 1 t1) (nth 2 t1))
15869 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15870 time (org-fix-decoded-time t1)
15871 str (org-add-props
15872 (format-time-string
15873 (substring tf 1 -1) (apply 'encode-time time))
15874 nil 'mouse-face 'highlight)
15875 w2 (length str))
15876 (if (not (= w2 w1))
15877 (add-text-properties (1+ beg) (+ 2 beg)
15878 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15879 (if (featurep 'xemacs)
15880 (progn
15881 (put-text-property beg end 'invisible t)
15882 (put-text-property beg end 'end-glyph (make-glyph str)))
15883 (put-text-property beg end 'display str))))
15885 (defun org-translate-time (string)
15886 "Translate all timestamps in STRING to custom format.
15887 But do this only if the variable `org-display-custom-times' is set."
15888 (when org-display-custom-times
15889 (save-match-data
15890 (let* ((start 0)
15891 (re org-ts-regexp-both)
15892 t1 with-hm inactive tf time str beg end)
15893 (while (setq start (string-match re string start))
15894 (setq beg (match-beginning 0)
15895 end (match-end 0)
15896 t1 (save-match-data
15897 (org-parse-time-string (substring string beg end) t))
15898 with-hm (and (nth 1 t1) (nth 2 t1))
15899 inactive (equal (substring string beg (1+ beg)) "[")
15900 tf (funcall (if with-hm 'cdr 'car)
15901 org-time-stamp-custom-formats)
15902 time (org-fix-decoded-time t1)
15903 str (format-time-string
15904 (concat
15905 (if inactive "[" "<") (substring tf 1 -1)
15906 (if inactive "]" ">"))
15907 (apply 'encode-time time))
15908 string (replace-match str t t string)
15909 start (+ start (length str)))))))
15910 string)
15912 (defun org-fix-decoded-time (time)
15913 "Set 0 instead of nil for the first 6 elements of time.
15914 Don't touch the rest."
15915 (let ((n 0))
15916 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15918 (defun org-days-to-time (timestamp-string)
15919 "Difference between TIMESTAMP-STRING and now in days."
15920 (- (time-to-days (org-time-string-to-time timestamp-string))
15921 (time-to-days (current-time))))
15923 (defun org-deadline-close (timestamp-string &optional ndays)
15924 "Is the time in TIMESTAMP-STRING close to the current date?"
15925 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15926 (and (< (org-days-to-time timestamp-string) ndays)
15927 (not (org-entry-is-done-p))))
15929 (defun org-get-wdays (ts)
15930 "Get the deadline lead time appropriate for timestring TS."
15931 (cond
15932 ((<= org-deadline-warning-days 0)
15933 ;; 0 or negative, enforce this value no matter what
15934 (- org-deadline-warning-days))
15935 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15936 ;; lead time is specified.
15937 (floor (* (string-to-number (match-string 1 ts))
15938 (cdr (assoc (match-string 2 ts)
15939 '(("d" . 1) ("w" . 7)
15940 ("m" . 30.4) ("y" . 365.25)
15941 ("h" . 0.041667)))))))
15942 ;; go for the default.
15943 (t org-deadline-warning-days)))
15945 (defun org-calendar-select-mouse (ev)
15946 "Return to `org-read-date' with the date currently selected.
15947 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15948 (interactive "e")
15949 (mouse-set-point ev)
15950 (when (calendar-cursor-to-date)
15951 (let* ((date (calendar-cursor-to-date))
15952 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15953 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15954 (if (active-minibuffer-window) (exit-minibuffer))))
15956 (defun org-check-deadlines (ndays)
15957 "Check if there are any deadlines due or past due.
15958 A deadline is considered due if it happens within `org-deadline-warning-days'
15959 days from today's date. If the deadline appears in an entry marked DONE,
15960 it is not shown. The prefix arg NDAYS can be used to test that many
15961 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15962 (interactive "P")
15963 (let* ((org-warn-days
15964 (cond
15965 ((equal ndays '(4)) 100000)
15966 (ndays (prefix-numeric-value ndays))
15967 (t (abs org-deadline-warning-days))))
15968 (case-fold-search nil)
15969 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15970 (callback
15971 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15973 (message "%d deadlines past-due or due within %d days"
15974 (org-occur regexp nil callback)
15975 org-warn-days)))
15977 (defsubst org-re-timestamp (type)
15978 "Return a regexp for timestamp TYPE.
15979 Allowed values for TYPE are:
15981 all: all timestamps
15982 active: only active timestamps (<...>)
15983 inactive: only inactive timestamps ([...])
15984 scheduled: only scheduled timestamps
15985 deadline: only deadline timestamps
15987 When TYPE is nil, fall back on returning a regexp that matches
15988 both scheduled and deadline timestamps."
15989 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15990 ((eq type 'active) org-ts-regexp)
15991 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15992 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15993 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15994 ((eq type 'scheduled-or-deadline)
15995 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15997 (defun org-check-before-date (date)
15998 "Check if there are deadlines or scheduled entries before DATE."
15999 (interactive (list (org-read-date)))
16000 (let ((case-fold-search nil)
16001 (regexp (org-re-timestamp org-ts-type))
16002 (callback
16003 (lambda () (time-less-p
16004 (org-time-string-to-time (match-string 1))
16005 (org-time-string-to-time date)))))
16006 (message "%d entries before %s"
16007 (org-occur regexp nil callback) date)))
16009 (defun org-check-after-date (date)
16010 "Check if there are deadlines or scheduled entries after DATE."
16011 (interactive (list (org-read-date)))
16012 (let ((case-fold-search nil)
16013 (regexp (org-re-timestamp org-ts-type))
16014 (callback
16015 (lambda () (not
16016 (time-less-p
16017 (org-time-string-to-time (match-string 1))
16018 (org-time-string-to-time date))))))
16019 (message "%d entries after %s"
16020 (org-occur regexp nil callback) date)))
16022 (defun org-check-dates-range (start-date end-date)
16023 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16024 (interactive (list (org-read-date nil nil nil "Range starts")
16025 (org-read-date nil nil nil "Range end")))
16026 (let ((case-fold-search nil)
16027 (regexp (org-re-timestamp org-ts-type))
16028 (callback
16029 (lambda ()
16030 (let ((match (match-string 1)))
16031 (and
16032 (not (time-less-p
16033 (org-time-string-to-time match)
16034 (org-time-string-to-time start-date)))
16035 (time-less-p
16036 (org-time-string-to-time match)
16037 (org-time-string-to-time end-date)))))))
16038 (message "%d entries between %s and %s"
16039 (org-occur regexp nil callback) start-date end-date)))
16041 (defun org-evaluate-time-range (&optional to-buffer)
16042 "Evaluate a time range by computing the difference between start and end.
16043 Normally the result is just printed in the echo area, but with prefix arg
16044 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16045 If the time range is actually in a table, the result is inserted into the
16046 next column.
16047 For time difference computation, a year is assumed to be exactly 365
16048 days in order to avoid rounding problems."
16049 (interactive "P")
16051 (org-clock-update-time-maybe)
16052 (save-excursion
16053 (unless (org-at-date-range-p t)
16054 (goto-char (point-at-bol))
16055 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16056 (if (not (org-at-date-range-p t))
16057 (error "Not at a time-stamp range, and none found in current line")))
16058 (let* ((ts1 (match-string 1))
16059 (ts2 (match-string 2))
16060 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16061 (match-end (match-end 0))
16062 (time1 (org-time-string-to-time ts1))
16063 (time2 (org-time-string-to-time ts2))
16064 (t1 (org-float-time time1))
16065 (t2 (org-float-time time2))
16066 (diff (abs (- t2 t1)))
16067 (negative (< (- t2 t1) 0))
16068 ;; (ys (floor (* 365 24 60 60)))
16069 (ds (* 24 60 60))
16070 (hs (* 60 60))
16071 (fy "%dy %dd %02d:%02d")
16072 (fy1 "%dy %dd")
16073 (fd "%dd %02d:%02d")
16074 (fd1 "%dd")
16075 (fh "%02d:%02d")
16076 y d h m align)
16077 (if havetime
16078 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16080 d (floor (/ diff ds)) diff (mod diff ds)
16081 h (floor (/ diff hs)) diff (mod diff hs)
16082 m (floor (/ diff 60)))
16083 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16085 d (floor (+ (/ diff ds) 0.5))
16086 h 0 m 0))
16087 (if (not to-buffer)
16088 (message "%s" (org-make-tdiff-string y d h m))
16089 (if (org-at-table-p)
16090 (progn
16091 (goto-char match-end)
16092 (setq align t)
16093 (and (looking-at " *|") (goto-char (match-end 0))))
16094 (goto-char match-end))
16095 (if (looking-at
16096 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16097 (replace-match ""))
16098 (if negative (insert " -"))
16099 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16100 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16101 (insert " " (format fh h m))))
16102 (if align (org-table-align))
16103 (message "Time difference inserted")))))
16105 (defun org-make-tdiff-string (y d h m)
16106 (let ((fmt "")
16107 (l nil))
16108 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16109 l (push y l)))
16110 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16111 l (push d l)))
16112 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16113 l (push h l)))
16114 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16115 l (push m l)))
16116 (apply 'format fmt (nreverse l))))
16118 (defun org-time-string-to-time (s &optional buffer pos)
16119 "Convert a timestamp string into internal time."
16120 (condition-case errdata
16121 (apply 'encode-time (org-parse-time-string s))
16122 (error (error "Bad timestamp `%s'%s\nError was: %s"
16123 s (if (not (and buffer pos))
16125 (format " at %d in buffer `%s'" pos buffer))
16126 (cdr errdata)))))
16128 (defun org-time-string-to-seconds (s)
16129 "Convert a timestamp string to a number of seconds."
16130 (org-float-time (org-time-string-to-time s)))
16132 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16133 "Convert a time stamp to an absolute day number.
16134 If there is a specifier for a cyclic time stamp, get the closest date to
16135 DAYNR.
16136 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16137 The variable date is bound by the calendar when this is called."
16138 (cond
16139 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16140 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16141 daynr
16142 (+ daynr 1000)))
16143 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16144 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16145 (time-to-days (current-time))) (match-string 0 s)
16146 prefer show-all))
16147 (t (time-to-days
16148 (condition-case errdata
16149 (apply 'encode-time (org-parse-time-string s))
16150 (error (error "Bad timestamp `%s'%s\nError was: %s"
16151 s (if (not (and buffer pos))
16153 (format " at %d in buffer `%s'" pos buffer))
16154 (cdr errdata))))))))
16156 (defun org-days-to-iso-week (days)
16157 "Return the iso week number."
16158 (require 'cal-iso)
16159 (car (calendar-iso-from-absolute days)))
16161 (defun org-small-year-to-year (year)
16162 "Convert 2-digit years into 4-digit years.
16163 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16164 The year 2000 cannot be abbreviated. Any year larger than 99
16165 is returned unchanged."
16166 (if (< year 38)
16167 (setq year (+ 2000 year))
16168 (if (< year 100)
16169 (setq year (+ 1900 year))))
16170 year)
16172 (defun org-time-from-absolute (d)
16173 "Return the time corresponding to date D.
16174 D may be an absolute day number, or a calendar-type list (month day year)."
16175 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16176 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16178 (defun org-calendar-holiday ()
16179 "List of holidays, for Diary display in Org-mode."
16180 (require 'holidays)
16181 (let ((hl (funcall
16182 (if (fboundp 'calendar-check-holidays)
16183 'calendar-check-holidays 'check-calendar-holidays) date)))
16184 (if hl (mapconcat 'identity hl "; "))))
16186 (defun org-diary-sexp-entry (sexp entry date)
16187 "Process a SEXP diary ENTRY for DATE."
16188 (require 'diary-lib)
16189 (let ((result (if calendar-debug-sexp
16190 (let ((stack-trace-on-error t))
16191 (eval (car (read-from-string sexp))))
16192 (condition-case nil
16193 (eval (car (read-from-string sexp)))
16194 (error
16195 (beep)
16196 (message "Bad sexp at line %d in %s: %s"
16197 (org-current-line)
16198 (buffer-file-name) sexp)
16199 (sleep-for 2))))))
16200 (cond ((stringp result) (split-string result "; "))
16201 ((and (consp result)
16202 (not (consp (cdr result)))
16203 (stringp (cdr result))) (cdr result))
16204 ((and (consp result)
16205 (stringp (car result))) result)
16206 (result entry))))
16208 (defun org-diary-to-ical-string (frombuf)
16209 "Get iCalendar entries from diary entries in buffer FROMBUF.
16210 This uses the icalendar.el library."
16211 (let* ((tmpdir (if (featurep 'xemacs)
16212 (temp-directory)
16213 temporary-file-directory))
16214 (tmpfile (make-temp-name
16215 (expand-file-name "orgics" tmpdir)))
16216 buf rtn b e)
16217 (with-current-buffer frombuf
16218 (icalendar-export-region (point-min) (point-max) tmpfile)
16219 (setq buf (find-buffer-visiting tmpfile))
16220 (set-buffer buf)
16221 (goto-char (point-min))
16222 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16223 (setq b (match-beginning 0)))
16224 (goto-char (point-max))
16225 (if (re-search-backward "^END:VEVENT" nil t)
16226 (setq e (match-end 0)))
16227 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16228 (kill-buffer buf)
16229 (delete-file tmpfile)
16230 rtn))
16232 (defun org-closest-date (start current change prefer show-all)
16233 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16234 When PREFER is `past', return a date that is either CURRENT or past.
16235 When PREFER is `future', return a date that is either CURRENT or future.
16236 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16237 ;; Make the proper lists from the dates
16238 (catch 'exit
16239 (let ((a1 '(("h" . hour)
16240 ("d" . day)
16241 ("w" . week)
16242 ("m" . month)
16243 ("y" . year)))
16244 (shour (nth 2 (org-parse-time-string start)))
16245 dn dw sday cday n1 n2 n0
16246 d m y y1 y2 date1 date2 nmonths nm ny m2)
16248 (setq start (org-date-to-gregorian start)
16249 current (org-date-to-gregorian
16250 (if show-all
16251 current
16252 (time-to-days (current-time))))
16253 sday (calendar-absolute-from-gregorian start)
16254 cday (calendar-absolute-from-gregorian current))
16256 (if (<= cday sday) (throw 'exit sday))
16258 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16259 (setq dn (string-to-number (match-string 1 change))
16260 dw (cdr (assoc (match-string 2 change) a1)))
16261 (error "Invalid change specifier: %s" change))
16262 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16263 (cond
16264 ((eq dw 'hour)
16265 (let ((missing-hours
16266 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16267 dn)))
16268 (setq n1 (if (zerop missing-hours) cday
16269 (- cday (1+ (floor (/ missing-hours 24)))))
16270 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16271 ((eq dw 'day)
16272 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16273 n2 (+ n1 dn)))
16274 ((eq dw 'year)
16275 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16276 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16277 (setq date1 (list m d y1)
16278 n1 (calendar-absolute-from-gregorian date1)
16279 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16280 n2 (calendar-absolute-from-gregorian date2)))
16281 ((eq dw 'month)
16282 ;; approx number of month between the two dates
16283 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16284 ;; How often does dn fit in there?
16285 (setq d (nth 1 start) m (car start) y (nth 2 start)
16286 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16287 m (+ m nm)
16288 ny (floor (/ m 12))
16289 y (+ y ny)
16290 m (- m (* ny 12)))
16291 (while (> m 12) (setq m (- m 12) y (1+ y)))
16292 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16293 (setq m2 (+ m dn) y2 y)
16294 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16295 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16296 (while (<= n2 cday)
16297 (setq n1 n2 m m2 y y2)
16298 (setq m2 (+ m dn) y2 y)
16299 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16300 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16301 ;; Make sure n1 is the earlier date
16302 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16303 (if show-all
16304 (cond
16305 ((eq prefer 'past) (if (= cday n2) n2 n1))
16306 ((eq prefer 'future) (if (= cday n1) n1 n2))
16307 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16308 (cond
16309 ((eq prefer 'past) (if (= cday n2) n2 n1))
16310 ((eq prefer 'future) (if (= cday n1) n1 n2))
16311 (t (if (= cday n1) n1 n2)))))))
16313 (defun org-date-to-gregorian (date)
16314 "Turn any specification of DATE into a Gregorian date for the calendar."
16315 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16316 ((and (listp date) (= (length date) 3)) date)
16317 ((stringp date)
16318 (setq date (org-parse-time-string date))
16319 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16320 ((listp date)
16321 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16323 (defun org-parse-time-string (s &optional nodefault)
16324 "Parse the standard Org-mode time string.
16325 This should be a lot faster than the normal `parse-time-string'.
16326 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16327 hour and minute fields will be nil if not given."
16328 (if (string-match org-ts-regexp0 s)
16329 (list 0
16330 (if (or (match-beginning 8) (not nodefault))
16331 (string-to-number (or (match-string 8 s) "0")))
16332 (if (or (match-beginning 7) (not nodefault))
16333 (string-to-number (or (match-string 7 s) "0")))
16334 (string-to-number (match-string 4 s))
16335 (string-to-number (match-string 3 s))
16336 (string-to-number (match-string 2 s))
16337 nil nil nil)
16338 (error "Not a standard Org-mode time string: %s" s)))
16340 (defun org-timestamp-up (&optional arg)
16341 "Increase the date item at the cursor by one.
16342 If the cursor is on the year, change the year. If it is on the month,
16343 the day or the time, change that.
16344 With prefix ARG, change by that many units."
16345 (interactive "p")
16346 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16348 (defun org-timestamp-down (&optional arg)
16349 "Decrease the date item at the cursor by one.
16350 If the cursor is on the year, change the year. If it is on the month,
16351 the day or the time, change that.
16352 With prefix ARG, change by that many units."
16353 (interactive "p")
16354 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16356 (defun org-timestamp-up-day (&optional arg)
16357 "Increase the date in the time stamp by one day.
16358 With prefix ARG, change that many days."
16359 (interactive "p")
16360 (if (and (not (org-at-timestamp-p t))
16361 (org-at-heading-p))
16362 (org-todo 'up)
16363 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16365 (defun org-timestamp-down-day (&optional arg)
16366 "Decrease the date in the time stamp by one day.
16367 With prefix ARG, change that many days."
16368 (interactive "p")
16369 (if (and (not (org-at-timestamp-p t))
16370 (org-at-heading-p))
16371 (org-todo 'down)
16372 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16374 (defun org-at-timestamp-p (&optional inactive-ok)
16375 "Determine if the cursor is in or at a timestamp."
16376 (interactive)
16377 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16378 (pos (point))
16379 (ans (or (looking-at tsr)
16380 (save-excursion
16381 (skip-chars-backward "^[<\n\r\t")
16382 (if (> (point) (point-min)) (backward-char 1))
16383 (and (looking-at tsr)
16384 (> (- (match-end 0) pos) -1))))))
16385 (and ans
16386 (boundp 'org-ts-what)
16387 (setq org-ts-what
16388 (cond
16389 ((= pos (match-beginning 0)) 'bracket)
16390 ;; Point is considered to be "on the bracket" whether
16391 ;; it's really on it or right after it.
16392 ((= pos (1- (match-end 0))) 'bracket)
16393 ((= pos (match-end 0)) 'after)
16394 ((org-pos-in-match-range pos 2) 'year)
16395 ((org-pos-in-match-range pos 3) 'month)
16396 ((org-pos-in-match-range pos 7) 'hour)
16397 ((org-pos-in-match-range pos 8) 'minute)
16398 ((or (org-pos-in-match-range pos 4)
16399 (org-pos-in-match-range pos 5)) 'day)
16400 ((and (> pos (or (match-end 8) (match-end 5)))
16401 (< pos (match-end 0)))
16402 (- pos (or (match-end 8) (match-end 5))))
16403 (t 'day))))
16404 ans))
16406 (defun org-toggle-timestamp-type ()
16407 "Toggle the type (<active> or [inactive]) of a time stamp."
16408 (interactive)
16409 (when (org-at-timestamp-p t)
16410 (let ((beg (match-beginning 0)) (end (match-end 0))
16411 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16412 (save-excursion
16413 (goto-char beg)
16414 (while (re-search-forward "[][<>]" end t)
16415 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16416 t t)))
16417 (message "Timestamp is now %sactive"
16418 (if (equal (char-after beg) ?<) "" "in")))))
16420 (defun org-at-clock-log-p nil
16421 "Is the cursor on the clock log line?"
16422 (save-excursion
16423 (move-beginning-of-line 1)
16424 (looking-at "^[ \t]*CLOCK:")))
16426 (defvar org-clock-history) ; defined in org-clock.el
16427 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16428 (defun org-timestamp-change (n &optional what updown)
16429 "Change the date in the time stamp at point.
16430 The date will be changed by N times WHAT. WHAT can be `day', `month',
16431 `year', `minute', `second'. If WHAT is not given, the cursor position
16432 in the timestamp determines what will be changed."
16433 (let ((origin (point)) origin-cat
16434 with-hm inactive
16435 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16436 org-ts-what
16437 extra rem
16438 ts time time0 fixnext clrgx)
16439 (if (not (org-at-timestamp-p t))
16440 (error "Not at a timestamp"))
16441 (if (and (not what) (eq org-ts-what 'bracket))
16442 (org-toggle-timestamp-type)
16443 ;; Point isn't on brackets. Remember the part of the time-stamp
16444 ;; the point was in. Indeed, size of time-stamps may change,
16445 ;; but point must be kept in the same category nonetheless.
16446 (setq origin-cat org-ts-what)
16447 (if (and (not what) (not (eq org-ts-what 'day))
16448 org-display-custom-times
16449 (get-text-property (point) 'display)
16450 (not (get-text-property (1- (point)) 'display)))
16451 (setq org-ts-what 'day))
16452 (setq org-ts-what (or what org-ts-what)
16453 inactive (= (char-after (match-beginning 0)) ?\[)
16454 ts (match-string 0))
16455 (replace-match "")
16456 (if (string-match
16457 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16459 (setq extra (match-string 1 ts)))
16460 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16461 (setq with-hm t))
16462 (setq time0 (org-parse-time-string ts))
16463 (when (and updown
16464 (eq org-ts-what 'minute)
16465 (not current-prefix-arg))
16466 ;; This looks like s-up and s-down. Change by one rounding step.
16467 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16468 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16469 (setcar (cdr time0) (+ (nth 1 time0)
16470 (if (> n 0) (- rem) (- dm rem))))))
16471 (setq time
16472 (encode-time (or (car time0) 0)
16473 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16474 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16475 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16476 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16477 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16478 (nthcdr 6 time0)))
16479 (when (and (member org-ts-what '(hour minute))
16480 extra
16481 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16482 (setq extra (org-modify-ts-extra
16483 extra
16484 (if (eq org-ts-what 'hour) 2 5)
16485 n dm)))
16486 (when (integerp org-ts-what)
16487 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16488 (if (eq what 'calendar)
16489 (let ((cal-date (org-get-date-from-calendar)))
16490 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16491 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16492 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16493 (setcar time0 (or (car time0) 0))
16494 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16495 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16496 (setq time (apply 'encode-time time0))))
16497 ;; Insert the new time-stamp, and ensure point stays in the same
16498 ;; category as before (i.e. not after the last position in that
16499 ;; category).
16500 (let ((pos (point)))
16501 ;; Stay before inserted string. `save-excursion' is of no use.
16502 (setq org-last-changed-timestamp
16503 (org-insert-time-stamp time with-hm inactive nil nil extra))
16504 (goto-char pos))
16505 (save-match-data
16506 (looking-at org-ts-regexp3)
16507 (goto-char (cond
16508 ;; `day' category ends before `hour' if any, or at
16509 ;; the end of the day name.
16510 ((eq origin-cat 'day)
16511 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16512 ((eq origin-cat 'hour) (min (match-end 7) origin))
16513 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16514 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16515 ;; `year' and `month' have both fixed size: point
16516 ;; couldn't have moved into another part.
16517 (t origin))))
16518 ;; Update clock if on a CLOCK line.
16519 (org-clock-update-time-maybe)
16520 ;; Maybe adjust the closest clock in `org-clock-history'
16521 (when org-clock-adjust-closest
16522 (if (not (and (org-at-clock-log-p)
16523 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16524 org-clock-history))))))
16525 (message "No clock to adjust")
16526 (cond ((save-excursion ; fix previous clock?
16527 (re-search-backward org-ts-regexp0 nil t)
16528 (org-looking-back (concat org-clock-string " \\[")))
16529 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16530 ((save-excursion ; fix next clock?
16531 (re-search-backward org-ts-regexp0 nil t)
16532 (looking-at (concat org-ts-regexp0 "\\] =>")))
16533 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16534 (save-window-excursion
16535 ;; Find closest clock to point, adjust the previous/next one in history
16536 (let* ((p (save-excursion (org-back-to-heading t)))
16537 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16538 (clfixnth
16539 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16540 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16541 (if (not clfixpos)
16542 (message "No clock to adjust")
16543 (save-excursion
16544 (org-goto-marker-or-bmk clfixpos)
16545 (org-show-subtree)
16546 (when (re-search-forward clrgx nil t)
16547 (goto-char (match-beginning 1))
16548 (let (org-clock-adjust-closest)
16549 (org-timestamp-change n org-ts-what updown))
16550 (message "Clock adjusted in %s for heading: %s"
16551 (file-name-nondirectory (buffer-file-name))
16552 (org-get-heading t t)))))))))
16553 ;; Try to recenter the calendar window, if any.
16554 (if (and org-calendar-follow-timestamp-change
16555 (get-buffer-window "*Calendar*" t)
16556 (memq org-ts-what '(day month year)))
16557 (org-recenter-calendar (time-to-days time))))))
16559 (defun org-modify-ts-extra (s pos n dm)
16560 "Change the different parts of the lead-time and repeat fields in timestamp."
16561 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16562 ng h m new rem)
16563 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16564 (cond
16565 ((or (org-pos-in-match-range pos 2)
16566 (org-pos-in-match-range pos 3))
16567 (setq m (string-to-number (match-string 3 s))
16568 h (string-to-number (match-string 2 s)))
16569 (if (org-pos-in-match-range pos 2)
16570 (setq h (+ h n))
16571 (setq n (* dm (org-no-warnings (signum n))))
16572 (when (not (= 0 (setq rem (% m dm))))
16573 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16574 (setq m (+ m n)))
16575 (if (< m 0) (setq m (+ m 60) h (1- h)))
16576 (if (> m 59) (setq m (- m 60) h (1+ h)))
16577 (setq h (min 24 (max 0 h)))
16578 (setq ng 1 new (format "-%02d:%02d" h m)))
16579 ((org-pos-in-match-range pos 6)
16580 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16581 ((org-pos-in-match-range pos 5)
16582 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16584 ((org-pos-in-match-range pos 9)
16585 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16586 ((org-pos-in-match-range pos 8)
16587 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16589 (when ng
16590 (setq s (concat
16591 (substring s 0 (match-beginning ng))
16593 (substring s (match-end ng))))))
16596 (defun org-recenter-calendar (date)
16597 "If the calendar is visible, recenter it to DATE."
16598 (let ((cwin (get-buffer-window "*Calendar*" t)))
16599 (when cwin
16600 (let ((calendar-move-hook nil))
16601 (with-selected-window cwin
16602 (calendar-goto-date (if (listp date) date
16603 (calendar-gregorian-from-absolute date))))))))
16605 (defun org-goto-calendar (&optional arg)
16606 "Go to the Emacs calendar at the current date.
16607 If there is a time stamp in the current line, go to that date.
16608 A prefix ARG can be used to force the current date."
16609 (interactive "P")
16610 (let ((tsr org-ts-regexp) diff
16611 (calendar-move-hook nil)
16612 (calendar-view-holidays-initially-flag nil)
16613 (calendar-view-diary-initially-flag nil))
16614 (if (or (org-at-timestamp-p)
16615 (save-excursion
16616 (beginning-of-line 1)
16617 (looking-at (concat ".*" tsr))))
16618 (let ((d1 (time-to-days (current-time)))
16619 (d2 (time-to-days
16620 (org-time-string-to-time (match-string 1)))))
16621 (setq diff (- d2 d1))))
16622 (calendar)
16623 (calendar-goto-today)
16624 (if (and diff (not arg)) (calendar-forward-day diff))))
16626 (defun org-get-date-from-calendar ()
16627 "Return a list (month day year) of date at point in calendar."
16628 (with-current-buffer "*Calendar*"
16629 (save-match-data
16630 (calendar-cursor-to-date))))
16632 (defun org-date-from-calendar ()
16633 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16634 If there is already a time stamp at the cursor position, update it."
16635 (interactive)
16636 (if (org-at-timestamp-p t)
16637 (org-timestamp-change 0 'calendar)
16638 (let ((cal-date (org-get-date-from-calendar)))
16639 (org-insert-time-stamp
16640 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16642 (defun org-minutes-to-hh:mm-string (m)
16643 "Compute H:MM from a number of minutes."
16644 (let ((h (/ m 60)))
16645 (setq m (- m (* 60 h)))
16646 (format org-time-clocksum-format h m)))
16648 (defun org-hh:mm-string-to-minutes (s)
16649 "Convert a string H:MM to a number of minutes.
16650 If the string is just a number, interpret it as minutes.
16651 In fact, the first hh:mm or number in the string will be taken,
16652 there can be extra stuff in the string.
16653 If no number is found, the return value is 0."
16654 (cond
16655 ((integerp s) s)
16656 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16657 (+ (* (string-to-number (match-string 1 s)) 60)
16658 (string-to-number (match-string 2 s))))
16659 ((string-match "\\([0-9]+\\)" s)
16660 (string-to-number (match-string 1 s)))
16661 (t 0)))
16663 (defcustom org-effort-durations
16664 `(("h" . 60)
16665 ("d" . ,(* 60 8))
16666 ("w" . ,(* 60 8 5))
16667 ("m" . ,(* 60 8 5 4))
16668 ("y" . ,(* 60 8 5 40)))
16669 "Conversion factor to minutes for an effort modifier.
16671 Each entry has the form (MODIFIER . MINUTES).
16673 In an effort string, a number followed by MODIFIER is multiplied
16674 by the specified number of MINUTES to obtain an effort in
16675 minutes.
16677 For example, if the value of this variable is ((\"hours\" . 60)), then an
16678 effort string \"2hours\" is equivalent to 120 minutes."
16679 :group 'org-agenda
16680 :version "24.1"
16681 :type '(alist :key-type (string :tag "Modifier")
16682 :value-type (number :tag "Minutes")))
16684 (defcustom org-agenda-inhibit-startup t
16685 "Inhibit startup when preparing agenda buffers.
16686 When this variable is `t' (the default), the initialization of
16687 the Org agenda buffers is inhibited: e.g. the visibility state
16688 is not set, the tables are not re-aligned, etc."
16689 :type 'boolean
16690 :version "24.3"
16691 :group 'org-agenda)
16693 (defun org-duration-string-to-minutes (s &optional output-to-string)
16694 "Convert a duration string S to minutes.
16696 A bare number is interpreted as minutes, modifiers can be set by
16697 customizing `org-effort-durations' (which see).
16699 Entries containing a colon are interpreted as H:MM by
16700 `org-hh:mm-string-to-minutes'."
16701 (let ((result 0)
16702 (re (concat "\\([0-9.]+\\) *\\("
16703 (regexp-opt (mapcar 'car org-effort-durations))
16704 "\\)")))
16705 (while (string-match re s)
16706 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16707 (string-to-number (match-string 1 s))))
16708 (setq s (replace-match "" nil t s)))
16709 (setq result (floor result))
16710 (incf result (org-hh:mm-string-to-minutes s))
16711 (if output-to-string (number-to-string result) result)))
16713 ;;;; Files
16715 (defun org-save-all-org-buffers ()
16716 "Save all Org-mode buffers without user confirmation."
16717 (interactive)
16718 (message "Saving all Org-mode buffers...")
16719 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16720 (when (featurep 'org-id) (org-id-locations-save))
16721 (message "Saving all Org-mode buffers... done"))
16723 (defun org-revert-all-org-buffers ()
16724 "Revert all Org-mode buffers.
16725 Prompt for confirmation when there are unsaved changes.
16726 Be sure you know what you are doing before letting this function
16727 overwrite your changes.
16729 This function is useful in a setup where one tracks org files
16730 with a version control system, to revert on one machine after pulling
16731 changes from another. I believe the procedure must be like this:
16733 1. M-x org-save-all-org-buffers
16734 2. Pull changes from the other machine, resolve conflicts
16735 3. M-x org-revert-all-org-buffers"
16736 (interactive)
16737 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16738 (error "Abort"))
16739 (save-excursion
16740 (save-window-excursion
16741 (mapc
16742 (lambda (b)
16743 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16744 (with-current-buffer b buffer-file-name))
16745 (org-pop-to-buffer-same-window b)
16746 (revert-buffer t 'no-confirm)))
16747 (buffer-list))
16748 (when (and (featurep 'org-id) org-id-track-globally)
16749 (org-id-locations-load)))))
16751 ;;;; Agenda files
16753 ;;;###autoload
16754 (defun org-switchb (&optional arg)
16755 "Switch between Org buffers.
16756 With one prefix argument, restrict available buffers to files.
16757 With two prefix arguments, restrict available buffers to agenda files.
16759 Defaults to `iswitchb' for buffer name completion.
16760 Set `org-completion-use-ido' to make it use ido instead."
16761 (interactive "P")
16762 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16763 ((equal arg '(16)) (org-buffer-list 'agenda))
16764 (t (org-buffer-list))))
16765 (org-completion-use-iswitchb org-completion-use-iswitchb)
16766 (org-completion-use-ido org-completion-use-ido))
16767 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16768 (setq org-completion-use-iswitchb t))
16769 (org-pop-to-buffer-same-window
16770 (org-icompleting-read "Org buffer: "
16771 (mapcar 'list (mapcar 'buffer-name blist))
16772 nil t))))
16774 ;;; Define some older names previously used for this functionality
16775 ;;;###autoload
16776 (defalias 'org-ido-switchb 'org-switchb)
16777 ;;;###autoload
16778 (defalias 'org-iswitchb 'org-switchb)
16780 (defun org-buffer-list (&optional predicate exclude-tmp)
16781 "Return a list of Org buffers.
16782 PREDICATE can be `export', `files' or `agenda'.
16784 export restrict the list to Export buffers.
16785 files restrict the list to buffers visiting Org files.
16786 agenda restrict the list to buffers visiting agenda files.
16788 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16789 (let* ((bfn nil)
16790 (agenda-files (and (eq predicate 'agenda)
16791 (mapcar 'file-truename (org-agenda-files t))))
16792 (filter
16793 (cond
16794 ((eq predicate 'files)
16795 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16796 ((eq predicate 'export)
16797 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16798 ((eq predicate 'agenda)
16799 (lambda (b)
16800 (with-current-buffer b
16801 (and (derived-mode-p 'org-mode)
16802 (setq bfn (buffer-file-name b))
16803 (member (file-truename bfn) agenda-files)))))
16804 (t (lambda (b) (with-current-buffer b
16805 (or (derived-mode-p 'org-mode)
16806 (string-match "\*Org .*Export"
16807 (buffer-name b)))))))))
16808 (delq nil
16809 (mapcar
16810 (lambda(b)
16811 (if (and (funcall filter b)
16812 (or (not exclude-tmp)
16813 (not (string-match "tmp" (buffer-name b)))))
16815 nil))
16816 (buffer-list)))))
16818 (defun org-agenda-files (&optional unrestricted archives)
16819 "Get the list of agenda files.
16820 Optional UNRESTRICTED means return the full list even if a restriction
16821 is currently in place.
16822 When ARCHIVES is t, include all archive files that are really being
16823 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16824 `org-agenda-archives-mode' is t."
16825 (let ((files
16826 (cond
16827 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16828 ((stringp org-agenda-files) (org-read-agenda-file-list))
16829 ((listp org-agenda-files) org-agenda-files)
16830 (t (error "Invalid value of `org-agenda-files'")))))
16831 (setq files (apply 'append
16832 (mapcar (lambda (f)
16833 (if (file-directory-p f)
16834 (directory-files
16835 f t org-agenda-file-regexp)
16836 (list f)))
16837 files)))
16838 (when org-agenda-skip-unavailable-files
16839 (setq files (delq nil
16840 (mapcar (function
16841 (lambda (file)
16842 (and (file-readable-p file) file)))
16843 files))))
16844 (when (or (eq archives t)
16845 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16846 (setq files (org-add-archive-files files)))
16847 files))
16849 (defun org-agenda-file-p (&optional file)
16850 "Return non-nil, if FILE is an agenda file.
16851 If FILE is omitted, use the file associated with the current
16852 buffer."
16853 (member (or file (buffer-file-name))
16854 (org-agenda-files t)))
16856 (defun org-edit-agenda-file-list ()
16857 "Edit the list of agenda files.
16858 Depending on setup, this either uses customize to edit the variable
16859 `org-agenda-files', or it visits the file that is holding the list. In the
16860 latter case, the buffer is set up in a way that saving it automatically kills
16861 the buffer and restores the previous window configuration."
16862 (interactive)
16863 (if (stringp org-agenda-files)
16864 (let ((cw (current-window-configuration)))
16865 (find-file org-agenda-files)
16866 (org-set-local 'org-window-configuration cw)
16867 (org-add-hook 'after-save-hook
16868 (lambda ()
16869 (set-window-configuration
16870 (prog1 org-window-configuration
16871 (kill-buffer (current-buffer))))
16872 (org-install-agenda-files-menu)
16873 (message "New agenda file list installed"))
16874 nil 'local)
16875 (message "%s" (substitute-command-keys
16876 "Edit list and finish with \\[save-buffer]")))
16877 (customize-variable 'org-agenda-files)))
16879 (defun org-store-new-agenda-file-list (list)
16880 "Set new value for the agenda file list and save it correctly."
16881 (if (stringp org-agenda-files)
16882 (let ((fe (org-read-agenda-file-list t)) b u)
16883 (while (setq b (find-buffer-visiting org-agenda-files))
16884 (kill-buffer b))
16885 (with-temp-file org-agenda-files
16886 (insert
16887 (mapconcat
16888 (lambda (f) ;; Keep un-expanded entries.
16889 (if (setq u (assoc f fe))
16890 (cdr u)
16892 list "\n")
16893 "\n")))
16894 (let ((org-mode-hook nil) (org-inhibit-startup t)
16895 (org-insert-mode-line-in-empty-file nil))
16896 (setq org-agenda-files list)
16897 (customize-save-variable 'org-agenda-files org-agenda-files))))
16899 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16900 "Read the list of agenda files from a file.
16901 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16902 filenames, used by `org-store-new-agenda-file-list' to write back
16903 un-expanded file names."
16904 (when (file-directory-p org-agenda-files)
16905 (error "`org-agenda-files' cannot be a single directory"))
16906 (when (stringp org-agenda-files)
16907 (with-temp-buffer
16908 (insert-file-contents org-agenda-files)
16909 (mapcar
16910 (lambda (f)
16911 (let ((e (expand-file-name (substitute-in-file-name f)
16912 org-directory)))
16913 (if pair-with-expansion
16914 (cons e f)
16915 e)))
16916 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16918 ;;;###autoload
16919 (defun org-cycle-agenda-files ()
16920 "Cycle through the files in `org-agenda-files'.
16921 If the current buffer visits an agenda file, find the next one in the list.
16922 If the current buffer does not, find the first agenda file."
16923 (interactive)
16924 (let* ((fs (org-agenda-files t))
16925 (files (append fs (list (car fs))))
16926 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16927 file)
16928 (unless files (error "No agenda files"))
16929 (catch 'exit
16930 (while (setq file (pop files))
16931 (if (equal (file-truename file) tcf)
16932 (when (car files)
16933 (find-file (car files))
16934 (throw 'exit t))))
16935 (find-file (car fs)))
16936 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16938 (defun org-agenda-file-to-front (&optional to-end)
16939 "Move/add the current file to the top of the agenda file list.
16940 If the file is not present in the list, it is added to the front. If it is
16941 present, it is moved there. With optional argument TO-END, add/move to the
16942 end of the list."
16943 (interactive "P")
16944 (let ((org-agenda-skip-unavailable-files nil)
16945 (file-alist (mapcar (lambda (x)
16946 (cons (file-truename x) x))
16947 (org-agenda-files t)))
16948 (ctf (file-truename
16949 (or buffer-file-name
16950 (error "Please save the current buffer to a file"))))
16951 x had)
16952 (setq x (assoc ctf file-alist) had x)
16954 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16955 (if to-end
16956 (setq file-alist (append (delq x file-alist) (list x)))
16957 (setq file-alist (cons x (delq x file-alist))))
16958 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16959 (org-install-agenda-files-menu)
16960 (message "File %s to %s of agenda file list"
16961 (if had "moved" "added") (if to-end "end" "front"))))
16963 (defun org-remove-file (&optional file)
16964 "Remove current file from the list of files in variable `org-agenda-files'.
16965 These are the files which are being checked for agenda entries.
16966 Optional argument FILE means use this file instead of the current."
16967 (interactive)
16968 (let* ((org-agenda-skip-unavailable-files nil)
16969 (file (or file buffer-file-name
16970 (error "Current buffer does not visit a file")))
16971 (true-file (file-truename file))
16972 (afile (abbreviate-file-name file))
16973 (files (delq nil (mapcar
16974 (lambda (x)
16975 (if (equal true-file
16976 (file-truename x))
16977 nil x))
16978 (org-agenda-files t)))))
16979 (if (not (= (length files) (length (org-agenda-files t))))
16980 (progn
16981 (org-store-new-agenda-file-list files)
16982 (org-install-agenda-files-menu)
16983 (message "Removed file: %s" afile))
16984 (message "File was not in list: %s (not removed)" afile))))
16986 (defun org-file-menu-entry (file)
16987 (vector file (list 'find-file file) t))
16989 (defun org-check-agenda-file (file)
16990 "Make sure FILE exists. If not, ask user what to do."
16991 (when (not (file-exists-p file))
16992 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16993 (abbreviate-file-name file))
16994 (let ((r (downcase (read-char-exclusive))))
16995 (cond
16996 ((equal r ?r)
16997 (org-remove-file file)
16998 (throw 'nextfile t))
16999 (t (error "Abort"))))))
17001 (defun org-get-agenda-file-buffer (file)
17002 "Get a buffer visiting FILE. If the buffer needs to be created, add
17003 it to the list of buffers which might be released later."
17004 (let ((buf (org-find-base-buffer-visiting file)))
17005 (if buf
17006 buf ; just return it
17007 ;; Make a new buffer and remember it
17008 (setq buf (find-file-noselect file))
17009 (if buf (push buf org-agenda-new-buffers))
17010 buf)))
17012 (defun org-release-buffers (blist)
17013 "Release all buffers in list, asking the user for confirmation when needed.
17014 When a buffer is unmodified, it is just killed. When modified, it is saved
17015 \(if the user agrees) and then killed."
17016 (let (buf file)
17017 (while (setq buf (pop blist))
17018 (setq file (buffer-file-name buf))
17019 (when (and (buffer-modified-p buf)
17020 file
17021 (y-or-n-p (format "Save file %s? " file)))
17022 (with-current-buffer buf (save-buffer)))
17023 (kill-buffer buf))))
17025 (defun org-agenda-prepare-buffers (files)
17026 "Create buffers for all agenda files, protect archived trees and comments."
17027 (interactive)
17028 (let ((pa '(:org-archived t))
17029 (pc '(:org-comment t))
17030 (pall '(:org-archived t :org-comment t))
17031 (inhibit-read-only t)
17032 (org-inhibit-startup org-agenda-inhibit-startup)
17033 (rea (concat ":" org-archive-tag ":"))
17034 bmp file re)
17035 (save-excursion
17036 (save-restriction
17037 (while (setq file (pop files))
17038 (catch 'nextfile
17039 (if (bufferp file)
17040 (set-buffer file)
17041 (org-check-agenda-file file)
17042 (set-buffer (org-get-agenda-file-buffer file)))
17043 (widen)
17044 (setq bmp (buffer-modified-p))
17045 (org-refresh-category-properties)
17046 (org-refresh-properties org-effort-property 'org-effort)
17047 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17048 (setq org-todo-keywords-for-agenda
17049 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17050 (setq org-done-keywords-for-agenda
17051 (append org-done-keywords-for-agenda org-done-keywords))
17052 (setq org-todo-keyword-alist-for-agenda
17053 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17054 (setq org-drawers-for-agenda
17055 (append org-drawers-for-agenda org-drawers))
17056 (setq org-tag-alist-for-agenda
17057 (append org-tag-alist-for-agenda org-tag-alist))
17059 (save-excursion
17060 (remove-text-properties (point-min) (point-max) pall)
17061 (when org-agenda-skip-archived-trees
17062 (goto-char (point-min))
17063 (while (re-search-forward rea nil t)
17064 (if (org-at-heading-p t)
17065 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17066 (goto-char (point-min))
17067 (setq re (format org-heading-keyword-regexp-format
17068 org-comment-string))
17069 (while (re-search-forward re nil t)
17070 (add-text-properties
17071 (match-beginning 0) (org-end-of-subtree t) pc)))
17072 (set-buffer-modified-p bmp)))))
17073 (setq org-todo-keywords-for-agenda
17074 (org-uniquify org-todo-keywords-for-agenda))
17075 (setq org-todo-keyword-alist-for-agenda
17076 (org-uniquify org-todo-keyword-alist-for-agenda)
17077 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17079 ;;;; Embedded LaTeX
17081 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17082 "Keymap for the minor `org-cdlatex-mode'.")
17084 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17085 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17086 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17087 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17088 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17090 (defvar org-cdlatex-texmathp-advice-is-done nil
17091 "Flag remembering if we have applied the advice to texmathp already.")
17093 (define-minor-mode org-cdlatex-mode
17094 "Toggle the minor `org-cdlatex-mode'.
17095 This mode supports entering LaTeX environment and math in LaTeX fragments
17096 in Org-mode.
17097 \\{org-cdlatex-mode-map}"
17098 nil " OCDL" nil
17099 (when org-cdlatex-mode
17100 (require 'cdlatex)
17101 (run-hooks 'cdlatex-mode-hook)
17102 (cdlatex-compute-tables))
17103 (unless org-cdlatex-texmathp-advice-is-done
17104 (setq org-cdlatex-texmathp-advice-is-done t)
17105 (defadvice texmathp (around org-math-always-on activate)
17106 "Always return t in org-mode buffers.
17107 This is because we want to insert math symbols without dollars even outside
17108 the LaTeX math segments. If Orgmode thinks that point is actually inside
17109 an embedded LaTeX fragment, let texmathp do its job.
17110 \\[org-cdlatex-mode-map]"
17111 (interactive)
17112 (let (p)
17113 (cond
17114 ((not (derived-mode-p 'org-mode)) ad-do-it)
17115 ((eq this-command 'cdlatex-math-symbol)
17116 (setq ad-return-value t
17117 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17119 (let ((p (org-inside-LaTeX-fragment-p)))
17120 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17121 (setq ad-return-value t
17122 texmathp-why '("Org-mode embedded math" . 0))
17123 (if p ad-do-it)))))))))
17125 (defun turn-on-org-cdlatex ()
17126 "Unconditionally turn on `org-cdlatex-mode'."
17127 (org-cdlatex-mode 1))
17129 (defun org-inside-LaTeX-fragment-p ()
17130 "Test if point is inside a LaTeX fragment.
17131 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17132 sequence appearing also before point.
17133 Even though the matchers for math are configurable, this function assumes
17134 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17135 delimiters are skipped when they have been removed by customization.
17136 The return value is nil, or a cons cell with the delimiter and the
17137 position of this delimiter.
17139 This function does a reasonably good job, but can locally be fooled by
17140 for example currency specifications. For example it will assume being in
17141 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17142 fragments that are properly closed, but during editing, we have to live
17143 with the uncertainty caused by missing closing delimiters. This function
17144 looks only before point, not after."
17145 (catch 'exit
17146 (let ((pos (point))
17147 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17148 (lim (progn
17149 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17150 (point)))
17151 dd-on str (start 0) m re)
17152 (goto-char pos)
17153 (when dodollar
17154 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17155 re (nth 1 (assoc "$" org-latex-regexps)))
17156 (while (string-match re str start)
17157 (cond
17158 ((= (match-end 0) (length str))
17159 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17160 ((= (match-end 0) (- (length str) 5))
17161 (throw 'exit nil))
17162 (t (setq start (match-end 0))))))
17163 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17164 (goto-char pos)
17165 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17166 (and (match-beginning 2) (throw 'exit nil))
17167 ;; count $$
17168 (while (re-search-backward "\\$\\$" lim t)
17169 (setq dd-on (not dd-on)))
17170 (goto-char pos)
17171 (if dd-on (cons "$$" m))))))
17173 (defun org-inside-latex-macro-p ()
17174 "Is point inside a LaTeX macro or its arguments?"
17175 (save-match-data
17176 (org-in-regexp
17177 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17179 (defun org-try-cdlatex-tab ()
17180 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17181 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17182 - inside a LaTeX fragment, or
17183 - after the first word in a line, where an abbreviation expansion could
17184 insert a LaTeX environment."
17185 (when org-cdlatex-mode
17186 (cond
17187 ;; Before any word on the line: No expansion possible.
17188 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17189 ;; Just after first word on the line: Expand it. Make sure it
17190 ;; cannot happen on headlines, though.
17191 ((save-excursion
17192 (skip-chars-backward "a-zA-Z0-9*")
17193 (skip-chars-backward " \t")
17194 (and (bolp) (not (org-at-heading-p))))
17195 (cdlatex-tab) t)
17196 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17198 (defun org-cdlatex-underscore-caret (&optional arg)
17199 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17200 Revert to the normal definition outside of these fragments."
17201 (interactive "P")
17202 (if (org-inside-LaTeX-fragment-p)
17203 (call-interactively 'cdlatex-sub-superscript)
17204 (let (org-cdlatex-mode)
17205 (call-interactively (key-binding (vector last-input-event))))))
17207 (defun org-cdlatex-math-modify (&optional arg)
17208 "Execute `cdlatex-math-modify' in LaTeX fragments.
17209 Revert to the normal definition outside of these fragments."
17210 (interactive "P")
17211 (if (org-inside-LaTeX-fragment-p)
17212 (call-interactively 'cdlatex-math-modify)
17213 (let (org-cdlatex-mode)
17214 (call-interactively (key-binding (vector last-input-event))))))
17216 (defvar org-latex-fragment-image-overlays nil
17217 "List of overlays carrying the images of latex fragments.")
17218 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17220 (defun org-remove-latex-fragment-image-overlays ()
17221 "Remove all overlays with LaTeX fragment images in current buffer."
17222 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17223 (setq org-latex-fragment-image-overlays nil))
17225 (defun org-preview-latex-fragment (&optional subtree)
17226 "Preview the LaTeX fragment at point, or all locally or globally.
17227 If the cursor is in a LaTeX fragment, create the image and overlay
17228 it over the source code. If there is no fragment at point, display
17229 all fragments in the current text, from one headline to the next. With
17230 prefix SUBTREE, display all fragments in the current subtree. With a
17231 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17232 the cursor is before the first headline,
17233 display all fragments in the buffer.
17234 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17235 (interactive "P")
17236 (unless buffer-file-name
17237 (error "Can't preview LaTeX fragment in a non-file buffer"))
17238 (org-remove-latex-fragment-image-overlays)
17239 (save-excursion
17240 (save-restriction
17241 (let (beg end at msg)
17242 (cond
17243 ((or (equal subtree '(16))
17244 (not (save-excursion
17245 (re-search-backward org-outline-regexp-bol nil t))))
17246 (setq beg (point-min) end (point-max)
17247 msg "Creating images for buffer...%s"))
17248 ((equal subtree '(4))
17249 (org-back-to-heading)
17250 (setq beg (point) end (org-end-of-subtree t)
17251 msg "Creating images for subtree...%s"))
17253 (if (setq at (org-inside-LaTeX-fragment-p))
17254 (goto-char (max (point-min) (- (cdr at) 2)))
17255 (org-back-to-heading))
17256 (setq beg (point) end (progn (outline-next-heading) (point))
17257 msg (if at "Creating image...%s"
17258 "Creating images for entry...%s"))))
17259 (message msg "")
17260 (narrow-to-region beg end)
17261 (goto-char beg)
17262 (org-format-latex
17263 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17264 (file-name-nondirectory
17265 buffer-file-name)))
17266 default-directory 'overlays msg at 'forbuffer
17267 org-latex-create-formula-image-program)
17268 (message msg "done. Use `C-c C-c' to remove images.")))))
17270 (defvar org-latex-regexps
17271 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17272 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17273 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17274 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17275 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17276 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17277 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17278 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17279 "Regular expressions for matching embedded LaTeX.")
17281 (defvar org-export-have-math nil) ;; dynamic scoping
17282 (defun org-format-latex (prefix &optional dir overlays msg at
17283 forbuffer processing-type)
17284 "Replace LaTeX fragments with links to an image, and produce images.
17285 Some of the options can be changed using the variable
17286 `org-format-latex-options'."
17287 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17288 (let* ((prefixnodir (file-name-nondirectory prefix))
17289 (absprefix (expand-file-name prefix dir))
17290 (todir (file-name-directory absprefix))
17291 (opt org-format-latex-options)
17292 (matchers (plist-get opt :matchers))
17293 (re-list org-latex-regexps)
17294 (org-format-latex-header-extra
17295 (plist-get (org-infile-export-plist) :latex-header-extra))
17296 (cnt 0) txt hash link beg end re e checkdir
17297 executables-checked string
17298 m n block-type block linkfile movefile ov)
17299 ;; Check the different regular expressions
17300 (while (setq e (pop re-list))
17301 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17302 block (if block-type "\n\n" ""))
17303 (when (member m matchers)
17304 (goto-char (point-min))
17305 (while (re-search-forward re nil t)
17306 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17307 (not (get-text-property (match-beginning n)
17308 'org-protected))
17309 (or (not overlays)
17310 (not (eq (get-char-property (match-beginning n)
17311 'org-overlay-type)
17312 'org-latex-overlay))))
17313 (setq org-export-have-math t)
17314 (cond
17315 ((eq processing-type 'verbatim)
17316 ;; Leave the text verbatim, just protect it
17317 (add-text-properties (match-beginning n) (match-end n)
17318 '(org-protected t)))
17319 ((eq processing-type 'mathjax)
17320 ;; Prepare for MathJax processing
17321 (setq string (match-string n))
17322 (if (member m '("$" "$1"))
17323 (save-excursion
17324 (delete-region (match-beginning n) (match-end n))
17325 (goto-char (match-beginning n))
17326 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17327 "\\)")
17328 '(org-protected t))))
17329 (add-text-properties (match-beginning n) (match-end n)
17330 '(org-protected t))))
17331 ((or (eq processing-type 'dvipng)
17332 (eq processing-type 'imagemagick))
17333 ;; Process to an image
17334 (setq txt (match-string n)
17335 beg (match-beginning n) end (match-end n)
17336 cnt (1+ cnt))
17337 (let (print-length print-level) ; make sure full list is printed
17338 (setq hash (sha1 (prin1-to-string
17339 (list org-format-latex-header
17340 org-format-latex-header-extra
17341 org-export-latex-default-packages-alist
17342 org-export-latex-packages-alist
17343 org-format-latex-options
17344 forbuffer txt)))
17345 linkfile (format "%s_%s.png" prefix hash)
17346 movefile (format "%s_%s.png" absprefix hash)))
17347 (setq link (concat block "[[file:" linkfile "]]" block))
17348 (if msg (message msg cnt))
17349 (goto-char beg)
17350 (unless checkdir ; make sure the directory exists
17351 (setq checkdir t)
17352 (or (file-directory-p todir) (make-directory todir t)))
17353 (cond
17354 ((eq processing-type 'dvipng)
17355 (unless executables-checked
17356 (org-check-external-command
17357 "latex" "needed to convert LaTeX fragments to images")
17358 (org-check-external-command
17359 "dvipng" "needed to convert LaTeX fragments to images")
17360 (setq executables-checked t))
17361 (unless (file-exists-p movefile)
17362 (org-create-formula-image-with-dvipng
17363 txt movefile opt forbuffer)))
17364 ((eq processing-type 'imagemagick)
17365 (unless executables-checked
17366 (org-check-external-command
17367 "convert" "you need to install imagemagick")
17368 (setq executables-checked t))
17369 (unless (file-exists-p movefile)
17370 (org-create-formula-image-with-imagemagick
17371 txt movefile opt forbuffer))))
17372 (if overlays
17373 (progn
17374 (mapc (lambda (o)
17375 (if (eq (overlay-get o 'org-overlay-type)
17376 'org-latex-overlay)
17377 (delete-overlay o)))
17378 (overlays-in beg end))
17379 (setq ov (make-overlay beg end))
17380 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17381 (if (featurep 'xemacs)
17382 (progn
17383 (overlay-put ov 'invisible t)
17384 (overlay-put
17385 ov 'end-glyph
17386 (make-glyph (vector 'png :file movefile))))
17387 (overlay-put
17388 ov 'display
17389 (list 'image :type 'png :file movefile :ascent 'center)))
17390 (push ov org-latex-fragment-image-overlays)
17391 (goto-char end))
17392 (delete-region beg end)
17393 (insert (org-add-props link
17394 (list 'org-latex-src
17395 (replace-regexp-in-string
17396 "\"" "" txt)
17397 'org-latex-src-embed-type
17398 (if block-type 'paragraph 'character))))))
17399 ((eq processing-type 'mathml)
17400 ;; Process to MathML
17401 (unless executables-checked
17402 (unless (save-match-data (org-format-latex-mathml-available-p))
17403 (error "LaTeX to MathML converter not configured"))
17404 (setq executables-checked t))
17405 (setq txt (match-string n)
17406 beg (match-beginning n) end (match-end n)
17407 cnt (1+ cnt))
17408 (if msg (message msg cnt))
17409 (goto-char beg)
17410 (delete-region beg end)
17411 (insert (org-format-latex-as-mathml
17412 txt block-type prefix dir)))
17414 (error "Unknown conversion type %s for latex fragments"
17415 processing-type)))))))))
17417 (defun org-create-math-formula (latex-frag &optional mathml-file)
17418 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17419 Use `org-latex-to-mathml-convert-command'. If the conversion is
17420 sucessful, return the portion between \"<math...> </math>\"
17421 elements otherwise return nil. When MATHML-FILE is specified,
17422 write the results in to that file. When invoked as an
17423 interactive command, prompt for LATEX-FRAG, with initial value
17424 set to the current active region and echo the results for user
17425 inspection."
17426 (interactive (list (let ((frag (when (org-region-active-p)
17427 (buffer-substring-no-properties
17428 (region-beginning) (region-end)))))
17429 (read-string "LaTeX Fragment: " frag nil frag))))
17430 (unless latex-frag (error "Invalid latex-frag"))
17431 (let* ((tmp-in-file (file-relative-name
17432 (make-temp-name (expand-file-name "ltxmathml-in"))))
17433 (ignore (write-region latex-frag nil tmp-in-file))
17434 (tmp-out-file (file-relative-name
17435 (make-temp-name (expand-file-name "ltxmathml-out"))))
17436 (cmd (format-spec
17437 org-latex-to-mathml-convert-command
17438 `((?j . ,(shell-quote-argument
17439 (expand-file-name org-latex-to-mathml-jar-file)))
17440 (?I . ,(shell-quote-argument tmp-in-file))
17441 (?o . ,(shell-quote-argument tmp-out-file)))))
17442 mathml shell-command-output)
17443 (when (org-called-interactively-p 'any)
17444 (unless (org-format-latex-mathml-available-p)
17445 (error "LaTeX to MathML converter not configured")))
17446 (message "Running %s" cmd)
17447 (setq shell-command-output (shell-command-to-string cmd))
17448 (setq mathml
17449 (when (file-readable-p tmp-out-file)
17450 (with-current-buffer (find-file-noselect tmp-out-file t)
17451 (goto-char (point-min))
17452 (when (re-search-forward
17453 (concat
17454 (regexp-quote
17455 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17456 "\\(.\\|\n\\)*"
17457 (regexp-quote "</math>")) nil t)
17458 (prog1 (match-string 0) (kill-buffer))))))
17459 (cond
17460 (mathml
17461 (setq mathml
17462 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17463 (when mathml-file
17464 (write-region mathml nil mathml-file))
17465 (when (org-called-interactively-p 'any)
17466 (message mathml)))
17467 ((message "LaTeX to MathML conversion failed")
17468 (message shell-command-output)))
17469 (delete-file tmp-in-file)
17470 (when (file-exists-p tmp-out-file)
17471 (delete-file tmp-out-file))
17472 mathml))
17474 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17475 prefix &optional dir)
17476 "Use `org-create-math-formula' but check local cache first."
17477 (let* ((absprefix (expand-file-name prefix dir))
17478 (print-length nil) (print-level nil)
17479 (formula-id (concat
17480 "formula-"
17481 (sha1
17482 (prin1-to-string
17483 (list latex-frag
17484 org-latex-to-mathml-convert-command)))))
17485 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17486 (formula-cache-dir (file-name-directory formula-cache)))
17488 (unless (file-directory-p formula-cache-dir)
17489 (make-directory formula-cache-dir t))
17491 (unless (file-exists-p formula-cache)
17492 (org-create-math-formula latex-frag formula-cache))
17494 (if (file-exists-p formula-cache)
17495 ;; Successful conversion. Return the link to MathML file.
17496 (org-add-props
17497 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17498 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17499 'org-latex-src-embed-type (if latex-frag-type
17500 'paragraph 'character)))
17501 ;; Failed conversion. Return the LaTeX fragment verbatim
17502 (add-text-properties
17503 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17504 latex-frag)))
17506 ;; This function borrows from Ganesh Swami's latex2png.el
17507 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17508 "This calls dvipng."
17509 (require 'org-latex)
17510 (let* ((tmpdir (if (featurep 'xemacs)
17511 (temp-directory)
17512 temporary-file-directory))
17513 (texfilebase (make-temp-name
17514 (expand-file-name "orgtex" tmpdir)))
17515 (texfile (concat texfilebase ".tex"))
17516 (dvifile (concat texfilebase ".dvi"))
17517 (pngfile (concat texfilebase ".png"))
17518 (fnh (if (featurep 'xemacs)
17519 (font-height (face-font 'default))
17520 (face-attribute 'default :height nil)))
17521 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17522 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17523 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17524 "Black"))
17525 (bg (or (plist-get options (if buffer :background :html-background))
17526 "Transparent")))
17527 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17528 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17529 (with-temp-file texfile
17530 (insert (org-splice-latex-header
17531 org-format-latex-header
17532 org-export-latex-default-packages-alist
17533 org-export-latex-packages-alist t
17534 org-format-latex-header-extra))
17535 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17536 (require 'org-latex)
17537 (org-export-latex-fix-inputenc))
17538 (let ((dir default-directory))
17539 (condition-case nil
17540 (progn
17541 (cd tmpdir)
17542 (call-process "latex" nil nil nil texfile))
17543 (error nil))
17544 (cd dir))
17545 (if (not (file-exists-p dvifile))
17546 (progn (message "Failed to create dvi file from %s" texfile) nil)
17547 (condition-case nil
17548 (if (featurep 'xemacs)
17549 (call-process "dvipng" nil nil nil
17550 "-fg" fg "-bg" bg
17551 "-T" "tight"
17552 "-o" pngfile
17553 dvifile)
17554 (call-process "dvipng" nil nil nil
17555 "-fg" fg "-bg" bg
17556 "-D" dpi
17557 ;;"-x" scale "-y" scale
17558 "-T" "tight"
17559 "-o" pngfile
17560 dvifile))
17561 (error nil))
17562 (if (not (file-exists-p pngfile))
17563 (if org-format-latex-signal-error
17564 (error "Failed to create png file from %s" texfile)
17565 (message "Failed to create png file from %s" texfile)
17566 nil)
17567 ;; Use the requested file name and clean up
17568 (copy-file pngfile tofile 'replace)
17569 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17570 (if (file-exists-p (concat texfilebase e))
17571 (delete-file (concat texfilebase e))))
17572 pngfile))))
17574 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17575 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17576 "This calls convert, which is included into imagemagick."
17577 (require 'org-latex)
17578 (let* ((tmpdir (if (featurep 'xemacs)
17579 (temp-directory)
17580 temporary-file-directory))
17581 (texfilebase (make-temp-name
17582 (expand-file-name "orgtex" tmpdir)))
17583 (texfile (concat texfilebase ".tex"))
17584 (pdffile (concat texfilebase ".pdf"))
17585 (pngfile (concat texfilebase ".png"))
17586 (fnh (if (featurep 'xemacs)
17587 (font-height (face-font 'default))
17588 (face-attribute 'default :height nil)))
17589 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17590 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17591 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17592 "black"))
17593 (bg (or (plist-get options (if buffer :background :html-background))
17594 "white")))
17595 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17596 (setq fg (org-latex-color-format fg)))
17597 (if (eq bg 'default) (setq bg (org-latex-color :background))
17598 (setq bg (org-latex-color-format
17599 (if (string= bg "Transparent")(setq bg "white")))))
17600 (with-temp-file texfile
17601 (insert (org-splice-latex-header
17602 org-format-latex-header
17603 org-export-latex-default-packages-alist
17604 org-export-latex-packages-alist t
17605 org-format-latex-header-extra))
17606 (insert "\n\\begin{document}\n"
17607 "\\definecolor{fg}{rgb}{" fg "}\n"
17608 "\\definecolor{bg}{rgb}{" bg "}\n"
17609 "\n\\pagecolor{bg}\n"
17610 "\n{\\color{fg}\n"
17611 string
17612 "\n}\n"
17613 "\n\\end{document}\n" )
17614 (require 'org-latex)
17615 (org-export-latex-fix-inputenc))
17616 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17617 (condition-case nil
17618 (progn
17619 (cd tmpdir)
17620 (setq cmds org-latex-to-pdf-process)
17621 (while cmds
17622 (setq latex-frags-cmds (pop cmds))
17623 (if (listp latex-frags-cmds)
17624 (setq cmds nil)
17625 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17626 (while latex-frags-cmds
17627 (setq cmd (pop latex-frags-cmds))
17628 (while (string-match "%b" cmd)
17629 (setq cmd (replace-match
17630 (save-match-data
17631 (shell-quote-argument texfile))
17632 t t cmd)))
17633 (while (string-match "%f" cmd)
17634 (setq cmd (replace-match
17635 (save-match-data
17636 (shell-quote-argument (file-name-nondirectory texfile)))
17637 t t cmd)))
17638 (while (string-match "%o" cmd)
17639 (setq cmd (replace-match
17640 (save-match-data
17641 (shell-quote-argument (file-name-directory texfile)))
17642 t t cmd)))
17643 (setq cmd (split-string cmd))
17644 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17645 (error nil))
17646 (cd dir))
17647 (if (not (file-exists-p pdffile))
17648 (progn (message "Failed to create pdf file from %s" texfile) nil)
17649 (condition-case nil
17650 (if (featurep 'xemacs)
17651 (call-process "convert" nil nil nil
17652 "-density" "96"
17653 "-trim"
17654 "-antialias"
17655 pdffile
17656 "-quality" "100"
17657 ;; "-sharpen" "0x1.0"
17658 pngfile)
17659 (call-process "convert" nil nil nil
17660 "-density" dpi
17661 "-trim"
17662 "-antialias"
17663 pdffile
17664 "-quality" "100"
17665 ; "-sharpen" "0x1.0"
17666 pngfile))
17667 (error nil))
17668 (if (not (file-exists-p pngfile))
17669 (if org-format-latex-signal-error
17670 (error "Failed to create png file from %s" texfile)
17671 (message "Failed to create png file from %s" texfile)
17672 nil)
17673 ;; Use the requested file name and clean up
17674 (copy-file pngfile tofile 'replace)
17675 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17676 (if (file-exists-p (concat texfilebase e))
17677 (delete-file (concat texfilebase e))))
17678 pngfile))))
17680 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17681 "Fill a LaTeX header template TPL.
17682 In the template, the following place holders will be recognized:
17684 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17685 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17686 [PACKAGES] \\usepackage statements for PKG
17687 [NO-PACKAGES] do not include PKG
17688 [EXTRA] the string EXTRA
17689 [NO-EXTRA] do not include EXTRA
17691 For backward compatibility, if both the positive and the negative place
17692 holder is missing, the positive one (without the \"NO-\") will be
17693 assumed to be present at the end of the template.
17694 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17695 EXTRA is a string.
17696 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17697 (let (rpl (end ""))
17698 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17699 (setq rpl (if (or (match-end 1) (not def-pkg))
17700 "" (org-latex-packages-to-string def-pkg snippets-p t))
17701 tpl (replace-match rpl t t tpl))
17702 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17704 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17705 (setq rpl (if (or (match-end 1) (not pkg))
17706 "" (org-latex-packages-to-string pkg snippets-p t))
17707 tpl (replace-match rpl t t tpl))
17708 (if pkg (setq end
17709 (concat end "\n"
17710 (org-latex-packages-to-string pkg snippets-p)))))
17712 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17713 (setq rpl (if (or (match-end 1) (not extra))
17714 "" (concat extra "\n"))
17715 tpl (replace-match rpl t t tpl))
17716 (if (and extra (string-match "\\S-" extra))
17717 (setq end (concat end "\n" extra))))
17719 (if (string-match "\\S-" end)
17720 (concat tpl "\n" end)
17721 tpl)))
17723 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17724 "Turn an alist of packages into a string with the \\usepackage macros."
17725 (setq pkg (mapconcat (lambda(p)
17726 (cond
17727 ((stringp p) p)
17728 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17729 (format "%% Package %s omitted" (cadr p)))
17730 ((equal "" (car p))
17731 (format "\\usepackage{%s}" (cadr p)))
17733 (format "\\usepackage[%s]{%s}"
17734 (car p) (cadr p)))))
17736 "\n"))
17737 (if newline (concat pkg "\n") pkg))
17739 (defun org-dvipng-color (attr)
17740 "Return a RGB color specification for dvipng."
17741 (apply 'format "rgb %s %s %s"
17742 (mapcar 'org-normalize-color
17743 (if (featurep 'xemacs)
17744 (color-rgb-components
17745 (face-property 'default
17746 (cond ((eq attr :foreground) 'foreground)
17747 ((eq attr :background) 'background))))
17748 (color-values (face-attribute 'default attr nil))))))
17750 (defun org-latex-color (attr)
17751 "Return a RGB color for the LaTeX color package."
17752 (apply 'format "%s,%s,%s"
17753 (mapcar 'org-normalize-color
17754 (if (featurep 'xemacs)
17755 (color-rgb-components
17756 (face-property 'default
17757 (cond ((eq attr :foreground) 'foreground)
17758 ((eq attr :background) 'background))))
17759 (color-values (face-attribute 'default attr nil))))))
17761 (defun org-latex-color-format (color-name)
17762 "Convert COLOR-NAME to a RGB color value."
17763 (apply 'format "%s,%s,%s"
17764 (mapcar 'org-normalize-color
17765 (color-values color-name))))
17767 (defun org-normalize-color (value)
17768 "Return string to be used as color value for an RGB component."
17769 (format "%g" (/ value 65535.0)))
17771 ;; Image display
17774 (defvar org-inline-image-overlays nil)
17775 (make-variable-buffer-local 'org-inline-image-overlays)
17777 (defun org-toggle-inline-images (&optional include-linked)
17778 "Toggle the display of inline images.
17779 INCLUDE-LINKED is passed to `org-display-inline-images'."
17780 (interactive "P")
17781 (if org-inline-image-overlays
17782 (progn
17783 (org-remove-inline-images)
17784 (message "Inline image display turned off"))
17785 (org-display-inline-images include-linked)
17786 (if org-inline-image-overlays
17787 (message "%d images displayed inline"
17788 (length org-inline-image-overlays))
17789 (message "No images to display inline"))))
17791 (defun org-redisplay-inline-images ()
17792 "Refresh the display of inline images."
17793 (interactive)
17794 (if (not org-inline-image-overlays)
17795 (org-toggle-inline-images)
17796 (org-toggle-inline-images)
17797 (org-toggle-inline-images)))
17799 (defun org-display-inline-images (&optional include-linked refresh beg end)
17800 "Display inline images.
17801 Normally only links without a description part are inlined, because this
17802 is how it will work for export. When INCLUDE-LINKED is set, also links
17803 with a description part will be inlined. This can be nice for a quick
17804 look at those images, but it does not reflect what exported files will look
17805 like.
17806 When REFRESH is set, refresh existing images between BEG and END.
17807 This will create new image displays only if necessary.
17808 BEG and END default to the buffer boundaries."
17809 (interactive "P")
17810 (unless refresh
17811 (org-remove-inline-images)
17812 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17813 (save-excursion
17814 (save-restriction
17815 (widen)
17816 (setq beg (or beg (point-min)) end (or end (point-max)))
17817 (goto-char beg)
17818 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17819 (substring (org-image-file-name-regexp) 0 -2)
17820 "\\)\\]" (if include-linked "" "\\]")))
17821 old file ov img)
17822 (while (re-search-forward re end t)
17823 (setq old (get-char-property-and-overlay (match-beginning 1)
17824 'org-image-overlay))
17825 (setq file (expand-file-name
17826 (concat (or (match-string 3) "") (match-string 4))))
17827 (when (file-exists-p file)
17828 (if (and (car-safe old) refresh)
17829 (image-refresh (overlay-get (cdr old) 'display))
17830 (setq img (save-match-data (create-image file)))
17831 (when img
17832 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17833 (overlay-put ov 'display img)
17834 (overlay-put ov 'face 'default)
17835 (overlay-put ov 'org-image-overlay t)
17836 (overlay-put ov 'modification-hooks
17837 (list 'org-display-inline-remove-overlay))
17838 (push ov org-inline-image-overlays)))))))))
17840 (define-obsolete-function-alias
17841 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17843 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17844 "Remove inline-display overlay if a corresponding region is modified."
17845 (let ((inhibit-modification-hooks t))
17846 (when (and ov after)
17847 (delete ov org-inline-image-overlays)
17848 (delete-overlay ov))))
17850 (defun org-remove-inline-images ()
17851 "Remove inline display of images."
17852 (interactive)
17853 (mapc 'delete-overlay org-inline-image-overlays)
17854 (setq org-inline-image-overlays nil))
17856 ;;;; Key bindings
17858 ;; Outline functions from `outline-mode-prefix-map'
17859 ;; that can be remapped in Org:
17860 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17861 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17862 (define-key org-mode-map [remap outline-forward-same-level]
17863 'org-forward-heading-same-level)
17864 (define-key org-mode-map [remap outline-backward-same-level]
17865 'org-backward-heading-same-level)
17866 (define-key org-mode-map [remap show-branches]
17867 'org-kill-note-or-show-branches)
17868 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17869 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17870 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17872 ;; Outline functions from `outline-mode-prefix-map' that can not
17873 ;; be remapped in Org:
17875 ;; - the column "key binding" shows whether the Outline function is still
17876 ;; available in Org mode on the same key that it has been bound to in
17877 ;; Outline mode:
17878 ;; - "overridden": key used for a different functionality in Org mode
17879 ;; - else: key still bound to the same Outline function in Org mode
17881 ;; | Outline function | key binding | Org replacement |
17882 ;; |------------------------------------+-------------+-----------------------|
17883 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17884 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17885 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17886 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17887 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17888 ;; | `show-entry' | overridden | no replacement |
17889 ;; | `show-children' | `C-c C-i' | visibility cycling |
17890 ;; | `show-branches' | `C-c C-k' | still same function |
17891 ;; | `show-subtree' | overridden | visibility cycling |
17892 ;; | `show-all' | overridden | no replacement |
17893 ;; | `hide-subtree' | overridden | visibility cycling |
17894 ;; | `hide-body' | overridden | no replacement |
17895 ;; | `hide-entry' | overridden | visibility cycling |
17896 ;; | `hide-leaves' | overridden | no replacement |
17897 ;; | `hide-sublevels' | overridden | no replacement |
17898 ;; | `hide-other' | overridden | no replacement |
17900 ;; Make `C-c C-x' a prefix key
17901 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17903 ;; TAB key with modifiers
17904 (org-defkey org-mode-map "\C-i" 'org-cycle)
17905 (org-defkey org-mode-map [(tab)] 'org-cycle)
17906 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17907 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17908 ;; The following line is necessary under Suse GNU/Linux
17909 (unless (featurep 'xemacs)
17910 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17911 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17912 (define-key org-mode-map [backtab] 'org-shifttab)
17914 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17915 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17916 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17918 ;; Cursor keys with modifiers
17919 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17920 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17921 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17922 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17924 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17925 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17926 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17927 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17929 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17930 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17931 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17932 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17934 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17935 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17936 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17937 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17939 ;; Babel keys
17940 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17941 (mapc (lambda (pair)
17942 (define-key org-babel-map (car pair) (cdr pair)))
17943 org-babel-key-bindings)
17945 ;;; Extra keys for tty access.
17946 ;; We only set them when really needed because otherwise the
17947 ;; menus don't show the simple keys
17949 (when (or org-use-extra-keys
17950 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17951 (not window-system))
17952 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17953 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17954 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17955 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17956 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17957 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17958 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17959 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17960 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17961 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17962 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17963 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17964 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17965 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17966 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17967 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17968 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17969 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17970 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17971 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17972 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17973 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17974 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17975 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17976 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17977 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17978 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17979 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17981 ;; All the other keys
17983 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17984 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17985 (if (boundp 'narrow-map)
17986 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17987 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17988 (if (boundp 'narrow-map)
17989 (org-defkey narrow-map "b" 'org-narrow-to-block)
17990 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17991 (if (boundp 'narrow-map)
17992 (org-defkey narrow-map "e" 'org-narrow-to-element)
17993 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17994 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17995 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17996 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17997 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17998 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17999 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18000 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18001 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18002 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18003 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18004 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18005 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18006 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18007 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18008 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18009 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18010 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18011 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18012 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18013 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18014 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18015 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18016 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18017 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18018 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18019 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18020 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18021 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18022 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18023 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18024 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18025 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18026 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18027 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18028 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18029 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18030 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18031 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18032 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18033 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18034 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18035 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18036 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18037 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18038 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18039 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18040 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18041 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18042 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18043 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18044 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18045 (org-defkey org-mode-map "\C-c^" 'org-sort)
18046 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18047 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18048 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18049 (org-defkey org-mode-map "\C-m" 'org-return)
18050 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18051 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18052 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18053 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18054 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18055 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18056 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18057 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18058 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18059 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18060 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18061 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18062 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18063 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18064 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18065 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18066 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18067 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18068 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18069 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18070 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18071 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18072 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18074 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18075 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18076 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18078 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18079 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18080 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18081 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18082 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18083 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18084 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18085 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18086 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18087 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18088 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18089 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18090 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18091 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18092 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18093 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18094 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18095 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18096 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18097 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18098 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18099 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18101 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18102 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18103 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18104 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18105 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18107 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18109 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18111 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18112 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18114 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18117 (when (featurep 'xemacs)
18118 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18121 (defconst org-speed-commands-default
18123 ("Outline Navigation")
18124 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18125 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18126 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18127 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18128 ("u" . (org-speed-move-safe 'outline-up-heading))
18129 ("j" . org-goto)
18130 ("g" . (org-refile t))
18131 ("Outline Visibility")
18132 ("c" . org-cycle)
18133 ("C" . org-shifttab)
18134 (" " . org-display-outline-path)
18135 ("=" . org-columns)
18136 ("Outline Structure Editing")
18137 ("U" . org-shiftmetaup)
18138 ("D" . org-shiftmetadown)
18139 ("r" . org-metaright)
18140 ("l" . org-metaleft)
18141 ("R" . org-shiftmetaright)
18142 ("L" . org-shiftmetaleft)
18143 ("i" . (progn (forward-char 1) (call-interactively
18144 'org-insert-heading-respect-content)))
18145 ("^" . org-sort)
18146 ("w" . org-refile)
18147 ("a" . org-archive-subtree-default-with-confirmation)
18148 ("." . org-mark-subtree)
18149 ("#" . org-toggle-comment)
18150 ("Clock Commands")
18151 ("I" . org-clock-in)
18152 ("O" . org-clock-out)
18153 ("Meta Data Editing")
18154 ("t" . org-todo)
18155 ("," . (org-priority))
18156 ("0" . (org-priority ?\ ))
18157 ("1" . (org-priority ?A))
18158 ("2" . (org-priority ?B))
18159 ("3" . (org-priority ?C))
18160 (":" . org-set-tags-command)
18161 ("e" . org-set-effort)
18162 ("E" . org-inc-effort)
18163 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18164 (org-entry-put (point) "APPT_WARNTIME" m)))
18165 ("Agenda Views etc")
18166 ("v" . org-agenda)
18167 ("/" . org-sparse-tree)
18168 ("Misc")
18169 ("o" . org-open-at-point)
18170 ("?" . org-speed-command-help)
18171 ("<" . (org-agenda-set-restriction-lock 'subtree))
18172 (">" . (org-agenda-remove-restriction-lock))
18174 "The default speed commands.")
18176 (defun org-print-speed-command (e)
18177 (if (> (length (car e)) 1)
18178 (progn
18179 (princ "\n")
18180 (princ (car e))
18181 (princ "\n")
18182 (princ (make-string (length (car e)) ?-))
18183 (princ "\n"))
18184 (princ (car e))
18185 (princ " ")
18186 (if (symbolp (cdr e))
18187 (princ (symbol-name (cdr e)))
18188 (prin1 (cdr e)))
18189 (princ "\n")))
18191 (defun org-speed-command-help ()
18192 "Show the available speed commands."
18193 (interactive)
18194 (if (not org-use-speed-commands)
18195 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18196 (with-output-to-temp-buffer "*Help*"
18197 (princ "User-defined Speed commands\n===========================\n")
18198 (mapc 'org-print-speed-command org-speed-commands-user)
18199 (princ "\n")
18200 (princ "Built-in Speed commands\n=======================\n")
18201 (mapc 'org-print-speed-command org-speed-commands-default))
18202 (with-current-buffer "*Help*"
18203 (setq truncate-lines t))))
18205 (defun org-speed-move-safe (cmd)
18206 "Execute CMD, but make sure that the cursor always ends up in a headline.
18207 If not, return to the original position and throw an error."
18208 (interactive)
18209 (let ((pos (point)))
18210 (call-interactively cmd)
18211 (unless (and (bolp) (org-at-heading-p))
18212 (goto-char pos)
18213 (error "Boundary reached while executing %s" cmd))))
18215 (defvar org-self-insert-command-undo-counter 0)
18217 (defvar org-table-auto-blank-field) ; defined in org-table.el
18218 (defvar org-speed-command nil)
18220 (define-obsolete-function-alias
18221 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18223 (defun org-speed-command-activate (keys)
18224 "Hook for activating single-letter speed commands.
18225 `org-speed-commands-default' specifies a minimal command set.
18226 Use `org-speed-commands-user' for further customization."
18227 (when (or (and (bolp) (looking-at org-outline-regexp))
18228 (and (functionp org-use-speed-commands)
18229 (funcall org-use-speed-commands)))
18230 (cdr (assoc keys (append org-speed-commands-user
18231 org-speed-commands-default)))))
18233 (define-obsolete-function-alias
18234 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18236 (defun org-babel-speed-command-activate (keys)
18237 "Hook for activating single-letter code block commands."
18238 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18239 (cdr (assoc keys org-babel-key-bindings))))
18241 (defcustom org-speed-command-hook
18242 '(org-speed-command-default-hook org-babel-speed-command-hook)
18243 "Hook for activating speed commands at strategic locations.
18244 Hook functions are called in sequence until a valid handler is
18245 found.
18247 Each hook takes a single argument, a user-pressed command key
18248 which is also a `self-insert-command' from the global map.
18250 Within the hook, examine the cursor position and the command key
18251 and return nil or a valid handler as appropriate. Handler could
18252 be one of an interactive command, a function, or a form.
18254 Set `org-use-speed-commands' to non-nil value to enable this
18255 hook. The default setting is `org-speed-command-activate'."
18256 :group 'org-structure
18257 :version "24.1"
18258 :type 'hook)
18260 (defun org-self-insert-command (N)
18261 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18262 If the cursor is in a table looking at whitespace, the whitespace is
18263 overwritten, and the table is not marked as requiring realignment."
18264 (interactive "p")
18265 (org-check-before-invisible-edit 'insert)
18266 (cond
18267 ((and org-use-speed-commands
18268 (setq org-speed-command
18269 (run-hook-with-args-until-success
18270 'org-speed-command-hook (this-command-keys))))
18271 (cond
18272 ((commandp org-speed-command)
18273 (setq this-command org-speed-command)
18274 (call-interactively org-speed-command))
18275 ((functionp org-speed-command)
18276 (funcall org-speed-command))
18277 ((and org-speed-command (listp org-speed-command))
18278 (eval org-speed-command))
18279 (t (let (org-use-speed-commands)
18280 (call-interactively 'org-self-insert-command)))))
18281 ((and
18282 (org-table-p)
18283 (progn
18284 ;; check if we blank the field, and if that triggers align
18285 (and (featurep 'org-table) org-table-auto-blank-field
18286 (member last-command
18287 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18288 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18289 ;; got extra space, this field does not determine column width
18290 (let (org-table-may-need-update) (org-table-blank-field))
18291 ;; no extra space, this field may determine column width
18292 (org-table-blank-field)))
18294 (eq N 1)
18295 (looking-at "[^|\n]* |"))
18296 (let (org-table-may-need-update)
18297 (goto-char (1- (match-end 0)))
18298 (backward-delete-char 1)
18299 (goto-char (match-beginning 0))
18300 (self-insert-command N)))
18302 (setq org-table-may-need-update t)
18303 (self-insert-command N)
18304 (org-fix-tags-on-the-fly)
18305 (if org-self-insert-cluster-for-undo
18306 (if (not (eq last-command 'org-self-insert-command))
18307 (setq org-self-insert-command-undo-counter 1)
18308 (if (>= org-self-insert-command-undo-counter 20)
18309 (setq org-self-insert-command-undo-counter 1)
18310 (and (> org-self-insert-command-undo-counter 0)
18311 buffer-undo-list (listp buffer-undo-list)
18312 (not (cadr buffer-undo-list)) ; remove nil entry
18313 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18314 (setq org-self-insert-command-undo-counter
18315 (1+ org-self-insert-command-undo-counter))))))))
18317 (defun org-check-before-invisible-edit (kind)
18318 "Check is editing if kind KIND would be dangerous with invisible text around.
18319 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18320 ;; First, try to get out of here as quickly as possible, to reduce overhead
18321 (if (and org-catch-invisible-edits
18322 (or (not (boundp 'visible-mode)) (not visible-mode))
18323 (or (get-char-property (point) 'invisible)
18324 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18325 ;; OK, we need to take a closer look
18326 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18327 (invisible-before-point (if (bobp) nil (get-char-property
18328 (1- (point)) 'invisible)))
18329 (border-and-ok-direction
18331 ;; Check if we are acting predictably before invisible text
18332 (and invisible-at-point (not invisible-before-point)
18333 (memq kind '(insert delete-backward)))
18334 ;; Check if we are acting predictably after invisible text
18335 ;; This works not well, and I have turned it off. It seems
18336 ;; better to always show and stop after invisible text.
18337 ;; (and (not invisible-at-point) invisible-before-point
18338 ;; (memq kind '(insert delete)))
18340 (when (or (memq invisible-at-point '(outline org-hide-block t))
18341 (memq invisible-before-point '(outline org-hide-block t)))
18342 (if (eq org-catch-invisible-edits 'error)
18343 (error "Editing in invisible areas is prohibited - make visible first"))
18344 (if (and org-custom-properties-overlays
18345 (y-or-n-p "Display invisible properties in this buffer? "))
18346 (org-toggle-custom-properties-visibility)
18347 ;; Make the area visible
18348 (save-excursion
18349 (if invisible-before-point
18350 (goto-char (previous-single-char-property-change
18351 (point) 'invisible)))
18352 (org-cycle))
18353 (cond
18354 ((eq org-catch-invisible-edits 'show)
18355 ;; That's it, we do the edit after showing
18356 (message
18357 "Unfolding invisible region around point before editing")
18358 (sit-for 1))
18359 ((and (eq org-catch-invisible-edits 'smart)
18360 border-and-ok-direction)
18361 (message "Unfolding invisible region around point before editing"))
18363 ;; Don't do the edit, make the user repeat it in full visibility
18364 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18366 (defun org-fix-tags-on-the-fly ()
18367 (when (and (equal (char-after (point-at-bol)) ?*)
18368 (org-at-heading-p))
18369 (org-align-tags-here org-tags-column)))
18371 (defun org-delete-backward-char (N)
18372 "Like `delete-backward-char', insert whitespace at field end in tables.
18373 When deleting backwards, in tables this function will insert whitespace in
18374 front of the next \"|\" separator, to keep the table aligned. The table will
18375 still be marked for re-alignment if the field did fill the entire column,
18376 because, in this case the deletion might narrow the column."
18377 (interactive "p")
18378 (save-match-data
18379 (org-check-before-invisible-edit 'delete-backward)
18380 (if (and (org-table-p)
18381 (eq N 1)
18382 (string-match "|" (buffer-substring (point-at-bol) (point)))
18383 (looking-at ".*?|"))
18384 (let ((pos (point))
18385 (noalign (looking-at "[^|\n\r]* |"))
18386 (c org-table-may-need-update))
18387 (backward-delete-char N)
18388 (if (not overwrite-mode)
18389 (progn
18390 (skip-chars-forward "^|")
18391 (insert " ")
18392 (goto-char (1- pos))))
18393 ;; noalign: if there were two spaces at the end, this field
18394 ;; does not determine the width of the column.
18395 (if noalign (setq org-table-may-need-update c)))
18396 (backward-delete-char N)
18397 (org-fix-tags-on-the-fly))))
18399 (defun org-delete-char (N)
18400 "Like `delete-char', but insert whitespace at field end in tables.
18401 When deleting characters, in tables this function will insert whitespace in
18402 front of the next \"|\" separator, to keep the table aligned. The table will
18403 still be marked for re-alignment if the field did fill the entire column,
18404 because, in this case the deletion might narrow the column."
18405 (interactive "p")
18406 (save-match-data
18407 (org-check-before-invisible-edit 'delete)
18408 (if (and (org-table-p)
18409 (not (bolp))
18410 (not (= (char-after) ?|))
18411 (eq N 1))
18412 (if (looking-at ".*?|")
18413 (let ((pos (point))
18414 (noalign (looking-at "[^|\n\r]* |"))
18415 (c org-table-may-need-update))
18416 (replace-match (concat
18417 (substring (match-string 0) 1 -1)
18418 " |"))
18419 (goto-char pos)
18420 ;; noalign: if there were two spaces at the end, this field
18421 ;; does not determine the width of the column.
18422 (if noalign (setq org-table-may-need-update c)))
18423 (delete-char N))
18424 (delete-char N)
18425 (org-fix-tags-on-the-fly))))
18427 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18428 (put 'org-self-insert-command 'delete-selection t)
18429 (put 'orgtbl-self-insert-command 'delete-selection t)
18430 (put 'org-delete-char 'delete-selection 'supersede)
18431 (put 'org-delete-backward-char 'delete-selection 'supersede)
18432 (put 'org-yank 'delete-selection 'yank)
18434 ;; Make `flyspell-mode' delay after some commands
18435 (put 'org-self-insert-command 'flyspell-delayed t)
18436 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18437 (put 'org-delete-char 'flyspell-delayed t)
18438 (put 'org-delete-backward-char 'flyspell-delayed t)
18440 ;; Make pabbrev-mode expand after org-mode commands
18441 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18442 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18444 ;; How to do this: Measure non-white length of current string
18445 ;; If equal to column width, we should realign.
18447 (defun org-remap (map &rest commands)
18448 "In MAP, remap the functions given in COMMANDS.
18449 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18450 (let (new old)
18451 (while commands
18452 (setq old (pop commands) new (pop commands))
18453 (if (fboundp 'command-remapping)
18454 (org-defkey map (vector 'remap old) new)
18455 (substitute-key-definition old new map global-map)))))
18457 (when (eq org-enable-table-editor 'optimized)
18458 ;; If the user wants maximum table support, we need to hijack
18459 ;; some standard editing functions
18460 (org-remap org-mode-map
18461 'self-insert-command 'org-self-insert-command
18462 'delete-char 'org-delete-char
18463 'delete-backward-char 'org-delete-backward-char)
18464 (org-defkey org-mode-map "|" 'org-force-self-insert))
18466 (defvar org-ctrl-c-ctrl-c-hook nil
18467 "Hook for functions attaching themselves to `C-c C-c'.
18469 This can be used to add additional functionality to the C-c C-c
18470 key which executes context-dependent commands. This hook is run
18471 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18472 run after the last test.
18474 Each function will be called with no arguments. The function
18475 must check if the context is appropriate for it to act. If yes,
18476 it should do its thing and then return a non-nil value. If the
18477 context is wrong, just do nothing and return nil.")
18479 (defvar org-ctrl-c-ctrl-c-final-hook nil
18480 "Hook for functions attaching themselves to `C-c C-c'.
18482 This can be used to add additional functionality to the C-c C-c
18483 key which executes context-dependent commands. This hook is run
18484 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18485 before the first test.
18487 Each function will be called with no arguments. The function
18488 must check if the context is appropriate for it to act. If yes,
18489 it should do its thing and then return a non-nil value. If the
18490 context is wrong, just do nothing and return nil.")
18492 (defvar org-tab-first-hook nil
18493 "Hook for functions to attach themselves to TAB.
18494 See `org-ctrl-c-ctrl-c-hook' for more information.
18495 This hook runs as the first action when TAB is pressed, even before
18496 `org-cycle' messes around with the `outline-regexp' to cater for
18497 inline tasks and plain list item folding.
18498 If any function in this hook returns t, any other actions that
18499 would have been caused by TAB (such as table field motion or visibility
18500 cycling) will not occur.")
18502 (defvar org-tab-after-check-for-table-hook nil
18503 "Hook for functions to attach themselves to TAB.
18504 See `org-ctrl-c-ctrl-c-hook' for more information.
18505 This hook runs after it has been established that the cursor is not in a
18506 table, but before checking if the cursor is in a headline or if global cycling
18507 should be done.
18508 If any function in this hook returns t, not other actions like visibility
18509 cycling will be done.")
18511 (defvar org-tab-after-check-for-cycling-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 it has been established that not table field motion and
18515 not visibility should be done because of current context. This is probably
18516 the place where a package like yasnippets can hook in.")
18518 (defvar org-tab-before-tab-emulation-hook nil
18519 "Hook for functions to attach themselves to TAB.
18520 See `org-ctrl-c-ctrl-c-hook' for more information.
18521 This hook runs after every other options for TAB have been exhausted, but
18522 before indentation and \t insertion takes place.")
18524 (defvar org-metaleft-hook nil
18525 "Hook for functions attaching themselves to `M-left'.
18526 See `org-ctrl-c-ctrl-c-hook' for more information.")
18527 (defvar org-metaright-hook nil
18528 "Hook for functions attaching themselves to `M-right'.
18529 See `org-ctrl-c-ctrl-c-hook' for more information.")
18530 (defvar org-metaup-hook nil
18531 "Hook for functions attaching themselves to `M-up'.
18532 See `org-ctrl-c-ctrl-c-hook' for more information.")
18533 (defvar org-metadown-hook nil
18534 "Hook for functions attaching themselves to `M-down'.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.")
18536 (defvar org-shiftmetaleft-hook nil
18537 "Hook for functions attaching themselves to `M-S-left'.
18538 See `org-ctrl-c-ctrl-c-hook' for more information.")
18539 (defvar org-shiftmetaright-hook nil
18540 "Hook for functions attaching themselves to `M-S-right'.
18541 See `org-ctrl-c-ctrl-c-hook' for more information.")
18542 (defvar org-shiftmetaup-hook nil
18543 "Hook for functions attaching themselves to `M-S-up'.
18544 See `org-ctrl-c-ctrl-c-hook' for more information.")
18545 (defvar org-shiftmetadown-hook nil
18546 "Hook for functions attaching themselves to `M-S-down'.
18547 See `org-ctrl-c-ctrl-c-hook' for more information.")
18548 (defvar org-metareturn-hook nil
18549 "Hook for functions attaching themselves to `M-RET'.
18550 See `org-ctrl-c-ctrl-c-hook' for more information.")
18551 (defvar org-shiftup-hook nil
18552 "Hook for functions attaching themselves to `S-up'.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.")
18554 (defvar org-shiftup-final-hook nil
18555 "Hook for functions attaching themselves to `S-up'.
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-shiftdown-hook nil
18559 "Hook for functions attaching themselves to `S-down'.
18560 See `org-ctrl-c-ctrl-c-hook' for more information.")
18561 (defvar org-shiftdown-final-hook nil
18562 "Hook for functions attaching themselves to `S-down'.
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-shiftleft-hook nil
18566 "Hook for functions attaching themselves to `S-left'.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.")
18568 (defvar org-shiftleft-final-hook nil
18569 "Hook for functions attaching themselves to `S-left'.
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.")
18572 (defvar org-shiftright-hook nil
18573 "Hook for functions attaching themselves to `S-right'.
18574 See `org-ctrl-c-ctrl-c-hook' for more information.")
18575 (defvar org-shiftright-final-hook nil
18576 "Hook for functions attaching themselves to `S-right'.
18577 This one runs after all other options except shift-select have been excluded.
18578 See `org-ctrl-c-ctrl-c-hook' for more information.")
18580 (defun org-modifier-cursor-error ()
18581 "Throw an error, a modified cursor command was applied in wrong context."
18582 (error "This command is active in special context like tables, headlines or items"))
18584 (defun org-shiftselect-error ()
18585 "Throw an error because Shift-Cursor command was applied in wrong context."
18586 (if (and (boundp 'shift-select-mode) shift-select-mode)
18587 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18588 (error "This command works only in special context like headlines or timestamps")))
18590 (defun org-call-for-shift-select (cmd)
18591 (let ((this-command-keys-shift-translated t))
18592 (call-interactively cmd)))
18594 (defun org-shifttab (&optional arg)
18595 "Global visibility cycling or move to previous table field.
18596 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18597 on context.
18598 See the individual commands for more information."
18599 (interactive "P")
18600 (cond
18601 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18602 ((integerp arg)
18603 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18604 (message "Content view to level: %d" arg)
18605 (org-content (prefix-numeric-value arg2))
18606 (setq org-cycle-global-status 'overview)))
18607 (t (call-interactively 'org-global-cycle))))
18609 (defun org-shiftmetaleft ()
18610 "Promote subtree or delete table column.
18611 Calls `org-promote-subtree', `org-outdent-item-tree', or
18612 `org-table-delete-column', depending on context. See the
18613 individual commands for more information."
18614 (interactive)
18615 (cond
18616 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18617 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18618 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18619 ((if (not (org-region-active-p)) (org-at-item-p)
18620 (save-excursion (goto-char (region-beginning))
18621 (org-at-item-p)))
18622 (call-interactively 'org-outdent-item-tree))
18623 (t (org-modifier-cursor-error))))
18625 (defun org-shiftmetaright ()
18626 "Demote subtree or insert table column.
18627 Calls `org-demote-subtree', `org-indent-item-tree', or
18628 `org-table-insert-column', depending on context. See the
18629 individual commands for more information."
18630 (interactive)
18631 (cond
18632 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18633 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18634 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18635 ((if (not (org-region-active-p)) (org-at-item-p)
18636 (save-excursion (goto-char (region-beginning))
18637 (org-at-item-p)))
18638 (call-interactively 'org-indent-item-tree))
18639 (t (org-modifier-cursor-error))))
18641 (defun org-shiftmetaup (&optional arg)
18642 "Move subtree up or kill table row.
18643 Calls `org-move-subtree-up' or `org-table-kill-row' or
18644 `org-move-item-up' or `org-timestamp-up', depending on context.
18645 See the individual commands for more information."
18646 (interactive "P")
18647 (cond
18648 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18649 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18650 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18651 ((org-at-item-p) (call-interactively 'org-move-item-up))
18652 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18653 (call-interactively 'org-timestamp-up)))
18654 (t (org-modifier-cursor-error))))
18656 (defun org-shiftmetadown (&optional arg)
18657 "Move subtree down or insert table row.
18658 Calls `org-move-subtree-down' or `org-table-insert-row' or
18659 `org-move-item-down' or `org-timestamp-up', depending on context.
18660 See the individual commands for more information."
18661 (interactive "P")
18662 (cond
18663 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18664 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18665 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18666 ((org-at-item-p) (call-interactively 'org-move-item-down))
18667 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18668 (call-interactively 'org-timestamp-down)))
18669 (t (org-modifier-cursor-error))))
18671 (defsubst org-hidden-tree-error ()
18672 (error
18673 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18675 (defun org-metaleft (&optional arg)
18676 "Promote heading or move table column to left.
18677 Calls `org-do-promote' or `org-table-move-column', depending on context.
18678 With no specific context, calls the Emacs default `backward-word'.
18679 See the individual commands for more information."
18680 (interactive "P")
18681 (cond
18682 ((run-hook-with-args-until-success 'org-metaleft-hook))
18683 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18684 ((org-with-limited-levels
18685 (or (org-at-heading-p)
18686 (and (org-region-active-p)
18687 (save-excursion
18688 (goto-char (region-beginning))
18689 (org-at-heading-p)))))
18690 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18691 (call-interactively 'org-do-promote))
18692 ;; At an inline task.
18693 ((org-at-heading-p)
18694 (call-interactively 'org-inlinetask-promote))
18695 ((or (org-at-item-p)
18696 (and (org-region-active-p)
18697 (save-excursion
18698 (goto-char (region-beginning))
18699 (org-at-item-p))))
18700 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18701 (call-interactively 'org-outdent-item))
18702 (t (call-interactively 'backward-word))))
18704 (defun org-metaright (&optional arg)
18705 "Demote a subtree, a list item or move table column to right.
18706 In front of a drawer or a block keyword, indent it correctly.
18707 With no specific context, calls the Emacs default `forward-word'.
18708 See the individual commands for more information."
18709 (interactive "P")
18710 (cond
18711 ((run-hook-with-args-until-success 'org-metaright-hook))
18712 ((org-at-table-p) (call-interactively 'org-table-move-column))
18713 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18714 ((org-at-block-p) (call-interactively 'org-indent-block))
18715 ((org-with-limited-levels
18716 (or (org-at-heading-p)
18717 (and (org-region-active-p)
18718 (save-excursion
18719 (goto-char (region-beginning))
18720 (org-at-heading-p)))))
18721 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18722 (call-interactively 'org-do-demote))
18723 ;; At an inline task.
18724 ((org-at-heading-p)
18725 (call-interactively 'org-inlinetask-demote))
18726 ((or (org-at-item-p)
18727 (and (org-region-active-p)
18728 (save-excursion
18729 (goto-char (region-beginning))
18730 (org-at-item-p))))
18731 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18732 (call-interactively 'org-indent-item))
18733 (t (call-interactively 'forward-word))))
18735 (defun org-check-for-hidden (what)
18736 "Check if there are hidden headlines/items in the current visual line.
18737 WHAT can be either `headlines' or `items'. If the current line is
18738 an outline or item heading and it has a folded subtree below it,
18739 this function returns t, nil otherwise."
18740 (let ((re (cond
18741 ((eq what 'headlines) org-outline-regexp-bol)
18742 ((eq what 'items) (org-item-beginning-re))
18743 (t (error "This should not happen"))))
18744 beg end)
18745 (save-excursion
18746 (catch 'exit
18747 (unless (org-region-active-p)
18748 (setq beg (point-at-bol))
18749 (beginning-of-line 2)
18750 (while (and (not (eobp)) ;; this is like `next-line'
18751 (get-char-property (1- (point)) 'invisible))
18752 (beginning-of-line 2))
18753 (setq end (point))
18754 (goto-char beg)
18755 (goto-char (point-at-eol))
18756 (setq end (max end (point)))
18757 (while (re-search-forward re end t)
18758 (if (get-char-property (match-beginning 0) 'invisible)
18759 (throw 'exit t))))
18760 nil))))
18762 (org-autoload "org-element" '(org-element-at-point org-element-type))
18764 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18765 (declare-function org-element-type "org-element" (element))
18766 (declare-function org-element-contents "org-element" (element))
18767 (declare-function org-element-property "org-element" (property element))
18768 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18769 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18770 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18771 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18772 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18774 (defun org-metaup (&optional arg)
18775 "Move subtree up or move table row up.
18776 Calls `org-move-subtree-up' or `org-table-move-row' or
18777 `org-move-item-up', depending on context. See the individual commands
18778 for more information."
18779 (interactive "P")
18780 (cond
18781 ((run-hook-with-args-until-success 'org-metaup-hook))
18782 ((org-region-active-p)
18783 (let* ((a (min (region-beginning) (region-end)))
18784 (b (1- (max (region-beginning) (region-end))))
18785 (c (save-excursion (goto-char a)
18786 (move-beginning-of-line 0)))
18787 (d (save-excursion (goto-char a)
18788 (move-end-of-line 0) (point))))
18789 (transpose-regions a b c d)
18790 (goto-char c)))
18791 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18792 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18793 ((org-at-item-p) (call-interactively 'org-move-item-up))
18794 (t (org-drag-element-backward))))
18796 (defun org-metadown (&optional arg)
18797 "Move subtree down or move table row down.
18798 Calls `org-move-subtree-down' or `org-table-move-row' or
18799 `org-move-item-down', depending on context. See the individual
18800 commands for more information."
18801 (interactive "P")
18802 (cond
18803 ((run-hook-with-args-until-success 'org-metadown-hook))
18804 ((org-region-active-p)
18805 (let* ((a (min (region-beginning) (region-end)))
18806 (b (max (region-beginning) (region-end)))
18807 (c (save-excursion (goto-char b)
18808 (move-beginning-of-line 1)))
18809 (d (save-excursion (goto-char b)
18810 (move-end-of-line 1) (1+ (point)))))
18811 (transpose-regions a b c d)
18812 (goto-char d)))
18813 ((org-at-table-p) (call-interactively 'org-table-move-row))
18814 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18815 ((org-at-item-p) (call-interactively 'org-move-item-down))
18816 (t (org-drag-element-forward))))
18818 (defun org-shiftup (&optional arg)
18819 "Increase item in timestamp or increase priority of current headline.
18820 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18821 depending on context. See the individual commands for more information."
18822 (interactive "P")
18823 (cond
18824 ((run-hook-with-args-until-success 'org-shiftup-hook))
18825 ((and org-support-shift-select (org-region-active-p))
18826 (org-call-for-shift-select 'previous-line))
18827 ((org-at-timestamp-p t)
18828 (call-interactively (if org-edit-timestamp-down-means-later
18829 'org-timestamp-down 'org-timestamp-up)))
18830 ((and (not (eq org-support-shift-select 'always))
18831 org-enable-priority-commands
18832 (org-at-heading-p))
18833 (call-interactively 'org-priority-up))
18834 ((and (not org-support-shift-select) (org-at-item-p))
18835 (call-interactively 'org-previous-item))
18836 ((org-clocktable-try-shift 'up arg))
18837 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18838 (org-support-shift-select
18839 (org-call-for-shift-select 'previous-line))
18840 (t (org-shiftselect-error))))
18842 (defun org-shiftdown (&optional arg)
18843 "Decrease item in timestamp or decrease priority of current headline.
18844 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18845 depending on context. See the individual commands for more information."
18846 (interactive "P")
18847 (cond
18848 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18849 ((and org-support-shift-select (org-region-active-p))
18850 (org-call-for-shift-select 'next-line))
18851 ((org-at-timestamp-p t)
18852 (call-interactively (if org-edit-timestamp-down-means-later
18853 'org-timestamp-up 'org-timestamp-down)))
18854 ((and (not (eq org-support-shift-select 'always))
18855 org-enable-priority-commands
18856 (org-at-heading-p))
18857 (call-interactively 'org-priority-down))
18858 ((and (not org-support-shift-select) (org-at-item-p))
18859 (call-interactively 'org-next-item))
18860 ((org-clocktable-try-shift 'down arg))
18861 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18862 (org-support-shift-select
18863 (org-call-for-shift-select 'next-line))
18864 (t (org-shiftselect-error))))
18866 (defun org-shiftright (&optional arg)
18867 "Cycle the thing at point or in the current line, depending on context.
18868 Depending on context, this does one of the following:
18870 - switch a timestamp at point one day into the future
18871 - on a headline, switch to the next TODO keyword.
18872 - on an item, switch entire list to the next bullet type
18873 - on a property line, switch to the next allowed value
18874 - on a clocktable definition line, move time block into the future"
18875 (interactive "P")
18876 (cond
18877 ((run-hook-with-args-until-success 'org-shiftright-hook))
18878 ((and org-support-shift-select (org-region-active-p))
18879 (org-call-for-shift-select 'forward-char))
18880 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18881 ((and (not (eq org-support-shift-select 'always))
18882 (org-at-heading-p))
18883 (let ((org-inhibit-logging
18884 (not org-treat-S-cursor-todo-selection-as-state-change))
18885 (org-inhibit-blocking
18886 (not org-treat-S-cursor-todo-selection-as-state-change)))
18887 (org-call-with-arg 'org-todo 'right)))
18888 ((or (and org-support-shift-select
18889 (not (eq org-support-shift-select 'always))
18890 (org-at-item-bullet-p))
18891 (and (not org-support-shift-select) (org-at-item-p)))
18892 (org-call-with-arg 'org-cycle-list-bullet nil))
18893 ((and (not (eq org-support-shift-select 'always))
18894 (org-at-property-p))
18895 (call-interactively 'org-property-next-allowed-value))
18896 ((org-clocktable-try-shift 'right arg))
18897 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18898 (org-support-shift-select
18899 (org-call-for-shift-select 'forward-char))
18900 (t (org-shiftselect-error))))
18902 (defun org-shiftleft (&optional arg)
18903 "Cycle the thing at point or in the current line, depending on context.
18904 Depending on context, this does one of the following:
18906 - switch a timestamp at point one day into the past
18907 - on a headline, switch to the previous TODO keyword.
18908 - on an item, switch entire list to the previous bullet type
18909 - on a property line, switch to the previous allowed value
18910 - on a clocktable definition line, move time block into the past"
18911 (interactive "P")
18912 (cond
18913 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18914 ((and org-support-shift-select (org-region-active-p))
18915 (org-call-for-shift-select 'backward-char))
18916 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18917 ((and (not (eq org-support-shift-select 'always))
18918 (org-at-heading-p))
18919 (let ((org-inhibit-logging
18920 (not org-treat-S-cursor-todo-selection-as-state-change))
18921 (org-inhibit-blocking
18922 (not org-treat-S-cursor-todo-selection-as-state-change)))
18923 (org-call-with-arg 'org-todo 'left)))
18924 ((or (and org-support-shift-select
18925 (not (eq org-support-shift-select 'always))
18926 (org-at-item-bullet-p))
18927 (and (not org-support-shift-select) (org-at-item-p)))
18928 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18929 ((and (not (eq org-support-shift-select 'always))
18930 (org-at-property-p))
18931 (call-interactively 'org-property-previous-allowed-value))
18932 ((org-clocktable-try-shift 'left arg))
18933 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18934 (org-support-shift-select
18935 (org-call-for-shift-select 'backward-char))
18936 (t (org-shiftselect-error))))
18938 (defun org-shiftcontrolright ()
18939 "Switch to next TODO set."
18940 (interactive)
18941 (cond
18942 ((and org-support-shift-select (org-region-active-p))
18943 (org-call-for-shift-select 'forward-word))
18944 ((and (not (eq org-support-shift-select 'always))
18945 (org-at-heading-p))
18946 (org-call-with-arg 'org-todo 'nextset))
18947 (org-support-shift-select
18948 (org-call-for-shift-select 'forward-word))
18949 (t (org-shiftselect-error))))
18951 (defun org-shiftcontrolleft ()
18952 "Switch to previous TODO set."
18953 (interactive)
18954 (cond
18955 ((and org-support-shift-select (org-region-active-p))
18956 (org-call-for-shift-select 'backward-word))
18957 ((and (not (eq org-support-shift-select 'always))
18958 (org-at-heading-p))
18959 (org-call-with-arg 'org-todo 'previousset))
18960 (org-support-shift-select
18961 (org-call-for-shift-select 'backward-word))
18962 (t (org-shiftselect-error))))
18964 (defun org-shiftcontrolup ()
18965 "Change timestamps synchronously up in CLOCK log lines."
18966 (interactive)
18967 (cond ((and (not org-support-shift-select)
18968 (org-at-clock-log-p)
18969 (org-at-timestamp-p t))
18970 (org-clock-timestamps-up))
18971 (t (org-shiftselect-error))))
18973 (defun org-shiftcontroldown ()
18974 "Change timestamps synchronously down in CLOCK log lines."
18975 (interactive)
18976 (cond ((and (not org-support-shift-select)
18977 (org-at-clock-log-p)
18978 (org-at-timestamp-p t))
18979 (org-clock-timestamps-down))
18980 (t (org-shiftselect-error))))
18982 (defun org-ctrl-c-ret ()
18983 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18984 (interactive)
18985 (cond
18986 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18987 (t (call-interactively 'org-insert-heading))))
18989 (defun org-find-visible ()
18990 (let ((s (point)))
18991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18992 (get-char-property s 'invisible)))
18994 (defun org-find-invisible ()
18995 (let ((s (point)))
18996 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18997 (not (get-char-property s 'invisible))))
19000 (defun org-copy-visible (beg end)
19001 "Copy the visible parts of the region."
19002 (interactive "r")
19003 (let (snippets s)
19004 (save-excursion
19005 (save-restriction
19006 (narrow-to-region beg end)
19007 (setq s (goto-char (point-min)))
19008 (while (not (= (point) (point-max)))
19009 (goto-char (org-find-invisible))
19010 (push (buffer-substring s (point)) snippets)
19011 (setq s (goto-char (org-find-visible))))))
19012 (kill-new (apply 'concat (nreverse snippets)))))
19014 (defun org-copy-special ()
19015 "Copy region in table or copy current subtree.
19016 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19017 See the individual commands for more information."
19018 (interactive)
19019 (call-interactively
19020 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19022 (defun org-cut-special ()
19023 "Cut region in table or cut current subtree.
19024 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19025 See the individual commands for more information."
19026 (interactive)
19027 (call-interactively
19028 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19030 (defun org-paste-special (arg)
19031 "Paste rectangular region into table, or past subtree relative to level.
19032 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19033 See the individual commands for more information."
19034 (interactive "P")
19035 (if (org-at-table-p)
19036 (org-table-paste-rectangle)
19037 (org-paste-subtree arg)))
19039 (defsubst org-in-fixed-width-region-p ()
19040 "Is point in a fixed-width region?"
19041 (save-match-data
19042 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19044 (defun org-edit-special (&optional arg)
19045 "Call a special editor for the stuff at point.
19046 When at a table, call the formula editor with `org-table-edit-formulas'.
19047 When in a source code block, call `org-edit-src-code'.
19048 When in a fixed-width region, call `org-edit-fixed-width-region'.
19049 When in an #+include line, visit the included file.
19050 On a link, call `ffap' to visit the link at point.
19051 Otherwise, return a user error."
19052 (interactive)
19053 ;; possibly prep session before editing source
19054 (when (and (org-in-src-block-p) arg)
19055 (let* ((info (org-babel-get-src-block-info))
19056 (lang (nth 0 info))
19057 (params (nth 2 info))
19058 (session (cdr (assoc :session params))))
19059 (when (and info session) ;; we are in a source-code block with a session
19060 (funcall
19061 (intern (concat "org-babel-prep-session:" lang)) session params))))
19062 (cond ;; proceed with `org-edit-special'
19063 ((save-excursion
19064 (beginning-of-line 1)
19065 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19066 (find-file (org-trim (match-string 1))))
19067 ((org-at-table.el-p) (org-edit-src-code))
19068 ((or (org-at-table-p)
19069 (save-excursion
19070 (beginning-of-line 1)
19071 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19072 (call-interactively 'org-table-edit-formulas))
19073 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19074 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19075 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19076 (t (user-error "No special environment to edit here"))))
19078 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19079 (defun org-ctrl-c-ctrl-c (&optional arg)
19080 "Set tags in headline, or update according to changed information at point.
19082 This command does many different things, depending on context:
19084 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19085 this is what we do.
19087 - If the cursor is on a statistics cookie, update it.
19089 - If the cursor is in a headline, prompt for tags and insert them
19090 into the current line, aligned to `org-tags-column'. When called
19091 with prefix arg, realign all tags in the current buffer.
19093 - If the cursor is in one of the special #+KEYWORD lines, this
19094 triggers scanning the buffer for these lines and updating the
19095 information.
19097 - If the cursor is inside a table, realign the table. This command
19098 works even if the automatic table editor has been turned off.
19100 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19101 the entire table.
19103 - If the cursor is at a footnote reference or definition, jump to
19104 the corresponding definition or references, respectively.
19106 - If the cursor is a the beginning of a dynamic block, update it.
19108 - If the current buffer is a capture buffer, close note and file it.
19110 - If the cursor is on a <<<target>>>, update radio targets and
19111 corresponding links in this buffer.
19113 - If the cursor is on a numbered item in a plain list, renumber the
19114 ordered list.
19116 - If the cursor is on a checkbox, toggle it.
19118 - If the cursor is on a code block, evaluate it. The variable
19119 `org-confirm-babel-evaluate' can be used to control prompting
19120 before code block evaluation, by default every code block
19121 evaluation requires confirmation. Code block evaluation can be
19122 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19123 (interactive "P")
19124 (let ((org-enable-table-editor t))
19125 (cond
19126 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19127 org-occur-highlights
19128 org-latex-fragment-image-overlays)
19129 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19130 (org-remove-occur-highlights)
19131 (org-remove-latex-fragment-image-overlays)
19132 (message "Temporary highlights/overlays removed from current buffer"))
19133 ((and (local-variable-p 'org-finish-function (current-buffer))
19134 (fboundp org-finish-function))
19135 (funcall org-finish-function))
19136 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19137 ((org-in-regexp org-ts-regexp-both)
19138 (org-timestamp-change 0 'day))
19139 ((or (looking-at org-property-start-re)
19140 (org-at-property-p))
19141 (call-interactively 'org-property-action))
19142 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19143 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19144 (or (org-at-heading-p) (org-at-item-p)))
19145 (call-interactively 'org-update-statistics-cookies))
19146 ((org-at-heading-p) (call-interactively 'org-set-tags))
19147 ((org-at-table.el-p)
19148 (message "Use C-c ' to edit table.el tables"))
19149 ((org-at-table-p)
19150 (org-table-maybe-eval-formula)
19151 (if arg
19152 (call-interactively 'org-table-recalculate)
19153 (org-table-maybe-recalculate-line))
19154 (call-interactively 'org-table-align)
19155 (orgtbl-send-table 'maybe))
19156 ((or (org-footnote-at-reference-p)
19157 (org-footnote-at-definition-p))
19158 (call-interactively 'org-footnote-action))
19159 ((org-at-item-checkbox-p)
19160 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19161 ;; list only if at top item.
19162 (let* ((cbox (match-string 1))
19163 (struct (org-list-struct))
19164 (old-struct (copy-tree struct))
19165 (parents (org-list-parents-alist struct))
19166 (orderedp (org-entry-get nil "ORDERED"))
19167 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19168 block-item)
19169 ;; Use a light version of `org-toggle-checkbox' to avoid
19170 ;; computing list structure twice.
19171 (let ((new-box (cond
19172 ((equal arg '(16)) "[-]")
19173 ((equal arg '(4)) nil)
19174 ((equal "[X]" cbox) "[ ]")
19175 (t "[X]"))))
19176 (if (and firstp arg)
19177 ;; If at first item of sub-list, remove check-box from
19178 ;; every item at the same level.
19179 (mapc
19180 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19181 (org-list-get-all-items
19182 (point-at-bol) struct (org-list-prevs-alist struct)))
19183 (org-list-set-checkbox (point-at-bol) struct new-box)))
19184 ;; Replicate `org-list-write-struct', while grabbing a return
19185 ;; value from `org-list-struct-fix-box'.
19186 (org-list-struct-fix-ind struct parents 2)
19187 (org-list-struct-fix-item-end struct)
19188 (let ((prevs (org-list-prevs-alist struct)))
19189 (org-list-struct-fix-bul struct prevs)
19190 (org-list-struct-fix-ind struct parents)
19191 (setq block-item
19192 (org-list-struct-fix-box struct parents prevs orderedp)))
19193 (if (equal struct old-struct)
19194 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19195 (org-list-struct-apply-struct struct old-struct)
19196 (org-update-checkbox-count-maybe))
19197 (when block-item
19198 (message
19199 "Checkboxes were removed due to unchecked box at line %d"
19200 (org-current-line block-item)))
19201 (when firstp (org-list-send-list 'maybe))))
19202 ((org-at-item-p)
19203 ;; Cursor at an item: repair list. Do checkbox related actions
19204 ;; only if function was called with an argument. Send list only
19205 ;; if at top item.
19206 (let* ((struct (org-list-struct))
19207 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19208 old-struct)
19209 (when arg
19210 (setq old-struct (copy-tree struct))
19211 (if firstp
19212 ;; If at first item of sub-list, add check-box to every
19213 ;; item at the same level.
19214 (mapc
19215 (lambda (pos)
19216 (unless (org-list-get-checkbox pos struct)
19217 (org-list-set-checkbox pos struct "[ ]")))
19218 (org-list-get-all-items
19219 (point-at-bol) struct (org-list-prevs-alist struct)))
19220 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19221 (org-list-write-struct
19222 struct (org-list-parents-alist struct) old-struct)
19223 (when arg (org-update-checkbox-count-maybe))
19224 (when firstp (org-list-send-list 'maybe))))
19225 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19226 ;; Dynamic block
19227 (beginning-of-line 1)
19228 (save-excursion (org-update-dblock)))
19229 ((save-excursion
19230 (let ((case-fold-search t))
19231 (beginning-of-line 1)
19232 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19233 (cond
19234 ((or (equal (match-string 1) "TBLFM")
19235 (equal (match-string 1) "tblfm"))
19236 ;; Recalculate the table before this line
19237 (save-excursion
19238 (beginning-of-line 1)
19239 (skip-chars-backward " \r\n\t")
19240 (if (org-at-table-p)
19241 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19243 (let ((org-inhibit-startup-visibility-stuff t)
19244 (org-startup-align-all-tables nil))
19245 (when (boundp 'org-table-coordinate-overlays)
19246 (mapc 'delete-overlay org-table-coordinate-overlays)
19247 (setq org-table-coordinate-overlays nil))
19248 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19249 (message "Local setup has been refreshed"))))
19250 ((org-clock-update-time-maybe))
19252 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19253 (error "C-c C-c can do nothing useful at this location"))))))
19255 (defun org-mode-restart ()
19256 "Restart Org-mode, to scan again for special lines.
19257 Also updates the keyword regular expressions."
19258 (interactive)
19259 (org-mode)
19260 (message "Org-mode restarted"))
19262 (defun org-kill-note-or-show-branches ()
19263 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19264 (interactive)
19265 (if (not org-finish-function)
19266 (progn
19267 (hide-subtree)
19268 (call-interactively 'show-branches))
19269 (let ((org-note-abort t))
19270 (funcall org-finish-function))))
19272 (defun org-return (&optional indent)
19273 "Goto next table row or insert a newline.
19274 Calls `org-table-next-row' or `newline', depending on context.
19275 See the individual commands for more information."
19276 (interactive)
19277 (let (org-ts-what)
19278 (cond
19279 ((or (bobp) (org-in-src-block-p))
19280 (if indent (newline-and-indent) (newline)))
19281 ((org-at-table-p)
19282 (org-table-justify-field-maybe)
19283 (call-interactively 'org-table-next-row))
19284 ;; when `newline-and-indent' is called within a list, make sure
19285 ;; text moved stays inside the item.
19286 ((and (org-in-item-p) indent)
19287 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19288 (progn
19289 (save-match-data (newline))
19290 (org-indent-line-to (length (match-string 0))))
19291 (let ((ind (org-get-indentation)))
19292 (newline)
19293 (if (org-looking-back org-list-end-re)
19294 (org-indent-line)
19295 (org-indent-line-to ind)))))
19296 ((and org-return-follows-link
19297 (org-at-timestamp-p t)
19298 (not (eq org-ts-what 'after)))
19299 (org-follow-timestamp-link))
19300 ((and org-return-follows-link
19301 (let ((tprop (get-text-property (point) 'face)))
19302 (or (eq tprop 'org-link)
19303 (and (listp tprop) (memq 'org-link tprop)))))
19304 (call-interactively 'org-open-at-point))
19305 ((and (org-at-heading-p)
19306 (looking-at
19307 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19308 (org-show-entry)
19309 (end-of-line 1)
19310 (newline))
19311 (t (if indent (newline-and-indent) (newline))))))
19313 (defun org-return-indent ()
19314 "Goto next table row or insert a newline and indent.
19315 Calls `org-table-next-row' or `newline-and-indent', depending on
19316 context. See the individual commands for more information."
19317 (interactive)
19318 (org-return t))
19320 (defun org-ctrl-c-star ()
19321 "Compute table, or change heading status of lines.
19322 Calls `org-table-recalculate' or `org-toggle-heading',
19323 depending on context."
19324 (interactive)
19325 (cond
19326 ((org-at-table-p)
19327 (call-interactively 'org-table-recalculate))
19329 ;; Convert all lines in region to list items
19330 (call-interactively 'org-toggle-heading))))
19332 (defun org-ctrl-c-minus ()
19333 "Insert separator line in table or modify bullet status of line.
19334 Also turns a plain line or a region of lines into list items.
19335 Calls `org-table-insert-hline', `org-toggle-item', or
19336 `org-cycle-list-bullet', depending on context."
19337 (interactive)
19338 (cond
19339 ((org-at-table-p)
19340 (call-interactively 'org-table-insert-hline))
19341 ((org-region-active-p)
19342 (call-interactively 'org-toggle-item))
19343 ((org-in-item-p)
19344 (call-interactively 'org-cycle-list-bullet))
19346 (call-interactively 'org-toggle-item))))
19348 (defun org-toggle-item (arg)
19349 "Convert headings or normal lines to items, items to normal lines.
19350 If there is no active region, only the current line is considered.
19352 If the first non blank line in the region is an headline, convert
19353 all headlines to items, shifting text accordingly.
19355 If it is an item, convert all items to normal lines.
19357 If it is normal text, change region into an item. With a prefix
19358 argument ARG, change each line in region into an item."
19359 (interactive "P")
19360 (let ((shift-text
19361 (function
19362 ;; Shift text in current section to IND, from point to END.
19363 ;; The function leaves point to END line.
19364 (lambda (ind end)
19365 (let ((min-i 1000) (end (copy-marker end)))
19366 ;; First determine the minimum indentation (MIN-I) of
19367 ;; the text.
19368 (save-excursion
19369 (catch 'exit
19370 (while (< (point) end)
19371 (let ((i (org-get-indentation)))
19372 (cond
19373 ;; Skip blank lines and inline tasks.
19374 ((looking-at "^[ \t]*$"))
19375 ((looking-at org-outline-regexp-bol))
19376 ;; We can't find less than 0 indentation.
19377 ((zerop i) (throw 'exit (setq min-i 0)))
19378 ((< i min-i) (setq min-i i))))
19379 (forward-line))))
19380 ;; Then indent each line so that a line indented to
19381 ;; MIN-I becomes indented to IND. Ignore blank lines
19382 ;; and inline tasks in the process.
19383 (let ((delta (- ind min-i)))
19384 (while (< (point) end)
19385 (unless (or (looking-at "^[ \t]*$")
19386 (looking-at org-outline-regexp-bol))
19387 (org-indent-line-to (+ (org-get-indentation) delta)))
19388 (forward-line)))))))
19389 (skip-blanks
19390 (function
19391 ;; Return beginning of first non-blank line, starting from
19392 ;; line at POS.
19393 (lambda (pos)
19394 (save-excursion
19395 (goto-char pos)
19396 (skip-chars-forward " \r\t\n")
19397 (point-at-bol)))))
19398 beg end)
19399 ;; Determine boundaries of changes.
19400 (if (org-region-active-p)
19401 (setq beg (funcall skip-blanks (region-beginning))
19402 end (copy-marker (region-end)))
19403 (setq beg (funcall skip-blanks (point-at-bol))
19404 end (copy-marker (point-at-eol))))
19405 ;; Depending on the starting line, choose an action on the text
19406 ;; between BEG and END.
19407 (org-with-limited-levels
19408 (save-excursion
19409 (goto-char beg)
19410 (cond
19411 ;; Case 1. Start at an item: de-itemize. Note that it only
19412 ;; happens when a region is active: `org-ctrl-c-minus'
19413 ;; would call `org-cycle-list-bullet' otherwise.
19414 ((org-at-item-p)
19415 (while (< (point) end)
19416 (when (org-at-item-p)
19417 (skip-chars-forward " \t")
19418 (delete-region (point) (match-end 0)))
19419 (forward-line)))
19420 ;; Case 2. Start at an heading: convert to items.
19421 ((org-at-heading-p)
19422 (let* ((bul (org-list-bullet-string "-"))
19423 (bul-len (length bul))
19424 ;; Indentation of the first heading. It should be
19425 ;; relative to the indentation of its parent, if any.
19426 (start-ind (save-excursion
19427 (cond
19428 ((not org-adapt-indentation) 0)
19429 ((not (outline-previous-heading)) 0)
19430 (t (length (match-string 0))))))
19431 ;; Level of first heading. Further headings will be
19432 ;; compared to it to determine hierarchy in the list.
19433 (ref-level (org-reduced-level (org-outline-level))))
19434 (while (< (point) end)
19435 (let* ((level (org-reduced-level (org-outline-level)))
19436 (delta (max 0 (- level ref-level))))
19437 ;; If current headline is less indented than the first
19438 ;; one, set it as reference, in order to preserve
19439 ;; subtrees.
19440 (when (< level ref-level) (setq ref-level level))
19441 (replace-match bul t t)
19442 (org-indent-line-to (+ start-ind (* delta bul-len)))
19443 ;; Ensure all text down to END (or SECTION-END) belongs
19444 ;; to the newly created item.
19445 (let ((section-end (save-excursion
19446 (or (outline-next-heading) (point)))))
19447 (forward-line)
19448 (funcall shift-text
19449 (+ start-ind (* (1+ delta) bul-len))
19450 (min end section-end)))))))
19451 ;; Case 3. Normal line with ARG: turn each non-item line into
19452 ;; an item.
19453 (arg
19454 (while (< (point) end)
19455 (unless (or (org-at-heading-p) (org-at-item-p))
19456 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19457 (replace-match
19458 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19459 (forward-line)))
19460 ;; Case 4. Normal line without ARG: make the first line of
19461 ;; region an item, and shift indentation of others
19462 ;; lines to set them as item's body.
19463 (t (let* ((bul (org-list-bullet-string "-"))
19464 (bul-len (length bul))
19465 (ref-ind (org-get-indentation)))
19466 (skip-chars-forward " \t")
19467 (insert bul)
19468 (forward-line)
19469 (while (< (point) end)
19470 ;; Ensure that lines less indented than first one
19471 ;; still get included in item body.
19472 (funcall shift-text
19473 (+ ref-ind bul-len)
19474 (min end (save-excursion (or (outline-next-heading)
19475 (point)))))
19476 (forward-line)))))))))
19478 (defun org-toggle-heading (&optional nstars)
19479 "Convert headings to normal text, or items or text to headings.
19480 If there is no active region, only the current line is considered.
19482 With a \\[universal-argument] prefix, convert the whole list at
19483 point into heading.
19485 In a region:
19487 - If the first non blank line is an headline, remove the stars
19488 from all headlines in the region.
19490 - If it is a normal line turn each and every normal line (i.e. not an
19491 heading or an item) in the region into a heading.
19493 - If it is a plain list item, turn all plain list items into headings.
19495 When converting a line into a heading, the number of stars is chosen
19496 such that the lines become children of the current entry. However,
19497 when a prefix argument is given, its value determines the number of
19498 stars to add."
19499 (interactive "P")
19500 (let ((skip-blanks
19501 (function
19502 ;; Return beginning of first non-blank line, starting from
19503 ;; line at POS.
19504 (lambda (pos)
19505 (save-excursion
19506 (goto-char pos)
19507 (while (org-at-comment-p) (forward-line))
19508 (skip-chars-forward " \r\t\n")
19509 (point-at-bol)))))
19510 beg end toggled)
19511 ;; Determine boundaries of changes. If a universal prefix has
19512 ;; been given, put the list in a region. If region ends at a bol,
19513 ;; do not consider the last line to be in the region.
19515 (when (and current-prefix-arg (org-at-item-p))
19516 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19517 (org-mark-element))
19519 (if (org-region-active-p)
19520 (setq beg (funcall skip-blanks (region-beginning))
19521 end (copy-marker (save-excursion
19522 (goto-char (region-end))
19523 (if (bolp) (point) (point-at-eol)))))
19524 (setq beg (funcall skip-blanks (point-at-bol))
19525 end (copy-marker (point-at-eol))))
19526 ;; Ensure inline tasks don't count as headings.
19527 (org-with-limited-levels
19528 (save-excursion
19529 (goto-char beg)
19530 (cond
19531 ;; Case 1. Started at an heading: de-star headings.
19532 ((org-at-heading-p)
19533 (while (< (point) end)
19534 (when (org-at-heading-p t)
19535 (looking-at org-outline-regexp) (replace-match "")
19536 (setq toggled t))
19537 (forward-line)))
19538 ;; Case 2. Started at an item: change items into headlines.
19539 ;; One star will be added by `org-list-to-subtree'.
19540 ((org-at-item-p)
19541 (let* ((stars (make-string
19542 (if nstars
19543 ;; subtract the star that will be added again by
19544 ;; `org-list-to-subtree'
19545 (1- (prefix-numeric-value current-prefix-arg))
19546 (or (org-current-level) 0))
19547 ?*))
19548 (add-stars
19549 (cond (nstars "") ; stars from prefix only
19550 ((equal stars "") "") ; before first heading
19551 (org-odd-levels-only "*") ; inside heading, odd
19552 (t "")))) ; inside heading, oddeven
19553 (while (< (point) end)
19554 (when (org-at-item-p)
19555 ;; Pay attention to cases when region ends before list.
19556 (let* ((struct (org-list-struct))
19557 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19558 (save-restriction
19559 (narrow-to-region (point) list-end)
19560 (insert
19561 (org-list-to-subtree
19562 (org-list-parse-list t)
19563 '(:istart (concat stars add-stars (funcall get-stars depth))
19564 :icount (concat stars add-stars (funcall get-stars depth)))))))
19565 (setq toggled t))
19566 (forward-line))))
19567 ;; Case 3. Started at normal text: make every line an heading,
19568 ;; skipping headlines and items.
19569 (t (let* ((stars (make-string
19570 (if nstars
19571 (prefix-numeric-value current-prefix-arg)
19572 (or (org-current-level) 0))
19573 ?*))
19574 (add-stars
19575 (cond (nstars "") ; stars from prefix only
19576 ((equal stars "") "*") ; before first heading
19577 (org-odd-levels-only "**") ; inside heading, odd
19578 (t "*"))) ; inside heading, oddeven
19579 (rpl (concat stars add-stars " ")))
19580 (while (< (point) end)
19581 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19582 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19583 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19584 (forward-line)))))))
19585 (unless toggled (message "Cannot toggle heading from here"))))
19587 (defun org-meta-return (&optional arg)
19588 "Insert a new heading or wrap a region in a table.
19589 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19590 See the individual commands for more information."
19591 (interactive "P")
19592 (cond
19593 ((run-hook-with-args-until-success 'org-metareturn-hook))
19594 ((or (org-at-drawer-p) (org-at-property-p))
19595 (newline-and-indent))
19596 ((org-at-table-p)
19597 (call-interactively 'org-table-wrap-region))
19598 (t (call-interactively 'org-insert-heading))))
19600 ;;; Menu entries
19602 (defsubst org-in-subtree-not-table-p ()
19603 "Are we in a subtree and not in a table?"
19604 (and (not (org-before-first-heading-p))
19605 (not (org-at-table-p))))
19607 ;; Define the Org-mode menus
19608 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19609 '("Tbl"
19610 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19611 ["Next Field" org-cycle (org-at-table-p)]
19612 ["Previous Field" org-shifttab (org-at-table-p)]
19613 ["Next Row" org-return (org-at-table-p)]
19614 "--"
19615 ["Blank Field" org-table-blank-field (org-at-table-p)]
19616 ["Edit Field" org-table-edit-field (org-at-table-p)]
19617 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19618 "--"
19619 ("Column"
19620 ["Move Column Left" org-metaleft (org-at-table-p)]
19621 ["Move Column Right" org-metaright (org-at-table-p)]
19622 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19623 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19624 ("Row"
19625 ["Move Row Up" org-metaup (org-at-table-p)]
19626 ["Move Row Down" org-metadown (org-at-table-p)]
19627 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19628 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19629 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19630 "--"
19631 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19632 ("Rectangle"
19633 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19634 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19635 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19636 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19637 "--"
19638 ("Calculate"
19639 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19640 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19641 ["Edit Formulas" org-edit-special (org-at-table-p)]
19642 "--"
19643 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19644 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19645 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19646 "--"
19647 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19648 "--"
19649 ["Sum Column/Rectangle" org-table-sum
19650 (or (org-at-table-p) (org-region-active-p))]
19651 ["Which Column?" org-table-current-column (org-at-table-p)])
19652 ["Debug Formulas"
19653 org-table-toggle-formula-debugger
19654 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19655 ["Show Col/Row Numbers"
19656 org-table-toggle-coordinate-overlays
19657 :style toggle
19658 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19659 "--"
19660 ["Create" org-table-create (and (not (org-at-table-p))
19661 org-enable-table-editor)]
19662 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19663 ["Import from File" org-table-import (not (org-at-table-p))]
19664 ["Export to File" org-table-export (org-at-table-p)]
19665 "--"
19666 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19668 (easy-menu-define org-org-menu org-mode-map "Org menu"
19669 '("Org"
19670 ("Show/Hide"
19671 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19672 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19673 ["Sparse Tree..." org-sparse-tree t]
19674 ["Reveal Context" org-reveal t]
19675 ["Show All" show-all t]
19676 "--"
19677 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19678 "--"
19679 ["New Heading" org-insert-heading t]
19680 ("Navigate Headings"
19681 ["Up" outline-up-heading t]
19682 ["Next" outline-next-visible-heading t]
19683 ["Previous" outline-previous-visible-heading t]
19684 ["Next Same Level" outline-forward-same-level t]
19685 ["Previous Same Level" outline-backward-same-level t]
19686 "--"
19687 ["Jump" org-goto t])
19688 ("Edit Structure"
19689 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19690 "--"
19691 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19692 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19693 "--"
19694 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19695 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19696 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19697 "--"
19698 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19699 "--"
19700 ["Copy visible text" org-copy-visible t]
19701 "--"
19702 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19703 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19704 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19705 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19706 "--"
19707 ["Sort Region/Children" org-sort t]
19708 "--"
19709 ["Convert to odd levels" org-convert-to-odd-levels t]
19710 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19711 ("Editing"
19712 ["Emphasis..." org-emphasize t]
19713 ["Edit Source Example" org-edit-special t]
19714 "--"
19715 ["Footnote new/jump" org-footnote-action t]
19716 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19717 ("Archive"
19718 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19719 "--"
19720 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19721 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19722 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19724 "--"
19725 ("Hyperlinks"
19726 ["Store Link (Global)" org-store-link t]
19727 ["Find existing link to here" org-occur-link-in-agenda-files t]
19728 ["Insert Link" org-insert-link t]
19729 ["Follow Link" org-open-at-point t]
19730 "--"
19731 ["Next link" org-next-link t]
19732 ["Previous link" org-previous-link t]
19733 "--"
19734 ["Descriptive Links"
19735 org-toggle-link-display
19736 :style radio
19737 :selected org-descriptive-links
19739 ["Literal Links"
19740 org-toggle-link-display
19741 :style radio
19742 :selected (not org-descriptive-links)])
19743 "--"
19744 ("TODO Lists"
19745 ["TODO/DONE/-" org-todo t]
19746 ("Select keyword"
19747 ["Next keyword" org-shiftright (org-at-heading-p)]
19748 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19749 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19750 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19751 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19752 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19753 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19754 "--"
19755 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19756 :selected org-enforce-todo-dependencies :style toggle :active t]
19757 "Settings for tree at point"
19758 ["Do Children sequentially" org-toggle-ordered-property :style radio
19759 :selected (org-entry-get nil "ORDERED")
19760 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19761 ["Do Children parallel" org-toggle-ordered-property :style radio
19762 :selected (not (org-entry-get nil "ORDERED"))
19763 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19764 "--"
19765 ["Set Priority" org-priority t]
19766 ["Priority Up" org-shiftup t]
19767 ["Priority Down" org-shiftdown t]
19768 "--"
19769 ["Get news from all feeds" org-feed-update-all t]
19770 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19771 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19772 ("TAGS and Properties"
19773 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19774 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19775 "--"
19776 ["Set property" org-set-property (not (org-before-first-heading-p))]
19777 ["Column view of properties" org-columns t]
19778 ["Insert Column View DBlock" org-insert-columns-dblock t])
19779 ("Dates and Scheduling"
19780 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19781 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19782 ("Change Date"
19783 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19784 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19785 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19786 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19787 ["Compute Time Range" org-evaluate-time-range t]
19788 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19789 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19790 "--"
19791 ["Custom time format" org-toggle-time-stamp-overlays
19792 :style radio :selected org-display-custom-times]
19793 "--"
19794 ["Goto Calendar" org-goto-calendar t]
19795 ["Date from Calendar" org-date-from-calendar t]
19796 "--"
19797 ["Start/Restart Timer" org-timer-start t]
19798 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19799 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19800 ["Insert Timer String" org-timer t]
19801 ["Insert Timer Item" org-timer-item t])
19802 ("Logging work"
19803 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19804 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19805 ["Clock out" org-clock-out t]
19806 ["Clock cancel" org-clock-cancel t]
19807 "--"
19808 ["Mark as default task" org-clock-mark-default-task t]
19809 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19810 ["Goto running clock" org-clock-goto t]
19811 "--"
19812 ["Display times" org-clock-display t]
19813 ["Create clock table" org-clock-report t]
19814 "--"
19815 ["Record DONE time"
19816 (progn (setq org-log-done (not org-log-done))
19817 (message "Switching to %s will %s record a timestamp"
19818 (car org-done-keywords)
19819 (if org-log-done "automatically" "not")))
19820 :style toggle :selected org-log-done])
19821 "--"
19822 ["Agenda Command..." org-agenda t]
19823 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19824 ("File List for Agenda")
19825 ("Special views current file"
19826 ["TODO Tree" org-show-todo-tree t]
19827 ["Check Deadlines" org-check-deadlines t]
19828 ["Timeline" org-timeline t]
19829 ["Tags/Property tree" org-match-sparse-tree t])
19830 "--"
19831 ["Export/Publish..." org-export t]
19832 ("LaTeX"
19833 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19834 :selected org-cdlatex-mode]
19835 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19836 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19837 ["Modify math symbol" org-cdlatex-math-modify
19838 (org-inside-LaTeX-fragment-p)]
19839 ["Insert citation" org-reftex-citation t]
19840 "--"
19841 ["Template for BEAMER" (progn (require 'org-beamer)
19842 (org-insert-beamer-options-template)) t])
19843 "--"
19844 ("MobileOrg"
19845 ["Push Files and Views" org-mobile-push t]
19846 ["Get Captured and Flagged" org-mobile-pull t]
19847 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19848 "--"
19849 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19850 "--"
19851 ("Documentation"
19852 ["Show Version" org-version t]
19853 ["Info Documentation" org-info t])
19854 ("Customize"
19855 ["Browse Org Group" org-customize t]
19856 "--"
19857 ["Expand This Menu" org-create-customize-menu
19858 (fboundp 'customize-menu-create)])
19859 ["Send bug report" org-submit-bug-report t]
19860 "--"
19861 ("Refresh/Reload"
19862 ["Refresh setup current buffer" org-mode-restart t]
19863 ["Reload Org (after update)" org-reload t]
19864 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
19867 (defun org-info (&optional node)
19868 "Read documentation for Org-mode in the info system.
19869 With optional NODE, go directly to that node."
19870 (interactive)
19871 (info (format "(org)%s" (or node ""))))
19873 ;;;###autoload
19874 (defun org-submit-bug-report ()
19875 "Submit a bug report on Org-mode via mail.
19877 Don't hesitate to report any problems or inaccurate documentation.
19879 If you don't have setup sending mail from (X)Emacs, please copy the
19880 output buffer into your mail program, as it gives us important
19881 information about your Org-mode version and configuration."
19882 (interactive)
19883 (require 'reporter)
19884 (org-load-modules-maybe)
19885 (org-require-autoloaded-modules)
19886 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19887 (reporter-submit-bug-report
19888 "emacs-orgmode@gnu.org"
19889 (org-version nil 'full)
19890 (let (list)
19891 (save-window-excursion
19892 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19893 (delete-other-windows)
19894 (erase-buffer)
19895 (insert "You are about to submit a bug report to the Org-mode mailing list.
19897 We would like to add your full Org-mode and Outline configuration to the
19898 bug report. This greatly simplifies the work of the maintainer and
19899 other experts on the mailing list.
19901 HOWEVER, some variables you have customized may contain private
19902 information. The names of customers, colleagues, or friends, might
19903 appear in the form of file names, tags, todo states, or search strings.
19904 If you answer yes to the prompt, you might want to check and remove
19905 such private information before sending the email.")
19906 (add-text-properties (point-min) (point-max) '(face org-warning))
19907 (when (yes-or-no-p "Include your Org-mode configuration ")
19908 (mapatoms
19909 (lambda (v)
19910 (and (boundp v)
19911 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19912 (or (and (symbol-value v)
19913 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19914 (and
19915 (get v 'custom-type) (get v 'standard-value)
19916 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19917 (push v list)))))
19918 (kill-buffer (get-buffer "*Warn about privacy*"))
19919 list))
19920 nil nil
19921 "Remember to cover the basics, that is, what you expected to happen and
19922 what in fact did happen. You don't know how to make a good report? See
19924 http://orgmode.org/manual/Feedback.html#Feedback
19926 Your bug report will be posted to the Org-mode mailing list.
19927 ------------------------------------------------------------------------")
19928 (save-excursion
19929 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19930 (replace-match "\\1Bug: \\3 [\\2]")))))
19933 (defun org-install-agenda-files-menu ()
19934 (let ((bl (buffer-list)))
19935 (save-excursion
19936 (while bl
19937 (set-buffer (pop bl))
19938 (if (derived-mode-p 'org-mode) (setq bl nil)))
19939 (when (derived-mode-p 'org-mode)
19940 (easy-menu-change
19941 '("Org") "File List for Agenda"
19942 (append
19943 (list
19944 ["Edit File List" (org-edit-agenda-file-list) t]
19945 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19946 ["Remove Current File from List" org-remove-file t]
19947 ["Cycle through agenda files" org-cycle-agenda-files t]
19948 ["Occur in all agenda files" org-occur-in-agenda-files t]
19949 "--")
19950 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19952 ;;;; Documentation
19954 (defun org-require-autoloaded-modules ()
19955 (interactive)
19956 (mapc 'require
19957 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19958 org-docbook org-exp org-html org-icalendar
19959 org-id org-latex
19960 org-publish org-remember org-table
19961 org-timer org-xoxo)))
19963 ;;;###autoload
19964 (defun org-reload (&optional uncompiled)
19965 "Reload all org lisp files.
19966 With prefix arg UNCOMPILED, load the uncompiled versions."
19967 (interactive "P")
19968 (require 'find-func)
19969 (let* ((file-re "^org\\(-.*\\)?\\.el")
19970 (dir-org (file-name-directory (org-find-library-dir "org")))
19971 (dir-org-contrib (ignore-errors
19972 (file-name-directory
19973 (org-find-library-dir "org-contribdir"))))
19974 (babel-files
19975 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19976 (append (list nil "comint" "eval" "exp" "keys"
19977 "lob" "ref" "table" "tangle")
19978 (delq nil
19979 (mapcar
19980 (lambda (lang)
19981 (when (cdr lang) (symbol-name (car lang))))
19982 org-babel-load-languages)))))
19983 (files
19984 (append babel-files
19985 (and dir-org-contrib
19986 (directory-files dir-org-contrib t file-re))
19987 (directory-files dir-org t file-re)))
19988 (remove-re (concat (if (featurep 'xemacs)
19989 "org-colview" "org-colview-xemacs")
19990 "\\'")))
19991 (setq files (mapcar 'file-name-sans-extension files))
19992 (setq files (mapcar
19993 (lambda (x) (if (string-match remove-re x) nil x))
19994 files))
19995 (setq files (delq nil files))
19996 (mapc
19997 (lambda (f)
19998 (when (featurep (intern (file-name-nondirectory f)))
19999 (if (and (not uncompiled)
20000 (file-exists-p (concat f ".elc")))
20001 (load (concat f ".elc") nil nil 'nosuffix)
20002 (load (concat f ".el") nil nil 'nosuffix))))
20003 files)
20004 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20005 (org-version nil 'full 'message))
20007 ;;;###autoload
20008 (defun org-customize ()
20009 "Call the customize function with org as argument."
20010 (interactive)
20011 (org-load-modules-maybe)
20012 (org-require-autoloaded-modules)
20013 (customize-browse 'org))
20015 (defun org-create-customize-menu ()
20016 "Create a full customization menu for Org-mode, insert it into the menu."
20017 (interactive)
20018 (org-load-modules-maybe)
20019 (org-require-autoloaded-modules)
20020 (if (fboundp 'customize-menu-create)
20021 (progn
20022 (easy-menu-change
20023 '("Org") "Customize"
20024 `(["Browse Org group" org-customize t]
20025 "--"
20026 ,(customize-menu-create 'org)
20027 ["Set" Custom-set t]
20028 ["Save" Custom-save t]
20029 ["Reset to Current" Custom-reset-current t]
20030 ["Reset to Saved" Custom-reset-saved t]
20031 ["Reset to Standard Settings" Custom-reset-standard t]))
20032 (message "\"Org\"-menu now contains full customization menu"))
20033 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20035 ;;;; Miscellaneous stuff
20037 ;;; Generally useful functions
20039 (defun org-get-at-bol (property)
20040 "Get text property PROPERTY at beginning of line."
20041 (get-text-property (point-at-bol) property))
20043 (defun org-find-text-property-in-string (prop s)
20044 "Return the first non-nil value of property PROP in string S."
20045 (or (get-text-property 0 prop s)
20046 (get-text-property (or (next-single-property-change 0 prop s) 0)
20047 prop s)))
20049 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20050 "Display the given MESSAGE as a warning."
20051 (if (fboundp 'display-warning)
20052 (display-warning 'org message
20053 (if (featurep 'xemacs) 'warning :warning))
20054 (let ((buf (get-buffer-create "*Org warnings*")))
20055 (with-current-buffer buf
20056 (goto-char (point-max))
20057 (insert "Warning (Org): " message)
20058 (unless (bolp)
20059 (newline)))
20060 (display-buffer buf)
20061 (sit-for 0))))
20063 (defun org-eval (form)
20064 "Eval FORM and return result."
20065 (condition-case error
20066 (eval form)
20067 (error (format "%%![Error: %s]" error))))
20069 (defun org-in-clocktable-p ()
20070 "Check if the cursor is in a clocktable."
20071 (let ((pos (point)) start)
20072 (save-excursion
20073 (end-of-line 1)
20074 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20075 (setq start (match-beginning 0))
20076 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20077 (>= (match-end 0) pos)
20078 start))))
20080 (defun org-in-commented-line ()
20081 "Is point in a line starting with `#'?"
20082 (equal (char-after (point-at-bol)) ?#))
20084 (defun org-in-indented-comment-line ()
20085 "Is point in a line starting with `#' after some white space?"
20086 (save-excursion
20087 (save-match-data
20088 (goto-char (point-at-bol))
20089 (looking-at "[ \t]*#"))))
20091 (defun org-in-verbatim-emphasis ()
20092 (save-match-data
20093 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20095 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20096 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20097 (if (and marker (marker-buffer marker)
20098 (buffer-live-p (marker-buffer marker)))
20099 (progn
20100 (org-pop-to-buffer-same-window (marker-buffer marker))
20101 (if (or (> marker (point-max)) (< marker (point-min)))
20102 (widen))
20103 (goto-char marker)
20104 (org-show-context 'org-goto))
20105 (if bookmark
20106 (bookmark-jump bookmark)
20107 (error "Cannot find location"))))
20109 (defun org-quote-csv-field (s)
20110 "Quote field for inclusion in CSV material."
20111 (if (string-match "[\",]" s)
20112 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20115 (defun org-force-self-insert (N)
20116 "Needed to enforce self-insert under remapping."
20117 (interactive "p")
20118 (self-insert-command N))
20120 (defun org-string-width (s)
20121 "Compute width of string, ignoring invisible characters.
20122 This ignores character with invisibility property `org-link', and also
20123 characters with property `org-cwidth', because these will become invisible
20124 upon the next fontification round."
20125 (let (b l)
20126 (when (or (eq t buffer-invisibility-spec)
20127 (assq 'org-link buffer-invisibility-spec))
20128 (while (setq b (text-property-any 0 (length s)
20129 'invisible 'org-link s))
20130 (setq s (concat (substring s 0 b)
20131 (substring s (or (next-single-property-change
20132 b 'invisible s) (length s)))))))
20133 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20134 (setq s (concat (substring s 0 b)
20135 (substring s (or (next-single-property-change
20136 b 'org-cwidth s) (length s))))))
20137 (setq l (string-width s) b -1)
20138 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20139 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20142 (defun org-shorten-string (s maxlength)
20143 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20144 If the string is shorter or has length MAXLENGTH, just return the
20145 original string. If it is longer, the functions finds a space in the
20146 string, breaks this string off at that locations and adds three dots
20147 as ellipsis. Including the ellipsis, the string will not be longer
20148 than MAXLENGTH. If finding a good breaking point in the string does
20149 not work, the string is just chopped off in the middle of a word
20150 if necessary."
20151 (if (<= (length s) maxlength)
20153 (let* ((n (max (- maxlength 4) 1))
20154 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20155 (if (string-match re s)
20156 (concat (match-string 1 s) "...")
20157 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20159 (defun org-get-indentation (&optional line)
20160 "Get the indentation of the current line, interpreting tabs.
20161 When LINE is given, assume it represents a line and compute its indentation."
20162 (if line
20163 (if (string-match "^ *" (org-remove-tabs line))
20164 (match-end 0))
20165 (save-excursion
20166 (beginning-of-line 1)
20167 (skip-chars-forward " \t")
20168 (current-column))))
20170 (defun org-get-string-indentation (s)
20171 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20172 (let ((n -1) (i 0) (w tab-width) c)
20173 (catch 'exit
20174 (while (< (setq n (1+ n)) (length s))
20175 (setq c (aref s n))
20176 (cond ((= c ?\ ) (setq i (1+ i)))
20177 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20178 (t (throw 'exit t)))))
20181 (defun org-remove-tabs (s &optional width)
20182 "Replace tabulators in S with spaces.
20183 Assumes that s is a single line, starting in column 0."
20184 (setq width (or width tab-width))
20185 (while (string-match "\t" s)
20186 (setq s (replace-match
20187 (make-string
20188 (- (* width (/ (+ (match-beginning 0) width) width))
20189 (match-beginning 0)) ?\ )
20190 t t s)))
20193 (defun org-fix-indentation (line ind)
20194 "Fix indentation in LINE.
20195 IND is a cons cell with target and minimum indentation.
20196 If the current indentation in LINE is smaller than the minimum,
20197 leave it alone. If it is larger than ind, set it to the target."
20198 (let* ((l (org-remove-tabs line))
20199 (i (org-get-indentation l))
20200 (i1 (car ind)) (i2 (cdr ind)))
20201 (if (>= i i2) (setq l (substring line i2)))
20202 (if (> i1 0)
20203 (concat (make-string i1 ?\ ) l)
20204 l)))
20206 (defun org-remove-indentation (code &optional n)
20207 "Remove the maximum common indentation from the lines in CODE.
20208 N may optionally be the number of spaces to remove."
20209 (with-temp-buffer
20210 (insert code)
20211 (org-do-remove-indentation n)
20212 (buffer-string)))
20214 (defun org-do-remove-indentation (&optional n)
20215 "Remove the maximum common indentation from the buffer."
20216 (untabify (point-min) (point-max))
20217 (let ((min 10000) re)
20218 (if n
20219 (setq min n)
20220 (goto-char (point-min))
20221 (while (re-search-forward "^ *[^ \n]" nil t)
20222 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20223 (unless (or (= min 0) (= min 10000))
20224 (setq re (format "^ \\{%d\\}" min))
20225 (goto-char (point-min))
20226 (while (re-search-forward re nil t)
20227 (replace-match "")
20228 (end-of-line 1))
20229 min)))
20231 (defun org-fill-template (template alist)
20232 "Find each %key of ALIST in TEMPLATE and replace it."
20233 (let ((case-fold-search nil)
20234 entry key value)
20235 (setq alist (sort (copy-sequence alist)
20236 (lambda (a b) (< (length (car a)) (length (car b))))))
20237 (while (setq entry (pop alist))
20238 (setq template
20239 (replace-regexp-in-string
20240 (concat "%" (regexp-quote (car entry)))
20241 (or (cdr entry) "") template t t)))
20242 template))
20244 (defun org-base-buffer (buffer)
20245 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20246 (if (not buffer)
20247 buffer
20248 (or (buffer-base-buffer buffer)
20249 buffer)))
20251 (defun org-trim (s)
20252 "Remove whitespace at beginning and end of string."
20253 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20254 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20257 (defun org-wrap (string &optional width lines)
20258 "Wrap string to either a number of lines, or a width in characters.
20259 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20260 that costs. If there is a word longer than WIDTH, the text is actually
20261 wrapped to the length of that word.
20262 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20263 many lines, whatever width that takes.
20264 The return value is a list of lines, without newlines at the end."
20265 (let* ((words (org-split-string string "[ \t\n]+"))
20266 (maxword (apply 'max (mapcar 'org-string-width words)))
20267 w ll)
20268 (cond (width
20269 (org-do-wrap words (max maxword width)))
20270 (lines
20271 (setq w maxword)
20272 (setq ll (org-do-wrap words maxword))
20273 (if (<= (length ll) lines)
20275 (setq ll words)
20276 (while (> (length ll) lines)
20277 (setq w (1+ w))
20278 (setq ll (org-do-wrap words w)))
20279 ll))
20280 (t (error "Cannot wrap this")))))
20282 (defun org-do-wrap (words width)
20283 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20284 (let (lines line)
20285 (while words
20286 (setq line (pop words))
20287 (while (and words (< (+ (length line) (length (car words))) width))
20288 (setq line (concat line " " (pop words))))
20289 (setq lines (push line lines)))
20290 (nreverse lines)))
20292 (defun org-split-string (string &optional separators)
20293 "Splits STRING into substrings at SEPARATORS.
20294 No empty strings are returned if there are matches at the beginning
20295 and end of string."
20296 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20297 (start 0)
20298 notfirst
20299 (list nil))
20300 (while (and (string-match rexp string
20301 (if (and notfirst
20302 (= start (match-beginning 0))
20303 (< start (length string)))
20304 (1+ start) start))
20305 (< (match-beginning 0) (length string)))
20306 (setq notfirst t)
20307 (or (eq (match-beginning 0) 0)
20308 (and (eq (match-beginning 0) (match-end 0))
20309 (eq (match-beginning 0) start))
20310 (setq list
20311 (cons (substring string start (match-beginning 0))
20312 list)))
20313 (setq start (match-end 0)))
20314 (or (eq start (length string))
20315 (setq list
20316 (cons (substring string start)
20317 list)))
20318 (nreverse list)))
20320 (defun org-quote-vert (s)
20321 "Replace \"|\" with \"\\vert\"."
20322 (while (string-match "|" s)
20323 (setq s (replace-match "\\vert" t t s)))
20326 (defun org-uuidgen-p (s)
20327 "Is S an ID created by UUIDGEN?"
20328 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20330 (defun org-in-src-block-p (&optional inside)
20331 "Whether point is in a code source block.
20332 When INSIDE is non-nil, don't consider we are within a src block
20333 when point is at #+BEGIN_SRC or #+END_SRC."
20334 (let ((case-fold-search t) ov)
20335 (or (and (setq ov (overlays-at (point)))
20336 (memq 'org-block-background
20337 (overlay-properties (car ov))))
20338 (and (not inside)
20339 (save-match-data
20340 (save-excursion
20341 (beginning-of-line)
20342 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20344 (defun org-context ()
20345 "Return a list of contexts of the current cursor position.
20346 If several contexts apply, all are returned.
20347 Each context entry is a list with a symbol naming the context, and
20348 two positions indicating start and end of the context. Possible
20349 contexts are:
20351 :headline anywhere in a headline
20352 :headline-stars on the leading stars in a headline
20353 :todo-keyword on a TODO keyword (including DONE) in a headline
20354 :tags on the TAGS in a headline
20355 :priority on the priority cookie in a headline
20356 :item on the first line of a plain list item
20357 :item-bullet on the bullet/number of a plain list item
20358 :checkbox on the checkbox in a plain list item
20359 :table in an org-mode table
20360 :table-special on a special filed in a table
20361 :table-table in a table.el table
20362 :clocktable in a clocktable
20363 :src-block in a source block
20364 :link on a hyperlink
20365 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20366 :target on a <<target>>
20367 :radio-target on a <<<radio-target>>>
20368 :latex-fragment on a LaTeX fragment
20369 :latex-preview on a LaTeX fragment with overlaid preview image
20371 This function expects the position to be visible because it uses font-lock
20372 faces as a help to recognize the following contexts: :table-special, :link,
20373 and :keyword."
20374 (let* ((f (get-text-property (point) 'face))
20375 (faces (if (listp f) f (list f)))
20376 (case-fold-search t)
20377 (p (point)) clist o)
20378 ;; First the large context
20379 (cond
20380 ((org-at-heading-p t)
20381 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20382 (when (progn
20383 (beginning-of-line 1)
20384 (looking-at org-todo-line-tags-regexp))
20385 (push (org-point-in-group p 1 :headline-stars) clist)
20386 (push (org-point-in-group p 2 :todo-keyword) clist)
20387 (push (org-point-in-group p 4 :tags) clist))
20388 (goto-char p)
20389 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20390 (if (looking-at "\\[#[A-Z0-9]\\]")
20391 (push (org-point-in-group p 0 :priority) clist)))
20393 ((org-at-item-p)
20394 (push (org-point-in-group p 2 :item-bullet) clist)
20395 (push (list :item (point-at-bol)
20396 (save-excursion (org-end-of-item) (point)))
20397 clist)
20398 (and (org-at-item-checkbox-p)
20399 (push (org-point-in-group p 0 :checkbox) clist)))
20401 ((org-at-table-p)
20402 (push (list :table (org-table-begin) (org-table-end)) clist)
20403 (if (memq 'org-formula faces)
20404 (push (list :table-special
20405 (previous-single-property-change p 'face)
20406 (next-single-property-change p 'face)) clist)))
20407 ((org-at-table-p 'any)
20408 (push (list :table-table) clist)))
20409 (goto-char p)
20411 (let ((case-fold-search t))
20412 ;; New the "medium" contexts: clocktables, source blocks
20413 (cond ((org-in-clocktable-p)
20414 (push (list :clocktable
20415 (and (or (looking-at "#\\+BEGIN: clocktable")
20416 (search-backward "#+BEGIN: clocktable" nil t))
20417 (match-beginning 0))
20418 (and (re-search-forward "#\\+END:?" nil t)
20419 (match-end 0))) clist))
20420 ((org-in-src-block-p)
20421 (push (list :src-block
20422 (and (or (looking-at "#\\+BEGIN_SRC")
20423 (search-backward "#+BEGIN_SRC" nil t))
20424 (match-beginning 0))
20425 (and (search-forward "#+END_SRC" nil t)
20426 (match-beginning 0))) clist))))
20427 (goto-char p)
20429 ;; Now the small context
20430 (cond
20431 ((org-at-timestamp-p)
20432 (push (org-point-in-group p 0 :timestamp) clist))
20433 ((memq 'org-link faces)
20434 (push (list :link
20435 (previous-single-property-change p 'face)
20436 (next-single-property-change p 'face)) clist))
20437 ((memq 'org-special-keyword faces)
20438 (push (list :keyword
20439 (previous-single-property-change p 'face)
20440 (next-single-property-change p 'face)) clist))
20441 ((org-at-target-p)
20442 (push (org-point-in-group p 0 :target) clist)
20443 (goto-char (1- (match-beginning 0)))
20444 (if (looking-at org-radio-target-regexp)
20445 (push (org-point-in-group p 0 :radio-target) clist))
20446 (goto-char p))
20447 ((setq o (car (delq nil
20448 (mapcar
20449 (lambda (x)
20450 (if (memq x org-latex-fragment-image-overlays) x))
20451 (overlays-at (point))))))
20452 (push (list :latex-fragment
20453 (overlay-start o) (overlay-end o)) clist)
20454 (push (list :latex-preview
20455 (overlay-start o) (overlay-end o)) clist))
20456 ((org-inside-LaTeX-fragment-p)
20457 ;; FIXME: positions wrong.
20458 (push (list :latex-fragment (point) (point)) clist)))
20460 (setq clist (nreverse (delq nil clist)))
20461 clist))
20463 ;; FIXME: Compare with at-regexp-p Do we need both?
20464 (defun org-in-regexp (re &optional nlines visually)
20465 "Check if point is inside a match of regexp.
20466 Normally only the current line is checked, but you can include NLINES extra
20467 lines both before and after point into the search.
20468 If VISUALLY is set, require that the cursor is not after the match but
20469 really on, so that the block visually is on the match."
20470 (catch 'exit
20471 (let ((pos (point))
20472 (eol (point-at-eol (+ 1 (or nlines 0))))
20473 (inc (if visually 1 0)))
20474 (save-excursion
20475 (beginning-of-line (- 1 (or nlines 0)))
20476 (while (re-search-forward re eol t)
20477 (if (and (<= (match-beginning 0) pos)
20478 (>= (+ inc (match-end 0)) pos))
20479 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20481 (defun org-at-regexp-p (regexp)
20482 "Is point inside a match of REGEXP in the current line?"
20483 (catch 'exit
20484 (save-excursion
20485 (let ((pos (point)) (end (point-at-eol)))
20486 (beginning-of-line 1)
20487 (while (re-search-forward regexp end t)
20488 (if (and (<= (match-beginning 0) pos)
20489 (>= (match-end 0) pos))
20490 (throw 'exit t)))
20491 nil))))
20493 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20494 "Non-nil when point is between matches of START-RE and END-RE.
20496 Also return a non-nil value when point is on one of the matches.
20498 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20499 buffer positions. Default values are the positions of headlines
20500 surrounding the point.
20502 The functions returns a cons cell whose car (resp. cdr) is the
20503 position before START-RE (resp. after END-RE)."
20504 (save-match-data
20505 (let ((pos (point))
20506 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20507 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20508 beg end)
20509 (save-excursion
20510 ;; Point is on a block when on START-RE or if START-RE can be
20511 ;; found before it...
20512 (and (or (org-at-regexp-p start-re)
20513 (re-search-backward start-re limit-up t))
20514 (setq beg (match-beginning 0))
20515 ;; ... and END-RE after it...
20516 (goto-char (match-end 0))
20517 (re-search-forward end-re limit-down t)
20518 (> (setq end (match-end 0)) pos)
20519 ;; ... without another START-RE in-between.
20520 (goto-char (match-beginning 0))
20521 (not (re-search-backward start-re (1+ beg) t))
20522 ;; Return value.
20523 (cons beg end))))))
20525 (defun org-in-block-p (names)
20526 "Non-nil when point belongs to a block whose name belongs to NAMES.
20528 NAMES is a list of strings containing names of blocks.
20530 Return first block name matched, or nil. Beware that in case of
20531 nested blocks, the returned name may not belong to the closest
20532 block from point."
20533 (save-match-data
20534 (catch 'exit
20535 (let ((case-fold-search t)
20536 (lim-up (save-excursion (outline-previous-heading)))
20537 (lim-down (save-excursion (outline-next-heading))))
20538 (mapc (lambda (name)
20539 (let ((n (regexp-quote name)))
20540 (when (org-between-regexps-p
20541 (concat "^[ \t]*#\\+begin_" n)
20542 (concat "^[ \t]*#\\+end_" n)
20543 lim-up lim-down)
20544 (throw 'exit n))))
20545 names))
20546 nil)))
20548 (defun org-occur-in-agenda-files (regexp &optional nlines)
20549 "Call `multi-occur' with buffers for all agenda files."
20550 (interactive "sOrg-files matching: \np")
20551 (let* ((files (org-agenda-files))
20552 (tnames (mapcar 'file-truename files))
20553 (extra org-agenda-text-search-extra-files)
20555 (when (eq (car extra) 'agenda-archives)
20556 (setq extra (cdr extra))
20557 (setq files (org-add-archive-files files)))
20558 (while (setq f (pop extra))
20559 (unless (member (file-truename f) tnames)
20560 (add-to-list 'files f 'append)
20561 (add-to-list 'tnames (file-truename f) 'append)))
20562 (multi-occur
20563 (mapcar (lambda (x)
20564 (with-current-buffer
20565 (or (get-file-buffer x) (find-file-noselect x))
20566 (widen)
20567 (current-buffer)))
20568 files)
20569 regexp)))
20571 (if (boundp 'occur-mode-find-occurrence-hook)
20572 ;; Emacs 23
20573 (add-hook 'occur-mode-find-occurrence-hook
20574 (lambda ()
20575 (when (derived-mode-p 'org-mode)
20576 (org-reveal))))
20577 ;; Emacs 22
20578 (defadvice occur-mode-goto-occurrence
20579 (after org-occur-reveal activate)
20580 (and (derived-mode-p 'org-mode) (org-reveal)))
20581 (defadvice occur-mode-goto-occurrence-other-window
20582 (after org-occur-reveal activate)
20583 (and (derived-mode-p 'org-mode) (org-reveal)))
20584 (defadvice occur-mode-display-occurrence
20585 (after org-occur-reveal activate)
20586 (when (derived-mode-p 'org-mode)
20587 (let ((pos (occur-mode-find-occurrence)))
20588 (with-current-buffer (marker-buffer pos)
20589 (save-excursion
20590 (goto-char pos)
20591 (org-reveal)))))))
20593 (defun org-occur-link-in-agenda-files ()
20594 "Create a link and search for it in the agendas.
20595 The link is not stored in `org-stored-links', it is just created
20596 for the search purpose."
20597 (interactive)
20598 (let ((link (condition-case nil
20599 (org-store-link nil)
20600 (error "Unable to create a link to here"))))
20601 (org-occur-in-agenda-files (regexp-quote link))))
20603 (defun org-uniquify (list)
20604 "Remove duplicate elements from LIST."
20605 (let (res)
20606 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20607 res))
20609 (defun org-delete-all (elts list)
20610 "Remove all elements in ELTS from LIST."
20611 (while elts
20612 (setq list (delete (pop elts) list)))
20613 list)
20615 (defun org-count (cl-item cl-seq)
20616 "Count the number of occurrences of ITEM in SEQ.
20617 Taken from `count' in cl-seq.el with all keyword arguments removed."
20618 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20619 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20620 (while (< cl-start cl-end)
20621 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20622 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20623 (setq cl-start (1+ cl-start)))
20624 cl-count))
20626 (defun org-remove-if (predicate seq)
20627 "Remove everything from SEQ that fulfills PREDICATE."
20628 (let (res e)
20629 (while seq
20630 (setq e (pop seq))
20631 (if (not (funcall predicate e)) (push e res)))
20632 (nreverse res)))
20634 (defun org-remove-if-not (predicate seq)
20635 "Remove everything from SEQ that does not fulfill PREDICATE."
20636 (let (res e)
20637 (while seq
20638 (setq e (pop seq))
20639 (if (funcall predicate e) (push e res)))
20640 (nreverse res)))
20642 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20643 "Reduce two-argument FUNCTION across SEQ.
20644 Taken from `reduce' in cl-seq.el with all keyword arguments but
20645 \":initial-value\" removed."
20646 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20647 (cadr (memq :initial-value cl-keys)))
20648 (cl-seq (pop cl-seq))
20649 (t (funcall cl-func)))))
20650 (while cl-seq
20651 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20652 cl-accum))
20654 (defun org-back-over-empty-lines ()
20655 "Move backwards over whitespace, to the beginning of the first empty line.
20656 Returns the number of empty lines passed."
20657 (let ((pos (point)))
20658 (if (cdr (assoc 'heading org-blank-before-new-entry))
20659 (skip-chars-backward " \t\n\r")
20660 (unless (eobp)
20661 (forward-line -1)))
20662 (beginning-of-line 2)
20663 (goto-char (min (point) pos))
20664 (count-lines (point) pos)))
20666 (defun org-skip-whitespace ()
20667 (skip-chars-forward " \t\n\r"))
20669 (defun org-point-in-group (point group &optional context)
20670 "Check if POINT is in match-group GROUP.
20671 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20672 match. If the match group does not exist or point is not inside it,
20673 return nil."
20674 (and (match-beginning group)
20675 (>= point (match-beginning group))
20676 (<= point (match-end group))
20677 (if context
20678 (list context (match-beginning group) (match-end group))
20679 t)))
20681 (defun org-switch-to-buffer-other-window (&rest args)
20682 "Switch to buffer in a second window on the current frame.
20683 In particular, do not allow pop-up frames.
20684 Returns the newly created buffer."
20685 (org-no-popups
20686 (apply 'switch-to-buffer-other-window args)))
20688 (defun org-combine-plists (&rest plists)
20689 "Create a single property list from all plists in PLISTS.
20690 The process starts by copying the first list, and then setting properties
20691 from the other lists. Settings in the last list are the most significant
20692 ones and overrule settings in the other lists."
20693 (let ((rtn (copy-sequence (pop plists)))
20694 p v ls)
20695 (while plists
20696 (setq ls (pop plists))
20697 (while ls
20698 (setq p (pop ls) v (pop ls))
20699 (setq rtn (plist-put rtn p v))))
20700 rtn))
20702 (defun org-replace-escapes (string table)
20703 "Replace %-escapes in STRING with values in TABLE.
20704 TABLE is an association list with keys like \"%a\" and string values.
20705 The sequences in STRING may contain normal field width and padding information,
20706 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20707 so values can contain further %-escapes if they are define later in TABLE."
20708 (let ((tbl (copy-alist table))
20709 (case-fold-search nil)
20710 (pchg 0)
20711 e re rpl)
20712 (while (setq e (pop tbl))
20713 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20714 (when (and (cdr e) (string-match re (cdr e)))
20715 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20716 (safe "SREF"))
20717 (add-text-properties 0 3 (list 'sref sref) safe)
20718 (setcdr e (replace-match safe t t (cdr e)))))
20719 (while (string-match re string)
20720 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20721 (cdr e)))
20722 (setq string (replace-match rpl t t string))))
20723 (while (setq pchg (next-property-change pchg string))
20724 (let ((sref (get-text-property pchg 'sref string)))
20725 (when (and sref (string-match "SREF" string pchg))
20726 (setq string (replace-match sref t t string)))))
20727 string))
20729 (defun org-sublist (list start end)
20730 "Return a section of LIST, from START to END.
20731 Counting starts at 1."
20732 (let (rtn (c start))
20733 (setq list (nthcdr (1- start) list))
20734 (while (and list (<= c end))
20735 (push (pop list) rtn)
20736 (setq c (1+ c)))
20737 (nreverse rtn)))
20739 (defun org-find-base-buffer-visiting (file)
20740 "Like `find-buffer-visiting' but always return the base buffer and
20741 not an indirect buffer."
20742 (let ((buf (or (get-file-buffer file)
20743 (find-buffer-visiting file))))
20744 (if buf
20745 (or (buffer-base-buffer buf) buf)
20746 nil)))
20748 (defun org-image-file-name-regexp (&optional extensions)
20749 "Return regexp matching the file names of images.
20750 If EXTENSIONS is given, only match these."
20751 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20752 (image-file-name-regexp)
20753 (let ((image-file-name-extensions
20754 (or extensions
20755 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20756 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20757 (concat "\\."
20758 (regexp-opt (nconc (mapcar 'upcase
20759 image-file-name-extensions)
20760 image-file-name-extensions)
20762 "\\'"))))
20764 (defun org-file-image-p (file &optional extensions)
20765 "Return non-nil if FILE is an image."
20766 (save-match-data
20767 (string-match (org-image-file-name-regexp extensions) file)))
20769 (defun org-get-cursor-date ()
20770 "Return the date at cursor in as a time.
20771 This works in the calendar and in the agenda, anywhere else it just
20772 returns the current time."
20773 (let (date day defd)
20774 (cond
20775 ((eq major-mode 'calendar-mode)
20776 (setq date (calendar-cursor-to-date)
20777 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20778 ((eq major-mode 'org-agenda-mode)
20779 (setq day (get-text-property (point) 'day))
20780 (if day
20781 (setq date (calendar-gregorian-from-absolute day)
20782 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20783 (nth 2 date))))))
20784 (or defd (current-time))))
20786 (defun org-mark-subtree (&optional up)
20787 "Mark the current subtree.
20788 This puts point at the start of the current subtree, and mark at
20789 the end. If a numeric prefix UP is given, move up into the
20790 hierarchy of headlines by UP levels before marking the subtree."
20791 (interactive "P")
20792 (org-with-limited-levels
20793 (cond ((org-at-heading-p) (beginning-of-line))
20794 ((org-before-first-heading-p) (error "Not in a subtree"))
20795 (t (outline-previous-visible-heading 1))))
20796 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20797 (if (org-called-interactively-p 'any)
20798 (call-interactively 'org-mark-element)
20799 (org-mark-element)))
20801 ;;; Indentation
20803 (defun org-indent-line ()
20804 "Indent line depending on context."
20805 (interactive)
20806 (let* ((pos (point))
20807 (itemp (org-at-item-p))
20808 (case-fold-search t)
20809 (org-drawer-regexp (or org-drawer-regexp "\000"))
20810 (inline-task-p (and (featurep 'org-inlinetask)
20811 (org-inlinetask-in-task-p)))
20812 (inline-re (and inline-task-p
20813 (org-inlinetask-outline-regexp)))
20814 column)
20815 (if (and orgstruct-is-++ (eq pos (point)))
20816 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20817 (indent-according-to-mode))
20818 (beginning-of-line 1)
20819 (cond
20820 ;; Headings
20821 ((looking-at org-outline-regexp) (setq column 0))
20822 ;; Included files
20823 ((looking-at "#\\+include:") (setq column 0))
20824 ;; Footnote definition
20825 ((looking-at org-footnote-definition-re) (setq column 0))
20826 ;; Literal examples
20827 ((looking-at "[ \t]*:\\( \\|$\\)")
20828 (setq column (org-get-indentation))) ; do nothing
20829 ;; Lists
20830 ((ignore-errors (goto-char (org-in-item-p)))
20831 (setq column (if itemp
20832 (org-get-indentation)
20833 (org-list-item-body-column (point))))
20834 (goto-char pos))
20835 ;; Drawers
20836 ((and (looking-at "[ \t]*:END:")
20837 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20838 (save-excursion
20839 (goto-char (1- (match-beginning 1)))
20840 (setq column (current-column))))
20841 ;; Special blocks
20842 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20843 (save-excursion
20844 (re-search-backward
20845 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20846 (setq column (org-get-indentation (match-string 0))))
20847 ((and (not (looking-at "[ \t]*#\\+begin_"))
20848 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20849 (save-excursion
20850 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20851 (setq column
20852 (cond ((equal (downcase (match-string 1)) "src")
20853 ;; src blocks: let `org-edit-src-exit' handle them
20854 (org-get-indentation))
20855 ((equal (downcase (match-string 1)) "example")
20856 (max (org-get-indentation)
20857 (org-get-indentation (match-string 0))))
20859 (org-get-indentation (match-string 0))))))
20860 ;; This line has nothing special, look at the previous relevant
20861 ;; line to compute indentation
20863 (beginning-of-line 0)
20864 (while (and (not (bobp))
20865 (not (looking-at org-table-line-regexp))
20866 (not (looking-at org-drawer-regexp))
20867 ;; When point started in an inline task, do not move
20868 ;; above task starting line.
20869 (not (and inline-task-p (looking-at inline-re)))
20870 ;; Skip drawers, blocks, empty lines, verbatim,
20871 ;; comments, tables, footnotes definitions, lists,
20872 ;; inline tasks.
20873 (or (and (looking-at "[ \t]*:END:")
20874 (re-search-backward org-drawer-regexp nil t))
20875 (and (looking-at "[ \t]*#\\+end_")
20876 (re-search-backward "[ \t]*#\\+begin_"nil t))
20877 (looking-at "[ \t]*[\n:#|]")
20878 (looking-at org-footnote-definition-re)
20879 (and (ignore-errors (goto-char (org-in-item-p)))
20880 (goto-char
20881 (org-list-get-top-point (org-list-struct))))
20882 (and (not inline-task-p)
20883 (featurep 'org-inlinetask)
20884 (org-inlinetask-in-task-p)
20885 (or (org-inlinetask-goto-beginning) t))))
20886 (beginning-of-line 0))
20887 (cond
20888 ;; There was an heading above.
20889 ((looking-at "\\*+[ \t]+")
20890 (if (not org-adapt-indentation)
20891 (setq column 0)
20892 (goto-char (match-end 0))
20893 (setq column (current-column))))
20894 ;; A drawer had started and is unfinished
20895 ((looking-at org-drawer-regexp)
20896 (goto-char (1- (match-beginning 1)))
20897 (setq column (current-column)))
20898 ;; Else, nothing noticeable found: get indentation and go on.
20899 (t (setq column (org-get-indentation))))))
20900 ;; Now apply indentation and move cursor accordingly
20901 (goto-char pos)
20902 (if (<= (current-column) (current-indentation))
20903 (org-indent-line-to column)
20904 (save-excursion (org-indent-line-to column)))
20905 ;; Special polishing for properties, see `org-property-format'
20906 (setq column (current-column))
20907 (beginning-of-line 1)
20908 (if (looking-at
20909 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20910 (replace-match (concat (match-string 1)
20911 (format org-property-format
20912 (match-string 2) (match-string 3)))
20913 t t))
20914 (org-move-to-column column))))
20916 (defun org-indent-drawer ()
20917 "Indent the drawer at point."
20918 (interactive)
20919 (let ((p (point))
20920 (e (and (save-excursion (re-search-forward ":END:" nil t))
20921 (match-end 0)))
20922 (folded
20923 (save-excursion
20924 (end-of-line)
20925 (when (overlays-at (point))
20926 (member 'invisible (overlay-properties
20927 (car (overlays-at (point)))))))))
20928 (when folded (org-cycle))
20929 (indent-for-tab-command)
20930 (while (and (move-beginning-of-line 2) (< (point) e))
20931 (indent-for-tab-command))
20932 (goto-char p)
20933 (when folded (org-cycle)))
20934 (message "Drawer at point indented"))
20936 (defun org-indent-block ()
20937 "Indent the block at point."
20938 (interactive)
20939 (let ((p (point))
20940 (case-fold-search t)
20941 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20942 (match-end 0)))
20943 (folded
20944 (save-excursion
20945 (end-of-line)
20946 (when (overlays-at (point))
20947 (member 'invisible (overlay-properties
20948 (car (overlays-at (point)))))))))
20949 (when folded (org-cycle))
20950 (indent-for-tab-command)
20951 (while (and (move-beginning-of-line 2) (< (point) e))
20952 (indent-for-tab-command))
20953 (goto-char p)
20954 (when folded (org-cycle)))
20955 (message "Block at point indented"))
20957 (defun org-indent-region (start end)
20958 "Indent region."
20959 (interactive "r")
20960 (save-excursion
20961 (let ((line-end (org-current-line end)))
20962 (goto-char start)
20963 (while (< (org-current-line) line-end)
20964 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20965 (t (call-interactively 'org-indent-line)))
20966 (move-beginning-of-line 2)))))
20969 ;;; Filling
20971 ;; We use our own fill-paragraph and auto-fill functions.
20973 ;; `org-fill-paragraph' relies on adaptive filling and context
20974 ;; checking. Appropriate `fill-prefix' is computed with
20975 ;; `org-adaptive-fill-function'.
20977 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20978 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20979 ;; `org-adaptive-fill-function' value. Internally,
20980 ;; `org-comment-line-break-function' breaks the line.
20982 ;; `org-setup-filling' installs filling and auto-filling related
20983 ;; variables during `org-mode' initialization.
20985 (defun org-setup-filling ()
20986 (interactive)
20987 ;; Prevent auto-fill from inserting unwanted new items.
20988 (when (boundp 'fill-nobreak-predicate)
20989 (org-set-local
20990 'fill-nobreak-predicate
20991 (org-uniquify
20992 (append fill-nobreak-predicate
20993 '(org-fill-paragraph-separate-nobreak-p
20994 org-fill-line-break-nobreak-p
20995 org-fill-paragraph-with-timestamp-nobreak-p)))))
20996 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20997 (org-set-local 'auto-fill-inhibit-regexp nil)
20998 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20999 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21000 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21002 (defvar org-element-paragraph-separate) ; org-element.el
21003 (defun org-fill-paragraph-separate-nobreak-p ()
21004 "Non-nil when a line break at point would insert a new item."
21005 (looking-at (substring org-element-paragraph-separate 1)))
21007 (defun org-fill-line-break-nobreak-p ()
21008 "Non-nil when a line break at point would create an Org line break."
21009 (save-excursion
21010 (skip-chars-backward "[ \t]")
21011 (skip-chars-backward "\\\\")
21012 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21014 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21015 "Non-nil when a line break at point would insert a new item."
21016 (and (org-at-timestamp-p t)
21017 (not (looking-at org-ts-regexp-both))))
21019 (declare-function message-in-body-p "message" ())
21020 (defvar org-element--affiliated-re) ; From org-element.el
21021 (defvar orgtbl-line-start-regexp) ; From org-table.el
21022 (defun org-adaptive-fill-function ()
21023 "Compute a fill prefix for the current line.
21024 Return fill prefix, as a string, or nil if current line isn't
21025 meant to be filled."
21026 (let (prefix)
21027 (catch 'exit
21028 (when (derived-mode-p 'message-mode)
21029 (save-excursion
21030 (beginning-of-line)
21031 (cond ((or (not (message-in-body-p))
21032 (looking-at orgtbl-line-start-regexp))
21033 (throw 'exit nil))
21034 ((looking-at message-cite-prefix-regexp)
21035 (throw 'exit (match-string-no-properties 0)))
21036 ((looking-at org-outline-regexp)
21037 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21038 (org-with-wide-buffer
21039 (let* ((p (line-beginning-position))
21040 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21041 (type (org-element-type element))
21042 (post-affiliated
21043 (save-excursion
21044 (goto-char (org-element-property :begin element))
21045 (while (looking-at org-element--affiliated-re) (forward-line))
21046 (point))))
21047 (unless (< p post-affiliated)
21048 (case type
21049 (comment (looking-at "[ \t]*# ?") (match-string 0))
21050 (footnote-definition "")
21051 ((item plain-list)
21052 (make-string (org-list-item-body-column post-affiliated) ? ))
21053 (paragraph
21054 ;; Fill prefix is usually the same as the current line,
21055 ;; except if the paragraph is at the beginning of an item.
21056 (let ((parent (org-element-property :parent element)))
21057 (cond ((eq (org-element-type parent) 'item)
21058 (make-string (org-list-item-body-column
21059 (org-element-property :begin parent))
21060 ? ))
21061 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21062 (match-string 0))
21063 (t ""))))
21064 (comment-block
21065 ;; Only fill contents if P is within block boundaries.
21066 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21067 (forward-line)
21068 (point)))
21069 (cend (save-excursion
21070 (goto-char (org-element-property :end element))
21071 (skip-chars-backward " \r\t\n")
21072 (line-beginning-position))))
21073 (when (and (>= p cbeg) (< p cend))
21074 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21075 (match-string 0)
21076 "")))))))))))
21078 (declare-function message-goto-body "message" ())
21079 (defvar message-cite-prefix-regexp) ; From message.el
21080 (defvar org-element-all-objects) ; From org-element.el
21081 (defun org-fill-paragraph (&optional justify)
21082 "Fill element at point, when applicable.
21084 This function only applies to comment blocks, comments, example
21085 blocks and paragraphs. Also, as a special case, re-align table
21086 when point is at one.
21088 If JUSTIFY is non-nil (interactively, with prefix argument),
21089 justify as well. If `sentence-end-double-space' is non-nil, then
21090 period followed by one space does not end a sentence, so don't
21091 break a line there. The variable `fill-column' controls the
21092 width for filling.
21094 For convenience, when point is at a plain list, an item or
21095 a footnote definition, try to fill the first paragraph within."
21096 (interactive)
21097 (if (and (derived-mode-p 'message-mode)
21098 (or (not (message-in-body-p))
21099 (save-excursion (move-beginning-of-line 1)
21100 (looking-at message-cite-prefix-regexp))))
21101 ;; First ensure filling is correct in message-mode.
21102 (let ((fill-paragraph-function
21103 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21104 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21105 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21106 (paragraph-separate
21107 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21108 (fill-paragraph nil))
21109 (save-excursion
21110 ;; Move to end of line in order to get the first paragraph
21111 ;; within a plain list or a footnote definition.
21112 (end-of-line)
21113 (let ((element (org-element-at-point)))
21114 ;; First check if point is in a blank line at the beginning of
21115 ;; the buffer. In that case, ignore filling.
21116 (if (< (point) (org-element-property :begin element)) t
21117 (case (org-element-type element)
21118 ;; Use major mode filling function is src blocks.
21119 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21120 ;; Align Org tables, leave table.el tables as-is.
21121 (table-row (org-table-align) t)
21122 (table
21123 (when (eq (org-element-property :type element) 'org)
21124 (org-table-align))
21126 (paragraph
21127 ;; Paragraphs may contain `line-break' type objects.
21128 (let ((beg (max (point-min)
21129 (org-element-property :contents-begin element)))
21130 (end (min (point-max)
21131 (org-element-property :contents-end element))))
21132 ;; Do nothing if point is at an affiliated keyword.
21133 (if (< (point) beg) t
21134 (when (derived-mode-p 'message-mode)
21135 ;; In `message-mode', do not fill following
21136 ;; citation in current paragraph nor text before
21137 ;; message body.
21138 (let ((body-start (save-excursion (message-goto-body))))
21139 (when body-start (setq beg (max body-start beg))))
21140 (when (save-excursion
21141 (re-search-forward
21142 (concat "^" message-cite-prefix-regexp) end t))
21143 (setq end (match-beginning 0))))
21144 ;; Fill paragraph, taking line breaks into
21145 ;; consideration. For that, slice the paragraph
21146 ;; using line breaks as separators, and fill the
21147 ;; parts in reverse order to avoid messing with
21148 ;; markers.
21149 (save-excursion
21150 (goto-char end)
21151 (mapc
21152 (lambda (pos)
21153 (fill-region-as-paragraph pos (point) justify)
21154 (goto-char pos))
21155 ;; Find the list of ending positions for line
21156 ;; breaks in the current paragraph. Add paragraph
21157 ;; beginning to include first slice.
21158 (nreverse
21159 (cons
21161 (org-element-map
21162 (org-element--parse-objects
21163 beg end nil org-element-all-objects)
21164 'line-break
21165 (lambda (lb) (org-element-property :end lb)))))))
21166 t)))
21167 ;; Contents of `comment-block' type elements should be
21168 ;; filled as plain text, but only if point is within block
21169 ;; markers.
21170 (comment-block
21171 (let* ((case-fold-search t)
21172 (beg (save-excursion
21173 (goto-char (org-element-property :begin element))
21174 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21175 (forward-line)
21176 (point)))
21177 (end (save-excursion
21178 (goto-char (org-element-property :end element))
21179 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21180 (line-beginning-position))))
21181 (when (and (>= (point) beg) (< (point) end))
21182 (fill-region-as-paragraph
21183 (save-excursion
21184 (end-of-line)
21185 (re-search-backward "^[ \t]*$" beg 'move)
21186 (line-beginning-position))
21187 (save-excursion
21188 (beginning-of-line)
21189 (re-search-forward "^[ \t]*$" end 'move)
21190 (line-beginning-position))
21191 justify)))
21193 ;; Fill comments.
21194 (comment (fill-comment-paragraph justify))
21195 ;; Ignore every other element.
21196 (otherwise t)))))))
21198 (defun org-auto-fill-function ()
21199 "Auto-fill function."
21200 ;; Check if auto-filling is meaningful.
21201 (let ((fc (current-fill-column)))
21202 (when (and fc (> (current-column) fc))
21203 (let* ((fill-prefix (org-adaptive-fill-function))
21204 ;; Enforce empty fill prefix, if required. Otherwise, it
21205 ;; will be computed again.
21206 (adaptive-fill-mode (not (equal fill-prefix ""))))
21207 (when fill-prefix (do-auto-fill))))))
21209 (defun org-comment-line-break-function (&optional soft)
21210 "Break line at point and indent, continuing comment if within one.
21211 The inserted newline is marked hard if variable
21212 `use-hard-newlines' is true, unless optional argument SOFT is
21213 non-nil."
21214 (if soft (insert-and-inherit ?\n) (newline 1))
21215 (save-excursion (forward-char -1) (delete-horizontal-space))
21216 (delete-horizontal-space)
21217 (indent-to-left-margin)
21218 (insert-before-markers-and-inherit fill-prefix))
21221 ;;; Comments
21223 ;; Org comments syntax is quite complex. It requires the entire line
21224 ;; to be just a comment. Also, even with the right syntax at the
21225 ;; beginning of line, some some elements (i.e. verse-block or
21226 ;; example-block) don't accept comments. Usual Emacs comment commands
21227 ;; cannot cope with those requirements. Therefore, Org replaces them.
21229 ;; Org still relies on `comment-dwim', but cannot trust
21230 ;; `comment-only-p'. So, `comment-region-function' and
21231 ;; `uncomment-region-function' both point
21232 ;; to`org-comment-or-uncomment-region'. Eventually,
21233 ;; `org-insert-comment' takes care of insertion of comments at the
21234 ;; beginning of line.
21236 ;; `org-setup-comments-handling' install comments related variables
21237 ;; during `org-mode' initialization.
21239 (defun org-setup-comments-handling ()
21240 (interactive)
21241 (org-set-local 'comment-use-syntax nil)
21242 (org-set-local 'comment-start "# ")
21243 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21244 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21245 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21246 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21248 (defun org-insert-comment ()
21249 "Insert an empty comment above current line.
21250 If the line is empty, insert comment at its beginning."
21251 (beginning-of-line)
21252 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21253 (org-indent-line)
21254 (insert "# "))
21256 (defvar comment-empty-lines) ; From newcomment.el.
21257 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21258 "Comment or uncomment each non-blank line in the region.
21259 Uncomment each non-blank line between BEG and END if it only
21260 contains commented lines. Otherwise, comment them."
21261 (save-restriction
21262 ;; Restrict region
21263 (narrow-to-region (save-excursion (goto-char beg)
21264 (skip-chars-forward " \r\t\n" end)
21265 (line-beginning-position))
21266 (save-excursion (goto-char end)
21267 (skip-chars-backward " \r\t\n" beg)
21268 (line-end-position)))
21269 (let ((uncommentp
21270 ;; UNCOMMENTP is non-nil when every non blank line between
21271 ;; BEG and END is a comment.
21272 (save-excursion
21273 (goto-char (point-min))
21274 (while (and (not (eobp))
21275 (let ((element (org-element-at-point)))
21276 (and (eq (org-element-type element) 'comment)
21277 (goto-char (min (point-max)
21278 (org-element-property
21279 :end element)))))))
21280 (eobp))))
21281 (if uncommentp
21282 ;; Only blank lines and comments in region: uncomment it.
21283 (save-excursion
21284 (goto-char (point-min))
21285 (while (not (eobp))
21286 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21287 (replace-match "" nil nil nil 1))
21288 (forward-line)))
21289 ;; Comment each line in region.
21290 (let ((min-indent (point-max)))
21291 ;; First find the minimum indentation across all lines.
21292 (save-excursion
21293 (goto-char (point-min))
21294 (while (and (not (eobp)) (not (zerop min-indent)))
21295 (unless (looking-at "[ \t]*$")
21296 (setq min-indent (min min-indent (current-indentation))))
21297 (forward-line)))
21298 ;; Then loop over all lines.
21299 (save-excursion
21300 (goto-char (point-min))
21301 (while (not (eobp))
21302 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21303 (org-move-to-column min-indent t)
21304 (insert comment-start))
21305 (forward-line))))))))
21308 ;;; Other stuff.
21310 (defun org-toggle-fixed-width-section (arg)
21311 "Toggle the fixed-width export.
21312 If there is no active region, the QUOTE keyword at the current headline is
21313 inserted or removed. When present, it causes the text between this headline
21314 and the next to be exported as fixed-width text, and unmodified.
21315 If there is an active region, this command adds or removes a colon as the
21316 first character of this line. If the first character of a line is a colon,
21317 this line is also exported in fixed-width font."
21318 (interactive "P")
21319 (let* ((cc 0)
21320 (regionp (org-region-active-p))
21321 (beg (if regionp (region-beginning) (point)))
21322 (end (if regionp (region-end)))
21323 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21324 (case-fold-search nil)
21325 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21326 off)
21327 (if regionp
21328 (save-excursion
21329 (goto-char beg)
21330 (setq cc (current-column))
21331 (beginning-of-line 1)
21332 (setq off (looking-at re))
21333 (while (> nlines 0)
21334 (setq nlines (1- nlines))
21335 (beginning-of-line 1)
21336 (cond
21337 (arg
21338 (org-move-to-column cc t)
21339 (insert ": \n")
21340 (forward-line -1))
21341 ((and off (looking-at re))
21342 (replace-match "" t t nil 1))
21343 ((not off) (org-move-to-column cc t) (insert ": ")))
21344 (forward-line 1)))
21345 (save-excursion
21346 (org-back-to-heading)
21347 (cond
21348 ((looking-at (format org-heading-keyword-regexp-format
21349 org-quote-string))
21350 (goto-char (match-end 1))
21351 (looking-at (concat " +" org-quote-string))
21352 (replace-match "" t t)
21353 (when (eolp) (insert " ")))
21354 ((looking-at org-outline-regexp)
21355 (goto-char (match-end 0))
21356 (insert org-quote-string " ")))))))
21358 (defun org-reftex-citation ()
21359 "Use reftex-citation to insert a citation into the buffer.
21360 This looks for a line like
21362 #+BIBLIOGRAPHY: foo plain option:-d
21364 and derives from it that foo.bib is the bibliography file relevant
21365 for this document. It then installs the necessary environment for RefTeX
21366 to work in this buffer and calls `reftex-citation' to insert a citation
21367 into the buffer.
21369 Export of such citations to both LaTeX and HTML is handled by the contributed
21370 package org-exp-bibtex by Taru Karttunen."
21371 (interactive)
21372 (let ((reftex-docstruct-symbol 'rds)
21373 (reftex-cite-format "\\cite{%l}")
21374 rds bib)
21375 (save-excursion
21376 (save-restriction
21377 (widen)
21378 (let ((case-fold-search t)
21379 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21380 (if (not (save-excursion
21381 (or (re-search-forward re nil t)
21382 (re-search-backward re nil t))))
21383 (error "No bibliography defined in file")
21384 (setq bib (concat (match-string 1) ".bib")
21385 rds (list (list 'bib bib)))))))
21386 (call-interactively 'reftex-citation)))
21388 ;;;; Functions extending outline functionality
21390 (defun org-beginning-of-line (&optional arg)
21391 "Go to the beginning of the current line. If that is invisible, continue
21392 to a visible line beginning. This makes the function of C-a more intuitive.
21393 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21394 first attempt, and only move to after the tags when the cursor is already
21395 beyond the end of the headline."
21396 (interactive "P")
21397 (let ((pos (point))
21398 (special (if (consp org-special-ctrl-a/e)
21399 (car org-special-ctrl-a/e)
21400 org-special-ctrl-a/e))
21401 refpos)
21402 (if (org-bound-and-true-p visual-line-mode)
21403 (beginning-of-visual-line 1)
21404 (beginning-of-line 1))
21405 (if (and arg (fboundp 'move-beginning-of-line))
21406 (call-interactively 'move-beginning-of-line)
21407 (if (bobp)
21409 (backward-char 1)
21410 (if (org-truely-invisible-p)
21411 (while (and (not (bobp)) (org-truely-invisible-p))
21412 (backward-char 1)
21413 (beginning-of-line 1))
21414 (forward-char 1))))
21415 (when special
21416 (cond
21417 ((and (looking-at org-complex-heading-regexp)
21418 (= (char-after (match-end 1)) ?\ ))
21419 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21420 (point-at-eol)))
21421 (goto-char
21422 (if (eq special t)
21423 (cond ((> pos refpos) refpos)
21424 ((= pos (point)) refpos)
21425 (t (point)))
21426 (cond ((> pos (point)) (point))
21427 ((not (eq last-command this-command)) (point))
21428 (t refpos)))))
21429 ((org-at-item-p)
21430 ;; Being at an item and not looking at an the item means point
21431 ;; was previously moved to beginning of a visual line, which
21432 ;; doesn't contain the item. Therefore, do nothing special,
21433 ;; just stay here.
21434 (when (looking-at org-list-full-item-re)
21435 ;; Set special position at first white space character after
21436 ;; bullet, and check-box, if any.
21437 (let ((after-bullet
21438 (let ((box (match-end 3)))
21439 (if (not box) (match-end 1)
21440 (let ((after (char-after box)))
21441 (if (and after (= after ? )) (1+ box) box))))))
21442 ;; Special case: Move point to special position when
21443 ;; currently after it or at beginning of line.
21444 (if (eq special t)
21445 (when (or (> pos after-bullet) (= (point) pos))
21446 (goto-char after-bullet))
21447 ;; Reversed case: Move point to special position when
21448 ;; point was already at beginning of line and command is
21449 ;; repeated.
21450 (when (and (= (point) pos) (eq last-command this-command))
21451 (goto-char after-bullet))))))))
21452 (org-no-warnings
21453 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21455 (defun org-end-of-line (&optional arg)
21456 "Go to the end of the line.
21457 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21458 tags on the first attempt, and only move to after the tags when
21459 the cursor is already beyond the end of the headline."
21460 (interactive "P")
21461 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21462 org-special-ctrl-a/e))
21463 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21464 'end-of-visual-line)
21465 ((fboundp 'move-end-of-line) 'move-end-of-line)
21466 (t 'end-of-line))))
21467 (if (or (not special) arg) (call-interactively move-fun)
21468 (let* ((element (save-excursion (beginning-of-line)
21469 (org-element-at-point)))
21470 (type (org-element-type element)))
21471 (cond
21472 ((memq type '(headline inlinetask))
21473 (let ((pos (point)))
21474 (beginning-of-line 1)
21475 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21476 (if (eq special t)
21477 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21478 (goto-char (match-beginning 1))
21479 (goto-char (match-end 0)))
21480 (if (or (< pos (match-end 0))
21481 (not (eq this-command last-command)))
21482 (goto-char (match-end 0))
21483 (goto-char (match-beginning 1))))
21484 (call-interactively move-fun))))
21485 ((org-element-property :hiddenp element)
21486 ;; If element is hidden, `move-end-of-line' would put point
21487 ;; after it. Use `end-of-line' to stay on current line.
21488 (call-interactively 'end-of-line))
21489 (t (call-interactively move-fun)))))
21490 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21492 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21493 (define-key org-mode-map "\C-e" 'org-end-of-line)
21495 (defun org-backward-sentence (&optional arg)
21496 "Go to beginning of sentence, or beginning of table field.
21497 This will call `backward-sentence' or `org-table-beginning-of-field',
21498 depending on context."
21499 (interactive "P")
21500 (cond
21501 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21502 (t (call-interactively 'backward-sentence))))
21504 (defun org-forward-sentence (&optional arg)
21505 "Go to end of sentence, or end of table field.
21506 This will call `forward-sentence' or `org-table-end-of-field',
21507 depending on context."
21508 (interactive "P")
21509 (cond
21510 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21511 (t (call-interactively 'forward-sentence))))
21513 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21514 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21516 (defun org-kill-line (&optional arg)
21517 "Kill line, to tags or end of line."
21518 (interactive "P")
21519 (cond
21520 ((or (not org-special-ctrl-k)
21521 (bolp)
21522 (not (org-at-heading-p)))
21523 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21524 org-ctrl-k-protect-subtree)
21525 (if (or (eq org-ctrl-k-protect-subtree 'error)
21526 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21527 (error "C-k aborted - would kill hidden subtree")))
21528 (call-interactively
21529 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21530 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21531 (kill-region (point) (match-beginning 1))
21532 (org-set-tags nil t))
21533 (t (kill-region (point) (point-at-eol)))))
21535 (define-key org-mode-map "\C-k" 'org-kill-line)
21537 (defun org-yank (&optional arg)
21538 "Yank. If the kill is a subtree, treat it specially.
21539 This command will look at the current kill and check if is a single
21540 subtree, or a series of subtrees[1]. If it passes the test, and if the
21541 cursor is at the beginning of a line or after the stars of a currently
21542 empty headline, then the yank is handled specially. How exactly depends
21543 on the value of the following variables, both set by default.
21545 org-yank-folded-subtrees
21546 When set, the subtree(s) will be folded after insertion, but only
21547 if doing so would now swallow text after the yanked text.
21549 org-yank-adjusted-subtrees
21550 When set, the subtree will be promoted or demoted in order to
21551 fit into the local outline tree structure, which means that the level
21552 will be adjusted so that it becomes the smaller one of the two
21553 *visible* surrounding headings.
21555 Any prefix to this command will cause `yank' to be called directly with
21556 no special treatment. In particular, a simple \\[universal-argument] prefix \
21557 will just
21558 plainly yank the text as it is.
21560 \[1] The test checks if the first non-white line is a heading
21561 and if there are no other headings with fewer stars."
21562 (interactive "P")
21563 (org-yank-generic 'yank arg))
21565 (defun org-yank-generic (command arg)
21566 "Perform some yank-like command.
21568 This function implements the behavior described in the `org-yank'
21569 documentation. However, it has been generalized to work for any
21570 interactive command with similar behavior."
21572 ;; pretend to be command COMMAND
21573 (setq this-command command)
21575 (if arg
21576 (call-interactively command)
21578 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21579 (and (org-kill-is-subtree-p)
21580 (or (bolp)
21581 (and (looking-at "[ \t]*$")
21582 (string-match
21583 "\\`\\*+\\'"
21584 (buffer-substring (point-at-bol) (point)))))))
21585 swallowp)
21586 (cond
21587 ((and subtreep org-yank-folded-subtrees)
21588 (let ((beg (point))
21589 end)
21590 (if (and subtreep org-yank-adjusted-subtrees)
21591 (org-paste-subtree nil nil 'for-yank)
21592 (call-interactively command))
21594 (setq end (point))
21595 (goto-char beg)
21596 (when (and (bolp) subtreep
21597 (not (setq swallowp
21598 (org-yank-folding-would-swallow-text beg end))))
21599 (org-with-limited-levels
21600 (or (looking-at org-outline-regexp)
21601 (re-search-forward org-outline-regexp-bol end t))
21602 (while (and (< (point) end) (looking-at org-outline-regexp))
21603 (hide-subtree)
21604 (org-cycle-show-empty-lines 'folded)
21605 (condition-case nil
21606 (outline-forward-same-level 1)
21607 (error (goto-char end))))))
21608 (when swallowp
21609 (message
21610 "Inserted text not folded because that would swallow text"))
21612 (goto-char end)
21613 (skip-chars-forward " \t\n\r")
21614 (beginning-of-line 1)
21615 (push-mark beg 'nomsg)))
21616 ((and subtreep org-yank-adjusted-subtrees)
21617 (let ((beg (point-at-bol)))
21618 (org-paste-subtree nil nil 'for-yank)
21619 (push-mark beg 'nomsg)))
21621 (call-interactively command))))))
21623 (defun org-yank-folding-would-swallow-text (beg end)
21624 "Would hide-subtree at BEG swallow any text after END?"
21625 (let (level)
21626 (org-with-limited-levels
21627 (save-excursion
21628 (goto-char beg)
21629 (when (or (looking-at org-outline-regexp)
21630 (re-search-forward org-outline-regexp-bol end t))
21631 (setq level (org-outline-level)))
21632 (goto-char end)
21633 (skip-chars-forward " \t\r\n\v\f")
21634 (if (or (eobp)
21635 (and (bolp) (looking-at org-outline-regexp)
21636 (<= (org-outline-level) level)))
21637 nil ; Nothing would be swallowed
21638 t))))) ; something would swallow
21640 (define-key org-mode-map "\C-y" 'org-yank)
21642 (defun org-truely-invisible-p ()
21643 "Check if point is at a character currently not visible.
21644 This version does not only check the character property, but also
21645 `visible-mode'."
21646 ;; Early versions of noutline don't have `outline-invisible-p'.
21647 (if (org-bound-and-true-p visible-mode)
21649 (outline-invisible-p)))
21651 (defun org-invisible-p2 ()
21652 "Check if point is at a character currently not visible."
21653 (save-excursion
21654 (if (and (eolp) (not (bobp))) (backward-char 1))
21655 ;; Early versions of noutline don't have `outline-invisible-p'.
21656 (outline-invisible-p)))
21658 (defun org-back-to-heading (&optional invisible-ok)
21659 "Call `outline-back-to-heading', but provide a better error message."
21660 (condition-case nil
21661 (outline-back-to-heading invisible-ok)
21662 (error (error "Before first headline at position %d in buffer %s"
21663 (point) (current-buffer)))))
21665 (defun org-before-first-heading-p ()
21666 "Before first heading?"
21667 (save-excursion
21668 (end-of-line)
21669 (null (re-search-backward org-outline-regexp-bol nil t))))
21671 (defun org-at-heading-p (&optional ignored)
21672 (outline-on-heading-p t))
21673 ;; Compatibility alias with Org versions < 7.8.03
21674 (defalias 'org-on-heading-p 'org-at-heading-p)
21676 (defun org-at-comment-p nil
21677 "Is cursor in a line starting with a # character?"
21678 (save-excursion
21679 (beginning-of-line)
21680 (looking-at "^#")))
21682 (defun org-at-drawer-p nil
21683 "Is cursor at a drawer keyword?"
21684 (save-excursion
21685 (move-beginning-of-line 1)
21686 (looking-at org-drawer-regexp)))
21688 (defun org-at-block-p nil
21689 "Is cursor at a block keyword?"
21690 (save-excursion
21691 (move-beginning-of-line 1)
21692 (looking-at org-block-regexp)))
21694 (defun org-point-at-end-of-empty-headline ()
21695 "If point is at the end of an empty headline, return t, else nil.
21696 If the heading only contains a TODO keyword, it is still still considered
21697 empty."
21698 (and (looking-at "[ \t]*$")
21699 (when org-todo-line-regexp
21700 (save-excursion
21701 (beginning-of-line 1)
21702 (let ((case-fold-search nil))
21703 (looking-at org-todo-line-regexp)
21704 (string= (match-string 3) ""))))))
21706 (defun org-at-heading-or-item-p ()
21707 (or (org-at-heading-p) (org-at-item-p)))
21709 (defun org-at-target-p ()
21710 (or (org-in-regexp org-radio-target-regexp)
21711 (org-in-regexp org-target-regexp)))
21712 ;; Compatibility alias with Org versions < 7.8.03
21713 (defalias 'org-on-target-p 'org-at-target-p)
21715 (defun org-up-heading-all (arg)
21716 "Move to the heading line of which the present line is a subheading.
21717 This function considers both visible and invisible heading lines.
21718 With argument, move up ARG levels."
21719 (if (fboundp 'outline-up-heading-all)
21720 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21721 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21723 (defun org-up-heading-safe ()
21724 "Move to the heading line of which the present line is a subheading.
21725 This version will not throw an error. It will return the level of the
21726 headline found, or nil if no higher level is found.
21728 Also, this function will be a lot faster than `outline-up-heading',
21729 because it relies on stars being the outline starters. This can really
21730 make a significant difference in outlines with very many siblings."
21731 (let (start-level re)
21732 (org-back-to-heading t)
21733 (setq start-level (funcall outline-level))
21734 (if (equal start-level 1)
21736 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21737 (if (re-search-backward re nil t)
21738 (funcall outline-level)))))
21740 (defun org-first-sibling-p ()
21741 "Is this heading the first child of its parents?"
21742 (interactive)
21743 (let ((re org-outline-regexp-bol)
21744 level l)
21745 (unless (org-at-heading-p t)
21746 (error "Not at a heading"))
21747 (setq level (funcall outline-level))
21748 (save-excursion
21749 (if (not (re-search-backward re nil t))
21751 (setq l (funcall outline-level))
21752 (< l level)))))
21754 (defun org-goto-sibling (&optional previous)
21755 "Goto the next sibling, even if it is invisible.
21756 When PREVIOUS is set, go to the previous sibling instead. Returns t
21757 when a sibling was found. When none is found, return nil and don't
21758 move point."
21759 (let ((fun (if previous 're-search-backward 're-search-forward))
21760 (pos (point))
21761 (re org-outline-regexp-bol)
21762 level l)
21763 (when (condition-case nil (org-back-to-heading t) (error nil))
21764 (setq level (funcall outline-level))
21765 (catch 'exit
21766 (or previous (forward-char 1))
21767 (while (funcall fun re nil t)
21768 (setq l (funcall outline-level))
21769 (when (< l level) (goto-char pos) (throw 'exit nil))
21770 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21771 (goto-char pos)
21772 nil))))
21774 (defun org-show-siblings ()
21775 "Show all siblings of the current headline."
21776 (save-excursion
21777 (while (org-goto-sibling) (org-flag-heading nil)))
21778 (save-excursion
21779 (while (org-goto-sibling 'previous)
21780 (org-flag-heading nil))))
21782 (defun org-goto-first-child ()
21783 "Goto the first child, even if it is invisible.
21784 Return t when a child was found. Otherwise don't move point and
21785 return nil."
21786 (let (level (pos (point)) (re org-outline-regexp-bol))
21787 (when (condition-case nil (org-back-to-heading t) (error nil))
21788 (setq level (outline-level))
21789 (forward-char 1)
21790 (if (and (re-search-forward re nil t) (> (outline-level) level))
21791 (progn (goto-char (match-beginning 0)) t)
21792 (goto-char pos) nil))))
21794 (defun org-show-hidden-entry ()
21795 "Show an entry where even the heading is hidden."
21796 (save-excursion
21797 (org-show-entry)))
21799 (defun org-flag-heading (flag &optional entry)
21800 "Flag the current heading. FLAG non-nil means make invisible.
21801 When ENTRY is non-nil, show the entire entry."
21802 (save-excursion
21803 (org-back-to-heading t)
21804 ;; Check if we should show the entire entry
21805 (if entry
21806 (progn
21807 (org-show-entry)
21808 (save-excursion
21809 (and (outline-next-heading)
21810 (org-flag-heading nil))))
21811 (outline-flag-region (max (point-min) (1- (point)))
21812 (save-excursion (outline-end-of-heading) (point))
21813 flag))))
21815 (defun org-get-next-sibling ()
21816 "Move to next heading of the same level, and return point.
21817 If there is no such heading, return nil.
21818 This is like outline-next-sibling, but invisible headings are ok."
21819 (let ((level (funcall outline-level)))
21820 (outline-next-heading)
21821 (while (and (not (eobp)) (> (funcall outline-level) level))
21822 (outline-next-heading))
21823 (if (or (eobp) (< (funcall outline-level) level))
21825 (point))))
21827 (defun org-get-last-sibling ()
21828 "Move to previous heading of the same level, and return point.
21829 If there is no such heading, return nil."
21830 (let ((opoint (point))
21831 (level (funcall outline-level)))
21832 (outline-previous-heading)
21833 (when (and (/= (point) opoint) (outline-on-heading-p t))
21834 (while (and (> (funcall outline-level) level)
21835 (not (bobp)))
21836 (outline-previous-heading))
21837 (if (< (funcall outline-level) level)
21839 (point)))))
21841 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21842 "Goto to the end of a subtree."
21843 ;; This contains an exact copy of the original function, but it uses
21844 ;; `org-back-to-heading', to make it work also in invisible
21845 ;; trees. And is uses an invisible-ok argument.
21846 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21847 ;; Furthermore, when used inside Org, finding the end of a large subtree
21848 ;; with many children and grandchildren etc, this can be much faster
21849 ;; than the outline version.
21850 (org-back-to-heading invisible-ok)
21851 (let ((first t)
21852 (level (funcall outline-level)))
21853 (if (and (derived-mode-p 'org-mode) (< level 1000))
21854 ;; A true heading (not a plain list item), in Org-mode
21855 ;; This means we can easily find the end by looking
21856 ;; only for the right number of stars. Using a regexp to do
21857 ;; this is so much faster than using a Lisp loop.
21858 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21859 (forward-char 1)
21860 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21861 ;; something else, do it the slow way
21862 (while (and (not (eobp))
21863 (or first (> (funcall outline-level) level)))
21864 (setq first nil)
21865 (outline-next-heading)))
21866 (unless to-heading
21867 (if (memq (preceding-char) '(?\n ?\^M))
21868 (progn
21869 ;; Go to end of line before heading
21870 (forward-char -1)
21871 (if (memq (preceding-char) '(?\n ?\^M))
21872 ;; leave blank line before heading
21873 (forward-char -1))))))
21874 (point))
21876 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21877 "Use Org version in org-mode, for dramatic speed-up."
21878 (if (derived-mode-p 'org-mode)
21879 (progn
21880 (org-end-of-subtree nil t)
21881 (unless (eobp) (backward-char 1)))
21882 ad-do-it))
21884 (defun org-end-of-meta-data-and-drawers ()
21885 "Jump to the first text after meta data and drawers in the current entry.
21886 This will move over empty lines, lines with planning time stamps,
21887 clocking lines, and drawers."
21888 (org-back-to-heading t)
21889 (let ((end (save-excursion (outline-next-heading) (point)))
21890 (re (concat "\\(" org-drawer-regexp "\\)"
21891 "\\|" "[ \t]*" org-keyword-time-regexp)))
21892 (forward-line 1)
21893 (while (re-search-forward re end t)
21894 (if (not (match-end 1))
21895 ;; empty or planning line
21896 (forward-line 1)
21897 ;; a drawer, find the end
21898 (re-search-forward "^[ \t]*:END:" end 'move)
21899 (forward-line 1)))
21900 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21901 (point)))
21903 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21904 "Move forward to the arg'th subheading at same level as this one.
21905 Stop at the first and last subheadings of a superior heading.
21906 Normally this only looks at visible headings, but when INVISIBLE-OK is
21907 non-nil it will also look at invisible ones."
21908 (interactive "p")
21909 (org-back-to-heading invisible-ok)
21910 (org-at-heading-p)
21911 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21912 (re (format "^\\*\\{1,%d\\} " level))
21914 (forward-char 1)
21915 (while (> arg 0)
21916 (while (and (re-search-forward re nil 'move)
21917 (setq l (- (match-end 0) (match-beginning 0) 1))
21918 (= l level)
21919 (not invisible-ok)
21920 (progn (backward-char 1) (outline-invisible-p)))
21921 (if (< l level) (setq arg 1)))
21922 (setq arg (1- arg)))
21923 (beginning-of-line 1)))
21925 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21926 "Move backward to the arg'th subheading at same level as this one.
21927 Stop at the first and last subheadings of a superior heading."
21928 (interactive "p")
21929 (org-back-to-heading)
21930 (org-at-heading-p)
21931 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21932 (re (format "^\\*\\{1,%d\\} " level))
21934 (while (> arg 0)
21935 (while (and (re-search-backward re nil 'move)
21936 (setq l (- (match-end 0) (match-beginning 0) 1))
21937 (= l level)
21938 (not invisible-ok)
21939 (outline-invisible-p))
21940 (if (< l level) (setq arg 1)))
21941 (setq arg (1- arg)))))
21943 (defun org-forward-element ()
21944 "Move forward by one element.
21945 Move to the next element at the same level, when possible."
21946 (interactive)
21947 (cond ((eobp) (error "Cannot move further down"))
21948 ((org-with-limited-levels (org-at-heading-p))
21949 (let ((origin (point)))
21950 (org-forward-heading-same-level 1)
21951 (unless (org-with-limited-levels (org-at-heading-p))
21952 (goto-char origin)
21953 (error "Cannot move further down"))))
21955 (let* ((elem (org-element-at-point))
21956 (end (org-element-property :end elem))
21957 (parent (org-element-property :parent elem)))
21958 (if (and parent (= (org-element-property :contents-end parent) end))
21959 (goto-char (org-element-property :end parent))
21960 (goto-char end))))))
21962 (defun org-backward-element ()
21963 "Move backward by one element.
21964 Move to the previous element at the same level, when possible."
21965 (interactive)
21966 (cond ((bobp) (error "Cannot move further up"))
21967 ((org-with-limited-levels (org-at-heading-p))
21968 ;; At an headline, move to the previous one, if any, or stay
21969 ;; here.
21970 (let ((origin (point)))
21971 (org-backward-heading-same-level 1)
21972 (unless (org-with-limited-levels (org-at-heading-p))
21973 (goto-char origin)
21974 (error "Cannot move further up"))))
21976 (let* ((trail (org-element-at-point 'keep-trail))
21977 (elem (car trail))
21978 (prev-elem (nth 1 trail))
21979 (beg (org-element-property :begin elem)))
21980 (cond
21981 ;; Move to beginning of current element if point isn't
21982 ;; there already.
21983 ((/= (point) beg) (goto-char beg))
21984 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21985 ((org-before-first-heading-p) (goto-char (point-min)))
21986 (t (org-back-to-heading)))))))
21988 (defun org-up-element ()
21989 "Move to upper element."
21990 (interactive)
21991 (if (org-with-limited-levels (org-at-heading-p))
21992 (unless (org-up-heading-safe) (error "No surrounding element"))
21993 (let* ((elem (org-element-at-point))
21994 (parent (org-element-property :parent elem)))
21995 (if parent (goto-char (org-element-property :begin parent))
21996 (if (org-with-limited-levels (org-before-first-heading-p))
21997 (error "No surrounding element")
21998 (org-with-limited-levels (org-back-to-heading)))))))
22000 (defvar org-element-greater-elements)
22001 (defun org-down-element ()
22002 "Move to inner element."
22003 (interactive)
22004 (let ((element (org-element-at-point)))
22005 (cond
22006 ((memq (org-element-type element) '(plain-list table))
22007 (goto-char (org-element-property :contents-begin element))
22008 (forward-char))
22009 ((memq (org-element-type element) org-element-greater-elements)
22010 ;; If contents are hidden, first disclose them.
22011 (when (org-element-property :hiddenp element) (org-cycle))
22012 (goto-char (or (org-element-property :contents-begin element)
22013 (error "No content for this element"))))
22014 (t (error "No inner element")))))
22016 (defun org-drag-element-backward ()
22017 "Move backward element at point."
22018 (interactive)
22019 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22020 (let* ((trail (org-element-at-point 'keep-trail))
22021 (elem (car trail))
22022 (prev-elem (nth 1 trail)))
22023 ;; Error out if no previous element or previous element is
22024 ;; a parent of the current one.
22025 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22026 (error "Cannot drag element backward")
22027 (let ((pos (point)))
22028 (org-element-swap-A-B prev-elem elem)
22029 (goto-char (+ (org-element-property :begin prev-elem)
22030 (- pos (org-element-property :begin elem)))))))))
22032 (defun org-drag-element-forward ()
22033 "Move forward element at point."
22034 (interactive)
22035 (let* ((pos (point))
22036 (elem (org-element-at-point)))
22037 (when (= (point-max) (org-element-property :end elem))
22038 (error "Cannot drag element forward"))
22039 (goto-char (org-element-property :end elem))
22040 (let ((next-elem (org-element-at-point)))
22041 (when (or (org-element-nested-p elem next-elem)
22042 (and (eq (org-element-type next-elem) 'headline)
22043 (not (eq (org-element-type elem) 'headline))))
22044 (goto-char pos)
22045 (error "Cannot drag element forward"))
22046 ;; Compute new position of point: it's shifted by NEXT-ELEM
22047 ;; body's length (without final blanks) and by the length of
22048 ;; blanks between ELEM and NEXT-ELEM.
22049 (let ((size-next (- (save-excursion
22050 (goto-char (org-element-property :end next-elem))
22051 (skip-chars-backward " \r\t\n")
22052 (forward-line)
22053 ;; Small correction if buffer doesn't end
22054 ;; with a newline character.
22055 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22056 (org-element-property :begin next-elem)))
22057 (size-blank (- (org-element-property :end elem)
22058 (save-excursion
22059 (goto-char (org-element-property :end elem))
22060 (skip-chars-backward " \r\t\n")
22061 (forward-line)
22062 (point)))))
22063 (org-element-swap-A-B elem next-elem)
22064 (goto-char (+ pos size-next size-blank))))))
22066 (defun org-mark-element ()
22067 "Put point at beginning of this element, mark at end.
22069 Interactively, if this command is repeated or (in Transient Mark
22070 mode) if the mark is active, it marks the next element after the
22071 ones already marked."
22072 (interactive)
22073 (let (deactivate-mark)
22074 (if (and (org-called-interactively-p 'any)
22075 (or (and (eq last-command this-command) (mark t))
22076 (and transient-mark-mode mark-active)))
22077 (set-mark
22078 (save-excursion
22079 (goto-char (mark))
22080 (goto-char (org-element-property :end (org-element-at-point)))))
22081 (let ((element (org-element-at-point)))
22082 (end-of-line)
22083 (push-mark (org-element-property :end element) t t)
22084 (goto-char (org-element-property :begin element))))))
22086 (defun org-narrow-to-element ()
22087 "Narrow buffer to current element."
22088 (interactive)
22089 (let ((elem (org-element-at-point)))
22090 (cond
22091 ((eq (car elem) 'headline)
22092 (narrow-to-region
22093 (org-element-property :begin elem)
22094 (org-element-property :end elem)))
22095 ((memq (car elem) org-element-greater-elements)
22096 (narrow-to-region
22097 (org-element-property :contents-begin elem)
22098 (org-element-property :contents-end elem)))
22100 (narrow-to-region
22101 (org-element-property :begin elem)
22102 (org-element-property :end elem))))))
22104 (defun org-transpose-element ()
22105 "Transpose current and previous elements, keeping blank lines between.
22106 Point is moved after both elements."
22107 (interactive)
22108 (org-skip-whitespace)
22109 (let ((end (org-element-property :end (org-element-at-point))))
22110 (org-drag-element-backward)
22111 (goto-char end)))
22113 (defun org-unindent-buffer ()
22114 "Un-indent the visible part of the buffer.
22115 Relative indentation (between items, inside blocks, etc.) isn't
22116 modified."
22117 (interactive)
22118 (unless (eq major-mode 'org-mode)
22119 (error "Cannot un-indent a buffer not in Org mode"))
22120 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22121 unindent-tree ; For byte-compiler.
22122 (unindent-tree
22123 (function
22124 (lambda (contents)
22125 (mapc
22126 (lambda (element)
22127 (if (memq (org-element-type element) '(headline section))
22128 (funcall unindent-tree (org-element-contents element))
22129 (save-excursion
22130 (save-restriction
22131 (narrow-to-region
22132 (org-element-property :begin element)
22133 (org-element-property :end element))
22134 (org-do-remove-indentation)))))
22135 (reverse contents))))))
22136 (funcall unindent-tree (org-element-contents parse-tree))))
22138 (defun org-show-subtree ()
22139 "Show everything after this heading at deeper levels."
22140 (interactive)
22141 (outline-flag-region
22142 (point)
22143 (save-excursion
22144 (org-end-of-subtree t t))
22145 nil))
22147 (defun org-show-entry ()
22148 "Show the body directly following this heading.
22149 Show the heading too, if it is currently invisible."
22150 (interactive)
22151 (save-excursion
22152 (condition-case nil
22153 (progn
22154 (org-back-to-heading t)
22155 (outline-flag-region
22156 (max (point-min) (1- (point)))
22157 (save-excursion
22158 (if (re-search-forward
22159 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22160 (match-beginning 1)
22161 (point-max)))
22162 nil)
22163 (org-cycle-hide-drawers 'children))
22164 (error nil))))
22166 (defun org-make-options-regexp (kwds &optional extra)
22167 "Make a regular expression for keyword lines."
22168 (concat
22169 "^#\\+\\("
22170 (mapconcat 'regexp-quote kwds "\\|")
22171 (if extra (concat "\\|" extra))
22172 "\\):[ \t]*\\(.*\\)"))
22174 ;; Make isearch reveal the necessary context
22175 (defun org-isearch-end ()
22176 "Reveal context after isearch exits."
22177 (when isearch-success ; only if search was successful
22178 (if (featurep 'xemacs)
22179 ;; Under XEmacs, the hook is run in the correct place,
22180 ;; we directly show the context.
22181 (org-show-context 'isearch)
22182 ;; In Emacs the hook runs *before* restoring the overlays.
22183 ;; So we have to use a one-time post-command-hook to do this.
22184 ;; (Emacs 22 has a special variable, see function `org-mode')
22185 (unless (and (boundp 'isearch-mode-end-hook-quit)
22186 isearch-mode-end-hook-quit)
22187 ;; Only when the isearch was not quitted.
22188 (org-add-hook 'post-command-hook 'org-isearch-post-command
22189 'append 'local)))
22190 (org-fix-ellipsis-at-bol)))
22192 (defun org-isearch-post-command ()
22193 "Remove self from hook, and show context."
22194 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22195 (org-show-context 'isearch))
22198 ;;;; Integration with and fixes for other packages
22200 ;;; Imenu support
22202 (defvar org-imenu-markers nil
22203 "All markers currently used by Imenu.")
22204 (make-variable-buffer-local 'org-imenu-markers)
22206 (defun org-imenu-new-marker (&optional pos)
22207 "Return a new marker for use by Imenu, and remember the marker."
22208 (let ((m (make-marker)))
22209 (move-marker m (or pos (point)))
22210 (push m org-imenu-markers)
22213 (defun org-imenu-get-tree ()
22214 "Produce the index for Imenu."
22215 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22216 (setq org-imenu-markers nil)
22217 (let* ((n org-imenu-depth)
22218 (re (concat "^" (org-get-limited-outline-regexp)))
22219 (subs (make-vector (1+ n) nil))
22220 (last-level 0)
22221 m level head0 head)
22222 (save-excursion
22223 (save-restriction
22224 (widen)
22225 (goto-char (point-max))
22226 (while (re-search-backward re nil t)
22227 (setq level (org-reduced-level (funcall outline-level)))
22228 (when (and (<= level n)
22229 (looking-at org-complex-heading-regexp)
22230 (setq head0 (org-match-string-no-properties 4)))
22231 (setq head (org-link-display-format head0)
22232 m (org-imenu-new-marker))
22233 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22234 (if (>= level last-level)
22235 (push (cons head m) (aref subs level))
22236 (push (cons head (aref subs (1+ level))) (aref subs level))
22237 (loop for i from (1+ level) to n do (aset subs i nil)))
22238 (setq last-level level)))))
22239 (aref subs 1)))
22241 (eval-after-load "imenu"
22242 '(progn
22243 (add-hook 'imenu-after-jump-hook
22244 (lambda ()
22245 (if (derived-mode-p 'org-mode)
22246 (org-show-context 'org-goto))))))
22248 (defun org-link-display-format (link)
22249 "Replace a link with either the description, or the link target
22250 if no description is present"
22251 (save-match-data
22252 (if (string-match org-bracket-link-analytic-regexp link)
22253 (replace-match (if (match-end 5)
22254 (match-string 5 link)
22255 (concat (match-string 1 link)
22256 (match-string 3 link)))
22257 nil t link)
22258 link)))
22260 (defun org-toggle-link-display ()
22261 "Toggle the literal or descriptive display of links."
22262 (interactive)
22263 (if org-descriptive-links
22264 (progn (org-remove-from-invisibility-spec '(org-link))
22265 (org-restart-font-lock)
22266 (setq org-descriptive-links nil))
22267 (progn (add-to-invisibility-spec '(org-link))
22268 (org-restart-font-lock)
22269 (setq org-descriptive-links t))))
22271 ;; Speedbar support
22273 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22274 "Overlay marking the agenda restriction line in speedbar.")
22275 (overlay-put org-speedbar-restriction-lock-overlay
22276 'face 'org-agenda-restriction-lock)
22277 (overlay-put org-speedbar-restriction-lock-overlay
22278 'help-echo "Agendas are currently limited to this item.")
22279 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22281 (defun org-speedbar-set-agenda-restriction ()
22282 "Restrict future agenda commands to the location at point in speedbar.
22283 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22284 (interactive)
22285 (require 'org-agenda)
22286 (let (p m tp np dir txt)
22287 (cond
22288 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22289 'org-imenu t))
22290 (setq m (get-text-property p 'org-imenu-marker))
22291 (with-current-buffer (marker-buffer m)
22292 (goto-char m)
22293 (org-agenda-set-restriction-lock 'subtree)))
22294 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22295 'speedbar-function 'speedbar-find-file))
22296 (setq tp (previous-single-property-change
22297 (1+ p) 'speedbar-function)
22298 np (next-single-property-change
22299 tp 'speedbar-function)
22300 dir (speedbar-line-directory)
22301 txt (buffer-substring-no-properties (or tp (point-min))
22302 (or np (point-max))))
22303 (with-current-buffer (find-file-noselect
22304 (let ((default-directory dir))
22305 (expand-file-name txt)))
22306 (unless (derived-mode-p 'org-mode)
22307 (error "Cannot restrict to non-Org-mode file"))
22308 (org-agenda-set-restriction-lock 'file)))
22309 (t (error "Don't know how to restrict Org-mode's agenda")))
22310 (move-overlay org-speedbar-restriction-lock-overlay
22311 (point-at-bol) (point-at-eol))
22312 (setq current-prefix-arg nil)
22313 (org-agenda-maybe-redo)))
22315 (eval-after-load "speedbar"
22316 '(progn
22317 (speedbar-add-supported-extension ".org")
22318 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22319 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22320 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22321 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22322 (add-hook 'speedbar-visiting-tag-hook
22323 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22325 ;;; Fixes and Hacks for problems with other packages
22327 ;; Make flyspell not check words in links, to not mess up our keymap
22328 (defun org-mode-flyspell-verify ()
22329 "Don't let flyspell put overlays at active buttons, or on
22330 {todo,all-time,additional-option-like}-keywords."
22331 (let ((pos (max (1- (point)) (point-min)))
22332 (word (thing-at-point 'word)))
22333 (and (not (get-text-property pos 'keymap))
22334 (not (get-text-property pos 'org-no-flyspell))
22335 (not (member word org-todo-keywords-1))
22336 (not (member word org-all-time-keywords))
22337 (not (member word org-options-keywords))
22338 (not (member word (mapcar 'car org-startup-options)))
22339 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22341 (defun org-remove-flyspell-overlays-in (beg end)
22342 "Remove flyspell overlays in region."
22343 (and (org-bound-and-true-p flyspell-mode)
22344 (fboundp 'flyspell-delete-region-overlays)
22345 (flyspell-delete-region-overlays beg end))
22346 (add-text-properties beg end '(org-no-flyspell t)))
22348 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22349 (eval-after-load "bookmark"
22350 '(if (boundp 'bookmark-after-jump-hook)
22351 ;; We can use the hook
22352 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22353 ;; Hook not available, use advice
22354 (defadvice bookmark-jump (after org-make-visible activate)
22355 "Make the position visible."
22356 (org-bookmark-jump-unhide))))
22358 ;; Make sure saveplace shows the location if it was hidden
22359 (eval-after-load "saveplace"
22360 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22361 "Make the position visible."
22362 (org-bookmark-jump-unhide)))
22364 ;; Make sure ecb shows the location if it was hidden
22365 (eval-after-load "ecb"
22366 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22367 "Make hierarchy visible when jumping into location from ECB tree buffer."
22368 (if (derived-mode-p 'org-mode)
22369 (org-show-context))))
22371 (defun org-bookmark-jump-unhide ()
22372 "Unhide the current position, to show the bookmark location."
22373 (and (derived-mode-p 'org-mode)
22374 (or (outline-invisible-p)
22375 (save-excursion (goto-char (max (point-min) (1- (point))))
22376 (outline-invisible-p)))
22377 (org-show-context 'bookmark-jump)))
22379 ;; Make session.el ignore our circular variable
22380 (eval-after-load "session"
22381 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22383 ;;;; Experimental code
22385 (defun org-closed-in-range ()
22386 "Sparse tree of items closed in a certain time range.
22387 Still experimental, may disappear in the future."
22388 (interactive)
22389 ;; Get the time interval from the user.
22390 (let* ((time1 (org-float-time
22391 (org-read-date nil 'to-time nil "Starting date: ")))
22392 (time2 (org-float-time
22393 (org-read-date nil 'to-time nil "End date:")))
22394 ;; callback function
22395 (callback (lambda ()
22396 (let ((time
22397 (org-float-time
22398 (apply 'encode-time
22399 (org-parse-time-string
22400 (match-string 1))))))
22401 ;; check if time in interval
22402 (and (>= time time1) (<= time time2))))))
22403 ;; make tree, check each match with the callback
22404 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22406 ;;;; Finish up
22408 (provide 'org)
22410 (run-hooks 'org-load-hook)
22412 ;;; org.el ends here